@fluidgrids/fe-sdk 0.0.0-stage → 2026.1203.7

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 (323) hide show
  1. package/README.md +564 -2
  2. package/dist/ActivityOptionsFields-C2u-hY2U.js +142 -0
  3. package/dist/AiStudioPage-B_hNTj-_.js +1137 -0
  4. package/dist/ApprovalInboxPage-ClITra3n.js +1312 -0
  5. package/dist/ChoiceSelect-LkK-uS9J.js +65 -0
  6. package/dist/ConfirmActionDialog-DHWTDRbp.js +31 -0
  7. package/dist/ConnectionFormDialog-C0kDgcrZ.js +153 -0
  8. package/dist/CreateFluidgridsTagDocument-Dtp9KPLJ.js +1055 -0
  9. package/dist/DataSinkDashboardPage-b4ezeqa6.js +278 -0
  10. package/dist/DataTablesPage-C1d9YGHz.js +5575 -0
  11. package/dist/DateTimeField-B1qR4ruo.js +51 -0
  12. package/dist/Disclosure-BNKij7-v.js +45 -0
  13. package/dist/ElementLibraryPage-8jNO6YmE.js +2256 -0
  14. package/dist/ElementLibrarySequenceDocument-B-W8SPzn.js +3979 -0
  15. package/dist/EnsureThemeProvider-BvlNjAd0.js +24 -0
  16. package/dist/EntityTagBadge-1OlP6p0c.js +25 -0
  17. package/dist/EntityTagPicker-BBrU5cE0.js +137 -0
  18. package/dist/ExecuteStepDocument-B4j1mdRT.js +189 -0
  19. package/dist/ExecutionDetailDocument-D6QuM-kp.js +875 -0
  20. package/dist/ExecutionDetailPage-D4CBtFdo.js +12217 -0
  21. package/dist/ExecutionDetailPage-DvQ667OE.d.ts +10 -0
  22. package/dist/ExecutionStatusBadge-BsDVor9t.js +221 -0
  23. package/dist/ExecutionsListDocument-Dan7ZiqB.js +459 -0
  24. package/dist/ExecutionsListPage-B3XT8ITL.js +4307 -0
  25. package/dist/FailureTriagePanel-DOJMaJ0n.js +1285 -0
  26. package/dist/FileDownloadUrlDocument-CVOYKcL5.js +92 -0
  27. package/dist/FluidGridsDocsLink-bX0Hnhxr.js +66 -0
  28. package/dist/FluidGridsMark-CE2blT7K.js +74 -0
  29. package/dist/HeldLoadRegion-BtTxbvOW.js +34 -0
  30. package/dist/HistoryPage-BLoRpJ1R.d.ts +6 -0
  31. package/dist/HistoryPage-BSBISXoj.js +2835 -0
  32. package/dist/Icon-BtQ0HXLh.js +160 -0
  33. package/dist/InsightsPage-D7ybj8N9.js +11245 -0
  34. package/dist/IsolationSetting-vy911E8b.js +1153 -0
  35. package/dist/LibraryParts-DOeNgR8A.js +413 -0
  36. package/dist/ManagedAiPolicyAuthority-BxwJ3ptd.js +40 -0
  37. package/dist/ManagedAiPolicyAuthority-DM3t3wNr.d.ts +18 -0
  38. package/dist/ManagedAiPolicyAuthorityContext-CNkxIOZ1.js +10 -0
  39. package/dist/McpTriggerServers-BCPCAOWB.js +459 -0
  40. package/dist/MissingNodesInstallModal-rO_SEDrC.js +224 -0
  41. package/dist/NavigationV2Provider-DCDt35eG.js +17 -0
  42. package/dist/NodeSchemaIntrospectionDocument-C1vAIcHd.js +95 -0
  43. package/dist/NodesPage-DEbnz9iU.d.ts +6 -0
  44. package/dist/NodesPage-O7KeeKtd.js +653 -0
  45. package/dist/OfflineIcon-TwMKYWjA.js +207 -0
  46. package/dist/OpenTemplateAsCodeButton-BhWJWIF3.js +94 -0
  47. package/dist/PaidTemplateConfirm-_G3ag6S4.js +28 -0
  48. package/dist/PublishCustomNodeAction-CIySbK4c.js +134 -0
  49. package/dist/RecordTaskDialog-BkpCDvhR.js +2078 -0
  50. package/dist/RunActionsMenu-DodOgIQm.js +59 -0
  51. package/dist/RunnerStatusPill-C1v967iq.js +24 -0
  52. package/dist/RunnersPage-dB0RSdY_.js +1929 -0
  53. package/dist/SandboxRuntimeExhaustedNotice-BFOIF93C.js +120 -0
  54. package/dist/SchedulesPage-DPWr1yvf.js +1607 -0
  55. package/dist/SearchBox-BGtYjvfs.js +49 -0
  56. package/dist/SequenceEditor-CFiHeHkR.js +497 -0
  57. package/dist/SettingsPage-0CQBNPZV.js +8695 -0
  58. package/dist/StewardPages-DAJhepen.js +47 -0
  59. package/dist/StewardRunImportPanel-Kva2DO0u.js +2844 -0
  60. package/dist/StoreTemplateCardCompact-CHn5kP7A.js +2166 -0
  61. package/dist/TagFilterSelect-CyA8QrS7.js +42 -0
  62. package/dist/TaskQueuesPage-DdnDCyat.js +3571 -0
  63. package/dist/TechnicalDetails-B0Oi4aZw.js +19 -0
  64. package/dist/TemplateConfigurationModal-CdvCYJLM.js +332 -0
  65. package/dist/TemplateDetailPanel-CbiKciuB.js +222 -0
  66. package/dist/TemplatePreview-cx7-NOeG.js +868 -0
  67. package/dist/TemplatesPage-BG3H-6v6.d.ts +10 -0
  68. package/dist/TemplatesPage-BVQpGYIV.js +3251 -0
  69. package/dist/TerminateExecutionDocument-B_HKNVrN.js +581 -0
  70. package/dist/TranslationBridge-Bd4aJKMs.d.ts +11 -0
  71. package/dist/TranslationBridge-Da-TPgQm.js +68 -0
  72. package/dist/TriggerWorkflowDocument-D9Km2Vv2.js +460 -0
  73. package/dist/UiSequencePickerSequenceDocument-BSYnSDV7.js +607 -0
  74. package/dist/UiStepScreenshot-Qh4QMyUp.js +146 -0
  75. package/dist/UsageTimeSeriesDocument-DcInx9-z.js +177 -0
  76. package/dist/VariablesPage-ChfGuW22.js +2243 -0
  77. package/dist/VersionDiffDialog-Bd2AeUwf.js +1702 -0
  78. package/dist/VersionLifecycleBar-BBeWVtz-.js +143 -0
  79. package/dist/WebhookDeliveriesPage-D66bua0j.js +1563 -0
  80. package/dist/WorkflowBuilder-B6wQD1TK.js +539 -0
  81. package/dist/WorkflowBuilder-DR4ku8Tr.js +1611 -0
  82. package/dist/WorkflowDefinitionDocument-DZLbTPUZ.js +321 -0
  83. package/dist/WorkflowEmbed-BXfFGy0i.js +708 -0
  84. package/dist/WorkflowEmbed-Cbqe1s1z.d.ts +6 -0
  85. package/dist/WorkflowPinnedDataDocument-BODT5omd.js +782 -0
  86. package/dist/WorkflowProposalCard-BruukdeF.js +96 -0
  87. package/dist/WorkflowProposalDocument-BdUbsrd0.js +620 -0
  88. package/dist/WorkflowSearchRedirect-C7zJ2MKH.js +40 -0
  89. package/dist/WorkflowSettingsDrawer-MVU1BKfY.d.ts +18 -0
  90. package/dist/WorkflowSettingsDrawer-gazs97WR.js +196 -0
  91. package/dist/WorkflowShareDialog-e8jJtLjU.js +469 -0
  92. package/dist/WorkflowVersionsDocument-DRVOp8Uj.js +3213 -0
  93. package/dist/WorkflowsList--hR2_8gf.js +4593 -0
  94. package/dist/WorkflowsList-CcNDQge5.d.ts +6 -0
  95. package/dist/WorkflowsListPageDocument-CnzcQm_o.js +934 -0
  96. package/dist/addonCatalog-CbZS4deh.js +58 -0
  97. package/dist/addonCatalog-sjlonAmR.d.ts +15 -0
  98. package/dist/addons.d.ts +3 -0
  99. package/dist/addons.js +4 -0
  100. package/dist/agent-form-Bfvm32j1.js +83 -0
  101. package/dist/agent-tools.d.ts +3 -0
  102. package/dist/agent-tools.js +5 -0
  103. package/dist/agentTools-CyL7DLOF.js +320 -0
  104. package/dist/ai-usage-BrxDgvdR.js +240 -0
  105. package/dist/aiCreditsBridge-BuE92tKo.js +49 -0
  106. package/dist/api-BKq-nIOZ.js +2286 -0
  107. package/dist/api-Ol7I8NxE.js +8289 -0
  108. package/dist/apollo-type-policies.d.ts +11 -0
  109. package/dist/apollo-type-policies.js +64 -0
  110. package/dist/askAboutBridge-ByYsQams.js +106 -0
  111. package/dist/askQuestions-Cmx7VnMm.js +742 -0
  112. package/dist/assert-rules-lfYEMc99.js +318 -0
  113. package/dist/assistant.d.ts +94 -0
  114. package/dist/assistant.js +99 -0
  115. package/dist/attach-node-helpers-HDKQOtrD.js +32 -0
  116. package/dist/badge-CXfPhoMH.js +26 -0
  117. package/dist/basil.generated-BK-EHbwN.js +10 -0
  118. package/dist/browser-steps-DMpS5TyB.js +533 -0
  119. package/dist/builderTimings-pvGnK1m-.js +510 -0
  120. package/dist/button-DG7y_FVJ.js +48 -0
  121. package/dist/canvasNoteTools-BxuP_AYO.js +137 -0
  122. package/dist/card-Bomy_1UG.js +44 -0
  123. package/dist/catalogGrid-BOrfMgi-.js +41 -0
  124. package/dist/channel-CPyQ1NR1.js +212 -0
  125. package/dist/chips-CvNrYJZa.js +27 -0
  126. package/dist/client-holder-C0M5Cfwl.js +68 -0
  127. package/dist/cn-QqidFIgr.js +10 -0
  128. package/dist/code-editor-diagnostics-Zr0cIcx1.js +46 -0
  129. package/dist/code-editor-field-x_JrY8KR.js +113 -0
  130. package/dist/codec-client-DPuD6mw7.js +515 -0
  131. package/dist/conditionBuilder-DwfEF0Q-.js +1144 -0
  132. package/dist/config-DO68jw5k.js +322 -0
  133. package/dist/constants-DgbVc24O.d.ts +296 -0
  134. package/dist/constants-DlRnHBfQ.js +217 -0
  135. package/dist/convert-browser-action-pfecelF7.js +347 -0
  136. package/dist/convert-dialog-B_o22NiJ.js +382 -0
  137. package/dist/create-workflow-first-Azg3JUdX.js +120 -0
  138. package/dist/definition-canvas-Bsda-rDT.js +31 -0
  139. package/dist/dialog-BVd152GS.js +94 -0
  140. package/dist/durable-nodes-BXyYCLxT.js +91 -0
  141. package/dist/duration-CDb7-mT_.js +33 -0
  142. package/dist/edge-mapper-wEAdGVU2.js +4477 -0
  143. package/dist/element-library-DkSlg_VE.js +727 -0
  144. package/dist/entities-I_0kio3q.js +38 -0
  145. package/dist/error-advice-QLr5NCm7.js +65 -0
  146. package/dist/errors-ClKb5sEt.js +188 -0
  147. package/dist/executions.d.ts +3 -0
  148. package/dist/executions.js +5 -0
  149. package/dist/feature-flags-B2qetXKd.js +385 -0
  150. package/dist/field-label-DPZRmE_B.js +153 -0
  151. package/dist/firstWorkflow-C_h0KMB2.js +133 -0
  152. package/dist/flags.d.ts +3 -0
  153. package/dist/flags.js +4 -0
  154. package/dist/flow-builder-DIvLOhz0.js +28038 -0
  155. package/dist/flow-store-holder-CUN7Terz.js +52 -0
  156. package/dist/fluent.generated-CA_e6-4l.js +14 -0
  157. package/dist/fluidgridsEvents-bbEQbwU6.js +175 -0
  158. package/dist/fluidgridsTheme-DUhvOgoy.js +297 -0
  159. package/dist/global-client-BQPuFrFa.js +433 -0
  160. package/dist/global-operations-BG6YgxrM.js +136 -0
  161. package/dist/graphql-types-UTYtujY9.js +21358 -0
  162. package/dist/history.d.ts +3 -0
  163. package/dist/history.js +4 -0
  164. package/dist/index-AoJAa5vU.d.ts +164958 -0
  165. package/dist/index-DEMT3iAM.d.ts +120 -0
  166. package/dist/index-ROZzNGyY.d.ts +76 -0
  167. package/dist/index.d.ts +20 -0
  168. package/dist/index.js +8123 -0
  169. package/dist/ion.generated-mbajjcAg.js +10 -0
  170. package/dist/label-Lzb8ZXf_.js +29 -0
  171. package/dist/labels-rXd9gYQz.js +1236 -0
  172. package/dist/liveCanvas-D5ytXDp8.js +103 -0
  173. package/dist/logos.generated-X6_0kjVR.js +21 -0
  174. package/dist/logs-panel-Cw0DkG0l.js +468 -0
  175. package/dist/lucide.generated-B6NVd3GT.js +29 -0
  176. package/dist/marksStore-a9oIMMot.js +175 -0
  177. package/dist/mcp-trigger-D0nRdvq5.js +307 -0
  178. package/dist/mdi.generated-D1BV74d6.js +292 -0
  179. package/dist/menus-CU3hDGYl.js +160 -0
  180. package/dist/mynaui.generated-DMWr5cXz.js +66 -0
  181. package/dist/navigation-v2.d.ts +3 -0
  182. package/dist/navigation-v2.js +5 -0
  183. package/dist/node-detail-view-Cgm5H1P-.js +1372 -0
  184. package/dist/node-editor-tab-body-CZ0fVuVP.js +187 -0
  185. package/dist/node-operation-selection-CdV3KI_V.js +3534 -0
  186. package/dist/node-registry-refresh-s3okf83X.js +27 -0
  187. package/dist/node-role-TMbnkmeP.js +132 -0
  188. package/dist/node-type-icon-BZa8n4iG.js +33 -0
  189. package/dist/nodes.d.ts +3 -0
  190. package/dist/nodes.js +4 -0
  191. package/dist/notesKey-5EaREBGA.js +12 -0
  192. package/dist/observability.d.ts +3 -0
  193. package/dist/observability.js +5 -0
  194. package/dist/offset-pages-zghoClB3.js +55 -0
  195. package/dist/operations-BBmT9ToP.js +663 -0
  196. package/dist/operations-WxRJWeqO.js +3133 -0
  197. package/dist/output-files-Ba8bu5lv.js +196 -0
  198. package/dist/page-operation-DrWuhd6Y.js +129 -0
  199. package/dist/page-twins.d.ts +13 -0
  200. package/dist/page-twins.js +186 -0
  201. package/dist/pageControlSpecs-DZJ9K37m.js +134 -0
  202. package/dist/pageControlsBridge-0pX9s-3k.js +54 -0
  203. package/dist/pageControlsBridge-DAuT3w7L.d.ts +36 -0
  204. package/dist/panels-PfBBAToE.js +346 -0
  205. package/dist/parts-B7fBcw-B.js +346 -0
  206. package/dist/popover-Dms9Vz3j.js +3389 -0
  207. package/dist/preloadable-lazy-Pp47mqQ9.js +65 -0
  208. package/dist/proactive.d.ts +66 -0
  209. package/dist/proactive.js +237 -0
  210. package/dist/quick-config-panel-DFd77xho.js +451 -0
  211. package/dist/quota-DeA_CJ2e.js +175 -0
  212. package/dist/quota.d.ts +3 -0
  213. package/dist/quota.js +4 -0
  214. package/dist/read-only-context-Dt9N9SIG.js +18 -0
  215. package/dist/relative-time-Dxt8ZIIu.js +55 -0
  216. package/dist/results-CwK_yDxK.js +325 -0
  217. package/dist/rolldown-runtime-hDbaFkMy.js +18 -0
  218. package/dist/route-data.d.ts +12 -0
  219. package/dist/route-data.js +69 -0
  220. package/dist/route-match-C-0_EnAt.d.ts +5 -0
  221. package/dist/route-match-DMkUICYV.js +41 -0
  222. package/dist/route-preload-C4DlGoCd.js +120 -0
  223. package/dist/run-display-UjLAoYqQ.js +81 -0
  224. package/dist/run-history-arGiHzGU.js +285 -0
  225. package/dist/run-list-links-DJn4Mf1T.js +98 -0
  226. package/dist/run-mode-USmM0-Uo.js +82 -0
  227. package/dist/run-parity-CWXqEJqM.js +144 -0
  228. package/dist/runsQuota-B6SyTbne.js +100 -0
  229. package/dist/runsQuota-DsniKiSg.d.ts +20 -0
  230. package/dist/safe-expression-Cw7-SCsm.js +1251 -0
  231. package/dist/save-status-store-C7nEYpfb.js +631 -0
  232. package/dist/schedule-panel-B4GYXzXQ.js +13774 -0
  233. package/dist/schedule-rules-ggVKRkBH.js +358 -0
  234. package/dist/secrets-Re_wSiE3.js +153 -0
  235. package/dist/settings.d.ts +4 -0
  236. package/dist/settings.js +6 -0
  237. package/dist/shared-DAWGGMSM.js +177 -0
  238. package/dist/sidebar-node-editor-6eSSgCzc.js +178 -0
  239. package/dist/solar.generated-CGYuUQAC.js +10 -0
  240. package/dist/stableTabbedDialog-BBhrfXGe.js +20 -0
  241. package/dist/start-url-CT6Yz96K.js +24 -0
  242. package/dist/status-CessxGpm.js +55 -0
  243. package/dist/store-icon-OctYp5zP.js +155 -0
  244. package/dist/styles-WGmTnZ2n.js +26 -0
  245. package/dist/styles.css +139 -0
  246. package/dist/svg-spinners.generated-CIPT7IhM.js +10 -0
  247. package/dist/template-code-CzN6JWNV.js +191 -0
  248. package/dist/template-graph-DLF9dygU.js +20 -0
  249. package/dist/template-preview-DcIIKOOL.js +32 -0
  250. package/dist/template-price-CdUHZRMF.js +40 -0
  251. package/dist/templates.d.ts +3 -0
  252. package/dist/templates.js +5 -0
  253. package/dist/theme-provider-CntfC4_i.js +23 -0
  254. package/dist/transient-DgZfhDfN.js +57 -0
  255. package/dist/typed-calls-C5tO03wq.js +26 -0
  256. package/dist/ui-script-By74Guk3.js +1094 -0
  257. package/dist/ui-script-editor-CqPu2bCN.js +2447 -0
  258. package/dist/ui-step-fix-8uM2_Hft.js +67 -0
  259. package/dist/ui-step-fix-store-CcO1FdRx.js +19 -0
  260. package/dist/ui-step-run-context-o7bLE6KP.js +46 -0
  261. package/dist/ui-target-editor-D2JhB_lD.js +673 -0
  262. package/dist/uiMarkTools-CSznnO1i.js +1054 -0
  263. package/dist/upgradePrompt-BAFBKKW5.js +72 -0
  264. package/dist/use-bare-node-registry-O6mKJO_n.js +11498 -0
  265. package/dist/use-browser-available-hj8wc3Kb.js +241 -0
  266. package/dist/use-edge-mapper-schemas-Bonofxow.js +496 -0
  267. package/dist/use-extension-bridge-B9ZreOkQ.js +608 -0
  268. package/dist/use-mobile-BTqCUjzS.js +27 -0
  269. package/dist/use-sdk-query-C697xZVv.js +116 -0
  270. package/dist/use-workflow-code-editor-CFoRFrZ5.js +753 -0
  271. package/dist/useActionParam-B2tU2BlY.js +85 -0
  272. package/dist/useAgentTokenStream-Bko_J0d0.js +4217 -0
  273. package/dist/useBrowserClients-3v95-gSh.js +103 -0
  274. package/dist/useCodeWorkflowInsights-w0tz9Ap_.js +600 -0
  275. package/dist/useConnections-DsgEJs05.js +439 -0
  276. package/dist/useDebouncedValue-BFekcv6n.js +18 -0
  277. package/dist/useDurableParity-8fnMZmBc.js +1787 -0
  278. package/dist/useEntityTags-D0spL6Ut.js +460 -0
  279. package/dist/useExecutions-2u5nGJJk.js +681 -0
  280. package/dist/useFluidGridsAnalytics-VM8lAi2x.js +238 -0
  281. package/dist/useGlobalStoreClient-BTdhkA2I.js +24 -0
  282. package/dist/useHumanRequests-zlYDp3l1.js +221 -0
  283. package/dist/useNavigationV2-C2WeqN7d.js +29 -0
  284. package/dist/useNavigationV2-DANUmg12.d.ts +9 -0
  285. package/dist/useObservability-BRlQ0tOA.js +285 -0
  286. package/dist/useRequestedProposal-B7uPXfZB.js +51 -0
  287. package/dist/useRunHistory-CXCMUPyf.js +2759 -0
  288. package/dist/useRunLive-D0JvVZT2.js +1060 -0
  289. package/dist/useRunnerList-Dbi59i1K.js +446 -0
  290. package/dist/useRunners-URUc5quU.js +173 -0
  291. package/dist/useRunsPage-DG656UCK.js +2709 -0
  292. package/dist/useVariables-BIelxcWr.js +463 -0
  293. package/dist/useVersionHistoryData-CTjqVw7l.js +292 -0
  294. package/dist/useWorkflowCodeExport-pqxyLHD1.js +522 -0
  295. package/dist/useWorkflowListExport-hcZNvTaB.js +232 -0
  296. package/dist/useWorkflowOrganization-CpBbOrs7.js +1772 -0
  297. package/dist/useWorkflowProposal-BH0VdNMA.js +3280 -0
  298. package/dist/useWorkflows-Cvg-Z_IE.js +1606 -0
  299. package/dist/utils-fvBb5qOD.js +89 -0
  300. package/dist/webhook-deliveries-AvQujaZy.js +99 -0
  301. package/dist/workflow-builder-CJygVkVv.d.ts +2 -0
  302. package/dist/workflow-builder.d.ts +3 -0
  303. package/dist/workflow-builder.js +8 -0
  304. package/dist/workflow-code-transfer-Bsy0JKAZ.js +323 -0
  305. package/dist/workflow-embed.d.ts +3 -0
  306. package/dist/workflow-embed.js +4 -0
  307. package/dist/workflow-git-sync--K9ZsPDC.js +263 -0
  308. package/dist/workflow-host.d.ts +6 -0
  309. package/dist/workflow-host.js +11 -0
  310. package/dist/workflow-pages-D-7ByLTB.d.ts +68 -0
  311. package/dist/workflow-pages.d.ts +3 -0
  312. package/dist/workflow-pages.js +115 -0
  313. package/dist/workflow-preview-canvas-CO8yzdE3.js +848 -0
  314. package/dist/workflow-preview.d.ts +65 -0
  315. package/dist/workflow-preview.js +4 -0
  316. package/dist/workflow-route.d.ts +33 -0
  317. package/dist/workflow-route.js +4 -0
  318. package/dist/workflow-save-state-D0l-DkLf.js +767 -0
  319. package/dist/workflow-transfer-CQnQC-ke.js +104 -0
  320. package/dist/workflowRouteData-BkfVOc-O.js +169 -0
  321. package/dist/workflows-list.d.ts +10 -0
  322. package/dist/workflows-list.js +5 -0
  323. package/package.json +320 -4
