@flowdrop/flowdrop 2.15.2 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/CHANGELOG.md +140 -0
  2. package/README.md +10 -1
  3. package/dist/components/App.svelte +219 -6
  4. package/dist/components/App.svelte.d.ts +8 -0
  5. package/dist/components/CanvasToolbar.svelte +40 -3
  6. package/dist/components/CanvasToolbar.svelte.d.ts +5 -1
  7. package/dist/components/ConnectPortPicker.svelte +8 -4
  8. package/dist/components/DoctorMenu.svelte +208 -126
  9. package/dist/components/ImpactConfirm.svelte +341 -0
  10. package/dist/components/ImpactConfirm.svelte.d.ts +12 -0
  11. package/dist/components/Input.svelte +2 -2
  12. package/dist/components/Navbar.svelte +48 -3
  13. package/dist/components/Navbar.svelte.d.ts +4 -0
  14. package/dist/components/NodeSidebar.svelte +36 -15
  15. package/dist/components/NodeSidebar.svelte.d.ts +2 -0
  16. package/dist/components/NodeSwapPicker.svelte +4 -14
  17. package/dist/components/RunBar.svelte +36 -1
  18. package/dist/components/RunBar.svelte.d.ts +5 -0
  19. package/dist/components/RunInputsDialog.svelte +198 -0
  20. package/dist/components/RunInputsDialog.svelte.d.ts +34 -0
  21. package/dist/components/SchemaForm.svelte +2 -1
  22. package/dist/components/SchemaForm.svelte.d.ts +2 -1
  23. package/dist/components/WorkflowCompareDialog.svelte +177 -0
  24. package/dist/components/WorkflowCompareDialog.svelte.d.ts +10 -0
  25. package/dist/components/WorkflowEditor.svelte +88 -6
  26. package/dist/components/WorkflowEditor.svelte.d.ts +6 -0
  27. package/dist/components/WorkflowInterfaceEditor.svelte +14 -4
  28. package/dist/components/WorkflowInterfaceEntryCard.svelte +19 -3
  29. package/dist/components/WorkflowInterfaceEntryCard.svelte.d.ts +2 -0
  30. package/dist/components/form/FormAutocomplete.svelte +76 -12
  31. package/dist/components/nodes/NodeCard.svelte +2 -2
  32. package/dist/components/primitives/Button.svelte +1 -1
  33. package/dist/components/primitives/Button.svelte.d.ts +1 -1
  34. package/dist/components/primitives/Card.svelte +1 -1
  35. package/dist/components/primitives/Card.svelte.d.ts +1 -1
  36. package/dist/components/primitives/Checkbox.svelte +1 -1
  37. package/dist/components/primitives/Checkbox.svelte.d.ts +1 -1
  38. package/dist/components/primitives/Chip.svelte +1 -1
  39. package/dist/components/primitives/Chip.svelte.d.ts +1 -1
  40. package/dist/components/primitives/Combobox.svelte +1 -1
  41. package/dist/components/primitives/Combobox.svelte.d.ts +1 -1
  42. package/dist/components/primitives/Composer.svelte +1 -1
  43. package/dist/components/primitives/Composer.svelte.d.ts +1 -1
  44. package/dist/components/primitives/EmptyState.svelte +1 -1
  45. package/dist/components/primitives/EmptyState.svelte.d.ts +1 -1
  46. package/dist/components/primitives/Field.svelte +1 -1
  47. package/dist/components/primitives/Field.svelte.d.ts +1 -1
  48. package/dist/components/primitives/IconButton.svelte +1 -1
  49. package/dist/components/primitives/IconButton.svelte.d.ts +1 -1
  50. package/dist/components/primitives/Menu.svelte +1 -1
  51. package/dist/components/primitives/Menu.svelte.d.ts +1 -1
  52. package/dist/components/primitives/Notice.svelte +1 -1
  53. package/dist/components/primitives/Notice.svelte.d.ts +1 -1
  54. package/dist/components/primitives/PanelHeader.svelte +1 -1
  55. package/dist/components/primitives/PanelHeader.svelte.d.ts +1 -1
  56. package/dist/components/primitives/Segmented.svelte +2 -2
  57. package/dist/components/primitives/Segmented.svelte.d.ts +2 -2
  58. package/dist/components/primitives/Select.svelte +1 -1
  59. package/dist/components/primitives/Select.svelte.d.ts +1 -1
  60. package/dist/components/primitives/StatusPill.svelte +1 -1
  61. package/dist/components/primitives/StatusPill.svelte.d.ts +1 -1
  62. package/dist/components/primitives/Switch.svelte +1 -1
  63. package/dist/components/primitives/Switch.svelte.d.ts +1 -1
  64. package/dist/components/primitives/Tabs.svelte +2 -2
  65. package/dist/components/primitives/Tabs.svelte.d.ts +2 -2
  66. package/dist/components/primitives/Toolbar.svelte +1 -1
  67. package/dist/components/primitives/Toolbar.svelte.d.ts +1 -1
  68. package/dist/components/primitives/ToolbarSeparator.svelte +1 -1
  69. package/dist/components/primitives/ToolbarSeparator.svelte.d.ts +1 -1
  70. package/dist/components/toast/DismissibleToast.svelte +25 -6
  71. package/dist/components/toast/DismissibleToast.svelte.d.ts +3 -0
  72. package/dist/config/endpoints.d.ts +7 -0
  73. package/dist/config/endpoints.js +2 -1
  74. package/dist/editor/connectCandidates.d.ts +3 -0
  75. package/dist/editor/connectCandidates.js +14 -5
  76. package/dist/editor/index.d.ts +1 -1
  77. package/dist/editor/index.js +1 -1
  78. package/dist/helpers/workflowEditorHelper.d.ts +15 -0
  79. package/dist/helpers/workflowEditorHelper.js +9 -0
  80. package/dist/index.d.ts +1 -0
  81. package/dist/messages/defaults.d.ts +101 -0
  82. package/dist/messages/defaults.js +92 -1
  83. package/dist/openapi/v1/openapi.yaml +10 -2
  84. package/dist/schemas/v1/workflow.schema.json +1 -1
  85. package/dist/services/draftStorage.d.ts +24 -10
  86. package/dist/services/draftStorage.js +60 -35
  87. package/dist/services/globalSave.d.ts +28 -10
  88. package/dist/services/globalSave.js +135 -31
  89. package/dist/services/impactGate.d.ts +34 -0
  90. package/dist/services/impactGate.js +70 -0
  91. package/dist/services/impactService.d.ts +28 -0
  92. package/dist/services/impactService.js +71 -0
  93. package/dist/services/toastQueue.d.ts +9 -0
  94. package/dist/services/toastService.d.ts +4 -0
  95. package/dist/services/toastService.js +9 -3
  96. package/dist/services/workflowLaunchService.js +3 -1
  97. package/dist/settings/index.d.ts +2 -2
  98. package/dist/settings/index.js +1 -1
  99. package/dist/stores/doctorStore.svelte.d.ts +24 -1
  100. package/dist/stores/doctorStore.svelte.js +105 -2
  101. package/dist/stores/instanceContainer.svelte.d.ts +16 -0
  102. package/dist/stores/instanceContainer.svelte.js +22 -2
  103. package/dist/stores/saveConflictStore.svelte.d.ts +62 -0
  104. package/dist/stores/saveConflictStore.svelte.js +169 -0
  105. package/dist/stores/workflowStore.svelte.d.ts +7 -3
  106. package/dist/stores/workflowStore.svelte.js +14 -5
  107. package/dist/styles/toast.css +10 -1
  108. package/dist/svelte-app.d.ts +23 -0
  109. package/dist/svelte-app.js +114 -3
  110. package/dist/themes/scopedSkinCss.d.ts +22 -0
  111. package/dist/themes/scopedSkinCss.js +27 -1
  112. package/dist/types/doctor.d.ts +3 -1
  113. package/dist/types/events.d.ts +20 -0
  114. package/dist/types/events.js +2 -0
  115. package/dist/types/impact.d.ts +25 -0
  116. package/dist/types/impact.js +7 -0
  117. package/dist/types/index.d.ts +11 -1
  118. package/dist/types/settings.d.ts +31 -0
  119. package/dist/types/settings.js +132 -0
  120. package/dist/ui/index.d.ts +76 -0
  121. package/dist/ui/index.js +81 -0
  122. package/dist/utils/apiUrl.d.ts +55 -0
  123. package/dist/utils/apiUrl.js +117 -0
  124. package/dist/utils/draftRestore.d.ts +27 -0
  125. package/dist/utils/draftRestore.js +36 -0
  126. package/dist/utils/interfaceTags.js +4 -1
  127. package/dist/utils/nodeSearch.d.ts +10 -0
  128. package/dist/utils/nodeSearch.js +37 -0
  129. package/dist/utils/portal.js +45 -3
  130. package/dist/utils/runOffer.d.ts +21 -0
  131. package/dist/utils/runOffer.js +13 -0
  132. package/dist/utils/workflowCompare.d.ts +35 -0
  133. package/dist/utils/workflowCompare.js +84 -0
  134. package/dist/utils/workflowInterface.d.ts +26 -1
  135. package/dist/utils/workflowInterface.js +91 -11
  136. package/dist/webmcp/index.d.ts +5 -0
  137. package/dist/webmcp/index.js +5 -0
  138. package/package.json +8 -2