@@ -0,0 +1,3534 @@
1
+ "use client";
2
+ import { r as useTr } from "./TranslationBridge-Da-TPgQm.js";
3
+ import { n as humanizeFieldName, o as mergeStickyNotes } from "./field-label-DPZRmE_B.js";
4
+ import { n as provideFlowStore } from "./flow-store-holder-CUN7Terz.js";
5
+ import { t as isNodeTrigger } from "./node-role-TMbnkmeP.js";
6
+ import { r as baseNodeType } from "./mcp-trigger-D0nRdvq5.js";
7
+ import { r as pageLocale, t as formatExactTime } from "./relative-time-Dxt8ZIIu.js";
8
+ import { t as Icon } from "./Icon-BtQ0HXLh.js";
9
+ import { t as NodeTypeIcon } from "./node-type-icon-BZa8n4iG.js";
10
+ import { t as formatDurationMs } from "./run-history-arGiHzGU.js";
11
+ import { n as nodeStateDurationMs } from "./duration-CDb7-mT_.js";
12
+ import { t as editorSeverity } from "./code-editor-diagnostics-Zr0cIcx1.js";
13
+ import * as React from "react";
14
+ import { useCallback, useEffect, useMemo, useRef } from "react";
15
+ import { create } from "zustand";
16
+ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
17
+ import { Handle, Position, addEdge, applyEdgeChanges, applyNodeChanges, getConnectedEdges, useNodeId, useStore, useUpdateNodeInternals } from "@xyflow/react";
18
+ import { chartSeriesColor, chartSeriesIndex, nodeCategoryColor } from "@burdenoff/fe-libs/shared/utils";
19
+ import { nanoid } from "nanoid/non-secure";
20
+ import { produce } from "immer";
21
+ import { cn } from "@burdenoff/fe-libs/utils";
22
+ import { CompactMarkOr } from "@burdenoff/fe-libs/ui";
23
+
24
+ // src/builder/collab/collab-changes.ts
25
+ const COLLECTIONS = [
26
+ "nodes",
27
+ "stickyNotes",
28
+ "edges"
29
+ ];
30
+ /**
31
+ * React Flow state of one page (what it has selected, is dragging, has
32
+ * measured): never sent, and kept from the local copy when an item arrives.
33
+ */
34
+ const VOLATILE_ITEM_KEYS = /* @__PURE__ */ new Set([
35
+ "selected",
36
+ "dragging",
37
+ "measured",
38
+ "resizing",
39
+ "positionAbsolute"
40
+ ]);
41
+ /** Nested values deeper than this are sent whole. */
42
+ const MAX_DIFF_DEPTH = 12;
43
+ function isRecord$3(value) {
44
+ return typeof value === "object" && value !== null && !Array.isArray(value);
45
+ }
46
+ function itemId(item) {
47
+ return isRecord$3(item) && typeof item.id === "string" ? item.id : null;
48
+ }
49
+ /** Deep equality of JSON values. */
50
+ function sameValue(a, b) {
51
+ if (a === b) return true;
52
+ if (Array.isArray(a) || Array.isArray(b)) {
53
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
54
+ return a.every((item, index) => sameValue(item, b[index]));
55
+ }
56
+ if (isRecord$3(a) && isRecord$3(b)) {
57
+ const keys = Object.keys(a);
58
+ if (keys.length !== Object.keys(b).length) return false;
59
+ return keys.every((key) => key in b && sameValue(a[key], b[key]));
60
+ }
61
+ return false;
62
+ }
63
+ /** An item without this page's React Flow state. */
64
+ function sharedPartOf(item) {
65
+ const shared = {};
66
+ for (const [key, value] of Object.entries(item)) if (!VOLATILE_ITEM_KEYS.has(key) && value !== void 0) shared[key] = value;
67
+ return shared;
68
+ }
69
+ function diffValue(target, previous, next, path, out) {
70
+ if (sameValue(previous, next)) return;
71
+ if (isRecord$3(previous) && isRecord$3(next) && path.length < MAX_DIFF_DEPTH) {
72
+ const keys = /* @__PURE__ */ new Set([...Object.keys(previous), ...Object.keys(next)]);
73
+ for (const key of keys) {
74
+ const before = previous[key];
75
+ const after = next[key];
76
+ if (after === void 0) {
77
+ if (before !== void 0) out.push({
78
+ op: "unset",
79
+ ...target,
80
+ path: [...path, key]
81
+ });
82
+ } else if (before === void 0) out.push({
83
+ op: "set",
84
+ ...target,
85
+ path: [...path, key],
86
+ value: after
87
+ });
88
+ else diffValue(target, before, after, [...path, key], out);
89
+ }
90
+ return;
91
+ }
92
+ out.push({
93
+ op: "set",
94
+ ...target,
95
+ path,
96
+ value: next
97
+ });
98
+ }
99
+ function byId(items) {
100
+ const map = /* @__PURE__ */ new Map();
101
+ for (const item of items) {
102
+ const id = itemId(item);
103
+ if (id !== null) map.set(id, item);
104
+ }
105
+ return map;
106
+ }
107
+ /** The changes that turn canvas `previous` into canvas `next`. */
108
+ function diffCanvas(previous, next) {
109
+ const changes = [];
110
+ for (const collection of COLLECTIONS) {
111
+ const before = byId(previous[collection]);
112
+ const after = byId(next[collection]);
113
+ for (const [id] of before) if (!after.has(id)) changes.push({
114
+ op: "remove",
115
+ in: collection,
116
+ id
117
+ });
118
+ for (const [id, item] of after) {
119
+ const old = before.get(id);
120
+ if (!old) changes.push({
121
+ op: "put",
122
+ in: collection,
123
+ id,
124
+ value: sharedPartOf(item)
125
+ });
126
+ else if (old !== item) {
127
+ const changed = [];
128
+ diffValue({
129
+ in: collection,
130
+ id
131
+ }, sharedPartOf(old), sharedPartOf(item), [], changed);
132
+ if (changed.some((change) => (change.op === "set" || change.op === "unset") && (change.path.length === 0 || change.path[0] === "id"))) changes.push({
133
+ op: "put",
134
+ in: collection,
135
+ id,
136
+ value: sharedPartOf(item)
137
+ });
138
+ else changes.push(...changed);
139
+ }
140
+ }
141
+ }
142
+ for (const name of ["name", "alias"]) if (previous[name] !== next[name]) changes.push({
143
+ op: "field",
144
+ name,
145
+ value: next[name]
146
+ });
147
+ return changes;
148
+ }
149
+ function cloneJson(value) {
150
+ return structuredClone(value);
151
+ }
152
+ function setIn(item, path, value) {
153
+ const [head, ...rest] = path;
154
+ if (head === void 0) return item;
155
+ const copy = Array.isArray(item) ? [...item] : { ...item };
156
+ if (rest.length === 0) copy[head] = cloneJson(value);
157
+ else {
158
+ const child = copy[head];
159
+ copy[head] = setIn(typeof child === "object" && child !== null ? child : typeof rest[0] === "number" ? [] : {}, rest, value);
160
+ }
161
+ return copy;
162
+ }
163
+ function unsetIn(item, path) {
164
+ const [head, ...rest] = path;
165
+ if (head === void 0) return item;
166
+ if (rest.length === 0) {
167
+ if (Array.isArray(item) && typeof head === "number") {
168
+ const copy = [...item];
169
+ copy.splice(head, 1);
170
+ return copy;
171
+ }
172
+ const { [head]: _removed, ...kept } = item;
173
+ return kept;
174
+ }
175
+ const child = item[head];
176
+ if (typeof child !== "object" || child === null) return item;
177
+ const copy = Array.isArray(item) ? [...item] : { ...item };
178
+ copy[head] = unsetIn(child, rest);
179
+ return copy;
180
+ }
181
+ /**
182
+ * Apply changes to one collection's items. A put keeps this page's React Flow
183
+ * state of the item it replaces; a change to an item that is gone is skipped.
184
+ * Returns the same array when nothing changed.
185
+ */
186
+ function applyToItems(items, changes, collections) {
187
+ const records = items;
188
+ let result = null;
189
+ const current = () => result ??= [...records];
190
+ const applies = new Set(collections);
191
+ for (const change of changes) {
192
+ if (change.op === "field" || !applies.has(change.in)) continue;
193
+ const list = current();
194
+ const index = list.findIndex((item) => itemId(item) === change.id);
195
+ if (change.op === "put") {
196
+ const volatile = index >= 0 ? Object.fromEntries(Object.entries(list[index] ?? {}).filter(([key]) => VOLATILE_ITEM_KEYS.has(key))) : {};
197
+ const item = {
198
+ ...cloneJson(change.value),
199
+ ...volatile
200
+ };
201
+ if (index >= 0) list[index] = item;
202
+ else list.push(item);
203
+ } else if (index >= 0) {
204
+ const existing = list[index] ?? {};
205
+ if (change.op === "remove") list.splice(index, 1);
206
+ else if (change.op === "set") list[index] = setIn(existing, change.path, change.value);
207
+ else list[index] = unsetIn(existing, change.path);
208
+ }
209
+ }
210
+ return result ?? [...records];
211
+ }
212
+ /**
213
+ * Items arriving whole (a reload) with this page's React Flow state of the
214
+ * same items kept: what it has selected and measured stays as it was.
215
+ */
216
+ function withLocalState(incoming, current) {
217
+ const local = /* @__PURE__ */ new Map();
218
+ for (const item of current) {
219
+ const id = itemId(item);
220
+ if (id === null) continue;
221
+ local.set(id, Object.fromEntries(Object.entries(item).filter(([key]) => VOLATILE_ITEM_KEYS.has(key))));
222
+ }
223
+ return incoming.map((item) => ({
224
+ ...item,
225
+ ...local.get(itemId(item) ?? "") ?? {}
226
+ }));
227
+ }
228
+ /** Apply changes to a whole canvas shape. */
229
+ function applyToShape(shape, changes) {
230
+ let name = shape.name;
231
+ let alias = shape.alias;
232
+ for (const change of changes) {
233
+ if (change.op !== "field") continue;
234
+ if (change.name === "name") name = change.value;
235
+ else alias = change.value;
236
+ }
237
+ return {
238
+ nodes: applyToItems(shape.nodes, changes, ["nodes"]),
239
+ stickyNotes: applyToItems(shape.stickyNotes, changes, ["stickyNotes"]),
240
+ edges: applyToItems(shape.edges, changes, ["edges"]),
241
+ name,
242
+ alias,
243
+ ...shape.description !== void 0 ? { description: shape.description } : {}
244
+ };
245
+ }
246
+ function spotOf(change) {
247
+ if (change.op === "field") return { field: change.name };
248
+ if (change.op === "put" || change.op === "remove") return {
249
+ in: change.in,
250
+ id: change.id,
251
+ path: null
252
+ };
253
+ return {
254
+ in: change.in,
255
+ id: change.id,
256
+ path: change.path
257
+ };
258
+ }
259
+ function overlaps(a, b) {
260
+ if ("field" in a || "field" in b) return "field" in a && "field" in b && a.field === b.field;
261
+ if (!(a.in === b.in || a.in !== "edges" && b.in !== "edges") || a.id !== b.id) return false;
262
+ if (a.path === null || b.path === null) return true;
263
+ const shorter = a.path.length <= b.path.length ? a.path : b.path;
264
+ const longer = shorter === a.path ? b.path : a.path;
265
+ return shorter.every((segment, index) => longer[index] === segment);
266
+ }
267
+ /**
268
+ * The changes of a remote batch that do not touch what this page changed and
269
+ * the service has not confirmed yet. Those local changes reach the service
270
+ * after the remote batch, so they win there; applying the remote value here
271
+ * would only flicker the old value back for a moment.
272
+ */
273
+ function withoutPendingConflicts(remote, pending) {
274
+ if (pending.length === 0) return [...remote];
275
+ const pendingSpots = pending.map(spotOf);
276
+ return remote.filter((change) => {
277
+ const spot = spotOf(change);
278
+ return !pendingSpots.some((mine) => overlaps(spot, mine));
279
+ });
280
+ }
281
+ /** Read a broadcast batch: only well-formed changes are kept. */
282
+ function parseChanges(raw) {
283
+ if (!Array.isArray(raw)) return [];
284
+ const changes = [];
285
+ for (const entry of raw) {
286
+ if (!isRecord$3(entry)) continue;
287
+ if (entry.op === "field") {
288
+ if ((entry.name === "name" || entry.name === "alias") && typeof entry.value === "string") changes.push({
289
+ op: "field",
290
+ name: entry.name,
291
+ value: entry.value
292
+ });
293
+ continue;
294
+ }
295
+ const collection = entry.in;
296
+ if (collection !== "nodes" && collection !== "edges" && collection !== "stickyNotes") continue;
297
+ if (typeof entry.id !== "string") continue;
298
+ const target = {
299
+ in: collection,
300
+ id: entry.id
301
+ };
302
+ const path = Array.isArray(entry.path) ? entry.path.filter((segment) => typeof segment === "string" || typeof segment === "number") : null;
303
+ if (entry.op === "put" && isRecord$3(entry.value)) changes.push({
304
+ op: "put",
305
+ ...target,
306
+ value: entry.value
307
+ });
308
+ else if (entry.op === "remove") changes.push({
309
+ op: "remove",
310
+ ...target
311
+ });
312
+ else if (entry.op === "set" && path && path.length > 0) changes.push({
313
+ op: "set",
314
+ ...target,
315
+ path,
316
+ value: entry.value
317
+ });
318
+ else if (entry.op === "unset" && path && path.length > 0) changes.push({
319
+ op: "unset",
320
+ ...target,
321
+ path
322
+ });
323
+ }
324
+ return changes;
325
+ }
326
+
327
+ // src/builder/stores/sidebar-on-load.ts
328
+ /**
329
+ * Below Tailwind's `xl` breakpoint the builder's side panel floats over the
330
+ * canvas instead of taking a column of its own (sidebar-panel-frame.tsx):
331
+ * most of the screen on a phone, 24rem on a tablet (BOFF-18043; it was `md`,
332
+ * and on a tablet the in-flow panel squeezed the canvas to 95 px). Keep this
333
+ * in step with that `xl:` layout.
334
+ */
335
+ const SIDEBAR_OVERLAY_QUERY = "(max-width: 1279px)";
336
+ /** Whether an open side panel would cover the canvas on this screen. */
337
+ function sidebarCoversCanvas() {
338
+ return typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(max-width: 1279px)").matches;
339
+ }
340
+ /**
341
+ * The sidebar a workflow opens with (BOFF-16627).
342
+ *
343
+ * A loaded workflow brings the sidebar state saved in its definition, and a
344
+ * blank or template workflow starts with the node store open. On a desktop
345
+ * that panel sits beside the canvas. On a phone or a tablet it covers the
346
+ * workflow the person came to see, so there the builder opens on the canvas
347
+ * instead.
348
+ *
349
+ * A panel opened for a reason stays: node properties with a node selected
350
+ * (the start-node flow selects the node it added).
351
+ */
352
+ function sidebarOnLoad(sidebar, coversCanvas) {
353
+ if (!coversCanvas) return sidebar;
354
+ return sidebar.active === "store-browse" || sidebar.active === "node-properties" && !sidebar.panels.nodeProperties.selectedNode ? {
355
+ ...sidebar,
356
+ active: "none"
357
+ } : sidebar;
358
+ }
359
+
360
+ // src/builder/hooks/use-is-valid-connection.ts
361
+ function isLoopController(source) {
362
+ const type = source?.type?.toLowerCase();
363
+ const disabled = source?.data?.disabled === true || source !== void 0 && "disabled" in source && source.disabled === true;
364
+ return (type === "internal:loop" || type === "loop") && !disabled;
365
+ }
366
+ function isRecord$2(value) {
367
+ return typeof value === "object" && value !== null && !Array.isArray(value);
368
+ }
369
+ function readRecord$1(value) {
370
+ return isRecord$2(value) ? value : void 0;
371
+ }
372
+ function loopBodyHandle(source) {
373
+ const node = readRecord$1(source);
374
+ const data = readRecord$1(node?.data);
375
+ const parameters = {
376
+ ...data,
377
+ ...readRecord$1(node?.config),
378
+ ...readRecord$1(readRecord$1(data?.args)?.state),
379
+ ...readRecord$1(readRecord$1(node?.args)?.state)
380
+ };
381
+ return typeof parameters.loopHandle === "string" && parameters.loopHandle ? parameters.loopHandle : "loop";
382
+ }
383
+ function isLoopBodyEdge(edge, nodes) {
384
+ const source = nodes.find((node) => node.id === edge.source);
385
+ return source !== void 0 && isLoopController(source) && edge.sourceHandle === loopBodyHandle(source);
386
+ }
387
+ function adjacency(edges) {
388
+ const outgoing = /* @__PURE__ */ new Map();
389
+ for (const edge of edges) {
390
+ const targets = outgoing.get(edge.source) ?? /* @__PURE__ */ new Set();
391
+ targets.add(edge.target);
392
+ outgoing.set(edge.source, targets);
393
+ }
394
+ return outgoing;
395
+ }
396
+ function reachable(starts, outgoing, blocked = /* @__PURE__ */ new Set()) {
397
+ const pending = [...starts];
398
+ const visited = /* @__PURE__ */ new Set();
399
+ while (pending.length > 0) {
400
+ const current = pending.pop();
401
+ if (current === void 0 || visited.has(current) || blocked.has(current)) continue;
402
+ visited.add(current);
403
+ pending.push(...outgoing.get(current) ?? []);
404
+ }
405
+ return visited;
406
+ }
407
+ function controlledReturns(nodes, edges) {
408
+ const outgoing = adjacency(edges);
409
+ const incomingTargets = new Set(edges.map((edge) => edge.target));
410
+ const entries = nodes.filter((node) => !incomingTargets.has(node.id) || isNodeTrigger(node)).map((node) => node.id);
411
+ const returns = /* @__PURE__ */ new Set();
412
+ for (const controller of nodes.filter(isLoopController)) {
413
+ const bodyHandle = loopBodyHandle(controller);
414
+ const controllerEdges = edges.filter((edge) => edge.source === controller.id);
415
+ const outside = reachable([...entries, ...controllerEdges.filter((edge) => edge.sourceHandle !== bodyHandle).map((edge) => edge.target)], outgoing, /* @__PURE__ */ new Set([controller.id]));
416
+ const body = reachable(controllerEdges.filter((edge) => edge.sourceHandle === bodyHandle).map((edge) => edge.target), outgoing, /* @__PURE__ */ new Set([controller.id, ...outside]));
417
+ for (const edge of edges) if (edge.target === controller.id && body.has(edge.source)) returns.add(edge);
418
+ }
419
+ return returns;
420
+ }
421
+ function isValidWorkflowConnection(nodes, edges, connection) {
422
+ if (connection.target === connection.source) return false;
423
+ const candidates = [...edges, connection];
424
+ const previousReturns = controlledReturns(nodes, edges);
425
+ const nextReturns = controlledReturns(nodes, candidates);
426
+ const outgoing = adjacency(candidates.filter((edge) => !nextReturns.has(edge)));
427
+ return [connection, ...previousReturns].filter((edge) => !nextReturns.has(edge)).every((edge) => !reachable([edge.target], outgoing).has(edge.source));
428
+ }
429
+ function useIsValidConnection(nodes, edges) {
430
+ return useCallback((connection) => isValidWorkflowConnection(nodes, edges, connection), [nodes, edges]);
431
+ }
432
+
433
+ // src/builder/lib/vector-store-memory.ts
434
+ const VECTOR_STORE_MEMORY_NODE_TYPE = "internal:vector-store-memory";
435
+ const VALID_SCOPES = /* @__PURE__ */ new Set([
436
+ "workflow",
437
+ "run",
438
+ "workspace"
439
+ ]);
440
+ const DEFAULT_OPERATION = "insert";
441
+ const DEFAULT_MEMORY_KEY = "default";
442
+ const DEFAULT_SCOPE = "workflow";
443
+ function asRecord(value) {
444
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
445
+ }
446
+ function nonEmptyString(value) {
447
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
448
+ }
449
+ function isTrueFlag(value) {
450
+ return value === true || value === "true";
451
+ }
452
+ function nonNegativeInt(value) {
453
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return null;
454
+ return Math.floor(value);
455
+ }
456
+ function positiveNumber(value) {
457
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return null;
458
+ return value;
459
+ }
460
+ function normalizeScope(value) {
461
+ const raw = nonEmptyString(value)?.toLowerCase();
462
+ if (raw && VALID_SCOPES.has(raw)) return raw;
463
+ return DEFAULT_SCOPE;
464
+ }
465
+ function isVectorStoreMemoryNodeType(type) {
466
+ return baseNodeType(type) === VECTOR_STORE_MEMORY_NODE_TYPE;
467
+ }
468
+ function nodeTypeOf(node) {
469
+ const data = asRecord(node.data);
470
+ const nodeData = asRecord(data?.nodeData);
471
+ return baseNodeType(node.type ?? data?.nodeType ?? nodeData?.nodeType ?? data?.type);
472
+ }
473
+ function paramsRecordOf(data) {
474
+ const record = asRecord(data);
475
+ if (!record) return {};
476
+ return asRecord(asRecord(record.args)?.state) ?? asRecord(record.state) ?? asRecord(record.parameters) ?? {};
477
+ }
478
+ /**
479
+ * Reads the In-memory Vector Store's saved operation, memory key, scope and
480
+ * `clearStore` flag from a canvas node's `data`, mirroring the worker defaults
481
+ * (`insert`, `default`, `workflow`, `false`).
482
+ */
483
+ function readVectorStoreMemoryConfig(data) {
484
+ const record = asRecord(data);
485
+ const params = paramsRecordOf(data);
486
+ const fallbackOperation = nonEmptyString(record?.operation_name);
487
+ return {
488
+ operation: nonEmptyString(params.operation) ?? (fallbackOperation && fallbackOperation.toLowerCase() !== "execute" ? fallbackOperation : void 0) ?? DEFAULT_OPERATION,
489
+ memoryKey: nonEmptyString(params.memoryKey) ?? DEFAULT_MEMORY_KEY,
490
+ scope: normalizeScope(params.scope),
491
+ clearStore: isTrueFlag(params.clearStore)
492
+ };
493
+ }
494
+ /**
495
+ * Returns the store target when running `node` will clear all documents in an
496
+ * In-memory Vector Store (`operation === "clear"`, or `operation === "insert"`
497
+ * with `clearStore` turned on). Returns `null` for every other node or mode.
498
+ */
499
+ function vectorStoreClearTarget(node) {
500
+ if (!node) return null;
501
+ if (nodeTypeOf(node) !== "internal:vector-store-memory") return null;
502
+ const config = readVectorStoreMemoryConfig(node.data);
503
+ const op = config.operation.toLowerCase();
504
+ if (op !== "clear" && !(op === "insert" && config.clearStore)) return null;
505
+ const data = asRecord(node.data);
506
+ const nodeData = asRecord(data?.nodeData);
507
+ const nodeLabel = nonEmptyString(data?.label) ?? nonEmptyString(nodeData?.name) ?? "In-memory Vector Store";
508
+ return {
509
+ nodeId: node.id,
510
+ nodeLabel,
511
+ operation: op === "clear" ? "clear" : "insert",
512
+ memoryKey: config.memoryKey,
513
+ scope: config.scope
514
+ };
515
+ }
516
+ /** Stable store cache key for a `(scope, memoryKey)` collection. */
517
+ function vectorStoreCollectionKey(scope, memoryKey) {
518
+ return `${scope}:${memoryKey}`;
519
+ }
520
+ function parseTimestampMs(iso) {
521
+ if (!iso) return null;
522
+ const parsed = Date.parse(iso);
523
+ return Number.isNaN(parsed) ? null : parsed;
524
+ }
525
+ function unwrapOutputRecord(output) {
526
+ if (Array.isArray(output)) return output.length === 1 ? asRecord(output[0]) : void 0;
527
+ return asRecord(output);
528
+ }
529
+ function previewFromCollectionStats(record, sourceOperation, observedAt, fallbackMemoryKey, fallbackScope) {
530
+ const count = nonNegativeInt(record.count);
531
+ if (count === null) return null;
532
+ const memoryKey = nonEmptyString(record.memoryKey) ?? fallbackMemoryKey ?? null;
533
+ if (!memoryKey) return null;
534
+ const scope = record.scope ? normalizeScope(record.scope) : fallbackScope ?? DEFAULT_SCOPE;
535
+ const dimension = positiveNumber(record.dimension);
536
+ const embeddingModel = nonEmptyString(record.embeddingModel) ?? null;
537
+ const ttlSeconds = positiveNumber(record.ttlSeconds);
538
+ const rawExpiresAt = nonEmptyString(record.expiresAt);
539
+ const expiresAt = rawExpiresAt && parseTimestampMs(rawExpiresAt) !== null ? rawExpiresAt : null;
540
+ return {
541
+ memoryKey,
542
+ scope,
543
+ count,
544
+ dimension: dimension !== null ? Math.floor(dimension) : null,
545
+ embeddingModel,
546
+ ttlSeconds,
547
+ expiresAt,
548
+ sourceOperation,
549
+ observedAt
550
+ };
551
+ }
552
+ /**
553
+ * Extracts zero or more store stats snapshots from a completed
554
+ * `internal:vector-store-memory` run output.
555
+ *
556
+ * Supported outputs:
557
+ * - `stats`: full snapshot (`count`, `dimension`, `embeddingModel`, `expiresAt`, `ttlSeconds`)
558
+ * - `insert` / `upsert`: post-write snapshot (`total`, `dimension`, `embeddingModel`, `ttlSeconds`)
559
+ * - `clear`: empty store (`count: 0`)
560
+ * - `listCollections`: one snapshot per collection entry
561
+ *
562
+ * `search`, `get` and `delete` outputs are ignored because their `count` is
563
+ * the hit/batch count, not the total documents in the store.
564
+ */
565
+ function extractVectorStoreStatsFromOutput(output, options) {
566
+ const record = unwrapOutputRecord(output);
567
+ if (!record) return [];
568
+ const observedAt = parseTimestampMs(options?.observedAtIso) ?? options?.nowMs ?? Date.now();
569
+ const op = nonEmptyString(record.operation)?.toLowerCase();
570
+ if (op === "listcollections") {
571
+ const collections = Array.isArray(record.collections) ? record.collections : [];
572
+ const results = [];
573
+ for (const item of collections) {
574
+ const entry = asRecord(item);
575
+ if (!entry) continue;
576
+ const preview = previewFromCollectionStats(entry, "listCollections", observedAt);
577
+ if (preview) results.push(preview);
578
+ }
579
+ return results;
580
+ }
581
+ if (op === "stats") {
582
+ const preview = previewFromCollectionStats(record, "stats", observedAt, options?.fallbackMemoryKey, options?.fallbackScope);
583
+ return preview ? [preview] : [];
584
+ }
585
+ if (op === "insert" || op === "upsert") {
586
+ const total = nonNegativeInt(record.total);
587
+ if (total === null) return [];
588
+ const memoryKey = nonEmptyString(record.memoryKey) ?? options?.fallbackMemoryKey ?? null;
589
+ if (!memoryKey) return [];
590
+ const scope = record.scope ? normalizeScope(record.scope) : options?.fallbackScope ?? DEFAULT_SCOPE;
591
+ const dimension = positiveNumber(record.dimension);
592
+ const embeddingModel = nonEmptyString(record.embeddingModel) ?? null;
593
+ const ttlSeconds = positiveNumber(record.ttlSeconds);
594
+ const rawExpiresAt = nonEmptyString(record.expiresAt);
595
+ const observedMsFromLog = parseTimestampMs(options?.observedAtIso);
596
+ const expiresAt = rawExpiresAt && parseTimestampMs(rawExpiresAt) !== null ? rawExpiresAt : ttlSeconds !== null && observedMsFromLog !== null ? new Date(observedMsFromLog + ttlSeconds * 1e3).toISOString() : null;
597
+ return [{
598
+ memoryKey,
599
+ scope,
600
+ count: total,
601
+ dimension: dimension !== null ? Math.floor(dimension) : null,
602
+ embeddingModel,
603
+ ttlSeconds,
604
+ expiresAt,
605
+ sourceOperation: op,
606
+ observedAt
607
+ }];
608
+ }
609
+ if (op === "clear") {
610
+ const memoryKey = nonEmptyString(record.memoryKey) ?? options?.fallbackMemoryKey ?? null;
611
+ if (!memoryKey) return [];
612
+ return [{
613
+ memoryKey,
614
+ scope: record.scope ? normalizeScope(record.scope) : options?.fallbackScope ?? DEFAULT_SCOPE,
615
+ count: 0,
616
+ dimension: null,
617
+ embeddingModel: null,
618
+ ttlSeconds: null,
619
+ expiresAt: null,
620
+ sourceOperation: "clear",
621
+ observedAt
622
+ }];
623
+ }
624
+ if (op === "search" || op === "get" || op === "delete") return [];
625
+ if (!op && !Array.isArray(record.documents) && !Array.isArray(record.collections) && ("dimension" in record || "embeddingModel" in record || "expiresAt" in record || "ttlSeconds" in record)) {
626
+ const preview = previewFromCollectionStats(record, "stats", observedAt, options?.fallbackMemoryKey, options?.fallbackScope);
627
+ return preview ? [preview] : [];
628
+ }
629
+ return [];
630
+ }
631
+ /**
632
+ * Picks the stats preview for a node from the store cache or its pinned output,
633
+ * matching the node's configured `(scope, memoryKey)`. Never returns stats from
634
+ * a different store.
635
+ */
636
+ function selectVectorStoreStatsForNode(config, cachedStats, pinnedOutput) {
637
+ if (config.operation.toLowerCase() === "listcollections") return null;
638
+ const key = vectorStoreCollectionKey(config.scope, config.memoryKey);
639
+ const cached = cachedStats[key];
640
+ if (cached) return cached;
641
+ if (pinnedOutput !== void 0 && pinnedOutput !== null) {
642
+ const match = extractVectorStoreStatsFromOutput(pinnedOutput, {
643
+ fallbackMemoryKey: config.memoryKey,
644
+ fallbackScope: config.scope
645
+ }).find((entry) => vectorStoreCollectionKey(entry.scope, entry.memoryKey) === key);
646
+ if (match) return match;
647
+ }
648
+ return null;
649
+ }
650
+ const MINUTE_MS = 6e4;
651
+ const HOUR_MS = 60 * MINUTE_MS;
652
+ const DAY_MS = 24 * HOUR_MS;
653
+ function formatCompactDuration(ms) {
654
+ if (ms < MINUTE_MS) return "<1m";
655
+ if (ms < HOUR_MS) return `${Math.floor(ms / MINUTE_MS)}m`;
656
+ if (ms < DAY_MS) {
657
+ const hours = Math.floor(ms / HOUR_MS);
658
+ const minutes = Math.floor(ms % HOUR_MS / MINUTE_MS);
659
+ return hours < 6 && minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
660
+ }
661
+ const days = Math.floor(ms / DAY_MS);
662
+ const hours = Math.floor(ms % DAY_MS / HOUR_MS);
663
+ return hours > 0 ? `${days}d ${hours}h` : `${days}d`;
664
+ }
665
+ /**
666
+ * Formats a store's expiry for the node card: remaining time until `expiresAt`
667
+ * (or "Expired"), falling back to its configured `ttlSeconds`, or a run-scope
668
+ * note when the store is cleared at run end.
669
+ */
670
+ function formatVectorStoreExpiry(stats, tr, nowMs = Date.now(), locale = pageLocale()) {
671
+ if (stats.expiresAt) {
672
+ const expiresAtMs = parseTimestampMs(stats.expiresAt);
673
+ if (expiresAtMs !== null) {
674
+ const title = formatExactTime(stats.expiresAt, locale);
675
+ const remainingMs = expiresAtMs - nowMs;
676
+ if (remainingMs <= 0) return {
677
+ text: tr("fluidgrids.builder.vectorStoreMemory.stats.expired", "Expired"),
678
+ title,
679
+ expired: true
680
+ };
681
+ return {
682
+ text: tr("fluidgrids.builder.vectorStoreMemory.stats.expiresIn", "Expires in {{duration}}", { duration: formatCompactDuration(remainingMs) }),
683
+ title,
684
+ expired: false
685
+ };
686
+ }
687
+ }
688
+ if (stats.ttlSeconds !== null && stats.ttlSeconds > 0) return {
689
+ text: tr("fluidgrids.builder.vectorStoreMemory.stats.ttl", "TTL {{duration}}", { duration: formatCompactDuration(stats.ttlSeconds * 1e3) }),
690
+ expired: false
691
+ };
692
+ if (stats.scope === "run") return {
693
+ text: tr("fluidgrids.builder.vectorStoreMemory.stats.runScopeExpiry", "Cleared after run"),
694
+ expired: false
695
+ };
696
+ return null;
697
+ }
698
+ /** Human-readable scope label that also names the canonical scope value. */
699
+ function vectorStoreScopeLabel(scope, tr) {
700
+ switch (scope) {
701
+ case "workflow": return tr("fluidgrids.builder.vectorStoreMemory.scope.workflow", "workflow (every run of this workflow)");
702
+ case "run": return tr("fluidgrids.builder.vectorStoreMemory.scope.run", "run (this run only)");
703
+ case "workspace": return tr("fluidgrids.builder.vectorStoreMemory.scope.workspace", "workspace (every workflow in this workspace)");
704
+ }
705
+ }
706
+ /** Compact scope badge label for the node card. */
707
+ function vectorStoreScopeShortLabel(scope, tr) {
708
+ switch (scope) {
709
+ case "workflow": return tr("fluidgrids.builder.vectorStoreMemory.scopeShort.workflow", "workflow");
710
+ case "run": return tr("fluidgrids.builder.vectorStoreMemory.scopeShort.run", "run");
711
+ case "workspace": return tr("fluidgrids.builder.vectorStoreMemory.scopeShort.workspace", "workspace");
712
+ }
713
+ }
714
+ /** Human-readable operation title matching the backend manifest choices. */
715
+ function vectorStoreOperationLabel(operation, tr) {
716
+ switch (operation.toLowerCase()) {
717
+ case "insert": return tr("fluidgrids.builder.vectorStoreMemory.operation.insert", "Insert documents");
718
+ case "upsert": return tr("fluidgrids.builder.vectorStoreMemory.operation.upsert", "Upsert documents");
719
+ case "search": return tr("fluidgrids.builder.vectorStoreMemory.operation.search", "Search");
720
+ case "get": return tr("fluidgrids.builder.vectorStoreMemory.operation.get", "Get documents");
721
+ case "delete": return tr("fluidgrids.builder.vectorStoreMemory.operation.delete", "Delete documents");
722
+ case "clear": return tr("fluidgrids.builder.vectorStoreMemory.operation.clear", "Clear the store");
723
+ case "stats": return tr("fluidgrids.builder.vectorStoreMemory.operation.stats", "Store statistics");
724
+ case "listcollections": return tr("fluidgrids.builder.vectorStoreMemory.operation.listCollections", "List stores");
725
+ default: return operation;
726
+ }
727
+ }
728
+
729
+ // src/builder/stores/vector-store-clear-confirm-store.ts
730
+ /**
731
+ * Builder-wide confirmation state for destructive In-memory Vector Store step
732
+ * runs (BOFF-16130).
733
+ *
734
+ * `useNodeExecution.executeStep` and `useNodeExecution.executeFromNode` await
735
+ * `confirmVectorStoreClear(target)` before starting a TEST run that clears a
736
+ * store (`operation === "clear"`, or `operation === "insert"` with Clear Store
737
+ * on). `VectorStoreClearConfirmController` mounts once in `FlowBuilder` and
738
+ * renders the shared `ConfirmActionDialog`, so every run button in the builder
739
+ * (card hover button, context menu, quick-config, NDV, sidebar editor) goes
740
+ * through one guard.
741
+ */
742
+ const useVectorStoreClearConfirmStore = create()(() => ({ pending: null }));
743
+ /**
744
+ * Opens the confirmation dialog for `target` and resolves `true` when the
745
+ * person confirms or `false` when they cancel (or the prompt is dismissed or
746
+ * superseded).
747
+ */
748
+ function confirmVectorStoreClear(target) {
749
+ const previous = useVectorStoreClearConfirmStore.getState().pending;
750
+ if (previous) {
751
+ useVectorStoreClearConfirmStore.setState({ pending: null });
752
+ previous.resolve(false);
753
+ }
754
+ return new Promise((resolve) => {
755
+ useVectorStoreClearConfirmStore.setState({ pending: {
756
+ target,
757
+ resolve
758
+ } });
759
+ });
760
+ }
761
+ /** Completes the active confirmation dialog, if one is open. */
762
+ function resolveVectorStoreClear(confirmed) {
763
+ const current = useVectorStoreClearConfirmStore.getState().pending;
764
+ if (!current) return;
765
+ useVectorStoreClearConfirmStore.setState({ pending: null });
766
+ current.resolve(confirmed);
767
+ }
768
+ /** Dismisses any pending confirmation dialog as cancelled (e.g. on unmount/reset). */
769
+ function resetVectorStoreClearConfirm() {
770
+ resolveVectorStoreClear(false);
771
+ }
772
+
773
+ // src/builder/stores/flow-store.ts
774
+ function mergeVectorStoreStats(current, logs, nodes) {
775
+ let next = null;
776
+ for (const log of logs) {
777
+ if (log.status !== "completed" || !log.output) continue;
778
+ const node = nodes.find((entry) => entry.id === log.nodeId);
779
+ if (!isVectorStoreMemoryNodeType(log.nodeType) && !isVectorStoreMemoryNodeType(node?.type)) continue;
780
+ const fallback = node ? readVectorStoreMemoryConfig(node.data) : void 0;
781
+ const previews = extractVectorStoreStatsFromOutput(log.output, {
782
+ fallbackMemoryKey: fallback?.memoryKey,
783
+ fallbackScope: fallback?.scope,
784
+ observedAtIso: log.endTime ?? log.startTime
785
+ });
786
+ for (const preview of previews) {
787
+ const key = vectorStoreCollectionKey(preview.scope, preview.memoryKey);
788
+ next ??= { ...current };
789
+ next[key] = preview;
790
+ }
791
+ }
792
+ return next ?? current;
793
+ }
794
+ /** The co-edited lists that live in the canvas's one node list (BOFF-15401). */
795
+ const CANVAS_NODE_LISTS = ["nodes", "stickyNotes"];
796
+ /** Bounds how far back undo can go — generous for an editing session without
797
+ * letting the stacks grow unbounded on a long-lived tab. */
798
+ const HISTORY_LIMIT = 100;
799
+ /** Canvas offset applied to duplicated/pasted nodes so clones never land
800
+ * exactly on top of their source (n8n/Figma-style paste offset). */
801
+ const CLONE_OFFSET = 48;
802
+ /**
803
+ * Deep-clone a value for history snapshots / node-and-edge duplication.
804
+ * `structuredClone` is preferred (fast, handles Dates/Maps/etc.), with a
805
+ * JSON round-trip fallback for the rare manifest blob that carries something
806
+ * structuredClone can't handle (e.g. a stray function reference) — dropping
807
+ * that field is safer than throwing and losing the whole undo/copy action.
808
+ */
809
+ function cloneValue(value) {
810
+ try {
811
+ return structuredClone(value);
812
+ } catch {
813
+ return JSON.parse(JSON.stringify(value));
814
+ }
815
+ }
816
+ /**
817
+ * The open editors (NDV, quick panel, side panel) record the type of the node
818
+ * they edit. When a node keeps its id but changes type (Convert to Use
819
+ * Browser, RPA plan P1-11b, and its undo and redo), this returns those
820
+ * records with the type of the node now on the canvas; it returns only the
821
+ * records that change.
822
+ */
823
+ function editorsFollowNodes(workflow, nodes) {
824
+ const typeOf = (id) => {
825
+ if (id === void 0) return void 0;
826
+ return nodes.find((node) => node.id === id)?.type || void 0;
827
+ };
828
+ const patch = {};
829
+ const { ndv, quickConfig, sidebar } = workflow;
830
+ const ndvType = typeOf(ndv?.nodeId);
831
+ if (ndv && ndvType && ndvType !== ndv.type) patch.ndv = {
832
+ ...ndv,
833
+ type: ndvType
834
+ };
835
+ const quickType = typeOf(quickConfig?.nodeId);
836
+ if (quickConfig && quickType && quickType !== quickConfig.type) patch.quickConfig = {
837
+ ...quickConfig,
838
+ type: quickType
839
+ };
840
+ const selected = sidebar.panels.nodeProperties.selectedNode;
841
+ const selectedType = typeOf(selected?.id);
842
+ if (selected && selectedType && selectedType !== selected.type) patch.sidebar = {
843
+ ...sidebar,
844
+ panels: {
845
+ ...sidebar.panels,
846
+ nodeProperties: {
847
+ ...sidebar.panels.nodeProperties,
848
+ selectedNode: {
849
+ ...selected,
850
+ type: selectedType
851
+ }
852
+ }
853
+ }
854
+ };
855
+ return patch;
856
+ }
857
+ const TAGS = [
858
+ {
859
+ value: "marketing",
860
+ label: "Marketing",
861
+ color: "var(--color-chart-5)"
862
+ },
863
+ {
864
+ value: "support",
865
+ label: "Support",
866
+ color: "var(--color-chart-5)"
867
+ },
868
+ {
869
+ value: "lead",
870
+ label: "Lead",
871
+ color: "var(--color-chart-4)"
872
+ },
873
+ {
874
+ value: "new",
875
+ label: "New",
876
+ color: "var(--color-chart-7)"
877
+ }
878
+ ];
879
+ /**
880
+ * Pristine execution state. The `execution` slice is global (one run at a
881
+ * time), so it MUST be reset whenever a different workflow is loaded —
882
+ * otherwise the previous workflow's run logs leak into the next workflow's
883
+ * Logs panel. Shared by the store initializer and `resetWorkflow`.
884
+ */
885
+ const INITIAL_EXECUTION = {
886
+ isExecuting: false,
887
+ executingNodeId: null,
888
+ currentRunId: null,
889
+ sourceRun: null,
890
+ stepPlan: null,
891
+ logs: [],
892
+ selectedLogId: null,
893
+ logFocus: 0,
894
+ panelExpanded: false,
895
+ nodeStatuses: {},
896
+ nodeItemCounts: {},
897
+ vectorStoreStats: {},
898
+ followRequest: null,
899
+ liveUpdates: "off"
900
+ };
901
+ const INITIAL_HISTORY = {
902
+ past: [],
903
+ future: []
904
+ };
905
+ const useFlowStore = create()((set, get) => {
906
+ let lastCheckpointKind = null;
907
+ let lastCheckpointAt = 0;
908
+ /**
909
+ * The canvas as it was when the current drag started (BOFF-15533). React
910
+ * Flow applies every drag frame as it goes, so by the drop the node already
911
+ * sits where it ends: the undo step must be taken at the start and kept
912
+ * only if the drag moved something.
913
+ */
914
+ let dragStart = null;
915
+ /** The current drag's step was already recorded (see pushCheckpoint). */
916
+ let dragRecorded = false;
917
+ /**
918
+ * Record an undo point BEFORE a mutation is applied.
919
+ *
920
+ * `coalesce: true` merges this call into the immediately preceding one when
921
+ * they share the same `kind` and land within the coalescing window — used
922
+ * for bursty writes (keystrokes in one field, a drag in progress) so undo
923
+ * has one step per logical edit, not one per change event. Structural
924
+ * actions (delete, connect, duplicate, disable, rename, …) always pass
925
+ * `coalesce: false` so each is its own undo step even if done quickly in
926
+ * succession.
927
+ */
928
+ function pushCheckpoint(kind, coalesce) {
929
+ if (dragStart) {
930
+ const start = dragStart;
931
+ dragStart = null;
932
+ dragRecorded = true;
933
+ set((s) => ({ history: {
934
+ past: [...s.history.past, start].slice(-100),
935
+ future: []
936
+ } }));
937
+ }
938
+ const now = Date.now();
939
+ if (!(coalesce && kind === lastCheckpointKind && now - lastCheckpointAt < 800)) {
940
+ const state = get();
941
+ const snapshot = {
942
+ nodes: cloneValue(state.workflow.nodes),
943
+ edges: cloneValue(state.workflow.edges)
944
+ };
945
+ set((s) => ({ history: {
946
+ past: [...s.history.past, snapshot].slice(-100),
947
+ future: []
948
+ } }));
949
+ } else if (get().history.future.length > 0) set((s) => ({ history: {
950
+ ...s.history,
951
+ future: []
952
+ } }));
953
+ lastCheckpointKind = kind;
954
+ lastCheckpointAt = now;
955
+ noteEdit();
956
+ }
957
+ /** Record that the person changed the workflow (see `editRevision`). */
958
+ function noteEdit() {
959
+ set((s) => ({ editRevision: s.editRevision + 1 }));
960
+ }
961
+ /**
962
+ * Deleting a node makes React Flow report TWO removals back to back: the
963
+ * node through `onNodesChange`, then every connection attached to it through
964
+ * `onEdgesChange`. They are one user action, so the second must not push its
965
+ * own checkpoint — otherwise one delete costs two Undo presses, and the first
966
+ * press only brings back the connection, which cannot draw without its node
967
+ * and so looks like Undo did nothing.
968
+ */
969
+ const REMOVAL_KINDS = /* @__PURE__ */ new Set(["nodes:remove", "edges:remove"]);
970
+ const SAME_ACTION_WINDOW_MS = 150;
971
+ function joinsPrecedingRemoval(kind) {
972
+ return lastCheckpointKind !== null && lastCheckpointKind !== kind && REMOVAL_KINDS.has(kind) && REMOVAL_KINDS.has(lastCheckpointKind) && Date.now() - lastCheckpointAt < SAME_ACTION_WINDOW_MS;
973
+ }
974
+ /** Reset coalescing so the next edit always starts a fresh checkpoint. */
975
+ function resetCoalescing() {
976
+ lastCheckpointKind = null;
977
+ lastCheckpointAt = 0;
978
+ dragStart = null;
979
+ dragRecorded = false;
980
+ }
981
+ return {
982
+ tags: TAGS,
983
+ history: { ...INITIAL_HISTORY },
984
+ editRevision: 0,
985
+ loadGeneration: 0,
986
+ workflow: {
987
+ id: nanoid(),
988
+ workflowKey: "",
989
+ name: "",
990
+ version: "",
991
+ alias: "",
992
+ edges: [],
993
+ nodes: [],
994
+ ndv: null,
995
+ quickConfig: null,
996
+ pendingConnection: null,
997
+ renamingNodeId: null,
998
+ sidebar: {
999
+ active: "none",
1000
+ panels: { nodeProperties: { selectedNode: null } }
1001
+ }
1002
+ },
1003
+ execution: { ...INITIAL_EXECUTION },
1004
+ actions: {
1005
+ saveWorkflow: () => {
1006
+ const { workflow } = get();
1007
+ const { id, name, version, alias, dbId, status, nodes, edges } = workflow;
1008
+ set({ workflow });
1009
+ return {
1010
+ id,
1011
+ name,
1012
+ version,
1013
+ alias,
1014
+ dbId,
1015
+ status,
1016
+ nodes,
1017
+ edges
1018
+ };
1019
+ },
1020
+ setWorkflow: (workflow) => {
1021
+ const current = get().workflow;
1022
+ if (workflow.name !== void 0 && workflow.name !== current.name || workflow.alias !== void 0 && workflow.alias !== current.alias) noteEdit();
1023
+ const nodes = workflow.nodes?.map((node) => node.data === void 0 || node.data === null ? {
1024
+ ...node,
1025
+ data: {}
1026
+ } : node);
1027
+ const sidebar = workflow.sidebar ? sidebarOnLoad(workflow.sidebar, sidebarCoversCanvas()) : void 0;
1028
+ set((state) => ({ workflow: {
1029
+ ...state.workflow,
1030
+ ...workflow,
1031
+ ...nodes ? { nodes } : {},
1032
+ ...sidebar ? { sidebar } : {}
1033
+ } }));
1034
+ },
1035
+ resetWorkflow: () => {
1036
+ resetCoalescing();
1037
+ resetVectorStoreClearConfirm();
1038
+ set((s) => ({
1039
+ loadGeneration: s.loadGeneration + 1,
1040
+ workflow: {
1041
+ id: nanoid(),
1042
+ workflowKey: "",
1043
+ name: "",
1044
+ version: "",
1045
+ alias: "",
1046
+ description: void 0,
1047
+ dbId: void 0,
1048
+ status: void 0,
1049
+ codeBuildId: void 0,
1050
+ edges: [],
1051
+ nodes: [],
1052
+ ndv: null,
1053
+ quickConfig: null,
1054
+ pendingConnection: null,
1055
+ renamingNodeId: null,
1056
+ sidebar: {
1057
+ active: "none",
1058
+ panels: { nodeProperties: { selectedNode: null } }
1059
+ }
1060
+ },
1061
+ execution: { ...INITIAL_EXECUTION },
1062
+ history: { ...INITIAL_HISTORY }
1063
+ }));
1064
+ },
1065
+ collab: {
1066
+ applyRemote: (changes) => {
1067
+ if (changes.length === 0) return;
1068
+ set((s) => {
1069
+ let { name, alias } = s.workflow;
1070
+ for (const change of changes) {
1071
+ if (change.op !== "field") continue;
1072
+ if (change.name === "name") name = change.value;
1073
+ else alias = change.value;
1074
+ }
1075
+ const rebase = (snapshot) => ({
1076
+ nodes: applyToItems(snapshot.nodes, changes, CANVAS_NODE_LISTS),
1077
+ edges: applyToItems(snapshot.edges, changes, ["edges"])
1078
+ });
1079
+ return {
1080
+ workflow: {
1081
+ ...s.workflow,
1082
+ name,
1083
+ alias,
1084
+ nodes: applyToItems(s.workflow.nodes, changes, CANVAS_NODE_LISTS),
1085
+ edges: applyToItems(s.workflow.edges, changes, ["edges"])
1086
+ },
1087
+ history: {
1088
+ past: s.history.past.map(rebase),
1089
+ future: s.history.future.map(rebase)
1090
+ }
1091
+ };
1092
+ });
1093
+ if (dragStart) dragStart = {
1094
+ nodes: applyToItems(dragStart.nodes, changes, CANVAS_NODE_LISTS),
1095
+ edges: applyToItems(dragStart.edges, changes, ["edges"])
1096
+ };
1097
+ },
1098
+ replaceCanvas: (shape) => {
1099
+ resetCoalescing();
1100
+ set((s) => ({
1101
+ workflow: {
1102
+ ...s.workflow,
1103
+ name: shape.name,
1104
+ alias: shape.alias,
1105
+ ...shape.description !== void 0 ? { description: shape.description } : {},
1106
+ nodes: withLocalState(mergeStickyNotes({
1107
+ nodes: [...shape.nodes],
1108
+ stickyNotes: [...shape.stickyNotes]
1109
+ }), s.workflow.nodes),
1110
+ edges: withLocalState(shape.edges, s.workflow.edges)
1111
+ },
1112
+ history: { ...INITIAL_HISTORY }
1113
+ }));
1114
+ }
1115
+ },
1116
+ history: {
1117
+ undo: () => {
1118
+ const { past, future } = get().history;
1119
+ const previous = past[past.length - 1];
1120
+ if (!previous) return;
1121
+ const { nodes, edges } = get().workflow;
1122
+ const current = {
1123
+ nodes: cloneValue(nodes),
1124
+ edges: cloneValue(edges)
1125
+ };
1126
+ resetCoalescing();
1127
+ noteEdit();
1128
+ set((s) => ({
1129
+ workflow: {
1130
+ ...s.workflow,
1131
+ nodes: previous.nodes,
1132
+ edges: previous.edges,
1133
+ ...editorsFollowNodes(s.workflow, previous.nodes)
1134
+ },
1135
+ history: {
1136
+ past: past.slice(0, -1),
1137
+ future: [current, ...future].slice(0, HISTORY_LIMIT)
1138
+ }
1139
+ }));
1140
+ },
1141
+ redo: () => {
1142
+ const { past, future } = get().history;
1143
+ const next = future[0];
1144
+ if (!next) return;
1145
+ const { nodes, edges } = get().workflow;
1146
+ const current = {
1147
+ nodes: cloneValue(nodes),
1148
+ edges: cloneValue(edges)
1149
+ };
1150
+ resetCoalescing();
1151
+ noteEdit();
1152
+ set((s) => ({
1153
+ workflow: {
1154
+ ...s.workflow,
1155
+ nodes: next.nodes,
1156
+ edges: next.edges,
1157
+ ...editorsFollowNodes(s.workflow, next.nodes)
1158
+ },
1159
+ history: {
1160
+ past: [...past, current].slice(-100),
1161
+ future: future.slice(1)
1162
+ }
1163
+ }));
1164
+ },
1165
+ clear: () => {
1166
+ resetCoalescing();
1167
+ set({ history: { ...INITIAL_HISTORY } });
1168
+ }
1169
+ },
1170
+ ndv: {
1171
+ open: (node) => set((state) => ({ workflow: {
1172
+ ...state.workflow,
1173
+ ndv: node,
1174
+ quickConfig: null
1175
+ } })),
1176
+ close: () => set((state) => ({ workflow: {
1177
+ ...state.workflow,
1178
+ ndv: null
1179
+ } }))
1180
+ },
1181
+ quickConfig: {
1182
+ open: (node) => set((state) => ({ workflow: {
1183
+ ...state.workflow,
1184
+ quickConfig: node
1185
+ } })),
1186
+ close: () => set((state) => ({ workflow: {
1187
+ ...state.workflow,
1188
+ quickConfig: null
1189
+ } }))
1190
+ },
1191
+ pendingConnection: {
1192
+ start: (connection) => set((state) => ({ workflow: {
1193
+ ...state.workflow,
1194
+ pendingConnection: connection,
1195
+ sidebar: {
1196
+ ...state.workflow.sidebar,
1197
+ active: "store-browse"
1198
+ }
1199
+ } })),
1200
+ clear: () => set((state) => ({ workflow: {
1201
+ ...state.workflow,
1202
+ pendingConnection: null
1203
+ } }))
1204
+ },
1205
+ sidebar: {
1206
+ setActivePanel: (panel) => set((state) => ({ workflow: {
1207
+ ...state.workflow,
1208
+ sidebar: {
1209
+ ...state.workflow.sidebar,
1210
+ active: panel
1211
+ },
1212
+ ...panel !== "store-browse" ? { pendingConnection: null } : {}
1213
+ } })),
1214
+ showNodePropertiesOf: (node) => {
1215
+ set((state) => ({ workflow: {
1216
+ ...state.workflow,
1217
+ pendingConnection: null,
1218
+ sidebar: {
1219
+ ...state.workflow.sidebar,
1220
+ active: "node-properties",
1221
+ panels: {
1222
+ ...state.workflow.sidebar.panels,
1223
+ nodeProperties: {
1224
+ ...state.workflow.sidebar.panels.nodeProperties,
1225
+ selectedNode: node
1226
+ }
1227
+ }
1228
+ }
1229
+ } }));
1230
+ },
1231
+ panels: {
1232
+ nodeProperties: { setSelectedNode: (node) => set((state) => ({ workflow: {
1233
+ ...state.workflow,
1234
+ sidebar: {
1235
+ ...state.workflow.sidebar,
1236
+ panels: {
1237
+ ...state.workflow.sidebar.panels,
1238
+ nodeProperties: {
1239
+ ...state.workflow.sidebar.panels.nodeProperties,
1240
+ selectedNode: node
1241
+ }
1242
+ }
1243
+ }
1244
+ } })) },
1245
+ tags: {
1246
+ setTags: (tags) => set({ tags }),
1247
+ createTag: (tag) => set((state) => ({ tags: [...state.tags, tag] })),
1248
+ updateTag: (tag, newTag) => set((state) => ({ tags: state.tags.map((f) => f.value === tag.value ? newTag : f) })),
1249
+ deleteTag: (tag) => set((state) => ({ tags: state.tags.filter((f) => f.value !== tag.value) }))
1250
+ }
1251
+ }
1252
+ },
1253
+ nodes: {
1254
+ onNodesChange: (changes) => {
1255
+ const removedIds = new Set(changes.filter((c) => c.type === "remove").map((c) => c.id));
1256
+ const addedCount = changes.filter((c) => c.type === "add").length;
1257
+ if (removedIds.size > 0) {
1258
+ if (get().workflow.nodes.some((n) => removedIds.has(n.id)) && !joinsPrecedingRemoval("nodes:remove")) pushCheckpoint("nodes:remove", false);
1259
+ } else if (addedCount > 0) pushCheckpoint("nodes:add", false);
1260
+ else {
1261
+ if (changes.some((c) => c.type === "position" && c.dragging === true && !get().workflow.nodes.find((n) => n.id === c.id)?.dragging)) {
1262
+ noteEdit();
1263
+ if (!dragStart) {
1264
+ const { nodes, edges } = get().workflow;
1265
+ dragStart = {
1266
+ nodes: cloneValue(nodes),
1267
+ edges: cloneValue(edges)
1268
+ };
1269
+ }
1270
+ }
1271
+ const finishedDragIds = changes.filter((c) => c.type === "position" && c.dragging === false);
1272
+ if (finishedDragIds.length > 0) {
1273
+ const start = dragStart;
1274
+ const recorded = dragRecorded;
1275
+ dragStart = null;
1276
+ dragRecorded = false;
1277
+ const endOf = (c) => c.position ?? get().workflow.nodes.find((n) => n.id === c.id)?.position;
1278
+ const moved = finishedDragIds.some((c) => {
1279
+ const end = endOf(c);
1280
+ const from = (start ?? get().workflow).nodes.find((n) => n.id === c.id)?.position;
1281
+ return !!end && !!from && (from.x !== end.x || from.y !== end.y);
1282
+ });
1283
+ if (moved && start) {
1284
+ set((s) => ({ history: {
1285
+ past: [...s.history.past, start].slice(-100),
1286
+ future: []
1287
+ } }));
1288
+ lastCheckpointKind = "nodes:move";
1289
+ lastCheckpointAt = Date.now();
1290
+ } else if (moved && !recorded) pushCheckpoint("nodes:move", false);
1291
+ }
1292
+ }
1293
+ set((state) => produce(state, (draft) => {
1294
+ const updatedNodes = applyNodeChanges(changes, draft.workflow.nodes);
1295
+ draft.workflow.nodes = updatedNodes;
1296
+ }));
1297
+ },
1298
+ setNodes: (nodes, opts) => {
1299
+ if (!opts?.skipHistory) pushCheckpoint(opts?.historyKind ?? "nodes:set", !!opts?.historyKind);
1300
+ set({ workflow: {
1301
+ ...get().workflow,
1302
+ nodes
1303
+ } });
1304
+ },
1305
+ deleteNode: (node) => {
1306
+ if (get().workflow.nodes.some((n) => n.id === node.id)) pushCheckpoint("nodes:delete", false);
1307
+ set((state) => ({ workflow: {
1308
+ ...state.workflow,
1309
+ nodes: state.workflow.nodes.filter((n) => n.id !== node.id),
1310
+ ...state.workflow.quickConfig?.nodeId === node.id ? { quickConfig: null } : {},
1311
+ ...state.workflow.pendingConnection?.nodeId === node.id ? { pendingConnection: null } : {}
1312
+ } }));
1313
+ },
1314
+ deleteNodes: (nodes) => {
1315
+ const ids = new Set(nodes.map((n) => n.id));
1316
+ if (ids.size === 0) return;
1317
+ if (get().workflow.nodes.some((n) => ids.has(n.id))) pushCheckpoint("nodes:delete", false);
1318
+ set((state) => ({ workflow: {
1319
+ ...state.workflow,
1320
+ nodes: state.workflow.nodes.filter((n) => !ids.has(n.id)),
1321
+ edges: state.workflow.edges.filter((e) => !ids.has(e.source) && !ids.has(e.target)),
1322
+ ...state.workflow.quickConfig && ids.has(state.workflow.quickConfig.nodeId) ? { quickConfig: null } : {},
1323
+ ...state.workflow.pendingConnection && ids.has(state.workflow.pendingConnection.nodeId) ? { pendingConnection: null } : {}
1324
+ } }));
1325
+ },
1326
+ duplicateNodes: (nodeIds) => {
1327
+ const { nodes, edges } = get().workflow;
1328
+ const idSet = new Set(nodeIds);
1329
+ const selected = nodes.filter((n) => idSet.has(n.id));
1330
+ if (selected.length === 0) return;
1331
+ pushCheckpoint("nodes:duplicate", false);
1332
+ const idMap = /* @__PURE__ */ new Map();
1333
+ const clones = selected.map((n) => {
1334
+ const newId = nanoid();
1335
+ idMap.set(n.id, newId);
1336
+ const cloned = cloneValue(n);
1337
+ return {
1338
+ ...cloned,
1339
+ id: newId,
1340
+ position: {
1341
+ x: cloned.position.x + CLONE_OFFSET,
1342
+ y: cloned.position.y + CLONE_OFFSET
1343
+ },
1344
+ selected: true
1345
+ };
1346
+ });
1347
+ const clonedEdges = edges.filter((e) => idMap.has(e.source) && idMap.has(e.target)).map((e) => {
1348
+ return {
1349
+ ...cloneValue(e),
1350
+ id: nanoid(),
1351
+ source: idMap.get(e.source),
1352
+ target: idMap.get(e.target),
1353
+ selected: false
1354
+ };
1355
+ });
1356
+ set((state) => ({ workflow: {
1357
+ ...state.workflow,
1358
+ nodes: [...state.workflow.nodes.map((n) => idSet.has(n.id) ? {
1359
+ ...n,
1360
+ selected: false
1361
+ } : n), ...clones],
1362
+ edges: [...state.workflow.edges, ...clonedEdges]
1363
+ } }));
1364
+ },
1365
+ replaceCanvas: (canvas) => {
1366
+ pushCheckpoint("canvas:replace", false);
1367
+ const ids = new Set(canvas.nodes.map((n) => n.id));
1368
+ set((state) => ({ workflow: {
1369
+ ...state.workflow,
1370
+ nodes: canvas.nodes,
1371
+ edges: canvas.edges,
1372
+ ...state.workflow.ndv && !ids.has(state.workflow.ndv.nodeId) ? { ndv: null } : {},
1373
+ ...state.workflow.quickConfig && !ids.has(state.workflow.quickConfig.nodeId) ? { quickConfig: null } : {},
1374
+ ...state.workflow.pendingConnection && !ids.has(state.workflow.pendingConnection.nodeId) ? { pendingConnection: null } : {},
1375
+ ...state.workflow.renamingNodeId && !ids.has(state.workflow.renamingNodeId) ? { renamingNodeId: null } : {}
1376
+ } }));
1377
+ },
1378
+ replaceNode: (nodeId, node) => {
1379
+ if (node.id !== nodeId || !node.type) return false;
1380
+ if (!get().workflow.nodes.some((n) => n.id === nodeId)) return false;
1381
+ pushCheckpoint("nodes:replace", false);
1382
+ set((state) => {
1383
+ const nodes = state.workflow.nodes.map((n) => n.id === nodeId ? node : n);
1384
+ return { workflow: {
1385
+ ...state.workflow,
1386
+ nodes,
1387
+ ...editorsFollowNodes(state.workflow, nodes)
1388
+ } };
1389
+ });
1390
+ return true;
1391
+ },
1392
+ pasteNodes: (payload) => {
1393
+ const pasteNodesIn = payload.nodes ?? [];
1394
+ if (pasteNodesIn.length === 0) return;
1395
+ pushCheckpoint("nodes:paste", false);
1396
+ const idMap = /* @__PURE__ */ new Map();
1397
+ const clones = pasteNodesIn.map((n) => {
1398
+ const newId = nanoid();
1399
+ idMap.set(n.id, newId);
1400
+ const cloned = cloneValue(n);
1401
+ return {
1402
+ ...cloned,
1403
+ id: newId,
1404
+ position: {
1405
+ x: (cloned.position?.x ?? 0) + CLONE_OFFSET,
1406
+ y: (cloned.position?.y ?? 0) + CLONE_OFFSET
1407
+ },
1408
+ selected: true
1409
+ };
1410
+ });
1411
+ const clonedEdges = (payload.edges ?? []).filter((e) => idMap.has(e.source) && idMap.has(e.target)).map((e) => {
1412
+ return {
1413
+ ...cloneValue(e),
1414
+ id: nanoid(),
1415
+ source: idMap.get(e.source),
1416
+ target: idMap.get(e.target),
1417
+ selected: false
1418
+ };
1419
+ });
1420
+ set((state) => ({ workflow: {
1421
+ ...state.workflow,
1422
+ nodes: [...state.workflow.nodes.map((n) => ({
1423
+ ...n,
1424
+ selected: false
1425
+ })), ...clones],
1426
+ edges: [...state.workflow.edges, ...clonedEdges]
1427
+ } }));
1428
+ },
1429
+ toggleDisabled: (nodeId) => {
1430
+ const { nodes, edges } = get().workflow;
1431
+ const updatedNodes = nodes.map((node) => {
1432
+ if (node.id !== nodeId) return node;
1433
+ const data = node.data ?? {};
1434
+ return {
1435
+ ...node,
1436
+ data: {
1437
+ ...data,
1438
+ disabled: !(data.disabled === true)
1439
+ }
1440
+ };
1441
+ });
1442
+ if (edges.some((edge) => edge.source === nodeId && isLoopBodyEdge(edge, nodes) && !isValidWorkflowConnection(updatedNodes, edges, edge))) return false;
1443
+ pushCheckpoint("nodes:disable", false);
1444
+ set((state) => ({ workflow: {
1445
+ ...state.workflow,
1446
+ nodes: updatedNodes
1447
+ } }));
1448
+ return true;
1449
+ },
1450
+ renameNode: (nodeId, label) => {
1451
+ pushCheckpoint("nodes:rename", false);
1452
+ set((state) => ({ workflow: {
1453
+ ...state.workflow,
1454
+ nodes: state.workflow.nodes.map((n) => n.id === nodeId ? {
1455
+ ...n,
1456
+ data: {
1457
+ ...n.data ?? {},
1458
+ label
1459
+ }
1460
+ } : n),
1461
+ renamingNodeId: null
1462
+ } }));
1463
+ },
1464
+ startRename: (nodeId) => {
1465
+ set((state) => ({ workflow: {
1466
+ ...state.workflow,
1467
+ renamingNodeId: nodeId
1468
+ } }));
1469
+ },
1470
+ endRename: () => {
1471
+ set((state) => ({ workflow: {
1472
+ ...state.workflow,
1473
+ renamingNodeId: null
1474
+ } }));
1475
+ }
1476
+ },
1477
+ edges: {
1478
+ onEdgesChange: (changes) => {
1479
+ const removedIds = new Set(changes.filter((c) => c.type === "remove").map((c) => c.id));
1480
+ if (removedIds.size > 0) {
1481
+ if (get().workflow.edges.some((e) => removedIds.has(e.id)) && !joinsPrecedingRemoval("edges:remove")) pushCheckpoint("edges:remove", false);
1482
+ } else if (changes.some((c) => c.type === "add")) pushCheckpoint("edges:add", false);
1483
+ set((state) => produce(state, (draft) => {
1484
+ const updatedEdges = applyEdgeChanges(changes, draft.workflow.edges);
1485
+ draft.workflow.edges = updatedEdges;
1486
+ }));
1487
+ },
1488
+ onConnect: (connection) => {
1489
+ pushCheckpoint("edges:connect", false);
1490
+ const edge = {
1491
+ ...connection,
1492
+ id: nanoid(),
1493
+ type: "deletable"
1494
+ };
1495
+ set({ workflow: {
1496
+ ...get().workflow,
1497
+ edges: addEdge(edge, get().workflow.edges)
1498
+ } });
1499
+ },
1500
+ setEdges: (edges, opts) => {
1501
+ if (!opts?.skipHistory) pushCheckpoint(opts?.historyKind ?? "edges:set", !!opts?.historyKind);
1502
+ set({ workflow: {
1503
+ ...get().workflow,
1504
+ edges
1505
+ } });
1506
+ },
1507
+ deleteEdge: (edge) => {
1508
+ if (get().workflow.edges.some((e) => e.id === edge.id)) pushCheckpoint("edges:delete", false);
1509
+ set((state) => ({ workflow: {
1510
+ ...state.workflow,
1511
+ edges: state.workflow.edges.filter((e) => e.id !== edge.id)
1512
+ } }));
1513
+ }
1514
+ },
1515
+ execution: {
1516
+ startExecution: (nodeId, runId, metadata) => {
1517
+ set((state) => ({ execution: {
1518
+ ...state.execution,
1519
+ isExecuting: true,
1520
+ executingNodeId: nodeId,
1521
+ currentRunId: runId,
1522
+ sourceRun: metadata ? {
1523
+ runId,
1524
+ ...metadata
1525
+ } : {
1526
+ runId,
1527
+ workflowKey: "",
1528
+ version: ""
1529
+ },
1530
+ panelExpanded: true,
1531
+ nodeStatuses: {
1532
+ ...state.execution.nodeStatuses,
1533
+ [nodeId]: "running"
1534
+ }
1535
+ } }));
1536
+ },
1537
+ setRunMetadata: (metadata) => {
1538
+ set((state) => {
1539
+ if (state.execution.currentRunId !== metadata.runId && state.execution.sourceRun?.runId !== metadata.runId) return state;
1540
+ return { execution: {
1541
+ ...state.execution,
1542
+ currentRunId: metadata.runId,
1543
+ sourceRun: metadata
1544
+ } };
1545
+ });
1546
+ },
1547
+ setStepPlan: (plan) => {
1548
+ set((state) => ({ execution: {
1549
+ ...state.execution,
1550
+ stepPlan: plan
1551
+ } }));
1552
+ },
1553
+ addLog: (log) => {
1554
+ set((state) => ({ execution: {
1555
+ ...state.execution,
1556
+ logs: [...state.execution.logs, log],
1557
+ selectedLogId: log.id,
1558
+ vectorStoreStats: mergeVectorStoreStats(state.execution.vectorStoreStats, [log], state.workflow.nodes)
1559
+ } }));
1560
+ },
1561
+ updateLog: (logId, updates) => {
1562
+ set((state) => {
1563
+ let updatedLog;
1564
+ const logs = state.execution.logs.map((log) => {
1565
+ if (log.id !== logId) return log;
1566
+ updatedLog = {
1567
+ ...log,
1568
+ ...updates
1569
+ };
1570
+ return updatedLog;
1571
+ });
1572
+ return { execution: {
1573
+ ...state.execution,
1574
+ logs,
1575
+ vectorStoreStats: updatedLog ? mergeVectorStoreStats(state.execution.vectorStoreStats, [updatedLog], state.workflow.nodes) : state.execution.vectorStoreStats
1576
+ } };
1577
+ });
1578
+ },
1579
+ setNodeStatus: (nodeId, status) => {
1580
+ set((state) => ({ execution: {
1581
+ ...state.execution,
1582
+ nodeStatuses: {
1583
+ ...state.execution.nodeStatuses,
1584
+ [nodeId]: status
1585
+ }
1586
+ } }));
1587
+ },
1588
+ setNodeItemCount: (nodeId, count) => {
1589
+ set((state) => ({ execution: {
1590
+ ...state.execution,
1591
+ nodeItemCounts: {
1592
+ ...state.execution.nodeItemCounts,
1593
+ [nodeId]: count
1594
+ }
1595
+ } }));
1596
+ },
1597
+ selectLog: (logId) => {
1598
+ set((state) => ({ execution: {
1599
+ ...state.execution,
1600
+ selectedLogId: logId
1601
+ } }));
1602
+ },
1603
+ showLog: (logId) => {
1604
+ set((state) => ({ execution: {
1605
+ ...state.execution,
1606
+ selectedLogId: logId,
1607
+ panelExpanded: true,
1608
+ logFocus: state.execution.logFocus + 1
1609
+ } }));
1610
+ },
1611
+ togglePanel: () => {
1612
+ set((state) => ({ execution: {
1613
+ ...state.execution,
1614
+ panelExpanded: !state.execution.panelExpanded
1615
+ } }));
1616
+ },
1617
+ clearLogs: () => {
1618
+ set((state) => ({ execution: {
1619
+ ...state.execution,
1620
+ logs: [],
1621
+ stepPlan: null,
1622
+ currentRunId: null,
1623
+ sourceRun: null,
1624
+ selectedLogId: null,
1625
+ nodeStatuses: {},
1626
+ nodeItemCounts: {}
1627
+ } }));
1628
+ },
1629
+ completeExecution: () => {
1630
+ set((state) => ({ execution: {
1631
+ ...state.execution,
1632
+ isExecuting: false,
1633
+ executingNodeId: null
1634
+ } }));
1635
+ },
1636
+ requestFollowRun: (runId, triggerNodeId) => {
1637
+ set((state) => ({ execution: {
1638
+ ...state.execution,
1639
+ followRequest: {
1640
+ runId,
1641
+ triggerNodeId
1642
+ }
1643
+ } }));
1644
+ },
1645
+ clearFollowRequest: () => {
1646
+ set((state) => ({ execution: {
1647
+ ...state.execution,
1648
+ followRequest: null
1649
+ } }));
1650
+ },
1651
+ setLiveUpdates: (status) => {
1652
+ set((state) => state.execution.liveUpdates === status ? state : { execution: {
1653
+ ...state.execution,
1654
+ liveUpdates: status
1655
+ } });
1656
+ },
1657
+ loadDebugRun: (runId, logs, metadata) => {
1658
+ const nodeStatuses = {};
1659
+ for (const log of logs) nodeStatuses[log.nodeId] = log.status === "completed" ? "success" : log.status === "failed" ? "error" : log.status === "running" ? "running" : "idle";
1660
+ set((state) => ({ execution: {
1661
+ ...INITIAL_EXECUTION,
1662
+ currentRunId: runId,
1663
+ sourceRun: metadata ? {
1664
+ runId,
1665
+ ...metadata
1666
+ } : {
1667
+ runId,
1668
+ workflowKey: "",
1669
+ version: ""
1670
+ },
1671
+ logs,
1672
+ nodeStatuses,
1673
+ vectorStoreStats: mergeVectorStoreStats(state.execution.vectorStoreStats, logs, state.workflow.nodes),
1674
+ panelExpanded: true
1675
+ } }));
1676
+ }
1677
+ }
1678
+ }
1679
+ };
1680
+ });
1681
+ provideFlowStore(useFlowStore);
1682
+ if (typeof window !== "undefined" && import.meta.env?.DEV) window.__fgFlowStore = useFlowStore;
1683
+
1684
+ // src/builder/components/flow-builder/components/connection-fx/connection-fx-styles.ts
1685
+ /**
1686
+ * Motion for the "electric current" connect effect (BOFF-17867), as one
1687
+ * scoped stylesheet the editable canvas renders inline.
1688
+ *
1689
+ * Inline on purpose, like `preview-styles.ts`: host apps build Tailwind from
1690
+ * a scan of this package's dist, which generates no novel keyframes, and they
1691
+ * may not load `styles.css`. Every colour is a semantic token, so the effect
1692
+ * follows light / dark mode and the brand accent.
1693
+ *
1694
+ * - Bolt: three jagged polylines between the line's end and the handle, each
1695
+ * shown for a third of a 150 ms cycle (`steps(1)`, staggered delays).
1696
+ * - Charge: a radial glow on the snapped handle that pulses, over a static
1697
+ * ring that marks the handle.
1698
+ * - Zap: after a connect, a ring that expands and fades around the target
1699
+ * card, once (about half a second).
1700
+ *
1701
+ * Sizes are multiplied by `--fgc-s` (BOFF-17926): the connection line and
1702
+ * the zap ring set it to the zoom-out enlargement from `fxScaleForZoom`, so
1703
+ * the effect keeps its on-screen size when the canvas is zoomed out.
1704
+ *
1705
+ * `prefers-reduced-motion: reduce` hides the bolt and the zap and stops the
1706
+ * charge pulse, leaving the static handle highlight.
1707
+ */
1708
+ const PREFIX$1 = "fgc";
1709
+ const CONNECT_FX_CLASS = {
1710
+ arc: `${PREFIX$1}-arc`,
1711
+ bolt: `${PREFIX$1}-bolt`,
1712
+ bolt2: `${PREFIX$1}-b2`,
1713
+ bolt3: `${PREFIX$1}-b3`,
1714
+ charge: `${PREFIX$1}-charge`,
1715
+ chargeGradient: `${PREFIX$1}-charge-gradient`,
1716
+ chargeRing: `${PREFIX$1}-charge-ring`,
1717
+ zap: `${PREFIX$1}-zap`
1718
+ };
1719
+ /** One flicker cycle of the three bolts. */
1720
+ const BOLT_CYCLE_MS = 150;
1721
+ /** The charge glow's pulse. */
1722
+ const CHARGE_PULSE_MS = 900;
1723
+ /** The zap ring on the target card. */
1724
+ const ZAP_MS = 500;
1725
+ const C = CONNECT_FX_CLASS;
1726
+ const ACCENT = "var(--color-accent-glow, var(--color-accent-primary))";
1727
+ const ACCENT_ALT = "var(--color-accent-glow-alt, var(--color-accent-primary))";
1728
+ /** A length in px at scale 1, multiplied by the zoom-out scale. */
1729
+ function px(value) {
1730
+ return `calc(${value}px * var(--fgc-s, 1))`;
1731
+ }
1732
+ const CONNECT_FX_STYLES = `
1733
+ .${C.arc} {
1734
+ pointer-events: none;
1735
+ }
1736
+ .${C.bolt} {
1737
+ fill: none;
1738
+ stroke: ${ACCENT};
1739
+ stroke-width: ${px(2)};
1740
+ stroke-linejoin: round;
1741
+ stroke-linecap: round;
1742
+ opacity: 0;
1743
+ filter:
1744
+ drop-shadow(0 0 ${px(2)} ${ACCENT})
1745
+ drop-shadow(0 0 ${px(6)} color-mix(in oklab, ${ACCENT_ALT} 70%, transparent));
1746
+ animation: ${PREFIX$1}-bolt ${150}ms steps(1, end) infinite;
1747
+ }
1748
+ .${C.bolt2} {
1749
+ animation-delay: ${150 / 3}ms;
1750
+ }
1751
+ .${C.bolt3} {
1752
+ animation-delay: 100ms;
1753
+ }
1754
+ @keyframes ${PREFIX$1}-bolt {
1755
+ 0% { opacity: 1; }
1756
+ 33% { opacity: 0; }
1757
+ 100% { opacity: 0; }
1758
+ }
1759
+ .${C.charge} {
1760
+ pointer-events: none;
1761
+ animation: ${PREFIX$1}-charge ${900}ms ease-in-out infinite;
1762
+ }
1763
+ .${C.chargeGradient} stop {
1764
+ stop-color: ${ACCENT};
1765
+ }
1766
+ @keyframes ${PREFIX$1}-charge {
1767
+ 0%, 100% { opacity: 0.6; transform: scale(0.85); }
1768
+ 20% { opacity: 1; transform: scale(1); }
1769
+ 40% { opacity: 0.55; transform: scale(1.2); }
1770
+ 60% { opacity: 1; transform: scale(0.95); }
1771
+ 80% { opacity: 0.7; transform: scale(1.25); }
1772
+ }
1773
+ .${C.chargeRing} {
1774
+ pointer-events: none;
1775
+ fill: none;
1776
+ stroke: ${ACCENT};
1777
+ stroke-width: ${px(2)};
1778
+ }
1779
+ .${C.zap} {
1780
+ position: absolute;
1781
+ inset: calc(-2px * var(--fgc-s, 1));
1782
+ pointer-events: none;
1783
+ animation: ${PREFIX$1}-zap ${500}ms ease-out forwards;
1784
+ }
1785
+ @keyframes ${PREFIX$1}-zap {
1786
+ 0% {
1787
+ box-shadow:
1788
+ 0 0 0 ${px(2)} ${ACCENT},
1789
+ 0 0 0 0 color-mix(in oklab, ${ACCENT} 85%, transparent);
1790
+ }
1791
+ 100% {
1792
+ box-shadow:
1793
+ 0 0 0 ${px(2)} color-mix(in oklab, ${ACCENT} 0%, transparent),
1794
+ 0 0 0 ${px(16)} color-mix(in oklab, ${ACCENT_ALT} 0%, transparent);
1795
+ }
1796
+ }
1797
+ @media (prefers-reduced-motion: reduce) {
1798
+ .${C.arc},
1799
+ .${C.zap} {
1800
+ display: none;
1801
+ }
1802
+ .${C.charge} {
1803
+ animation: none;
1804
+ opacity: 0.8;
1805
+ }
1806
+ }
1807
+ `;
1808
+
1809
+ // src/builder/stores/connect-zap-store.ts
1810
+ /**
1811
+ * The node that just received a connection the person drew themselves
1812
+ * (BOFF-17867), for the target card's one-off "zap" flash.
1813
+ *
1814
+ * Transient UI state, kept out of the flow store on purpose: it is never
1815
+ * saved, never sent to co-editors and never part of undo history. Only the
1816
+ * canvas's own `onConnect` (a connection dropped by the local pointer) sets
1817
+ * it, so loading a workflow, undo / redo, paste and a co-editor's change
1818
+ * (`collab.applyRemote`) never zap a card.
1819
+ */
1820
+ const useConnectZapStore = create(() => ({ zap: null }));
1821
+ /** The zap is cleared a little after its animation has played out. */
1822
+ const ZAP_CLEAR_MS = 500 + 100;
1823
+ let lastSeq = 0;
1824
+ let clearTimer;
1825
+ /**
1826
+ * Flash the target card of a connection the person just made. `scale` is the
1827
+ * canvas's zoom-out enlargement at that moment (1 at 100% and above).
1828
+ */
1829
+ function zapConnectTarget(nodeId, scale = 1) {
1830
+ lastSeq += 1;
1831
+ const seq = lastSeq;
1832
+ useConnectZapStore.setState({ zap: {
1833
+ nodeId,
1834
+ seq,
1835
+ scale
1836
+ } });
1837
+ if (clearTimer !== void 0) clearTimeout(clearTimer);
1838
+ clearTimer = setTimeout(() => {
1839
+ clearTimer = void 0;
1840
+ if (useConnectZapStore.getState().zap?.seq === seq) useConnectZapStore.setState({ zap: null });
1841
+ }, ZAP_CLEAR_MS);
1842
+ }
1843
+ /** Back to no zap (tests, and a builder that unmounts mid-flash). */
1844
+ function resetConnectZap() {
1845
+ if (clearTimer !== void 0) clearTimeout(clearTimer);
1846
+ clearTimer = void 0;
1847
+ useConnectZapStore.setState({ zap: null });
1848
+ }
1849
+ /**
1850
+ * The current zap while `nodeId` is the zapped card, else null. The store
1851
+ * keeps one object per zap, so a card re-renders only when its own zap
1852
+ * starts or ends.
1853
+ */
1854
+ function useConnectZap(nodeId) {
1855
+ return useConnectZapStore((state) => nodeId !== null && state.zap?.nodeId === nodeId ? state.zap : null);
1856
+ }
1857
+
1858
+ // src/builder/components/flow-builder/components/connection-fx/zoom-scale.ts
1859
+ /** How far from a handle, on screen, a dragged line snaps to it. */
1860
+ const CONNECT_RADIUS_SCREEN_PX = 100;
1861
+ /** React Flow's own default radius, in canvas px; never snap tighter. */
1862
+ const MIN_CONNECT_RADIUS = 20;
1863
+ /**
1864
+ * The most the effect is enlarged when zoomed far out, so a huge flow
1865
+ * fitted to the screen does not get bolts wider than its cards.
1866
+ */
1867
+ const MAX_FX_SCALE = 4;
1868
+ /** The CSS custom property the connect stylesheet multiplies sizes by. */
1869
+ const FX_SCALE_VAR = "--fgc-s";
1870
+ function usableZoom(zoom) {
1871
+ return Number.isFinite(zoom) && zoom > 0 ? zoom : null;
1872
+ }
1873
+ /**
1874
+ * The `connectionRadius` (canvas px) that snaps from
1875
+ * `CONNECT_RADIUS_SCREEN_PX` on screen at this zoom, rounded to a whole
1876
+ * pixel so small zoom steps do not rewrite React Flow's store, and never
1877
+ * below React Flow's default.
1878
+ */
1879
+ function connectionRadiusForZoom(zoom) {
1880
+ const usable = usableZoom(zoom);
1881
+ if (usable === null) return 20;
1882
+ return Math.max(20, Math.round(100 / usable));
1883
+ }
1884
+ /**
1885
+ * How much to enlarge the effect's canvas sizes so it keeps its on-screen
1886
+ * size when zoomed out: `1 / zoom`, between 1 and `MAX_FX_SCALE`, to two
1887
+ * decimals. Zoomed in it stays 1, and the effect grows with the canvas as
1888
+ * every card and edge does.
1889
+ */
1890
+ function fxScaleForZoom(zoom) {
1891
+ const usable = usableZoom(zoom);
1892
+ if (usable === null) return 1;
1893
+ const scale = Math.min(4, Math.max(1, 1 / usable));
1894
+ return Math.round(scale * 100) / 100;
1895
+ }
1896
+ /**
1897
+ * An inline style that hands the scale to the connect stylesheet, merged
1898
+ * over `base`.
1899
+ */
1900
+ function fxScaleStyle(scale, base = {}) {
1901
+ return {
1902
+ ...base,
1903
+ [FX_SCALE_VAR]: String(scale)
1904
+ };
1905
+ }
1906
+
1907
+ // src/builder/components/flow-builder/components/connection-fx/connect-zap-ring.tsx
1908
+ /**
1909
+ * The target card's "zap" after the person drops a connection on it
1910
+ * (BOFF-17867): a ring that expands and fades once around the card. Keyed by
1911
+ * the zap, so a second connect restarts it. Styled by the canvas's connect
1912
+ * stylesheet (`connection-fx-styles.ts`), which also hides it for reduced
1913
+ * motion. Renders nothing for any other card, or outside a canvas. The ring
1914
+ * keeps its on-screen size when zoomed out, using the scale recorded with
1915
+ * the zap (BOFF-17926).
1916
+ */
1917
+ function ConnectZapRing({ nodeId, radius }) {
1918
+ const zap = useConnectZap(nodeId);
1919
+ if (zap === null) return null;
1920
+ return /* @__PURE__ */ jsx("span", {
1921
+ "aria-hidden": true,
1922
+ "data-testid": "node-connect-zap",
1923
+ className: CONNECT_FX_CLASS.zap,
1924
+ style: fxScaleStyle(zap.scale, { borderRadius: radius })
1925
+ }, zap.seq);
1926
+ }
1927
+
1928
+ // src/builder/components/flow-builder/components/ui/node-card-status.ts
1929
+ /**
1930
+ * What a builder node card's status line says (BOFF-17997).
1931
+ *
1932
+ * One line, in words, for how a step stands: needs a connection, needs
1933
+ * fields, ready, running, done, failed or turned off. Pure functions only, so
1934
+ * the card stays a thin render of what is decided here and the rules are unit
1935
+ * tested on their own.
1936
+ */
1937
+ const TONE = {
1938
+ running: "info",
1939
+ off: "neutral",
1940
+ failed: "error",
1941
+ done: "success",
1942
+ connect: "warning",
1943
+ fields: "warning",
1944
+ ready: "neutral"
1945
+ };
1946
+ const ACTION = {
1947
+ running: null,
1948
+ off: "turnOn",
1949
+ failed: "details",
1950
+ done: "output",
1951
+ connect: "connect",
1952
+ fields: "configure",
1953
+ ready: null
1954
+ };
1955
+ /**
1956
+ * Which status the card shows. When several apply, the first wins: running,
1957
+ * turned off, failed, done, needs a connection, needs fields, ready. A step
1958
+ * that is running is running; a turned-off step will be skipped whatever its
1959
+ * last result was; a run result beats set-up hints, because a run that
1960
+ * finished proves the step could run.
1961
+ */
1962
+ function nodeCardStatusKind(input) {
1963
+ if (input.executionStatus === "running") return "running";
1964
+ if (input.disabled) return "off";
1965
+ if (input.executionStatus === "error") return "failed";
1966
+ if (input.executionStatus === "success") return "done";
1967
+ if (input.missingConnection) return "connect";
1968
+ if (input.missingFields.length > 0) return "fields";
1969
+ return "ready";
1970
+ }
1971
+ /** The status line for a card: its kind, tone, action and the run details. */
1972
+ function nodeCardStatus(input) {
1973
+ const kind = nodeCardStatusKind(input);
1974
+ const log = input.log ?? null;
1975
+ const error = log?.error?.trim() ? log.error.trim() : null;
1976
+ return {
1977
+ kind,
1978
+ tone: TONE[kind],
1979
+ action: ACTION[kind],
1980
+ startedAt: kind === "running" ? log?.startTime ?? null : null,
1981
+ durationMs: kind === "done" || kind === "failed" ? logDuration(log) : null,
1982
+ itemCount: kind === "done" && typeof input.itemCount === "number" ? input.itemCount : null,
1983
+ error: kind === "failed" ? error : null,
1984
+ missingFields: kind === "fields" ? input.missingFields : []
1985
+ };
1986
+ }
1987
+ function logDuration(log) {
1988
+ if (!log) return null;
1989
+ return nodeStateDurationMs(log);
1990
+ }
1991
+ /** Milliseconds since `startedAt`, never negative; null when unknown. */
1992
+ function elapsedMs(startedAt, now = Date.now()) {
1993
+ if (!startedAt) return null;
1994
+ const start = new Date(startedAt).getTime();
1995
+ if (!Number.isFinite(start)) return null;
1996
+ return Math.max(0, now - start);
1997
+ }
1998
+ const SEP = " · ";
1999
+ /** "Subject", "Subject and Queue", "Subject, Queue and 2 more". */
2000
+ function missingFieldsText(fields, tr) {
2001
+ const [first = "", second = ""] = fields;
2002
+ if (fields.length <= 1) return tr("fluidgrids.builder.nodeCard.status.fillInOne", "Fill in {{first}}", { first });
2003
+ if (fields.length === 2) return tr("fluidgrids.builder.nodeCard.status.fillInTwo", "Fill in {{first}} and {{second}}", {
2004
+ first,
2005
+ second
2006
+ });
2007
+ return tr("fluidgrids.builder.nodeCard.status.fillInMany", "Fill in {{first}}, {{second}} and {{count}} more", {
2008
+ first,
2009
+ second,
2010
+ count: fields.length - 2
2011
+ });
2012
+ }
2013
+ /**
2014
+ * The words on the status line. `appName` names the app to connect;
2015
+ * `nowMs` is the clock for a running step's time.
2016
+ */
2017
+ function nodeCardStatusText(status, appName, tr, nowMs = Date.now()) {
2018
+ switch (status.kind) {
2019
+ case "connect": return tr("fluidgrids.builder.nodeCard.status.connect", "Connect {{app}} to run this step", { app: appName });
2020
+ case "fields": return missingFieldsText(status.missingFields, tr);
2021
+ case "ready": return [tr("fluidgrids.builder.nodeCard.status.ready", "Ready"), tr("fluidgrids.builder.nodeCard.status.notRunYet", "not run yet")].join(SEP);
2022
+ case "running": {
2023
+ const label = tr("fluidgrids.builder.nodeCard.status.running", "Running");
2024
+ const elapsed = elapsedMs(status.startedAt, nowMs);
2025
+ return elapsed === null ? label : [label, formatDurationMs(elapsed)].join(SEP);
2026
+ }
2027
+ case "done": {
2028
+ const parts = [tr("fluidgrids.builder.nodeCard.status.done", "Done")];
2029
+ if (status.itemCount !== null) parts.push(status.itemCount === 1 ? tr("fluidgrids.builder.nodeCard.status.itemsOne", "1 item") : tr("fluidgrids.builder.nodeCard.status.itemsOther", "{{count}} items", { count: status.itemCount }));
2030
+ if (status.durationMs !== null) parts.push(formatDurationMs(status.durationMs));
2031
+ return parts.join(SEP);
2032
+ }
2033
+ case "failed": {
2034
+ const label = tr("fluidgrids.builder.nodeCard.status.failed", "Failed");
2035
+ return status.error ? [label, status.error].join(SEP) : label;
2036
+ }
2037
+ case "off": return [tr("fluidgrids.builder.nodeCard.status.turnedOff", "Turned off"), tr("fluidgrids.builder.nodeCard.status.skippedOnRun", "skipped on run")].join(SEP);
2038
+ }
2039
+ }
2040
+ /** The label of the status line's action button. */
2041
+ function nodeCardActionText(action, tr) {
2042
+ switch (action) {
2043
+ case "connect": return tr("fluidgrids.builder.nodeCard.action.connect", "Connect");
2044
+ case "configure": return tr("fluidgrids.builder.nodeCard.action.configure", "Configure");
2045
+ case "output": return tr("fluidgrids.builder.nodeCard.action.output", "Output");
2046
+ case "details": return tr("fluidgrids.builder.nodeCard.action.details", "Details");
2047
+ case "turnOn": return tr("fluidgrids.builder.nodeCard.action.turnOn", "Turn on");
2048
+ }
2049
+ }
2050
+ /** Generic operation names that say nothing beyond the app's own name. */
2051
+ const GENERIC_OPERATIONS = /* @__PURE__ */ new Set([
2052
+ "execute",
2053
+ "run",
2054
+ "default",
2055
+ "main"
2056
+ ]);
2057
+ /**
2058
+ * An operation in plain words, in sentence case: "sendMessage" → "Send
2059
+ * message", "get_record_by_id" → "Get record by ID". Acronyms stay upper
2060
+ * case. Empty for no operation or a generic one ("execute"), where the app's
2061
+ * name already says what the step does.
2062
+ */
2063
+ function operationInPlainWords(operation) {
2064
+ const name = (operation ?? "").trim();
2065
+ if (!name || GENERIC_OPERATIONS.has(name.toLowerCase())) return "";
2066
+ return humanizeFieldName(name).split(" ").filter(Boolean).map((word, index) => {
2067
+ if (index === 0) return word;
2068
+ return /^[A-Z0-9]{2,}s?$/.test(word) ? word : word.toLowerCase();
2069
+ }).join(" ");
2070
+ }
2071
+ /** The card's second line: "Slack · Send message", or just the app. */
2072
+ function nodeCardSubtitle(appName, operation) {
2073
+ return operation ? [appName, operation].join(SEP) : appName;
2074
+ }
2075
+ /**
2076
+ * The status line's action handler for a card, or undefined when the action
2077
+ * can't be used here: Output and Details need the step's log line; the
2078
+ * others change the step, so a read-only canvas leaves them out.
2079
+ */
2080
+ function nodeCardStatusActionHandler(action, options) {
2081
+ if (action === null) return void 0;
2082
+ const { readOnly, logId, handlers } = options;
2083
+ if (action === "output" || action === "details" ? logId === null : readOnly) return void 0;
2084
+ return (chosen) => {
2085
+ if (chosen === "connect") handlers.connect();
2086
+ else if (chosen === "configure") handlers.configure();
2087
+ else if (chosen === "turnOn") handlers.turnOn();
2088
+ else if (logId !== null) handlers.showLog(logId);
2089
+ };
2090
+ }
2091
+
2092
+ // src/builder/components/flow-builder/components/ui/node-card-tones.ts
2093
+ /**
2094
+ * Theme tokens per status tone. A subtle background (the shell's
2095
+ * `--color-status-*-bg-subtle` alias, the convention across this SDK) with
2096
+ * the status text colour is the pair every theme (light, dark, its depths, the brand themes
2097
+ * and high contrast) defines for readable status copy; the dot uses the
2098
+ * canvas's node-state colours. Neutral uses the muted surface and secondary
2099
+ * text.
2100
+ */
2101
+ const NODE_CARD_TONE = {
2102
+ warning: {
2103
+ bg: "var(--color-status-warning-bg-subtle)",
2104
+ fg: "var(--color-status-warning-text)",
2105
+ dot: "var(--color-node-state-warning)",
2106
+ border: "var(--color-status-warning-border)"
2107
+ },
2108
+ info: {
2109
+ bg: "var(--color-status-info-bg-subtle)",
2110
+ fg: "var(--color-status-info-text)",
2111
+ dot: "var(--color-node-state-running)",
2112
+ border: "var(--color-status-info-border)"
2113
+ },
2114
+ success: {
2115
+ bg: "var(--color-status-success-bg-subtle)",
2116
+ fg: "var(--color-status-success-text)",
2117
+ dot: "var(--color-node-state-success)",
2118
+ border: "var(--color-status-success-border)"
2119
+ },
2120
+ error: {
2121
+ bg: "var(--color-status-error-bg-subtle)",
2122
+ fg: "var(--color-status-error-text)",
2123
+ dot: "var(--color-node-state-error)",
2124
+ border: "var(--color-status-error-border)"
2125
+ },
2126
+ neutral: {
2127
+ bg: "var(--color-bg-muted)",
2128
+ fg: "var(--color-text-secondary)",
2129
+ dot: "var(--color-node-state-skipped)",
2130
+ border: null
2131
+ }
2132
+ };
2133
+ /**
2134
+ * The card border colour for a status, or null to keep the card's own
2135
+ * border (ready and turned off).
2136
+ */
2137
+ function nodeCardStatusBorder(tone) {
2138
+ return NODE_CARD_TONE[tone].border;
2139
+ }
2140
+ /**
2141
+ * The colour of the hover and selection ring (BOFF-18075): the status's own
2142
+ * strong colour when the card has a status tint, so a card never shows two
2143
+ * colours at once, else the step's role accent. The strong dot colour, not the
2144
+ * pale border one, keeps the ring visible in light themes.
2145
+ */
2146
+ function nodeCardRingColor(tone, roleAccent) {
2147
+ if (tone === null || NODE_CARD_TONE[tone].border === null) return roleAccent;
2148
+ return NODE_CARD_TONE[tone].dot;
2149
+ }
2150
+ /** The ring's look: none at rest, faint on hover, clearer when selected. */
2151
+ function nodeCardFocusRing(args) {
2152
+ const { color, selected, hovered } = args;
2153
+ if (selected) return {
2154
+ opacity: 1,
2155
+ boxShadow: `0 0 0 1.5px ${color}, 0 0 0 4.5px color-mix(in srgb, ${color} 14%, transparent)`
2156
+ };
2157
+ return {
2158
+ opacity: hovered ? 1 : 0,
2159
+ boxShadow: `0 0 0 1px color-mix(in srgb, ${color} 50%, transparent)`
2160
+ };
2161
+ }
2162
+
2163
+ // src/builder/components/flow-builder/components/ui/node-card.tsx
2164
+ const PROVIDER_ACCENTS = [
2165
+ [/gmail|google/, "var(--color-chart-5)"],
2166
+ [/slack/, "var(--color-chart-3)"],
2167
+ [/github|gitlab/, nodeCategoryColor("utility")],
2168
+ [/stripe/, "var(--color-chart-12)"],
2169
+ [/discord|telegram/, "var(--color-chart-1)"],
2170
+ [/notion/, "var(--color-text-primary)"],
2171
+ [/whatsapp|sheet|excel/, "var(--color-chart-7)"],
2172
+ [/openai|anthropic|claude/, nodeCategoryColor("ai")],
2173
+ [/twilio/, "var(--color-chart-10)"],
2174
+ [/http|api|webhook|rest/, nodeCategoryColor("integration")],
2175
+ [/db|sql|postgres|mysql|mongo/, nodeCategoryColor("data")]
2176
+ ];
2177
+ function nodeAccent(key) {
2178
+ const k = (key || "").toLowerCase();
2179
+ for (const [re, color] of PROVIDER_ACCENTS) if (re.test(k)) return color;
2180
+ return chartSeriesColor(chartSeriesIndex(k));
2181
+ }
2182
+ /**
2183
+ * Corner radius of the node card: the semantic card radius token, so a host
2184
+ * theme (`radius.card`) or the embed `radius` param restyles the canvas
2185
+ * nodes. Inline rather than a `rounded-card` utility because hosts do not
2186
+ * always register the token as a Tailwind theme key; the 12px fallback is
2187
+ * the token's default and the radius the card had before (`rounded-xl`).
2188
+ */
2189
+ const NODE_CARD_RADIUS = "var(--radius-card, 12px)";
2190
+ /** Translucent tint of an accent that layers cleanly over light/dark cards. */
2191
+ function tint(color, pct = 14) {
2192
+ return `color-mix(in srgb, ${color} ${pct}%, transparent)`;
2193
+ }
2194
+ function InlineEditableLabel({ value, placeholder, editing, onStartEdit, onCommit, onCancel, className, inputClassName }) {
2195
+ const tr = useTr();
2196
+ const [draft, setDraft] = React.useState(value);
2197
+ const inputRef = React.useRef(null);
2198
+ React.useEffect(() => {
2199
+ if (!editing) return;
2200
+ setDraft(value);
2201
+ const raf = requestAnimationFrame(() => {
2202
+ inputRef.current?.focus();
2203
+ inputRef.current?.select();
2204
+ });
2205
+ return () => cancelAnimationFrame(raf);
2206
+ }, [editing, value]);
2207
+ if (editing) return /* @__PURE__ */ jsx("input", {
2208
+ ref: inputRef,
2209
+ value: draft,
2210
+ onChange: (e) => setDraft(e.target.value),
2211
+ onClick: (e) => e.stopPropagation(),
2212
+ onDoubleClick: (e) => e.stopPropagation(),
2213
+ onMouseDown: (e) => e.stopPropagation(),
2214
+ onKeyDown: (e) => {
2215
+ e.stopPropagation();
2216
+ if (e.key === "Enter") {
2217
+ e.preventDefault();
2218
+ onCommit(draft.trim());
2219
+ } else if (e.key === "Escape") {
2220
+ e.preventDefault();
2221
+ onCancel();
2222
+ }
2223
+ },
2224
+ onBlur: () => onCommit(draft.trim()),
2225
+ className: cn("min-w-0 flex-1 rounded border border-primary/50 bg-card px-1 text-inherit outline-none", inputClassName)
2226
+ });
2227
+ return /* @__PURE__ */ jsx("span", {
2228
+ className: cn("cursor-text", className),
2229
+ title: tr("fluidgrids.builder.nodeCard.renameTooltip", "Double-click or press F2 to rename"),
2230
+ onDoubleClick: (e) => {
2231
+ e.stopPropagation();
2232
+ onStartEdit();
2233
+ },
2234
+ children: value || placeholder
2235
+ });
2236
+ }
2237
+ /**
2238
+ * The toolbar of a selected node on a touch screen (`hover: none`): shown,
2239
+ * since a tap selects the node but never hovers it (BOFF-18043). Exported for
2240
+ * tests.
2241
+ */
2242
+ const NODE_TOOLBAR_SELECTED_TOUCH = "[@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100";
2243
+ const NodeCard = React.forwardRef(({ className, selected = false, isTrigger = false, accent = nodeCategoryColor("action"), statusTone = null, executionStatus = "idle", onSettings, onExecute, onDelete, isExecuting = false, infoButton, disabled = false, onToggleDisabled, onAskAi, belowCard, children, ...props }, ref) => {
2244
+ const tr = useTr();
2245
+ const [hovered, setHovered] = React.useState(false);
2246
+ const nodeId = useNodeId();
2247
+ const statusBorder = statusTone ? nodeCardStatusBorder(statusTone) : null;
2248
+ const ring = nodeCardFocusRing({
2249
+ color: nodeCardRingColor(statusTone, accent),
2250
+ selected,
2251
+ hovered
2252
+ });
2253
+ return /* @__PURE__ */ jsxs("div", {
2254
+ className: "group/node relative",
2255
+ onMouseEnter: () => setHovered(true),
2256
+ onMouseLeave: () => setHovered(false),
2257
+ children: [
2258
+ (onAskAi || onSettings || onExecute || onDelete || onToggleDisabled || infoButton) && /* @__PURE__ */ jsxs("div", {
2259
+ "data-testid": "node-card-toolbar",
2260
+ className: cn("absolute right-2 z-20 flex items-center gap-0.5 rounded-xl border border-border bg-card p-1 shadow-lg transition-all duration-150", hovered ? "pointer-events-auto opacity-100" : "pointer-events-none opacity-0", selected && "[@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100"),
2261
+ style: {
2262
+ top: -40,
2263
+ transform: hovered || selected ? "translateY(0)" : "translateY(4px)"
2264
+ },
2265
+ onClick: (e) => e.stopPropagation(),
2266
+ onDoubleClick: (e) => e.stopPropagation(),
2267
+ children: [
2268
+ onAskAi && /* @__PURE__ */ jsx(ToolbarButton, {
2269
+ "data-agent": "deny",
2270
+ "data-testid": "node-ask-ai",
2271
+ title: tr("fluidgrids.builder.nodeCard.askAiTooltip", "Ask AI about this step"),
2272
+ onClick: onAskAi,
2273
+ children: /* @__PURE__ */ jsx(Icon, {
2274
+ icon: "lucide:sparkles",
2275
+ className: "size-4",
2276
+ style: { color: "var(--color-accent-primary)" }
2277
+ })
2278
+ }),
2279
+ onSettings && /* @__PURE__ */ jsx(ToolbarButton, {
2280
+ title: tr("fluidgrids.builder.nodeCard.configureTooltip", "Configure"),
2281
+ onClick: onSettings,
2282
+ children: /* @__PURE__ */ jsx(Icon, {
2283
+ icon: "lucide:sliders-horizontal",
2284
+ className: "size-4"
2285
+ })
2286
+ }),
2287
+ onExecute && /* @__PURE__ */ jsx(ToolbarButton, {
2288
+ "data-agent": "confirm",
2289
+ title: tr("fluidgrids.builder.nodeCard.executeTooltip", "Execute step"),
2290
+ onClick: onExecute,
2291
+ disabled: isExecuting,
2292
+ children: isExecuting ? /* @__PURE__ */ jsx(CompactMarkOr, {
2293
+ today: /* @__PURE__ */ jsx(Icon, {
2294
+ icon: "svg-spinners:ring-resize",
2295
+ className: "size-4 text-[var(--color-status-success-text)]"
2296
+ }),
2297
+ className: "size-4"
2298
+ }) : /* @__PURE__ */ jsx(Icon, {
2299
+ icon: "mdi:play",
2300
+ className: "size-4 text-[var(--color-status-success-text)]"
2301
+ })
2302
+ }),
2303
+ infoButton,
2304
+ onToggleDisabled && /* @__PURE__ */ jsx(ToolbarButton, {
2305
+ title: disabled ? tr("fluidgrids.builder.nodeCard.enableTooltip", "Enable node") : tr("fluidgrids.builder.nodeCard.disableTooltip", "Disable node (skip on run)"),
2306
+ onClick: onToggleDisabled,
2307
+ children: /* @__PURE__ */ jsx(Icon, {
2308
+ icon: disabled ? "mdi:power" : "mdi:power-off",
2309
+ className: cn("size-4", disabled ? "text-[var(--color-status-warning-text)]" : "text-muted-foreground")
2310
+ })
2311
+ }),
2312
+ onDelete && /* @__PURE__ */ jsx(ToolbarButton, {
2313
+ title: tr("fluidgrids.builder.nodeCard.deleteTooltip", "Delete"),
2314
+ onClick: onDelete,
2315
+ children: /* @__PURE__ */ jsx(Icon, {
2316
+ icon: "mynaui:trash",
2317
+ className: "size-4 text-[var(--color-status-error-text)]"
2318
+ })
2319
+ })
2320
+ ]
2321
+ }),
2322
+ /* @__PURE__ */ jsxs("div", {
2323
+ ref,
2324
+ "data-selected": selected,
2325
+ "data-execution-status": executionStatus,
2326
+ className: cn("relative w-72 border border-border bg-card shadow-sm will-change-transform", className),
2327
+ style: {
2328
+ borderRadius: NODE_CARD_RADIUS,
2329
+ ...statusBorder ? { borderColor: statusBorder } : {},
2330
+ transition: "transform 0.15s ease, box-shadow 0.15s ease, border-color 0.15s ease",
2331
+ transform: hovered ? "translateY(-2px)" : "none",
2332
+ boxShadow: hovered ? "var(--shadow-float)" : void 0
2333
+ },
2334
+ ...props,
2335
+ children: [
2336
+ /* @__PURE__ */ jsx("div", {
2337
+ className: "pointer-events-none absolute -inset-px transition-[opacity,box-shadow] duration-150",
2338
+ style: {
2339
+ borderRadius: `calc(${NODE_CARD_RADIUS} + 1px)`,
2340
+ opacity: ring.opacity,
2341
+ boxShadow: ring.boxShadow
2342
+ }
2343
+ }),
2344
+ /* @__PURE__ */ jsx(ConnectZapRing, {
2345
+ nodeId,
2346
+ radius: `calc(${NODE_CARD_RADIUS} + 2px)`
2347
+ }),
2348
+ isTrigger && /* @__PURE__ */ jsx("div", {
2349
+ className: "absolute -top-2 -left-2 z-10 flex size-5 items-center justify-center rounded-full shadow-md ring-2 ring-card",
2350
+ style: { backgroundColor: "var(--color-status-success-text)" },
2351
+ children: /* @__PURE__ */ jsx(Icon, {
2352
+ icon: "mdi:lightning-bolt",
2353
+ className: "size-3",
2354
+ style: { color: "var(--color-status-success-text-inverse)" }
2355
+ })
2356
+ }),
2357
+ children
2358
+ ]
2359
+ }),
2360
+ belowCard && /* @__PURE__ */ jsx("div", {
2361
+ className: "absolute inset-x-0 top-full z-10 mt-1.5",
2362
+ children: belowCard
2363
+ })
2364
+ ]
2365
+ });
2366
+ });
2367
+ NodeCard.displayName = "NodeCard";
2368
+ function ToolbarButton({ title, onClick, disabled, children, "data-agent": agent, "data-testid": testId }) {
2369
+ return /* @__PURE__ */ jsx("button", {
2370
+ type: "button",
2371
+ "data-agent": agent,
2372
+ "data-testid": testId,
2373
+ title,
2374
+ "aria-label": title,
2375
+ disabled,
2376
+ onClick: (e) => {
2377
+ e.stopPropagation();
2378
+ onClick?.();
2379
+ },
2380
+ className: "flex size-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 disabled:opacity-50",
2381
+ children
2382
+ });
2383
+ }
2384
+ const NodeCardHeader = React.forwardRef(({ icon, appName, accentKey, operation = "", label, dimmed = false, isRenaming = false, onStartRename, onCommitRename, onCancelRename }, ref) => {
2385
+ const accent = nodeAccent(accentKey);
2386
+ const nameClass = "line-clamp-2 break-words text-[14.5px] font-semibold leading-snug text-card-foreground";
2387
+ return /* @__PURE__ */ jsxs("div", {
2388
+ ref,
2389
+ className: "flex items-start gap-3 px-3 pb-2.5 pt-3.5",
2390
+ style: dimmed ? {
2391
+ opacity: .55,
2392
+ filter: "saturate(0.4)"
2393
+ } : void 0,
2394
+ children: [/* @__PURE__ */ jsx("div", {
2395
+ className: "flex size-9 shrink-0 items-center justify-center rounded-lg",
2396
+ style: {
2397
+ backgroundColor: tint(accent, 13),
2398
+ color: accent,
2399
+ border: `1px solid ${tint(accent, 26)}`
2400
+ },
2401
+ children: /* @__PURE__ */ jsx(NodeTypeIcon, {
2402
+ icon,
2403
+ alt: appName,
2404
+ className: "size-5"
2405
+ })
2406
+ }), /* @__PURE__ */ jsxs("div", {
2407
+ className: "flex min-w-0 flex-1 flex-col gap-0.5",
2408
+ children: [onStartRename && onCommitRename && onCancelRename ? /* @__PURE__ */ jsx(InlineEditableLabel, {
2409
+ value: label ?? "",
2410
+ placeholder: appName,
2411
+ editing: isRenaming,
2412
+ onStartEdit: onStartRename,
2413
+ onCommit: onCommitRename,
2414
+ onCancel: onCancelRename,
2415
+ className: nameClass,
2416
+ inputClassName: "text-[14.5px] font-semibold"
2417
+ }) : /* @__PURE__ */ jsx("span", {
2418
+ className: nameClass,
2419
+ children: label || appName
2420
+ }), /* @__PURE__ */ jsx("span", {
2421
+ "data-testid": "node-card-subtitle",
2422
+ className: "truncate text-xs text-muted-foreground",
2423
+ children: nodeCardSubtitle(appName, operation)
2424
+ })]
2425
+ })]
2426
+ });
2427
+ });
2428
+ NodeCardHeader.displayName = "NodeCardHeader";
2429
+
2430
+ // src/builder/components/flow-builder/components/ui/node-card-styles.ts
2431
+ /**
2432
+ * Motion for the node card (BOFF-17997), as one scoped stylesheet the canvas
2433
+ * renders inline. Inline for the same reason as `connection-fx-styles.ts`:
2434
+ * host apps build Tailwind from a scan of this package's dist, which makes
2435
+ * no new keyframes.
2436
+ *
2437
+ * - Progress: the sweep along the bottom of a running step's card.
2438
+ *
2439
+ * With `prefers-reduced-motion: reduce` the sweep stands still as a short
2440
+ * bar, so the running state still shows without movement.
2441
+ */
2442
+ const PREFIX = "fgn";
2443
+ const NODE_CARD_CLASS = { progress: `${PREFIX}-progress` };
2444
+ /** One sweep of the running bar. */
2445
+ const PROGRESS_SWEEP_MS = 1200;
2446
+ const NODE_CARD_STYLES = `
2447
+ .${NODE_CARD_CLASS.progress} {
2448
+ width: 40%;
2449
+ height: 100%;
2450
+ border-radius: 999px;
2451
+ animation: ${PREFIX}-sweep ${PROGRESS_SWEEP_MS}ms ease-in-out infinite;
2452
+ }
2453
+ @keyframes ${PREFIX}-sweep {
2454
+ 0% { transform: translateX(-100%); }
2455
+ 100% { transform: translateX(260%); }
2456
+ }
2457
+ @media (prefers-reduced-motion: reduce) {
2458
+ .${NODE_CARD_CLASS.progress} {
2459
+ animation: none;
2460
+ transform: translateX(75%);
2461
+ }
2462
+ }
2463
+ `;
2464
+
2465
+ // src/builder/components/flow-builder/components/ui/node-card-status-line.tsx
2466
+ /** Re-renders every second while `active`, for a running step's time. */
2467
+ function useTicker(active) {
2468
+ const [now, setNow] = React.useState(() => Date.now());
2469
+ React.useEffect(() => {
2470
+ if (!active) return;
2471
+ setNow(Date.now());
2472
+ const timer = setInterval(() => setNow(Date.now()), 1e3);
2473
+ return () => clearInterval(timer);
2474
+ }, [active]);
2475
+ return now;
2476
+ }
2477
+ /**
2478
+ * The card's one status line (BOFF-17997): a dot (a spinner while running),
2479
+ * the status in words, and the one action that fixes or explains it. The
2480
+ * action is left out when `onAction` is not given (a read-only canvas).
2481
+ */
2482
+ function NodeCardStatusLine({ status, appName, onAction }) {
2483
+ const tr = useTr();
2484
+ const running = status.kind === "running";
2485
+ const now = useTicker(running);
2486
+ const tone = NODE_CARD_TONE[status.tone];
2487
+ const text = nodeCardStatusText(status, appName, tr, now);
2488
+ const action = status.action && onAction ? status.action : null;
2489
+ const stop = (event) => event.stopPropagation();
2490
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsxs("div", {
2491
+ "data-testid": "node-card-status",
2492
+ "data-status": status.kind,
2493
+ className: "mx-3 mb-3 flex min-h-8 items-center gap-2 rounded-lg px-2.5 py-1.5 text-[12.5px] font-medium leading-tight",
2494
+ style: {
2495
+ backgroundColor: tone.bg,
2496
+ color: tone.fg
2497
+ },
2498
+ children: [
2499
+ running ? /* @__PURE__ */ jsx(Icon, {
2500
+ icon: "svg-spinners:ring-resize",
2501
+ className: "size-3 shrink-0",
2502
+ style: { color: tone.dot }
2503
+ }) : /* @__PURE__ */ jsx("span", {
2504
+ "aria-hidden": true,
2505
+ className: "size-2 shrink-0 rounded-full",
2506
+ style: { backgroundColor: tone.dot }
2507
+ }),
2508
+ /* @__PURE__ */ jsx("span", {
2509
+ className: "line-clamp-2 min-w-0 flex-1 break-words",
2510
+ title: text,
2511
+ children: text
2512
+ }),
2513
+ action && /* @__PURE__ */ jsx("button", {
2514
+ type: "button",
2515
+ "data-testid": "node-card-status-action",
2516
+ "data-action": action,
2517
+ className: "nodrag nopan -my-1 shrink-0 rounded-md px-1.5 py-1 font-semibold underline underline-offset-2 hover:opacity-80 focus-visible:outline-2 focus-visible:outline-offset-1",
2518
+ style: {
2519
+ color: "inherit",
2520
+ outlineColor: "currentColor"
2521
+ },
2522
+ onMouseDown: stop,
2523
+ onDoubleClick: stop,
2524
+ onClick: (event) => {
2525
+ event.stopPropagation();
2526
+ onAction?.(action);
2527
+ },
2528
+ children: nodeCardActionText(action, tr)
2529
+ })
2530
+ ]
2531
+ }), running && /* @__PURE__ */ jsx("div", {
2532
+ "aria-hidden": true,
2533
+ className: "pointer-events-none absolute inset-x-0 bottom-0 h-[3px] overflow-hidden",
2534
+ style: {
2535
+ backgroundColor: tone.bg,
2536
+ borderBottomLeftRadius: "var(--radius-card, 12px)",
2537
+ borderBottomRightRadius: "var(--radius-card, 12px)"
2538
+ },
2539
+ children: /* @__PURE__ */ jsx("div", {
2540
+ className: NODE_CARD_CLASS.progress,
2541
+ style: { backgroundColor: tone.dot }
2542
+ })
2543
+ })] });
2544
+ }
2545
+
2546
+ // src/builder/components/flow-builder/components/handles/handle-connectable.ts
2547
+ /**
2548
+ * Whether a handle accepts another connection, read from the React Flow store
2549
+ * (BOFF-17172). CustomHandle selects this boolean instead of the store's
2550
+ * edges and nodes, so it re-renders only when the answer changes.
2551
+ */
2552
+ /**
2553
+ * Whether the handle of `nodeId` accepts another connection, read from the
2554
+ * React Flow store. Selected by CustomHandle on every store update.
2555
+ */
2556
+ function handleConnectableIn(state, nodeId, isConnectable) {
2557
+ if (!nodeId) return false;
2558
+ const node = state.nodeLookup.get(nodeId);
2559
+ if (!node) return false;
2560
+ if (typeof isConnectable === "function") return isConnectable({
2561
+ node,
2562
+ connectedEdges: getConnectedEdges([node], state.edges)
2563
+ });
2564
+ if (typeof isConnectable === "number") return getConnectedEdges([node], state.edges).length < isConnectable;
2565
+ return isConnectable;
2566
+ }
2567
+
2568
+ // src/builder/components/flow-builder/components/handles/custom-handler.tsx
2569
+ function CustomHandle({ className, isConnectable, accent, ...props }) {
2570
+ const nodeId = useNodeId();
2571
+ const selectConnectable = useCallback((state) => handleConnectableIn(state, nodeId, isConnectable), [isConnectable, nodeId]);
2572
+ const isHandleConnectable = useStore(selectConnectable);
2573
+ return /* @__PURE__ */ jsx("span", { children: /* @__PURE__ */ jsx(Handle, {
2574
+ className: cn("cursor-crosshair transition-transform hover:scale-110", !accent && "size-3 border-2 border-card-foreground/40 hover:border-primary/50", className),
2575
+ isConnectable: isHandleConnectable,
2576
+ style: accent ? {
2577
+ width: 14,
2578
+ height: 14,
2579
+ borderRadius: "50%",
2580
+ background: "var(--color-node-bg)",
2581
+ border: `2.5px solid ${accent}`,
2582
+ boxShadow: `0 0 0 3px color-mix(in srgb, ${accent} 12%, transparent)`
2583
+ } : void 0,
2584
+ ...props
2585
+ }) });
2586
+ }
2587
+
2588
+ // src/builder/components/flow-builder/components/blocks/nodes/node/handle-plus-drag.ts
2589
+ /**
2590
+ * Dragging from an output handle's "+" button connects like dragging from
2591
+ * the round handle itself (BOFF-17926). A click without a drag still opens
2592
+ * the Node Store.
2593
+ *
2594
+ * A press on the "+" is only watched at first. Once the pointer has moved
2595
+ * more than `PLUS_CLICK_SLOP_PX` while still down, the press is handed to
2596
+ * the real React Flow handle beside it as a fresh `mousedown` (or
2597
+ * `touchstart`) at the point where the press began. React Flow's own handle
2598
+ * code then runs the drag exactly as if the handle had been pressed:
2599
+ * snapping, the electric arc, `isValidConnection`, `onConnect` (which zaps
2600
+ * the target) and `onConnectEnd` (drop on empty canvas). Nothing about
2601
+ * connecting is reimplemented here, so the two ways of starting a link
2602
+ * cannot drift apart.
2603
+ *
2604
+ * Waiting for real movement keeps a plain click a click: a press that never
2605
+ * leaves the "+" never reaches React Flow, so its release cannot count as a
2606
+ * drop on empty canvas and open the add-node menu next to the Node Store.
2607
+ */
2608
+ /** Moving further than this (px) while pressed turns a press into a drag. */
2609
+ const PLUS_CLICK_SLOP_PX = 4;
2610
+ /**
2611
+ * The React Flow source handle `handleId` of node `nodeId`, searched within
2612
+ * the card that holds `from` (the "+" button).
2613
+ */
2614
+ function findSourceHandle(from, nodeId, handleId) {
2615
+ const card = from.closest(".react-flow__node");
2616
+ if (card === null) return null;
2617
+ const handles = card.querySelectorAll(".react-flow__handle.source");
2618
+ for (const handle of handles) if (handle.dataset.nodeid === nodeId && handle.dataset.handleid === handleId) return handle;
2619
+ return null;
2620
+ }
2621
+ /** Whether `point` is more than `PLUS_CLICK_SLOP_PX` away from `press`. */
2622
+ function beyondSlop(press, point) {
2623
+ return Math.hypot(point.x - press.x, point.y - press.y) > 4;
2624
+ }
2625
+ function isTouchEvent(event) {
2626
+ return "touches" in event;
2627
+ }
2628
+ /** Where a mouse or (first) touch event is, or null for a touch with none. */
2629
+ function eventPoint(event) {
2630
+ if (!isTouchEvent(event)) return {
2631
+ x: event.clientX,
2632
+ y: event.clientY
2633
+ };
2634
+ const touch = event.touches[0] ?? event.changedTouches[0];
2635
+ return touch ? {
2636
+ x: touch.clientX,
2637
+ y: touch.clientY
2638
+ } : null;
2639
+ }
2640
+ /** A copy of `press` for `handle`, so React Flow sees the handle pressed. */
2641
+ function pressFor(press) {
2642
+ if (isTouchEvent(press)) {
2643
+ if (typeof TouchEvent !== "function") return null;
2644
+ const touches = Array.from(press.touches);
2645
+ return new TouchEvent("touchstart", {
2646
+ bubbles: true,
2647
+ cancelable: true,
2648
+ composed: true,
2649
+ touches,
2650
+ targetTouches: touches,
2651
+ changedTouches: Array.from(press.changedTouches)
2652
+ });
2653
+ }
2654
+ return new MouseEvent("mousedown", {
2655
+ bubbles: true,
2656
+ cancelable: true,
2657
+ composed: true,
2658
+ view: press.view,
2659
+ button: 0,
2660
+ buttons: press.buttons,
2661
+ clientX: press.clientX,
2662
+ clientY: press.clientY,
2663
+ screenX: press.screenX,
2664
+ screenY: press.screenY,
2665
+ ctrlKey: press.ctrlKey,
2666
+ shiftKey: press.shiftKey,
2667
+ altKey: press.altKey,
2668
+ metaKey: press.metaKey
2669
+ });
2670
+ }
2671
+ /**
2672
+ * Presses the handle behind the "+" button with a copy of `press`, which
2673
+ * starts React Flow's connection drag. Returns whether the handle was found
2674
+ * and pressed.
2675
+ */
2676
+ function forwardPressToHandle(button, nodeId, handleId, press) {
2677
+ const handle = findSourceHandle(button, nodeId, handleId);
2678
+ if (handle === null) return false;
2679
+ const event = pressFor(press);
2680
+ if (event === null) return false;
2681
+ handle.dispatchEvent(event);
2682
+ return true;
2683
+ }
2684
+ /**
2685
+ * Watches a press on the "+" until it ends. The first move beyond the slop
2686
+ * forwards the press to the handle and calls `onDrag`; a press released in
2687
+ * place does nothing here (the button's click handles it). Returns a stop
2688
+ * function that removes the listeners.
2689
+ */
2690
+ function watchPlusPress(args) {
2691
+ const { button, nodeId, handleId, press, onDrag } = args;
2692
+ const start = eventPoint(press);
2693
+ const doc = button.ownerDocument;
2694
+ const touch = isTouchEvent(press);
2695
+ const moveType = touch ? "touchmove" : "mousemove";
2696
+ const endTypes = touch ? ["touchend", "touchcancel"] : ["mouseup"];
2697
+ const stop = () => {
2698
+ doc.removeEventListener(moveType, onMove);
2699
+ for (const type of endTypes) doc.removeEventListener(type, stop);
2700
+ };
2701
+ function onMove(event) {
2702
+ const point = eventPoint(event);
2703
+ if (start === null || point === null || !beyondSlop(start, point)) return;
2704
+ stop();
2705
+ onDrag();
2706
+ forwardPressToHandle(button, nodeId, handleId, press);
2707
+ }
2708
+ if (start === null) return stop;
2709
+ doc.addEventListener(moveType, onMove);
2710
+ for (const type of endTypes) doc.addEventListener(type, stop);
2711
+ return stop;
2712
+ }
2713
+ /**
2714
+ * The "+" button's handlers: a press that moves becomes a connection drag
2715
+ * from handle `handleId`; a click that did not follow a drag calls `onAdd`
2716
+ * (opens the Node Store). A keyboard click (`detail` 0) is always a click.
2717
+ * Each handler stops the event so the canvas neither pans nor deselects.
2718
+ */
2719
+ function usePlusPress(nodeId, handleId, onAdd) {
2720
+ const draggedRef = useRef(false);
2721
+ const stopRef = useRef(null);
2722
+ useEffect(() => () => stopRef.current?.(), []);
2723
+ const watch = (button, press) => {
2724
+ stopRef.current?.();
2725
+ draggedRef.current = false;
2726
+ stopRef.current = watchPlusPress({
2727
+ button,
2728
+ nodeId,
2729
+ handleId,
2730
+ press,
2731
+ onDrag: () => {
2732
+ draggedRef.current = true;
2733
+ }
2734
+ });
2735
+ };
2736
+ return {
2737
+ onMouseDown: (event) => {
2738
+ event.stopPropagation();
2739
+ if (event.button !== 0) return;
2740
+ watch(event.currentTarget, event.nativeEvent);
2741
+ },
2742
+ onTouchStart: (event) => {
2743
+ event.stopPropagation();
2744
+ watch(event.currentTarget, event.nativeEvent);
2745
+ },
2746
+ onClick: (event) => {
2747
+ event.stopPropagation();
2748
+ const dragged = draggedRef.current;
2749
+ draggedRef.current = false;
2750
+ if (event.detail !== 0 && dragged) return;
2751
+ onAdd();
2752
+ }
2753
+ };
2754
+ }
2755
+
2756
+ // src/builder/components/flow-builder/components/blocks/nodes/node/handle-spec.ts
2757
+ function isDynamicSpec(spec) {
2758
+ return !!spec && !Array.isArray(spec) && typeof spec.fromStateRecord === "string";
2759
+ }
2760
+ /**
2761
+ * Whether a node's `data.nodeData` carries a manifest — what a palette drop
2762
+ * stores (name, operations, handles, adapters). A definition built outside the
2763
+ * builder (API, MCP tools, code) stores at most `{ nodeType }`: such a "bare"
2764
+ * node has no handle spec of its own, so its handles come from the node
2765
+ * registry instead (BOFF-11434).
2766
+ */
2767
+ function hasNodeManifest(nodeData) {
2768
+ if (typeof nodeData !== "object" || nodeData === null) return false;
2769
+ const manifest = nodeData;
2770
+ return [
2771
+ "operations",
2772
+ "outputHandles",
2773
+ "inputHandles",
2774
+ "nodeAdapters",
2775
+ "name"
2776
+ ].some((key) => manifest[key] !== void 0 && manifest[key] !== null);
2777
+ }
2778
+ /**
2779
+ * The manifest a node's connection points are read from: the node's own copy
2780
+ * whenever it has one (so a node saved from the builder keeps exactly the
2781
+ * handles it was saved with), and the registry's manifest for a bare node.
2782
+ */
2783
+ function handleManifestOf(data, registryNodeData) {
2784
+ const own = data?.nodeData;
2785
+ if (hasNodeManifest(own)) return own;
2786
+ return registryNodeData ?? own;
2787
+ }
2788
+ /**
2789
+ * A node's adapter ports (AI Agent "Chat Model", "Memory", ...): from its own
2790
+ * manifest, or from the registry's for a bare node, as its handles are.
2791
+ * `T` is the caller's adapter type: every source is the node manifest JSON,
2792
+ * whose `nodeAdapters` field is that list.
2793
+ */
2794
+ function nodeAdaptersOf(nodeData, registryNodeData) {
2795
+ const adapters = handleManifestOf({ nodeData }, registryNodeData)?.nodeAdapters;
2796
+ return Array.isArray(adapters) ? adapters : void 0;
2797
+ }
2798
+ /**
2799
+ * The output of each Switch rule (`{ name, handle }`), labelled as the
2800
+ * builder's rule editor labels it: the rule's name, else "Rule <n>".
2801
+ */
2802
+ function ruleHandles(rules) {
2803
+ if (!Array.isArray(rules)) return [];
2804
+ return rules.flatMap((rule, index) => {
2805
+ if (typeof rule !== "object" || rule === null) return [];
2806
+ const { name, handle } = rule;
2807
+ if (typeof handle !== "string" || !handle) return [];
2808
+ return [{
2809
+ id: handle,
2810
+ label: typeof name === "string" && name ? name : `Rule ${index + 1}`
2811
+ }];
2812
+ });
2813
+ }
2814
+ /**
2815
+ * The output a Switch sends unmatched items to, when the node names one: the
2816
+ * worker reads `fallbackHandle`, then `defaultHandle` (conditional-handler).
2817
+ */
2818
+ function fallbackHandleOf(state, data) {
2819
+ for (const value of [
2820
+ state?.fallbackHandle,
2821
+ state?.defaultHandle,
2822
+ data?.fallbackHandle,
2823
+ data?.defaultHandle
2824
+ ]) if (typeof value === "string" && value) return value;
2825
+ }
2826
+ /** The default single unlabeled source handle (legacy card behavior). */
2827
+ const DEFAULT_HANDLES = [{
2828
+ id: "source",
2829
+ label: ""
2830
+ }];
2831
+ /**
2832
+ * Handles of node types whose routing is fixed by the engine, used when the
2833
+ * node carries no manifest spec (a definition imported or written in code
2834
+ * before the manifest reached the registry). `internal:wait-for-signal`
2835
+ * routes a delivered signal to `received` and an expired limit to `timedOut`
2836
+ * (spec code-first 05 §3, the worker's strict `signalResumeResult` handles).
2837
+ */
2838
+ const BUILTIN_OUTPUT_HANDLES = { "internal:wait-for-signal": [{
2839
+ id: "received",
2840
+ label: "Received",
2841
+ tone: "success"
2842
+ }, {
2843
+ id: "timedOut",
2844
+ label: "Timed out",
2845
+ tone: "warning"
2846
+ }] };
2847
+ /**
2848
+ * Resolve the output handles a node card should render.
2849
+ *
2850
+ * Reads the manifest handle spec from `data.nodeData.outputHandles`; dynamic
2851
+ * specs (Switch cases) additionally read the configured record from the
2852
+ * node's `args.state` (NDV writes there) falling back to top-level data
2853
+ * (legacy panels wrote there).
2854
+ *
2855
+ * `registryNodeData` is the node registry's manifest for the node's type. It
2856
+ * is used only for a bare node (see `hasNodeManifest`), so a template or an
2857
+ * API-built workflow draws its IF / Loop / Switch / Send-and-wait outputs
2858
+ * instead of a single `source` that drops every branch edge (BOFF-11434).
2859
+ */
2860
+ function resolveOutputHandles(data, nodeType, registryNodeData) {
2861
+ const nodeData = handleManifestOf(data, registryNodeData);
2862
+ const operationsBlob = Array.isArray(nodeData?.operations) ? void 0 : nodeData?.operations;
2863
+ const operationList = Array.isArray(nodeData?.operations) ? nodeData.operations : operationsBlob?.operations ?? [];
2864
+ const operationName = typeof data?.operation_name === "string" ? data.operation_name : void 0;
2865
+ const spec = (operationName ? operationList.find((op) => op?.name === operationName)?.outputHandles : void 0) ?? nodeData?.outputHandles ?? operationsBlob?.outputHandles;
2866
+ if (!spec) return nodeType && BUILTIN_OUTPUT_HANDLES[nodeType] || DEFAULT_HANDLES;
2867
+ if (isDynamicSpec(spec)) {
2868
+ const state = (data?.args)?.state;
2869
+ const record = state?.[spec.fromStateRecord] ?? data?.[spec.fromStateRecord] ?? {};
2870
+ const handles = Object.entries(record).filter(([, handleId]) => typeof handleId === "string" && handleId).map(([label, handleId]) => ({
2871
+ id: handleId,
2872
+ label
2873
+ }));
2874
+ const add = (handle) => {
2875
+ if (!handles.some((existing) => existing.id === handle.id)) handles.push(handle);
2876
+ };
2877
+ for (const handle of ruleHandles(state?.rules)) add(handle);
2878
+ for (const handle of spec.extra ?? []) add(handle);
2879
+ const fallback = fallbackHandleOf(state, data);
2880
+ if (fallback) add({
2881
+ id: fallback,
2882
+ label: fallback,
2883
+ tone: "neutral"
2884
+ });
2885
+ return handles;
2886
+ }
2887
+ if (spec.length === 0) return DEFAULT_HANDLES;
2888
+ return spec;
2889
+ }
2890
+ /** The default single unlabeled input target (legacy card behavior). */
2891
+ const DEFAULT_INPUT_HANDLES = [{
2892
+ id: "target",
2893
+ label: ""
2894
+ }];
2895
+ /**
2896
+ * Numbered inputs of node types whose inputs are fixed by the engine, used
2897
+ * when neither the node's own manifest nor the registry's carries the spec: a
2898
+ * Merge node saved before the spec existed keeps its two static handles in
2899
+ * its own copy, and must still grow when its number of inputs is raised.
2900
+ */
2901
+ const BUILTIN_INPUT_HANDLES_FROM = { "internal:merge": {
2902
+ fromCount: "numberInputs",
2903
+ min: 2,
2904
+ max: 10,
2905
+ idPrefix: "input-",
2906
+ labelPrefix: "Input "
2907
+ } };
2908
+ function readDynamicInputs(value) {
2909
+ if (typeof value !== "object" || value === null) return void 0;
2910
+ const { fromCount, min, max, idPrefix, labelPrefix } = value;
2911
+ if (typeof fromCount !== "string" || typeof min !== "number" || typeof max !== "number" || typeof idPrefix !== "string" || typeof labelPrefix !== "string" || !Number.isInteger(min) || !Number.isInteger(max) || min < 1 || max < min) return;
2912
+ return {
2913
+ fromCount,
2914
+ min,
2915
+ max,
2916
+ idPrefix,
2917
+ labelPrefix
2918
+ };
2919
+ }
2920
+ function dynamicInputsIn(manifest) {
2921
+ if (!manifest) return void 0;
2922
+ const operations = manifest.operations;
2923
+ const blob = typeof operations === "object" && operations !== null && !Array.isArray(operations) ? operations : void 0;
2924
+ return readDynamicInputs(manifest.inputHandlesFrom) ?? readDynamicInputs(blob?.inputHandlesFrom);
2925
+ }
2926
+ /**
2927
+ * The numbered-inputs spec of a node (BOFF-9738): from its own manifest, the
2928
+ * registry's, or the engine's built-in table, in that order. Undefined for a
2929
+ * node whose inputs are not numbered by a setting.
2930
+ */
2931
+ function dynamicInputHandlesOf(data, registryNodeData, nodeType) {
2932
+ return dynamicInputsIn(data?.nodeData) ?? dynamicInputsIn(registryNodeData) ?? (nodeType ? BUILTIN_INPUT_HANDLES_FROM[nodeType] : void 0);
2933
+ }
2934
+ /**
2935
+ * The input number a handle id names under a spec (`input-3` → 3), or
2936
+ * undefined when it names none.
2937
+ */
2938
+ function inputNumberOfHandle(spec, handleId) {
2939
+ if (!handleId || !handleId.startsWith(spec.idPrefix)) return void 0;
2940
+ const rest = handleId.slice(spec.idPrefix.length);
2941
+ if (!/^\d{1,3}$/.test(rest)) return void 0;
2942
+ const input = Number(rest);
2943
+ return input >= 1 ? input : void 0;
2944
+ }
2945
+ /**
2946
+ * The number of inputs a node's setting asks for, clamped to the spec's
2947
+ * bounds; the minimum when unset or not a number. The setting is read from
2948
+ * `args.state` (where the NDV writes), then from top-level data.
2949
+ */
2950
+ function configuredInputCount(spec, data) {
2951
+ const args = data?.args;
2952
+ return clampInputCount(spec, args?.state?.[spec.fromCount] ?? data?.[spec.fromCount]);
2953
+ }
2954
+ /** A number-of-inputs value as the card draws it (see configuredInputCount). */
2955
+ function clampInputCount(spec, raw) {
2956
+ let parsed = NaN;
2957
+ if (typeof raw === "number") parsed = raw;
2958
+ else if (typeof raw === "string") parsed = Number.parseInt(raw.trim(), 10);
2959
+ if (!Number.isFinite(parsed)) return spec.min;
2960
+ return Math.min(spec.max, Math.max(spec.min, Math.trunc(parsed)));
2961
+ }
2962
+ /**
2963
+ * Resolve the input handles a node card should render (e.g. Merge Input 1/2,
2964
+ * Compare Datasets A/B). Defaults to the single "target" handle.
2965
+ * `registryNodeData` is used for a bare node only, as in resolveOutputHandles.
2966
+ *
2967
+ * BOFF-9738: a node whose inputs are numbered by a setting (Merge "Number of
2968
+ * inputs") draws one handle per input, `input-1` … `input-N`.
2969
+ */
2970
+ function resolveInputHandles(data, registryNodeData, options = {}) {
2971
+ const dynamic = dynamicInputHandlesOf(data, registryNodeData, options.nodeType);
2972
+ if (dynamic) {
2973
+ let count = configuredInputCount(dynamic, data);
2974
+ for (const handle of options.connectedHandles ?? []) {
2975
+ const input = inputNumberOfHandle(dynamic, handle);
2976
+ if (input !== void 0 && input <= dynamic.max) count = Math.max(count, input);
2977
+ }
2978
+ return Array.from({ length: count }, (_, index) => ({
2979
+ id: `${dynamic.idPrefix}${index + 1}`,
2980
+ label: `${dynamic.labelPrefix}${index + 1}`
2981
+ }));
2982
+ }
2983
+ const nodeData = handleManifestOf(data, registryNodeData);
2984
+ const spec = nodeData?.inputHandles ?? nodeData?.operations?.inputHandles;
2985
+ if (!Array.isArray(spec) || spec.length === 0) return DEFAULT_INPUT_HANDLES;
2986
+ return spec;
2987
+ }
2988
+ /**
2989
+ * The ids a node's one plain output has been saved under. `source` is the
2990
+ * card's default handle: a node with no handle spec draws it, and every bare
2991
+ * node drew it before BOFF-11434. `output` is the id the registry manifests
2992
+ * give a single-output node (Code, HTTP Request, Set, ...). A workflow carries
2993
+ * edges saved under either id, depending on which handle its source card drew
2994
+ * when the edge was made; on a node with one plain output both name that
2995
+ * output.
2996
+ */
2997
+ const PLAIN_OUTPUT_IDS = /* @__PURE__ */ new Set(["source", "output"]);
2998
+ /**
2999
+ * The port a stored edge leaves its source card from, given the ids of the
3000
+ * card's source ports in render order, or null when the card has no port for
3001
+ * it (React Flow then does not draw the edge):
3002
+ * - no stored id: the first port, as React Flow picks it;
3003
+ * - a stored id the card has: that port;
3004
+ * - a plain output id (`source` / `output`) the card lacks: the card's one
3005
+ * plain output, when it has exactly one;
3006
+ * - any other id: none.
3007
+ */
3008
+ function landingSourceHandle(portIds, stored) {
3009
+ if (!stored) return portIds[0] ?? null;
3010
+ if (portIds.includes(stored)) return stored;
3011
+ if (!PLAIN_OUTPUT_IDS.has(stored)) return null;
3012
+ const plain = portIds.filter((id) => PLAIN_OUTPUT_IDS.has(id));
3013
+ return plain.length === 1 ? plain[0] : null;
3014
+ }
3015
+ /**
3016
+ * The edges as a canvas hands them to React Flow: an edge saved under one
3017
+ * plain output id whose source card draws the other (see `PLAIN_OUTPUT_IDS`)
3018
+ * is given the id the card has, so it is drawn instead of dropped. Display
3019
+ * only: the stored edges are not changed, so opening a workflow does not mark
3020
+ * it unsaved. Returns `edges` itself when no edge needed it.
3021
+ *
3022
+ * `sourcePortIds` returns a node's source port ids (its output handles, then
3023
+ * its adapter ports), or undefined for a node the canvas does not have.
3024
+ */
3025
+ function alignPlainOutputEdges(edges, sourcePortIds) {
3026
+ let changed = false;
3027
+ const aligned = edges.map((edge) => {
3028
+ const stored = edge.sourceHandle;
3029
+ if (!stored || !PLAIN_OUTPUT_IDS.has(stored)) return edge;
3030
+ const ports = sourcePortIds(edge.source);
3031
+ if (!ports) return edge;
3032
+ const landing = landingSourceHandle(ports, stored);
3033
+ if (!landing || landing === stored) return edge;
3034
+ changed = true;
3035
+ return {
3036
+ ...edge,
3037
+ sourceHandle: landing
3038
+ };
3039
+ });
3040
+ return changed ? aligned : edges;
3041
+ }
3042
+ /**
3043
+ * Extra vertical room (px) the card body needs so multi-handle rows don't
3044
+ * crowd the header/body content. Zero for the standard 1-2 handle cards.
3045
+ */
3046
+ function outputHandlesSpacerHeight(count) {
3047
+ return count > 2 ? (count - 2) * 26 : 0;
3048
+ }
3049
+ /**
3050
+ * BOFF-9738: the highest connected input that setting `field` to `value`
3051
+ * would remove from the card, or undefined when the change removes none (or
3052
+ * `field` is not the node's number-of-inputs setting). The builder refuses
3053
+ * such a change, so lowering the number of inputs never drops an edge.
3054
+ */
3055
+ function connectedInputDroppedBy(spec, connectedHandles, field, value) {
3056
+ if (!spec || field !== spec.fromCount) return void 0;
3057
+ const count = clampInputCount(spec, value);
3058
+ let highest;
3059
+ for (const handle of connectedHandles) {
3060
+ const input = inputNumberOfHandle(spec, handle);
3061
+ if (input !== void 0 && input > count) highest = Math.max(highest ?? input, input);
3062
+ }
3063
+ return highest;
3064
+ }
3065
+
3066
+ // src/builder/components/flow-builder/components/blocks/nodes/node/output-handles.tsx
3067
+ /** Tones map to the same accent language the redesigned card uses. */
3068
+ const TONE_COLORS = {
3069
+ success: "var(--color-status-success-text)",
3070
+ error: "var(--color-status-error-text)",
3071
+ warning: "var(--color-status-warning-text)",
3072
+ info: "var(--color-status-info-text)",
3073
+ neutral: "var(--color-text-muted)"
3074
+ };
3075
+ /**
3076
+ * n8n-style "+" stub rendered after an output handle that has no outgoing
3077
+ * connection yet: a short dashed connector ending in a round + button.
3078
+ * Clicking it arms attach mode (flow-store `pendingConnection`) and opens the
3079
+ * Node Store panel — picking an operation there creates the node and wires it
3080
+ * to this exact handle. Dragging from it draws a connection exactly like
3081
+ * dragging from the round handle (BOFF-17926, see `handle-plus-drag.ts`).
3082
+ * Connected handles render nothing (n8n parity).
3083
+ *
3084
+ * `anchor="card"` positions relative to the node card (single centered
3085
+ * handle); `anchor="point"` positions relative to the zero-size per-handle
3086
+ * wrapper used by multi-output cards.
3087
+ */
3088
+ function HandlePlusStub({ nodeId, handleId, color, isConnectable, isOnlyHandle, anchor }) {
3089
+ const tr = useTr();
3090
+ const startAttach = useFlowStore((s) => s.actions.pendingConnection.start);
3091
+ const plusPress = usePlusPress(nodeId, handleId, () => startAttach({
3092
+ nodeId,
3093
+ handleId
3094
+ }));
3095
+ const isArmedHere = useFlowStore((s) => s.workflow.pendingConnection?.nodeId === nodeId && s.workflow.pendingConnection?.handleId === handleId);
3096
+ if (useStore((s) => s.edges.some((e) => e.source === nodeId && (e.sourceHandle === handleId || isOnlyHandle && (e.sourceHandle === null || e.sourceHandle === void 0)))) || isConnectable === false) return null;
3097
+ return /* @__PURE__ */ jsxs("div", {
3098
+ className: "nodrag nopan absolute flex items-center",
3099
+ style: {
3100
+ ...anchor === "card" ? {
3101
+ left: "100%",
3102
+ top: "50%",
3103
+ transform: "translateY(-50%)",
3104
+ marginLeft: 10
3105
+ } : {
3106
+ left: 10,
3107
+ top: 0,
3108
+ transform: "translateY(-50%)"
3109
+ },
3110
+ pointerEvents: "none",
3111
+ zIndex: 5
3112
+ },
3113
+ children: [/* @__PURE__ */ jsx("div", { style: {
3114
+ width: 16,
3115
+ borderTop: `1.5px dashed ${color}`,
3116
+ opacity: .5
3117
+ } }), /* @__PURE__ */ jsx("button", {
3118
+ type: "button",
3119
+ title: tr("fluidgrids.builder.outputHandles.addNextNodeTooltip", "Add next node"),
3120
+ "aria-label": `Add next node from ${handleId}`,
3121
+ "data-testid": `handle-plus-${nodeId}-${handleId}`,
3122
+ onClick: plusPress.onClick,
3123
+ onDoubleClick: (e) => e.stopPropagation(),
3124
+ onMouseDown: plusPress.onMouseDown,
3125
+ onTouchStart: plusPress.onTouchStart,
3126
+ className: "group/plus flex size-4 shrink-0 cursor-pointer items-center justify-center rounded-full [@media(pointer:coarse)]:-m-2 [@media(pointer:coarse)]:size-8",
3127
+ style: { pointerEvents: "all" },
3128
+ children: /* @__PURE__ */ jsx("span", {
3129
+ "aria-hidden": "true",
3130
+ className: "flex size-4 items-center justify-center rounded-full transition-transform group-hover/plus:scale-110",
3131
+ style: {
3132
+ border: `1.5px solid ${color}`,
3133
+ background: isArmedHere ? color : "var(--color-node-bg)",
3134
+ color: isArmedHere ? "var(--color-node-bg)" : color,
3135
+ boxShadow: isArmedHere ? `0 0 0 3px color-mix(in srgb, ${color} 22%, transparent)` : `0 0 0 2px color-mix(in srgb, ${color} 10%, transparent)`,
3136
+ transition: "transform .12s ease, background .12s ease, color .12s ease"
3137
+ },
3138
+ children: /* @__PURE__ */ jsx(Icon, {
3139
+ icon: "mdi:plus",
3140
+ className: "size-2.5"
3141
+ })
3142
+ })
3143
+ })]
3144
+ });
3145
+ }
3146
+ /**
3147
+ * Right-edge output handles for the node card.
3148
+ *
3149
+ * A single-handle spec renders exactly like the legacy card (one centered
3150
+ * unlabeled port). Multi-handle specs render n8n-style: evenly distributed
3151
+ * ports on the right edge, each with a small tone-colored label inside the
3152
+ * card. Handle geometry is re-measured whenever the resolved set changes
3153
+ * (e.g. Switch cases edited in the NDV).
3154
+ */
3155
+ function OutputHandles({ nodeId, handles, accent, isConnectable }) {
3156
+ const updateNodeInternals = useUpdateNodeInternals();
3157
+ const signature = useMemo(() => handles.map((h) => h.id).join("|"), [handles]);
3158
+ useEffect(() => {
3159
+ updateNodeInternals(nodeId);
3160
+ }, [
3161
+ nodeId,
3162
+ signature,
3163
+ updateNodeInternals
3164
+ ]);
3165
+ if (handles.length === 1) {
3166
+ const handle = handles[0];
3167
+ const color = handle.tone ? TONE_COLORS[handle.tone] : accent;
3168
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(CustomHandle, {
3169
+ type: "source",
3170
+ id: handle.id,
3171
+ position: Position.Right,
3172
+ isConnectable,
3173
+ accent: color
3174
+ }), /* @__PURE__ */ jsx(HandlePlusStub, {
3175
+ nodeId,
3176
+ handleId: handle.id,
3177
+ color,
3178
+ isConnectable,
3179
+ isOnlyHandle: true,
3180
+ anchor: "card"
3181
+ })] });
3182
+ }
3183
+ const total = handles.length;
3184
+ return /* @__PURE__ */ jsx(Fragment$1, { children: handles.map((handle, index) => {
3185
+ const top = `${(index + 1) / (total + 1) * 100}%`;
3186
+ const color = handle.tone ? TONE_COLORS[handle.tone] : accent;
3187
+ return /* @__PURE__ */ jsxs("div", {
3188
+ className: "absolute right-0",
3189
+ style: {
3190
+ top,
3191
+ transform: "translateY(-50%)"
3192
+ },
3193
+ children: [
3194
+ /* @__PURE__ */ jsx(CustomHandle, {
3195
+ type: "source",
3196
+ id: handle.id,
3197
+ position: Position.Right,
3198
+ isConnectable,
3199
+ accent: color
3200
+ }),
3201
+ handle.label && /* @__PURE__ */ jsx("span", {
3202
+ className: "pointer-events-none absolute whitespace-nowrap text-[10px] font-medium leading-none",
3203
+ style: {
3204
+ color,
3205
+ left: 12,
3206
+ bottom: 8
3207
+ },
3208
+ title: handle.label,
3209
+ children: handle.label
3210
+ }),
3211
+ /* @__PURE__ */ jsx(HandlePlusStub, {
3212
+ nodeId,
3213
+ handleId: handle.id,
3214
+ color,
3215
+ isConnectable,
3216
+ isOnlyHandle: false,
3217
+ anchor: "point"
3218
+ })
3219
+ ]
3220
+ }, handle.id);
3221
+ }) });
3222
+ }
3223
+ /**
3224
+ * Left-edge input handles, mirroring OutputHandles: single specs render as
3225
+ * the classic centered target; multi-input specs distribute down the left
3226
+ * edge with n8n-style labels OUTSIDE the card.
3227
+ */
3228
+ function InputHandles({ nodeId, handles, accent, isConnectable }) {
3229
+ const updateNodeInternals = useUpdateNodeInternals();
3230
+ const signature = useMemo(() => handles.map((h) => h.id).join("|"), [handles]);
3231
+ useEffect(() => {
3232
+ updateNodeInternals(nodeId);
3233
+ }, [
3234
+ nodeId,
3235
+ signature,
3236
+ updateNodeInternals
3237
+ ]);
3238
+ if (handles.length === 1) {
3239
+ const handle = handles[0];
3240
+ return /* @__PURE__ */ jsx(CustomHandle, {
3241
+ type: "target",
3242
+ id: handle.id,
3243
+ position: Position.Left,
3244
+ isConnectable,
3245
+ accent: handle.tone ? TONE_COLORS[handle.tone] : accent
3246
+ });
3247
+ }
3248
+ const total = handles.length;
3249
+ return /* @__PURE__ */ jsx(Fragment$1, { children: handles.map((handle, index) => {
3250
+ const top = `${(index + 1) / (total + 1) * 100}%`;
3251
+ const color = handle.tone ? TONE_COLORS[handle.tone] : accent;
3252
+ return /* @__PURE__ */ jsxs("div", {
3253
+ className: "absolute left-0",
3254
+ style: {
3255
+ top,
3256
+ transform: "translateY(-50%)"
3257
+ },
3258
+ children: [/* @__PURE__ */ jsx(CustomHandle, {
3259
+ type: "target",
3260
+ id: handle.id,
3261
+ position: Position.Left,
3262
+ isConnectable,
3263
+ accent: color
3264
+ }), handle.label && /* @__PURE__ */ jsx("span", {
3265
+ className: "pointer-events-none absolute whitespace-nowrap text-[10px] font-medium leading-none",
3266
+ style: {
3267
+ color,
3268
+ right: "100%",
3269
+ marginRight: 16,
3270
+ top: "50%",
3271
+ transform: "translateY(-50%)"
3272
+ },
3273
+ title: handle.label,
3274
+ children: handle.label
3275
+ })]
3276
+ }, handle.id);
3277
+ }) });
3278
+ }
3279
+
3280
+ // src/builder/components/flow-builder/components/blocks/nodes/node/logic-node-card.tsx
3281
+ /**
3282
+ * Compact n8n-style card for internal control-flow nodes (IF, Switch, Merge,
3283
+ * Loop, Compare Datasets, …).
3284
+ *
3285
+ * App/action nodes keep the rich card (brand header, operation, description);
3286
+ * logic nodes read better as small squares whose whole story is their labeled
3287
+ * output handles — rendered OUTSIDE the right edge, n8n-style, so they never
3288
+ * collide with the card content. Height grows with the handle count.
3289
+ *
3290
+ * Like the app card, it ends in the status line (BOFF-17997), so a branch
3291
+ * that ran says how it went on the card.
3292
+ */
3293
+ function LogicNodeCard({ title, subtitle, icon, accent, selected, status, onStatusAction, isTrigger, isExecuting, nodeId, inputHandles, outputHandles, isConnectable, onClick, onDoubleClick, onSettings, onExecute, onDelete, infoButton, disabled = false, onToggleDisabled, onAskAi, isRenaming = false, onStartRename, onCommitRename, onCancelRename }) {
3294
+ const minHeight = Math.max(64, Math.max(outputHandles.length, inputHandles.length) * 30 + 24);
3295
+ return /* @__PURE__ */ jsxs(NodeCard, {
3296
+ className: "w-48",
3297
+ "data-selected": selected,
3298
+ selected,
3299
+ onClick,
3300
+ onDoubleClick,
3301
+ statusTone: status?.tone ?? null,
3302
+ isTrigger,
3303
+ accent,
3304
+ isExecuting,
3305
+ onSettings,
3306
+ onExecute,
3307
+ onDelete,
3308
+ infoButton,
3309
+ disabled,
3310
+ onToggleDisabled,
3311
+ onAskAi,
3312
+ children: [
3313
+ /* @__PURE__ */ jsxs("div", {
3314
+ className: "flex flex-col items-center justify-center gap-1 px-3 py-3 text-center",
3315
+ style: {
3316
+ minHeight,
3317
+ ...disabled ? {
3318
+ opacity: .55,
3319
+ filter: "saturate(0.4)"
3320
+ } : {}
3321
+ },
3322
+ children: [
3323
+ /* @__PURE__ */ jsx("div", {
3324
+ className: "flex size-9 items-center justify-center rounded-lg bg-muted",
3325
+ children: /* @__PURE__ */ jsx(Icon, {
3326
+ icon,
3327
+ className: "size-5",
3328
+ style: { color: accent }
3329
+ })
3330
+ }),
3331
+ onStartRename && onCommitRename && onCancelRename ? /* @__PURE__ */ jsx(InlineEditableLabel, {
3332
+ value: title,
3333
+ placeholder: title,
3334
+ editing: isRenaming,
3335
+ onStartEdit: onStartRename,
3336
+ onCommit: onCommitRename,
3337
+ onCancel: onCancelRename,
3338
+ className: "max-w-full truncate text-sm font-semibold leading-tight",
3339
+ inputClassName: "text-sm font-semibold text-center"
3340
+ }) : /* @__PURE__ */ jsx("span", {
3341
+ className: "max-w-full truncate text-sm font-semibold leading-tight",
3342
+ children: title
3343
+ }),
3344
+ subtitle && /* @__PURE__ */ jsx("span", {
3345
+ className: "max-w-full truncate font-mono text-[10px] text-muted-foreground",
3346
+ title: subtitle,
3347
+ children: subtitle
3348
+ })
3349
+ ]
3350
+ }),
3351
+ status && /* @__PURE__ */ jsx(NodeCardStatusLine, {
3352
+ status,
3353
+ appName: title,
3354
+ onAction: onStatusAction
3355
+ }),
3356
+ /* @__PURE__ */ jsx(InputHandles, {
3357
+ nodeId,
3358
+ handles: inputHandles,
3359
+ accent,
3360
+ isConnectable
3361
+ }),
3362
+ /* @__PURE__ */ jsx(OutputHandles, {
3363
+ nodeId,
3364
+ handles: outputHandles,
3365
+ accent,
3366
+ isConnectable
3367
+ })
3368
+ ]
3369
+ });
3370
+ }
3371
+
3372
+ // src/builder/components/code-workflow/code-workflow-state.ts
3373
+ /**
3374
+ * Pure helpers behind the code-workflow node's card, Source, Trace and
3375
+ * Interface panels (BOFF-9905, spec code-first 01 §3 and 07 §5).
3376
+ */
3377
+ const CODE_WORKFLOW_NODE_TYPE = "internal:code-workflow";
3378
+ const WAIT_FOR_SIGNAL_NODE_TYPE = "internal:wait-for-signal";
3379
+ function isRecord$1(value) {
3380
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3381
+ }
3382
+ function str(value) {
3383
+ return typeof value === "string" && value.trim() ? value : void 0;
3384
+ }
3385
+ /** The code-workflow node's `args.state`, with the spec defaults applied. */
3386
+ function readCodeWorkflowState(state) {
3387
+ const s = isRecord$1(state) ? state : {};
3388
+ const waitForCompletion = s.waitForCompletion !== false;
3389
+ const policy = s.parentClosePolicy;
3390
+ return {
3391
+ workflowFn: str(s.workflowFn),
3392
+ taskQueue: str(s.taskQueue) ?? "managed",
3393
+ waitForCompletion,
3394
+ parentClosePolicy: policy === "TERMINATE" || policy === "ABANDON" || policy === "REQUEST_CANCEL" ? policy : waitForCompletion ? "TERMINATE" : "ABANDON",
3395
+ timeout: typeof s.timeout === "number" && s.timeout > 0 ? s.timeout : 0
3396
+ };
3397
+ }
3398
+ /** The `signalName` a wait-for-signal node waits for, if set. */
3399
+ function readSignalName(state) {
3400
+ return isRecord$1(state) ? str(state.signalName) : void 0;
3401
+ }
3402
+ function typeLabel(schema) {
3403
+ if (!isRecord$1(schema)) return "any";
3404
+ if (Array.isArray(schema.enum)) return schema.enum.map(String).join(" | ");
3405
+ if (Array.isArray(schema.type)) return schema.type.map(String).join(" | ");
3406
+ if (schema.type === "array") return `${typeLabel(schema.items)}[]`;
3407
+ return typeof schema.type === "string" ? schema.type : "any";
3408
+ }
3409
+ /** Top-level properties of an object schema (the card's inputs and outputs). */
3410
+ function interfaceFields(schema) {
3411
+ if (!isRecord$1(schema) || !isRecord$1(schema.properties)) return [];
3412
+ const required = new Set(Array.isArray(schema.required) ? schema.required.map(String) : []);
3413
+ return Object.entries(schema.properties).map(([name, property]) => ({
3414
+ name,
3415
+ type: typeLabel(property),
3416
+ required: required.has(name),
3417
+ description: isRecord$1(property) ? str(property.description) : void 0
3418
+ }));
3419
+ }
3420
+ /** Names of the signals, queries and updates an interface declares. */
3421
+ function interfaceHandlers(iface) {
3422
+ const of = (key) => isRecord$1(iface) && isRecord$1(iface[key]) ? Object.keys(iface[key]).sort() : [];
3423
+ return {
3424
+ signals: of("signals"),
3425
+ queries: of("queries"),
3426
+ updates: of("updates")
3427
+ };
3428
+ }
3429
+ /**
3430
+ * The child run a code-workflow node started in a run: the node state's
3431
+ * `childRunId`, else the `_childRunId` of its parked output. The latest state
3432
+ * of the node wins (a loop runs it more than once).
3433
+ */
3434
+ function childRunIdOf(nodeStates, nodeId) {
3435
+ const states = nodeStates.filter((state) => state.nodeId === nodeId);
3436
+ for (let i = states.length - 1; i >= 0; i -= 1) {
3437
+ const state = states[i];
3438
+ const fromColumn = str(state.childRunId);
3439
+ if (fromColumn) return fromColumn;
3440
+ if (isRecord$1(state.output)) {
3441
+ const fromOutput = str(state.output._childRunId);
3442
+ if (fromOutput) return fromOutput;
3443
+ }
3444
+ }
3445
+ }
3446
+ function sourceLanguageOf(path) {
3447
+ if (/\.(ts|tsx|mts|cts)$/.test(path)) return "typescript";
3448
+ if (/\.py$/.test(path)) return "python";
3449
+ if (/\.json$/.test(path)) return "json";
3450
+ return "text";
3451
+ }
3452
+ /**
3453
+ * Whether the browser may edit a file: TypeScript and JSON project files.
3454
+ * Python files only with `python` (Phase C, fluidgrids.python-durable-functions
3455
+ * on: the service builds them on a Python build VM); vendored packages
3456
+ * (`_vendor/`) and the generated node clients, which every build rewrites,
3457
+ * never.
3458
+ */
3459
+ function isEditableSourcePath(path, { python = false } = {}) {
3460
+ if (path.startsWith(".fluidgrids/")) return false;
3461
+ const language = sourceLanguageOf(path);
3462
+ if (language === "python") return python && !path.startsWith("_vendor/") && !path.includes("/_vendor/");
3463
+ return language === "typescript" || language === "json";
3464
+ }
3465
+ /** The project's language: Python when any workflow module is Python. */
3466
+ function projectLanguage(files) {
3467
+ return files.some((file) => file.path.startsWith("workflows/") && file.path.endsWith(".py")) ? "python" : "typescript";
3468
+ }
3469
+ /** Files whose content differs from what was loaded, in path order. */
3470
+ function changedSourceFiles(loaded, current) {
3471
+ return loaded.filter((file) => {
3472
+ const now = current[file.path];
3473
+ return now !== void 0 && now !== file.content;
3474
+ }).map((file) => ({
3475
+ path: file.path,
3476
+ content: current[file.path]
3477
+ })).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
3478
+ }
3479
+ /** The entry module to open first: the workflow file, else the first file. */
3480
+ function defaultSourcePath(files, entry, options = {}) {
3481
+ if (entry && files.some((file) => file.path === entry)) return entry;
3482
+ return files.find((file) => file.path.startsWith("workflows/") && isEditableSourcePath(file.path, options))?.path ?? files[0]?.path;
3483
+ }
3484
+ /**
3485
+ * Splits the build's diagnostics per file. A diagnostic without a path (a
3486
+ * project-level error such as an export mismatch) is listed under `""`.
3487
+ */
3488
+ function diagnosticsByPath(diagnostics) {
3489
+ const result = /* @__PURE__ */ new Map();
3490
+ for (const diagnostic of diagnostics) {
3491
+ const path = diagnostic.path?.replace(/^\.\//, "") ?? "";
3492
+ const list = result.get(path) ?? [];
3493
+ list.push({
3494
+ line: diagnostic.line,
3495
+ column: diagnostic.column,
3496
+ severity: editorSeverity(diagnostic.severity),
3497
+ code: diagnostic.code,
3498
+ message: diagnostic.message
3499
+ });
3500
+ result.set(path, list);
3501
+ }
3502
+ return result;
3503
+ }
3504
+
3505
+ // src/builder/lib/node-operation-selection.ts
3506
+ function resolveOperationName(selectedOperation, fallback) {
3507
+ return typeof selectedOperation === "string" && selectedOperation.trim() ? selectedOperation : fallback;
3508
+ }
3509
+ function isRecord(value) {
3510
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3511
+ }
3512
+ function readRecord(value) {
3513
+ return isRecord(value) ? value : void 0;
3514
+ }
3515
+ function readOperations(value) {
3516
+ const operations = Array.isArray(value) ? value : readRecord(value)?.operations;
3517
+ return Array.isArray(operations) ? operations : [];
3518
+ }
3519
+ function synchronizeOperationUpdate(currentData, updates, registeredOperations) {
3520
+ const operationName = resolveOperationName(updates.operation_name, "");
3521
+ if (!operationName || operationName === currentData.operation_name) return updates;
3522
+ const manifest = readRecord(updates.nodeData ?? currentData.nodeData);
3523
+ const selected = readRecord([...readOperations(manifest?.operations), ...readOperations(registeredOperations)].find((operation) => readRecord(operation)?.name === operationName));
3524
+ return {
3525
+ ...updates,
3526
+ operation_type: typeof selected?.type === "string" ? selected.type : updates.operation_type,
3527
+ nodeData: {
3528
+ ...manifest,
3529
+ operations: selected ? [selected] : []
3530
+ }
3531
+ };
3532
+ }
3533
+
3534
+ export { vectorStoreCollectionKey as $, NodeCard as A, zapConnectTarget as B, landingSourceHandle as C, resolveOutputHandles as D, resolveInputHandles as E, operationInPlainWords as F, resetVectorStoreClearConfirm as G, CONNECT_FX_STYLES as H, connectionRadiusForZoom as I, formatVectorStoreExpiry as J, resolveVectorStoreClear as K, fxScaleForZoom as L, nodeAccent as M, nodeCardStatus as N, NodeCardStatusLine as O, nodeCardStatusActionHandler as P, vectorStoreClearTarget as Q, fxScaleStyle as R, hasNodeManifest as S, outputHandlesSpacerHeight as T, useFlowStore as U, CONNECT_FX_CLASS as V, confirmVectorStoreClear as W, readVectorStoreMemoryConfig as X, isVectorStoreMemoryNodeType as Y, selectVectorStoreStatsForNode as Z, InputHandles as _, changedSourceFiles as a, diffCanvas as at, connectedInputDroppedBy as b, diagnosticsByPath as c, isEditableSourcePath as d, vectorStoreOperationLabel as et, projectLanguage as f, LogicNodeCard as g, sourceLanguageOf as h, WAIT_FOR_SIGNAL_NODE_TYPE as i, applyToShape as it, NodeCardHeader as j, NODE_CARD_STYLES as k, interfaceFields as l, readSignalName as m, synchronizeOperationUpdate as n, vectorStoreScopeShortLabel as nt, childRunIdOf as o, parseChanges as ot, readCodeWorkflowState as p, useVectorStoreClearConfirmStore as q, CODE_WORKFLOW_NODE_TYPE as r, useIsValidConnection as rt, defaultSourcePath as s, withoutPendingConflicts as st, resolveOperationName as t, vectorStoreScopeLabel as tt, interfaceHandlers as u, OutputHandles as v, nodeAdaptersOf as w, dynamicInputHandlesOf as x, alignPlainOutputEdges as y, resetConnectZap as z };