@@ -15,7 +15,10 @@ import { DEFAULT_WORKFLOW_FORMAT } from '../types/index.js';
15
15
  import { stripExecutionInfo } from '../utils/nodeStatus.js';
16
16
  import { playgroundForSave } from '../utils/playgroundChat.js';
17
17
  import { buildSaveBody } from '../utils/workflowDraft.js';
18
- import { apiToasts, workflowToasts, dismissToast } from './toastService.js';
18
+ import { apiToasts, workflowToasts, dismissToast, showInfo } from './toastService.js';
19
+ import { checkImpact, impactSupported } from './impactService.js';
20
+ import { confirmImpact, impactPending } from './impactGate.js';
21
+ import { scopeSelector } from '../themes/scopedSkinCss.js';
19
22
  import { DEFAULT_FEATURES } from '../types/events.js';
20
23
  // ---------------------------------------------------------------------------
21
24
  // Internal helpers
@@ -44,6 +47,11 @@ function ensureApiConfiguration(fd) {
44
47
  });
45
48
  fd.api.configure(config);
46
49
  }
50
+ /** The error when a save was refused because the workflow changed on the server meanwhile. */
51
+ function isSaveConflict(error) {
52
+ const e = error;
53
+ return e?.status === 409 && e.errorData?.error_code === 'CONFLICT' ? error : null;
54
+ }
47
55
  /**
48
56
  * Flush any pending form changes by blurring the active element.
49
57
  * This ensures focusout handlers (like ConfigForm's handleFormBlur)
@@ -61,34 +69,72 @@ async function flushPendingFormChanges() {
61
69
  // ---------------------------------------------------------------------------
62
70
  // Public API
63
71
  // ---------------------------------------------------------------------------
72
+ /** The save running now, per instance: a second call joins it. */
73
+ const inFlight = new WeakMap();
74
+ /** The editVersion at which a non-interactive save was last refused for needing an answer. */
75
+ const autosaveRefusedAt = new WeakMap();
76
+ /** Stable toast id so the autosave notice never stacks. */
77
+ function autosaveToastId(fd) {
78
+ return `flowdrop:autosave-waiting:${fd.skinScope ?? ''}`;
79
+ }
64
80
  /**
65
81
  * Save the current workflow to the backend.
66
82
  *
67
83
  * This is the single source of truth for save logic. App.svelte delegates
68
84
  * to this function rather than reimplementing the steps.
69
85
  *
86
+ * Joining: a call made while a save of the same instance is in flight (double
87
+ * Cmd+S, autosave plus a manual save) returns that save's promise instead of
88
+ * starting another, which would send the superseded revision and be refused as
89
+ * a conflict. Edits made meanwhile stay dirty and go with the next save.
90
+ *
70
91
  * Steps performed:
92
+ * 0. Join a save already in flight, or drop the call while the impact question is open
71
93
  * 1. Flush pending form changes (blur active element + tick)
72
- * 2. Optionally call onBeforeSave — return false cancels the save
73
- * 3. Build the canonical Workflow object (preserving metadata, format, etc.)
74
- * 4. Persist via the instance's API client (fd.api.client)
75
- * 5. Update the store if the server assigned a new ID
76
- * 6. Call onMarkAsSaved / onAfterSave hooks
77
- * 7. Show toast notifications (respecting features.showToasts)
78
- */
79
- /**
94
+ * 2. Build the canonical Workflow object (preserving metadata, format, etc.)
95
+ * and note the edit version it was taken at
96
+ * 3. Ask the backend what the save changes for the workflow's users; ask the
97
+ * person when something breaks or changes (autosave does not ask: it waits
98
+ * for a person, and says so once)
99
+ * 4. Optionally call onBeforeSave — return false cancels the save
100
+ * 5. Persist via the instance's API client (fd.api.client)
101
+ * 6. Update the store if the server assigned a new ID
102
+ * 7. Call onMarkAsSaved (up to the version noted in step 2) / onAfterSave hooks
103
+ * 8. Show toast notifications (respecting features.showToasts)
104
+ *
80
105
  * Resolves `true` when the workflow was written, `false` when nothing was
81
- * saved because there was no workflow or `onBeforeSave` cancelled. A failed
106
+ * saved because there was no workflow, `onBeforeSave` cancelled or the person
107
+ * cancelled the impact question. A failed
82
108
  * request throws. Callers that relay the outcome (the WebMCP `save` tool)
83
109
  * must not read a quiet return as a save.
84
110
  */
85
- export async function globalSaveWorkflow(options = {}) {
111
+ export function globalSaveWorkflow(options = {}) {
112
+ const fd = options.instance ?? getDefaultInstance();
113
+ const running = inFlight.get(fd);
114
+ if (running) {
115
+ // A person's save that lands on an autosave waits for it, then asks itself
116
+ // when the autosave did not write (it never asks the impact question).
117
+ if (options.interactive === false || running.interactive)
118
+ return running.promise;
119
+ return running.promise.then((saved) => saved && !fd.workflow.isDirty ? true : globalSaveWorkflow(options));
120
+ }
121
+ const promise = runSave(fd, options).finally(() => {
122
+ if (inFlight.get(fd)?.promise === promise)
123
+ inFlight.delete(fd);
124
+ });
125
+ inFlight.set(fd, { promise, interactive: options.interactive !== false });
126
+ return promise;
127
+ }
128
+ async function runSave(fd, options) {
86
129
  const { eventHandlers, onMarkAsSaved, onSaved } = options;
87
130
  const features = { ...DEFAULT_FEATURES, ...options.features };
88
- // Resolve the target instance; defaults to the page-default instance.
89
- const fd = options.instance ?? getDefaultInstance();
90
131
  const readWorkflow = () => fd.workflow.current;
91
- // Step 1 — Flush pending form changes (single location for this logic)
132
+ // A save while the impact question is open is dropped, not queued: the open
133
+ // dialog is the one answer. Checked before the flush, which would blur its
134
+ // focused button.
135
+ if (impactPending(fd))
136
+ return false;
137
+ // Flush pending form changes (single location for this logic)
92
138
  await flushPendingFormChanges();
93
139
  // Get current workflow from the instance's store after flush
94
140
  const currentWorkflow = readWorkflow();
@@ -98,18 +144,16 @@ export async function globalSaveWorkflow(options = {}) {
98
144
  }
99
145
  return false;
100
146
  }
101
- // Step 2 — Allow the parent to cancel the save
102
- if (eventHandlers?.onBeforeSave) {
103
- const shouldContinue = await eventHandlers.onBeforeSave(currentWorkflow);
104
- if (shouldContinue === false) {
105
- return false;
106
- }
107
- }
108
- const loadingToast = features.showToasts ? apiToasts.loading('Saving workflow') : null;
147
+ // Autosave already declined this very version: nothing changed, so asking
148
+ // the backend again would only repeat the refusal.
149
+ const interactive = options.interactive !== false;
150
+ if (!interactive && autosaveRefusedAt.get(fd) === fd.workflow.editVersion)
151
+ return false;
152
+ let loadingToast = null;
109
153
  try {
110
154
  // Ensure API configuration is initialised (needed when called outside App.svelte)
111
155
  ensureApiConfiguration(fd);
112
- // Step 3 — Build the canonical workflow object.
156
+ // Build the canonical workflow object.
113
157
  // Preserve all existing metadata fields (format, tags, etc.) so nothing is dropped.
114
158
  //
115
159
  // Determine new vs existing BEFORE the uuidv4() fallback: if the store already
@@ -118,14 +162,58 @@ export async function globalSaveWorkflow(options = {}) {
118
162
  const isExistingWorkflow = !!currentWorkflow.id;
119
163
  const workflowId = currentWorkflow.id || uuidv4();
120
164
  const finalWorkflow = buildSaveBody(currentWorkflow, workflowId);
121
- // Step 4 — Persist via this instance's API client.
165
+ // What this snapshot contains: only up to here may be marked saved.
166
+ let savedVersion = fd.workflow.editVersion;
167
+ // Ask what this save changes for what uses the workflow. A backend
168
+ // without the route (or that does not know the workflow) leaves the save
169
+ // unasked; a failed check is shown and the person decides.
170
+ const apiConfig = fd.api.config;
171
+ if (isExistingWorkflow && apiConfig && impactSupported(apiConfig)) {
172
+ const result = await checkImpact(apiConfig, fd.api.authProvider, finalWorkflow.id, finalWorkflow);
173
+ // This instance's editor (a page may hold several), for the dialog's skin.
174
+ const host = (fd.skinScope ? document.querySelector(scopeSelector(fd.skinScope)) : null) ??
175
+ document.body;
176
+ const needsAnswer = (result.status === 'ok' && result.report.confirm) || result.status === 'error';
177
+ if (needsAnswer) {
178
+ if (!interactive) {
179
+ // Say so once per version, then stay quiet until something changes.
180
+ if (autosaveRefusedAt.get(fd) !== savedVersion && features.showToasts) {
181
+ showInfo(fd.messages().autoSave.waiting, { id: autosaveToastId(fd) });
182
+ }
183
+ autosaveRefusedAt.set(fd, savedVersion);
184
+ return false;
185
+ }
186
+ const answer = await confirmImpact({
187
+ report: result.status === 'ok' ? result.report : undefined,
188
+ error: result.status === 'error' ? result.message : undefined,
189
+ host,
190
+ instance: fd,
191
+ messages: fd.messages
192
+ });
193
+ if (!answer)
194
+ return false;
195
+ }
196
+ }
197
+ // Allow the parent to cancel the save (after the impact question, so a
198
+ // cancelled question leaves no onBeforeSave without an outcome hook).
199
+ if (eventHandlers?.onBeforeSave) {
200
+ const shouldContinue = await eventHandlers.onBeforeSave(currentWorkflow);
201
+ if (shouldContinue === false) {
202
+ return false;
203
+ }
204
+ }
205
+ loadingToast = features.showToasts ? apiToasts.loading('Saving workflow') : null;
206
+ // Persist via this instance's API client.
122
207
  // id-presence (computed above) decides update vs create — never UUID-regex.
123
208
  const apiClient = fd.api.client;
124
209
  const savedWorkflow = isExistingWorkflow
125
210
  ? await apiClient.updateWorkflow(finalWorkflow.id, finalWorkflow)
126
211
  : await apiClient.saveWorkflow(finalWorkflow);
127
- // Step 5 — If the server assigned a new ID, sync the store
212
+ // If the server assigned a new ID, sync the store
128
213
  if (savedWorkflow.id && savedWorkflow.id !== finalWorkflow.id) {
214
+ // The sync bumps editVersion itself; it counts as saved, but only when
215
+ // nothing else changed the workflow before it.
216
+ const cleanBeforeSync = fd.workflow.editVersion === savedVersion;
129
217
  fd.workflow.batchUpdate({
130
218
  nodes: finalWorkflow.nodes,
131
219
  edges: finalWorkflow.edges,
@@ -135,18 +223,22 @@ export async function globalSaveWorkflow(options = {}) {
135
223
  ...savedWorkflow.metadata
136
224
  }
137
225
  });
226
+ if (cleanBeforeSync)
227
+ savedVersion = fd.workflow.editVersion;
138
228
  }
139
- // Step 5b — The save minted a new revision (and may have refreshed what the
229
+ // The save minted a new revision (and may have refreshed what the
140
230
  // user may do); take the server's word so the next save sends the current
141
231
  // stamp rather than the one this save just superseded.
142
232
  fd.workflow.acknowledgeServer({ revision: savedWorkflow.revision, can: savedWorkflow.can });
143
- // Step 6a — Mark dirty state as clean
233
+ // Mark dirty state as clean
144
234
  if (onMarkAsSaved) {
145
- onMarkAsSaved();
235
+ onMarkAsSaved(savedVersion);
146
236
  }
147
237
  else {
148
- fd.workflow.markAsSaved();
238
+ fd.workflow.markAsSaved(savedVersion);
149
239
  }
240
+ autosaveRefusedAt.delete(fd);
241
+ dismissToast(autosaveToastId(fd));
150
242
  // A conversation open in the editor's Playground marks the new version.
151
243
  // Not awaited: it asks the server which version this save made.
152
244
  void fd.runs.noteWorkflowSaved();
@@ -160,7 +252,7 @@ export async function globalSaveWorkflow(options = {}) {
160
252
  if (features.showToasts) {
161
253
  workflowToasts.saved(finalWorkflow.name);
162
254
  }
163
- // Step 6b — After-save hook
255
+ // After-save hook
164
256
  if (eventHandlers?.onAfterSave) {
165
257
  await eventHandlers.onAfterSave(savedWorkflow);
166
258
  }
@@ -180,7 +272,19 @@ export async function globalSaveWorkflow(options = {}) {
180
272
  if (eventHandlers?.onApiError) {
181
273
  suppressToast = eventHandlers.onApiError(errorObj, 'save') === true;
182
274
  }
183
- if (features.showToasts && !suppressToast) {
275
+ // Someone else saved first: offer Keep mine / Load saved version / Compare
276
+ // instead of the generic error. Other 409s (a taken id) keep the normal toast.
277
+ // The choices are reported even when toasts are off, only the toast is not.
278
+ const conflict = isSaveConflict(error);
279
+ if (conflict) {
280
+ const details = conflict.errorData.details;
281
+ const current = details?.current;
282
+ fd.saveConflict.report({
283
+ currentRevision: current === undefined || current === null || current === '' ? null : String(current),
284
+ retry: () => globalSaveWorkflow(options)
285
+ }, features.showToasts && !suppressToast);
286
+ }
287
+ else if (features.showToasts && !suppressToast) {
184
288
  // The error object, not its message: an ApiError carries the server's
185
289
  // reasons as `details`, and the toast renders them as a list.
186
290
  // "Show problems" opens the navbar's problems popover, when there are
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Impact gate: mounts the {@link ImpactConfirm} dialog imperatively and
3
+ * resolves once with the person's decision.
4
+ *
5
+ * The dialog mounts outside the editor tree, so the host passes the element
6
+ * whose scope it should look like (`host`: the editor root, read for the skin
7
+ * scope and colour scheme) or the scheme itself (`theme`).
8
+ *
9
+ * @module services/impactGate
10
+ */
11
+ import { type Messages } from '../messages/index.js';
12
+ import type { ImpactReport } from '../types/impact.js';
13
+ import type { FlowDropInstance } from '../stores/instanceContainer.svelte.js';
14
+ export interface ConfirmImpactOptions {
15
+ /** What the check found. */
16
+ report?: ImpactReport;
17
+ /** The reason the check failed; the dialog then shows that one line. */
18
+ error?: string;
19
+ /** The editor element; its skin scope is copied onto the dialog. Default `document.body` for mounting only. */
20
+ host?: HTMLElement;
21
+ /** The colour scheme (`light` | `dark`). Default: follows the editor's resolved scheme. */
22
+ theme?: string;
23
+ /** The editor's messages (`fd.messages`). Default: the built-in English. */
24
+ messages?: () => Messages;
25
+ /**
26
+ * The editor instance asking. At most one question is open per instance: a
27
+ * second ask while one is open resolves `false` and opens no second dialog.
28
+ */
29
+ instance?: FlowDropInstance;
30
+ }
31
+ /** Whether this instance has an impact question open. */
32
+ export declare function impactPending(instance: FlowDropInstance): boolean;
33
+ /** Ask whether the save may go ahead. Resolves `true` to save, `false` to cancel. */
34
+ export declare function confirmImpact(options: ConfirmImpactOptions): Promise<boolean>;
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Impact gate: mounts the {@link ImpactConfirm} dialog imperatively and
3
+ * resolves once with the person's decision.
4
+ *
5
+ * The dialog mounts outside the editor tree, so the host passes the element
6
+ * whose scope it should look like (`host`: the editor root, read for the skin
7
+ * scope and colour scheme) or the scheme itself (`theme`).
8
+ *
9
+ * @module services/impactGate
10
+ */
11
+ import { mount, unmount } from 'svelte';
12
+ import { defaultMessages, messagesContext } from '../messages/index.js';
13
+ import ImpactConfirm from '../components/ImpactConfirm.svelte';
14
+ import { SCOPE_ATTR } from '../utils/portal.js';
15
+ import { themeScope } from '../utils/themeScope.svelte.js';
16
+ const pending = new WeakSet();
17
+ /** Whether this instance has an impact question open. */
18
+ export function impactPending(instance) {
19
+ return pending.has(instance);
20
+ }
21
+ /** Ask whether the save may go ahead. Resolves `true` to save, `false` to cancel. */
22
+ export function confirmImpact(options) {
23
+ if (typeof document === 'undefined') {
24
+ // No DOM to ask in: refuse rather than silently save.
25
+ return Promise.resolve(false);
26
+ }
27
+ const key = options.instance;
28
+ if (key && pending.has(key))
29
+ return Promise.resolve(false);
30
+ if (key)
31
+ pending.add(key);
32
+ return new Promise((resolve) => {
33
+ let settled = false;
34
+ const element = document.createElement('div');
35
+ element.className = 'fd-impact-confirm-host';
36
+ const scope = options.host?.closest(`[${SCOPE_ATTR}]`)?.getAttribute(SCOPE_ATTR);
37
+ if (scope)
38
+ element.setAttribute(SCOPE_ATTR, scope);
39
+ const theme = options.theme ? null : themeScope(element);
40
+ if (options.theme)
41
+ element.setAttribute('data-theme', options.theme);
42
+ document.body.appendChild(element);
43
+ let component = null;
44
+ let forget = null;
45
+ const finish = (save) => {
46
+ if (settled)
47
+ return;
48
+ settled = true;
49
+ forget?.();
50
+ if (key)
51
+ pending.delete(key);
52
+ if (component)
53
+ void unmount(component);
54
+ theme?.destroy();
55
+ element.remove();
56
+ resolve(save);
57
+ };
58
+ component = mount(ImpactConfirm, {
59
+ target: element,
60
+ context: messagesContext(options.messages ?? (() => defaultMessages)),
61
+ props: {
62
+ report: options.report ?? null,
63
+ error: options.error,
64
+ onResolve: finish
65
+ }
66
+ });
67
+ // The instance going away takes the question with it.
68
+ forget = key?.onDestroy(() => finish(false)) ?? null;
69
+ });
70
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Impact service: asks the backend what saving the editor's draft would change
3
+ * for the workflows, profiles and triggers that use it. Nothing is saved.
4
+ *
5
+ * Refusals are results, not exceptions: a backend without the route simply
6
+ * leaves the save unasked.
7
+ *
8
+ * @module services/impactService
9
+ */
10
+ import type { EndpointConfig } from '../config/endpoints.js';
11
+ import type { AuthProvider } from '../types/auth.js';
12
+ import type { ImpactReport } from '../types/impact.js';
13
+ import type { Workflow } from '../types/index.js';
14
+ export type ImpactResult = {
15
+ status: 'ok';
16
+ report: ImpactReport;
17
+ }
18
+ /** The backend has no such route, refuses it, or does not know this workflow. */
19
+ | {
20
+ status: 'unavailable';
21
+ } | {
22
+ status: 'error';
23
+ message: string;
24
+ };
25
+ /** Whether the configuration offers the impact check at all. */
26
+ export declare function impactSupported(config: EndpointConfig | null | undefined): boolean;
27
+ /** Ask what saving `draft` over the saved workflow `workflowId` would change. */
28
+ export declare function checkImpact(config: EndpointConfig, authProvider: AuthProvider | undefined, workflowId: string, draft: Workflow): Promise<ImpactResult>;
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Impact service: asks the backend what saving the editor's draft would change
3
+ * for the workflows, profiles and triggers that use it. Nothing is saved.
4
+ *
5
+ * Refusals are results, not exceptions: a backend without the route simply
6
+ * leaves the save unasked.
7
+ *
8
+ * @module services/impactService
9
+ */
10
+ import { buildEndpointUrl } from '../config/endpoints.js';
11
+ import { authenticatedFetch } from '../utils/fetchWithAuth.js';
12
+ const SEVERITIES = ['breaks', 'changes', 'info'];
13
+ /** Whether the configuration offers the impact check at all. */
14
+ export function impactSupported(config) {
15
+ return !!config?.endpoints?.workflows?.impact;
16
+ }
17
+ function parseReport(data) {
18
+ const d = (typeof data === 'object' && data !== null ? data : {});
19
+ const iface = (typeof d.interface === 'object' && d.interface !== null ? d.interface : {});
20
+ const items = [];
21
+ for (const raw of Array.isArray(d.items) ? d.items : []) {
22
+ if (typeof raw !== 'object' || raw === null)
23
+ continue;
24
+ const i = raw;
25
+ if (typeof i.label !== 'string' || typeof i.message !== 'string')
26
+ continue;
27
+ items.push({
28
+ kind: typeof i.kind === 'string' ? i.kind : '',
29
+ severity: SEVERITIES.includes(i.severity)
30
+ ? i.severity
31
+ : 'info',
32
+ label: i.label,
33
+ message: i.message,
34
+ url: typeof i.url === 'string' ? i.url : null
35
+ });
36
+ }
37
+ return {
38
+ confirm: d.confirm === true,
39
+ interfaceLevel: typeof iface.level === 'string' ? iface.level : '',
40
+ interfaceBreaking: iface.breaking === true,
41
+ items
42
+ };
43
+ }
44
+ async function errorMessage(response) {
45
+ const payload = (await response.json().catch(() => ({})));
46
+ return payload.error ?? payload.message ?? `HTTP ${response.status}: ${response.statusText}`;
47
+ }
48
+ /** Ask what saving `draft` over the saved workflow `workflowId` would change. */
49
+ export async function checkImpact(config, authProvider, workflowId, draft) {
50
+ const path = config.endpoints.workflows.impact;
51
+ if (!path)
52
+ return { status: 'unavailable' };
53
+ try {
54
+ const response = await authenticatedFetch(buildEndpointUrl(config, path, { id: workflowId }), { method: 'POST', body: JSON.stringify(draft) }, { config, endpointKey: 'workflows.impact', authProvider });
55
+ // 404/405: no such route. 401/403: a backend that answers an unknown route
56
+ // with a login or access refusal. The route ships in the default endpoints,
57
+ // so these must not read as a failed check before every save.
58
+ if ([401, 403, 404, 405].includes(response.status))
59
+ return { status: 'unavailable' };
60
+ if (!response.ok)
61
+ return { status: 'error', message: await errorMessage(response) };
62
+ const body = (await response.json().catch(() => null));
63
+ if (!body || body.success === false) {
64
+ return { status: 'error', message: body?.error ?? 'Impact check failed' };
65
+ }
66
+ return { status: 'ok', report: parseReport(body.data) };
67
+ }
68
+ catch (error) {
69
+ return { status: 'error', message: error instanceof Error ? error.message : String(error) };
70
+ }
71
+ }
@@ -12,6 +12,15 @@ export type ToastKind = 'success' | 'error' | 'warning' | 'info' | 'loading';
12
12
  export interface ToastAction {
13
13
  label: string;
14
14
  onClick: () => void;
15
+ /** Draws this action as the main one when a toast offers several (default: the first). */
16
+ primary?: boolean;
17
+ /**
18
+ * Leave the toast on screen after this action runs (default: it is
19
+ * dismissed). For a choice that can fail or be cancelled, where the person
20
+ * still needs the other options; the caller dismisses the toast itself once
21
+ * the matter is settled.
22
+ */
23
+ keepOpen?: boolean;
15
24
  }
16
25
  export interface ActiveToast {
17
26
  id: string;
@@ -28,6 +28,8 @@ export interface ToastContent {
28
28
  body?: string;
29
29
  details?: readonly string[];
30
30
  action?: ToastAction;
31
+ /** Several follow-up steps; listed after `action`. */
32
+ actions?: readonly ToastAction[];
31
33
  }
32
34
  /** What the show* helpers take: a plain string (the title) or its parts. */
33
35
  export type ToastInput = string | ToastContent;
@@ -44,6 +46,8 @@ export interface ToastOptions {
44
46
  details?: readonly string[];
45
47
  /** Same as `action` on a `ToastContent`; the content's own action wins. */
46
48
  action?: ToastAction;
49
+ /** Same as `actions` on a `ToastContent`; the content's own list wins. */
50
+ actions?: readonly ToastAction[];
47
51
  /**
48
52
  * Stable id: a toast with the same id replaces the one already showing
49
53
  * instead of stacking. Errors and warnings default to an id derived from
@@ -52,9 +52,14 @@ function toContent(input, options) {
52
52
  return {
53
53
  ...content,
54
54
  details: content.details ?? options?.details,
55
- action: content.action ?? options?.action
55
+ action: content.action ?? options?.action,
56
+ actions: content.actions ?? options?.actions
56
57
  };
57
58
  }
59
+ /** Every action a toast offers, in order: the single `action` first, then `actions`. */
60
+ function actionList(content) {
61
+ return [...(content.action ? [content.action] : []), ...(content.actions ?? [])];
62
+ }
58
63
  /** Default id for a persistent toast: one per distinct text. */
59
64
  function dedupeId(kind, content) {
60
65
  return `${kind}:${[content.title, content.body ?? '', ...(content.details ?? [])].join('\n')}`;
@@ -74,7 +79,8 @@ function present(kind, input, options, defaults) {
74
79
  const content = toContent(input, options);
75
80
  // An action is the next step the user may take: it must not vanish while they
76
81
  // read (or reach for) it, so it never auto-dismisses and can always be closed.
77
- const sticky = content.action !== undefined;
82
+ const actions = actionList(content);
83
+ const sticky = actions.length > 0;
78
84
  const id = options?.id ?? defaults.id ?? dedupeId(kind, content);
79
85
  for (const evicted of planToastEviction(activeToasts(), { id, kind })) {
80
86
  toast.dismiss(evicted);
@@ -85,7 +91,7 @@ function present(kind, input, options, defaults) {
85
91
  text: content.title,
86
92
  body: content.body,
87
93
  details: content.details ?? [],
88
- action: content.action,
94
+ actions,
89
95
  kind,
90
96
  dismissible: sticky || defaults.dismissible
91
97
  },
@@ -73,7 +73,9 @@ class WorkflowLaunchService {
73
73
  return { status: 'invalid-workflow', message, errors: payload.details ?? [] };
74
74
  }
75
75
  if (response.status === 400) {
76
- return { status: 'invalid-input', message };
76
+ // Per-input details, when the backend names them, are the useful message.
77
+ const detail = (payload.details ?? []).map((item) => item.message).filter(Boolean);
78
+ return { status: 'invalid-input', message: detail.length > 0 ? detail.join(' ') : message };
77
79
  }
78
80
  return { status: 'failed', message };
79
81
  }
@@ -19,8 +19,8 @@
19
19
  export { default as ThemeToggle } from '../components/ThemeToggle.svelte';
20
20
  export { default as SettingsPanel } from '../components/SettingsPanel.svelte';
21
21
  export { default as SettingsModal } from '../components/SettingsModal.svelte';
22
- export type { ThemeSettings, EditorSettings, UISettings, BehaviorSettings, ApiSettings, FlowDropSettings, SettingsCategory, PartialSettings, DeepPartial, SettingsChangeEvent, SettingsChangeCallback, SyncStatus, SettingsStoreState } from '../types/settings.js';
22
+ export type { ThemeSettings, EditorSettings, UISettings, BehaviorSettings, ApiSettings, FlowDropSettings, SettingsCategory, SettingsFieldSchema, SettingsFieldSchemaMap, PartialSettings, DeepPartial, SettingsChangeEvent, SettingsChangeCallback, SyncStatus, SettingsStoreState } from '../types/settings.js';
23
23
  export type { ZoomTierConfig, ZoomTierName } from '../utils/zoomTier.js';
24
- export { SETTINGS_CATEGORIES, SETTINGS_CATEGORY_LABELS, SETTINGS_CATEGORY_ICONS, DEFAULT_THEME_SETTINGS, DEFAULT_EDITOR_SETTINGS, DEFAULT_UI_SETTINGS, DEFAULT_BEHAVIOR_SETTINGS, DEFAULT_API_SETTINGS, DEFAULT_SETTINGS, SETTINGS_STORAGE_KEY } from '../types/settings.js';
24
+ export { SETTINGS_CATEGORIES, SETTINGS_CATEGORY_LABELS, SETTINGS_CATEGORY_ICONS, DEFAULT_THEME_SETTINGS, DEFAULT_EDITOR_SETTINGS, DEFAULT_UI_SETTINGS, DEFAULT_BEHAVIOR_SETTINGS, DEFAULT_API_SETTINGS, DEFAULT_SETTINGS, SETTINGS_FIELD_SCHEMA, SETTINGS_STORAGE_KEY } from '../types/settings.js';
25
25
  export { getSettings as settingsStore, getThemeSettings as themeSettings, getEditorSettings as editorSettings, getUiSettings as uiSettings, getBehaviorSettings as behaviorSettings, getApiSettings as apiSettings, getSyncStatus as syncStatusStore, updateSettings, resetSettings, getSettings, initializeSettings, setSettingsService, syncSettingsToApi, loadSettingsFromApi, onSettingsChange } from '../stores/settingsStore.svelte.js';
26
26
  export { settingsApi, SettingsService, createSettingsService, setSettingsEndpointConfig, getSettingsEndpointConfig } from '../services/settingsService.js';
@@ -22,7 +22,7 @@
22
22
  export { default as ThemeToggle } from '../components/ThemeToggle.svelte';
23
23
  export { default as SettingsPanel } from '../components/SettingsPanel.svelte';
24
24
  export { default as SettingsModal } from '../components/SettingsModal.svelte';
25
- export { SETTINGS_CATEGORIES, SETTINGS_CATEGORY_LABELS, SETTINGS_CATEGORY_ICONS, DEFAULT_THEME_SETTINGS, DEFAULT_EDITOR_SETTINGS, DEFAULT_UI_SETTINGS, DEFAULT_BEHAVIOR_SETTINGS, DEFAULT_API_SETTINGS, DEFAULT_SETTINGS, SETTINGS_STORAGE_KEY } from '../types/settings.js';
25
+ export { SETTINGS_CATEGORIES, SETTINGS_CATEGORY_LABELS, SETTINGS_CATEGORY_ICONS, DEFAULT_THEME_SETTINGS, DEFAULT_EDITOR_SETTINGS, DEFAULT_UI_SETTINGS, DEFAULT_BEHAVIOR_SETTINGS, DEFAULT_API_SETTINGS, DEFAULT_SETTINGS, SETTINGS_FIELD_SCHEMA, SETTINGS_STORAGE_KEY } from '../types/settings.js';
26
26
  // ============================================================================
27
27
  // Settings Stores
28
28
  // ============================================================================
@@ -11,13 +11,28 @@
11
11
  * workflow update, which is one undo step; an operation the editor cannot map
12
12
  * aborts the whole remedy before anything changes.
13
13
  *
14
+ * A remedy the server marks `params.automatic` is applied by the editor itself
15
+ * when its problem first appears after the workflow loaded (never for a problem
16
+ * present at load, a destructive remedy or one that needs a choice), once per
17
+ * code per workflow, with an Undo toast. See {@link DoctorStore.setAutoApply}.
18
+ *
14
19
  * @module stores/doctorStore
15
20
  */
16
21
  import type { DoctorProblem, DoctorRemedy, DoctorSeverity } from '../types/doctor.js';
17
22
  import type { WorkflowStore } from './workflowStore.svelte.js';
18
23
  import type { ApiContext } from './apiContext.js';
24
+ import { type Messages } from '../messages/index.js';
19
25
  /** How long the draft must sit still before it is diagnosed. */
20
26
  export declare const DOCTOR_IDLE_MS = 800;
27
+ /** What a {@link DoctorStore} can be given beyond the workflow and the api. */
28
+ export interface DoctorStoreOptions {
29
+ /** How long the draft must sit still before it is diagnosed. Default {@link DOCTOR_IDLE_MS}. */
30
+ idleMs?: number;
31
+ /** The undo history, for the Undo toast. Default: nothing to undo. */
32
+ history?: DoctorHistory;
33
+ /** The editor's messages. Default: the built-in English. */
34
+ messages?: () => Messages;
35
+ }
21
36
  export type DoctorStatus = 'off' | 'idle' | 'checking' | 'ready' | 'error';
22
37
  /** What the last remedy attempt ended in, other than success. The view words it. */
23
38
  export type DoctorNotice = {
@@ -34,9 +49,17 @@ export type DoctorNotice = {
34
49
  problemId: string;
35
50
  message: string;
36
51
  };
52
+ /** The undo history as the store needs it: undo one step, and say where the history stands. */
53
+ export interface DoctorHistory {
54
+ undo(): boolean;
55
+ /** A number that changes with every step added, undone or redone. */
56
+ position(): number;
57
+ }
37
58
  export declare class DoctorStore {
38
59
  #private;
39
- constructor(workflow: WorkflowStore, api: ApiContext, idleMs?: number);
60
+ constructor(workflow: WorkflowStore, api: ApiContext, options?: DoctorStoreOptions);
61
+ /** Whether the editor may apply automatic remedies (the canvas is editable). */
62
+ setAutoApply(enabled: boolean): void;
40
63
  /** Whether the backend offers a Doctor (the endpoints are configured). */
41
64
  get supported(): boolean;
42
65
  get status(): DoctorStatus;