@dudousxd/nestjs-catalog-react 0.18.0 → 0.19.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 (40) hide show
  1. package/dist/CatalogManager.d.ts +23 -1
  2. package/dist/CatalogManager.js +76 -13
  3. package/dist/ConnectionPanel.js +15 -123
  4. package/dist/LoadedBySection.d.ts +39 -0
  5. package/dist/LoadedBySection.js +143 -0
  6. package/dist/WorkflowCanvas.d.ts +16 -0
  7. package/dist/WorkflowCanvas.js +1026 -78
  8. package/dist/connection-form.d.ts +241 -0
  9. package/dist/connection-form.js +235 -0
  10. package/dist/context.d.ts +78 -4
  11. package/dist/context.js +11 -0
  12. package/dist/index.d.ts +5 -1
  13. package/dist/index.js +23 -0
  14. package/dist/routes.d.ts +30 -0
  15. package/dist/routes.js +2 -0
  16. package/dist/schema-discovery.d.ts +17 -1
  17. package/dist/schema-discovery.js +3 -3
  18. package/dist/source-connection.d.ts +82 -0
  19. package/dist/source-connection.js +176 -0
  20. package/dist/source-fields.d.ts +15 -2
  21. package/dist/source-fields.js +15 -2
  22. package/dist/ui/combobox.d.ts +97 -0
  23. package/dist/ui/combobox.js +80 -0
  24. package/dist/workflow/edges.d.ts +110 -0
  25. package/dist/workflow/edges.js +112 -0
  26. package/dist/workflow/graph.d.ts +63 -2
  27. package/dist/workflow/graph.js +322 -43
  28. package/dist/workflow/index.d.ts +7 -1
  29. package/dist/workflow/index.js +10 -5
  30. package/dist/workflow/lifecycle.d.ts +0 -29
  31. package/dist/workflow/lifecycle.js +2 -35
  32. package/dist/workflow/model.d.ts +28 -3
  33. package/dist/workflow/model.js +12 -2
  34. package/dist/workflow/nodes.d.ts +4 -1
  35. package/dist/workflow/nodes.js +226 -11
  36. package/dist/workflow/templates.js +21 -0
  37. package/dist/workflow/validate.js +11 -0
  38. package/dist/workflow/wiring.d.ts +84 -0
  39. package/dist/workflow/wiring.js +254 -0
  40. package/package.json +8 -8
@@ -7,27 +7,33 @@ import { Background, BackgroundVariant, ConnectionLineType, Controls, MiniMap, N
7
7
  // See src/styles.d.ts for why `tsc` tolerates this import.
8
8
  import '@xyflow/react/dist/style.css';
9
9
  import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
10
- import { ArrowRight, CircleAlert, CircleDashed, Code2, Database, ExternalLink, LayoutGrid, Link2, Loader2, Plug, Plus, Repeat, Save, Trash2, TriangleAlert, Unplug, } from 'lucide-react';
10
+ import { ArrowRight, CircleAlert, CircleDashed, Code2, Database, ExternalLink, GitBranch, LayoutGrid, Link2, Loader2, Plug, Plus, Repeat, Save, Trash2, TriangleAlert, Unplug, } from 'lucide-react';
11
+ import { useReducedMotion } from 'motion/react';
11
12
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
12
13
  import { connectionOptionsFor } from './ConnectionPanel';
13
14
  import { TransformEditor } from './TransformEditor';
14
15
  import { cn } from './cn';
15
16
  import { catalogQueryKeys, useCatalogClient } from './context';
16
17
  import { SchemaDiscoveryPanel, narrowDiscovery, } from './schema-discovery';
18
+ import { SourceConnectionCreator } from './source-connection';
17
19
  import { INLINE_CONNECTION, KIND_OPTIONS, ReadModeFields, SourceFields, readsIncrementally, sourceConfigFrom, sourceDraftFrom, toConnectorKind, usesConnection, } from './source-fields';
18
20
  import { Button } from './ui/button';
21
+ import { ComboboxField } from './ui/combobox';
19
22
  import { ConfirmDialog } from './ui/dialog';
20
- import { TextAreaField, TextField } from './ui/field';
23
+ import { FieldGroup, TextAreaField, TextField } from './ui/field';
21
24
  import { Select, SelectField } from './ui/select';
22
25
  import { Sheet } from './ui/sheet';
26
+ import { Switch } from './ui/switch';
23
27
  import { Tooltip, TooltipProvider } from './ui/tooltip';
24
- import { NODE_HEIGHT, NODE_WIDTH, defaultLabel, layout, layoutIfUnarranged, nextPosition, toFlowEdges, toFlowNodes, } from './workflow/graph';
25
- import { AdoptionNote, PublishControls, RunControls, SchedulePanel, ShrinkRefusalNote, WorkflowStatusBadge, } from './workflow/lifecycle';
26
- import { WORKFLOW_NODE_KINDS, describeDurability, isWorkflowNodeKind, newLocalId, nodeName, producedTypes, } from './workflow/model';
28
+ import { WorkflowEdgeProvider, workflowEdgeTypes } from './workflow/edges';
29
+ import { NODE_HEIGHT, NODE_WIDTH, defaultLabel, describeFilterPredicate, flowingEdgeIds, layout, layoutIfUnarranged, nextPosition, toFlowEdges, toFlowNodes, } from './workflow/graph';
30
+ import { PublishControls, RunControls, SchedulePanel, ShrinkRefusalNote, WorkflowStatusBadge, } from './workflow/lifecycle';
31
+ import { WORKFLOW_BRANCH_LABELS, WORKFLOW_FILTER_MAX_DEPTH, WORKFLOW_FILTER_MAX_VALUES, WORKFLOW_FILTER_OPERATORS, WORKFLOW_NODE_KINDS, callableWorkflowBlock, describeDurability, isWorkflowBranchLabel, isWorkflowFilterOperator, isWorkflowFilterPredicateKind, isWorkflowNodeKind, isWorkflowPredicateKind, newLocalId, nodeName, producedTypes, unreachableFilterPredicateKind, unreachableNodeKind, unreachablePredicateKind, workflowNarrowedTypes, } from './workflow/model';
27
32
  import { WORKFLOW_NAME } from './workflow/name';
28
33
  import { WorkflowNodeProvider, workflowNodeTypes } from './workflow/nodes';
29
34
  import { RunsAsPanel } from './workflow/runs';
30
35
  import { canConnect, edgeId, hasBlockingProblem, problemsByNode, validateWorkflow, } from './workflow/validate';
36
+ import { PendingWireLine, WiringHint, useClickWiring, } from './workflow/wiring';
31
37
  const MUTED = 'text-zinc-400 dark:text-zinc-500';
32
38
  const RULE = 'border-zinc-200 dark:border-zinc-800';
33
39
  const PANEL = 'bg-white dark:bg-zinc-900';
@@ -145,7 +151,73 @@ function newNodeOfKind(kind, id, position, name) {
145
151
  // version 1 in whatever deployment this graph is promoted into.
146
152
  return { id, name, kind: 'call', callName: '', callVersion: '', config: {}, position };
147
153
  }
148
- return { id, name, kind: 'sink', targetType: '', position };
154
+ if (kind === 'if') {
155
+ // No variable, so the graph is invalid until somebody names one. There is
156
+ // nothing to guess: which variable tells this deployment apart from another
157
+ // is the entire content of the node, and a default would be a decision the
158
+ // graph appears to make and nobody authored.
159
+ //
160
+ // The *kind* of test does get a default, and it is the deployment one,
161
+ // because a predicate has to be one of them and an empty variable name is a
162
+ // gate that visibly refuses to publish. A row-count gate with its default
163
+ // threshold would publish happily while testing something nobody chose.
164
+ return { id, name, kind: 'if', predicate: { kind: 'env', envVar: '' }, position };
165
+ }
166
+ if (kind === 'filter') {
167
+ // One empty comparison rather than an empty `all`, and rather than nothing.
168
+ //
169
+ // Nothing is not available: the model has no "no predicate yet" state, on
170
+ // purpose, because a filter whose test is absent has to be given one by
171
+ // somebody and every default is a rule about rows nobody wrote. An empty
172
+ // `all` *is* representable and is refused by the validator, which is exactly
173
+ // why it is not the starting point — a group with no conditions keeps every
174
+ // row, so a filter that started that way would draw as a working node that
175
+ // does nothing.
176
+ //
177
+ // So it starts as one comparison with no column, which the validator refuses
178
+ // by name: the node says "needs a column" on the canvas from the moment it
179
+ // is dropped. The operator defaults to `equals` because it is the only one
180
+ // that is a guess about *form* rather than about data — every other choice
181
+ // implies something about the column's type before a column is chosen.
182
+ return {
183
+ id,
184
+ name,
185
+ kind: 'filter',
186
+ predicate: { kind: 'compare', column: '', operator: 'equals', value: '' },
187
+ position,
188
+ };
189
+ }
190
+ if (kind === 'sink') {
191
+ return { id, name, kind: 'sink', targetType: '', position };
192
+ }
193
+ return unreachableNodeKind(kind, 'newNodeOfKind');
194
+ }
195
+ /**
196
+ * A wire, with its branch already decided when it leaves an `if`.
197
+ *
198
+ * Assigned here rather than left blank for somebody to fill in, because a blank
199
+ * one is refused by `validateWorkflow` and the refusal would fire on the very
200
+ * first wire out of a node somebody just created — the premature-error problem
201
+ * `partitionProblems` exists to describe, arrived at from a different direction.
202
+ *
203
+ * The first wire out of a gate is the `then`, the second is the `else`, and
204
+ * after that it is `then` again. That ordering is not arbitrary: those are the
205
+ * two somebody is drawing when they draw a gate, in that order, and a third wire
206
+ * is fan-out on a side they then choose in the inspector. Every one of them is
207
+ * editable there, so this is a default and never a decision.
208
+ */
209
+ function newEdge(nodes, edges, from, to) {
210
+ const source = nodes.find((node) => node.id === from);
211
+ if (source?.kind !== 'if')
212
+ return { from, to };
213
+ const taken = edges.filter((edge) => edge.from === from).map((edge) => edge.branch);
214
+ const free = WORKFLOW_BRANCH_LABELS.find((label) => !taken.includes(label));
215
+ return { from, to, branch: free ?? 'then' };
216
+ }
217
+ /** The same graph with one wire moved onto the other side of its gate. */
218
+ function edgeOnBranch(edges, moving, branch) {
219
+ const id = edgeId(moving);
220
+ return edges.map((edge) => (edgeId(edge) === id ? { ...edge, branch } : edge));
149
221
  }
150
222
  /**
151
223
  * The code a transform created from this canvas starts as: the batch, unchanged.
@@ -382,6 +454,11 @@ const TODO_FOR = {
382
454
  'missing-transform': 'choose a transform that still exists',
383
455
  'source-has-input': 'unwire whatever feeds it — a source reads, it is not fed',
384
456
  'sink-has-output': 'unwire what it feeds — nothing runs after a sink',
457
+ 'if-not-named': 'name the environment variable it decides on',
458
+ 'if-threshold-invalid': 'give it a whole number of rows, 1 or more, to branch on',
459
+ 'if-needs-one-input': 'leave it one input — a gate carries one stream through',
460
+ 'branch-not-labelled': 'say whether that wire is the "then" or the "else"',
461
+ 'branch-on-plain-edge': 'remove the branch label — only an if node branches',
385
462
  };
386
463
  function todoFor(problem) {
387
464
  return TODO_FOR[problem.code] ?? 'finish setting it up';
@@ -469,7 +546,7 @@ function CanvasActions({ draft, stored, canEdit, blocked, unfinished, saving, ru
469
546
  }
470
547
  /** The four things that can be put on the canvas, and the button that tidies them. */
471
548
  function AddNodeBar({ refreshing, onAdd, onTidy, }) {
472
- return (_jsxs("div", { className: "flex shrink-0 flex-wrap items-center gap-2 px-6 pt-3", children: [_jsx(AddButton, { icon: Plug, label: "Source", hint: "Reads records out of a system: a kind, an optional named connection, and a config.", onClick: () => onAdd('source') }), _jsx(AddButton, { icon: Repeat, label: "Transform", hint: "Code that reshapes whatever is wired into it.", onClick: () => onAdd('transform') }), _jsx(AddButton, { icon: Database, label: "Sink", hint: "Writes and commits one object type. Several are fine \u2014 each commits independently.", onClick: () => onAdd('sink') }), _jsx(AddButton, { icon: ExternalLink, label: "Call", hint: "Hands this step to a durable workflow that already exists, by name and pinned version. It runs as a child of this load, with its own retries.", onClick: () => onAdd('call') }), _jsx(Tooltip, { content: "Lay the nodes out left to right by dependency, with every sink in the last column.", children: _jsxs("button", { type: "button", onClick: onTidy, className: cn('flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-xs', RULE, MUTED, 'hover:bg-zinc-50 dark:hover:bg-zinc-800'), children: [_jsx(LayoutGrid, { size: 12 }), "Tidy"] }) }), refreshing && (
549
+ return (_jsxs("div", { className: "flex shrink-0 flex-wrap items-center gap-2 px-6 pt-3", children: [_jsx(AddButton, { icon: Plug, label: "Source", hint: "Reads records out of a system: a kind, an optional named connection, and a config.", onClick: () => onAdd('source') }), _jsx(AddButton, { icon: Repeat, label: "Transform", hint: "Code that reshapes whatever is wired into it.", onClick: () => onAdd('transform') }), _jsx(AddButton, { icon: Database, label: "Sink", hint: "Writes and commits one object type. Several are fine \u2014 each commits independently.", onClick: () => onAdd('sink') }), _jsx(AddButton, { icon: ExternalLink, label: "Call", hint: "Hands this step to a durable workflow that already exists, by name and pinned version. It runs as a child of this load, with its own retries.", onClick: () => onAdd('call') }), _jsx(AddButton, { icon: GitBranch, label: "If", hint: "Sends the rows down one of two branches, depending on an environment variable where the load runs. The other branch is skipped \u2014 a sink on it commits nothing and leaves what is published alone.", onClick: () => onAdd('if') }), _jsx(Tooltip, { content: "Lay the nodes out left to right by dependency, with every sink in the last column.", children: _jsxs("button", { type: "button", onClick: onTidy, className: cn('flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-xs', RULE, MUTED, 'hover:bg-zinc-50 dark:hover:bg-zinc-800'), children: [_jsx(LayoutGrid, { size: 12 }), "Tidy"] }) }), refreshing && (
473
550
  // A background refetch says so without replacing anything: the graph on
474
551
  // screen stays exactly where it is.
475
552
  _jsx("span", { className: cn('ml-auto font-mono text-[10px]', MUTED), children: "refreshing\u2026" }))] }));
@@ -510,6 +587,17 @@ function miniMapColor(data) {
510
587
  // and the canvas agree about which boxes are somebody else's workflow.
511
588
  if (kind === 'call')
512
589
  return '#f59e0b';
590
+ // Fuchsia-500, the gate's own accent, and deliberately not the violet a
591
+ // transform gets: the overview is where somebody looks to find the branch in
592
+ // a graph too big to read, so it is the one place the two must not blur.
593
+ if (kind === 'if')
594
+ return '#d946ef';
595
+ // Rose-500, the filter's own accent (see `KIND_STYLE`), and specifically not
596
+ // the fuchsia beside it: the overview is where somebody looks for "where do
597
+ // rows disappear in this graph", and a gate and a filter are the two boxes
598
+ // that answer that question in completely different ways.
599
+ if (kind === 'filter')
600
+ return '#f43f5e';
513
601
  return '#8b5cf6';
514
602
  }
515
603
  /**
@@ -519,12 +607,18 @@ function miniMapColor(data) {
519
607
  * place of the screen, so the header and its controls stay put while a refetch
520
608
  * resolves — and a failed read never looks like an empty workflow.
521
609
  */
522
- function GraphSurface({ loading, failed, error, onRetry, canEdit, draft, flowNodes, flowEdges, onInspect, onEditCode, onNodesChange, onEdgesChange, onConnect, isValidConnection, onConnectEnd, onNodeEnter, onNodeLeave, onPaneClick, nodeMenu, }) {
523
- return (_jsxs("div", { className: cn('relative h-[55vh] min-h-[15rem] shrink-0 overflow-hidden rounded-lg border', 'lg:h-auto lg:min-h-0 lg:flex-1 lg:shrink', RULE), children: [loading && _jsx(CanvasSkeleton, {}), failed && _jsx(CanvasFailure, { error: error, onRetry: onRetry }), !loading && !failed && (_jsx(WorkflowNodeProvider, { handlers: { onInspect, onEditCode, canEdit }, children: _jsxs(ReactFlow, { className: CANVAS_THEME, nodes: flowNodes, edges: flowEdges, nodeTypes: workflowNodeTypes, onNodesChange: onNodesChange, onEdgesChange: onEdgesChange, onConnect: onConnect, isValidConnection: isValidConnection, onConnectEnd: onConnectEnd, onNodeMouseEnter: (_event, node) => onNodeEnter(node.id), onNodeMouseLeave: onNodeLeave, onPaneClick: onPaneClick, connectionLineType: ConnectionLineType.SmoothStep, nodesDraggable: canEdit, nodesConnectable: canEdit, elementsSelectable: true, nodesFocusable: true, edgesFocusable: true, deleteKeyCode: canEdit ? ['Delete', 'Backspace'] : null,
524
- // A wider drop zone than the 20px default, because these handles are
525
- // the only drop target on the screen and missing one reads as the
526
- // canvas ignoring you.
527
- connectionRadius: 28, proOptions: { hideAttribution: false }, ariaLabelConfig: ARIA_LABELS, "aria-label": `${WORKFLOW_NAME.title} canvas. ${draft.nodes.length} nodes, ${draft.edges.length} connections.`, fitView: true, children: [_jsx(Background, { variant: BackgroundVariant.Dots, gap: 18, size: 1 }), _jsx(Controls, { showInteractive: false }), _jsx(MiniMap, { pannable: true, zoomable: true, nodeColor: (node) => miniMapColor(node.data) }), nodeMenu] }) }))] }));
610
+ function GraphSurface({ loading, failed, error, onRetry, canEdit, draft, flowNodes, flowEdges, onInspect, onEditCode, onNodesChange, onEdgesChange, onConnect, isValidConnection, onConnectEnd, onNodeEnter, onNodeLeave, onPaneClick, onDisconnect, wiring, wiringRefusal, nodeMenu, }) {
611
+ return (_jsxs("div", { className: cn('relative h-[55vh] min-h-[15rem] shrink-0 overflow-hidden rounded-lg border', 'lg:h-auto lg:min-h-0 lg:flex-1 lg:shrink', RULE), children: [loading && _jsx(CanvasSkeleton, {}), failed && _jsx(CanvasFailure, { error: error, onRetry: onRetry }), !loading && !failed && (_jsx(WorkflowNodeProvider, { handlers: { onInspect, onEditCode, canEdit, wiring }, children: _jsx(WorkflowEdgeProvider, { handlers: { onDisconnect, canEdit }, children: _jsxs(ReactFlow, { className: CANVAS_THEME, nodes: flowNodes, edges: flowEdges, nodeTypes: workflowNodeTypes, edgeTypes: workflowEdgeTypes, onNodesChange: onNodesChange, onEdgesChange: onEdgesChange, onConnect: onConnect, isValidConnection: isValidConnection, onConnectEnd: onConnectEnd, onNodeMouseEnter: (_event, node) => onNodeEnter(node.id), onNodeMouseLeave: onNodeLeave, onPaneClick: onPaneClick, connectionLineType: ConnectionLineType.SmoothStep,
612
+ // Off, so there is exactly ONE click path through a handle and it
613
+ // is the one in `workflow/wiring.tsx`. React Flow's own click
614
+ // wiring connects but draws nothing while it is open and cannot
615
+ // say why it refused — running both would mean two states
616
+ // disagreeing about whether a wire is in flight.
617
+ connectOnClick: false, nodesDraggable: canEdit, nodesConnectable: canEdit, elementsSelectable: true, nodesFocusable: true, edgesFocusable: true, deleteKeyCode: canEdit ? ['Delete', 'Backspace'] : null,
618
+ // A wider drop zone than the 20px default, because these handles are
619
+ // the only drop target on the screen and missing one reads as the
620
+ // canvas ignoring you.
621
+ connectionRadius: 28, proOptions: { hideAttribution: false }, ariaLabelConfig: ARIA_LABELS, "aria-label": `${WORKFLOW_NAME.title} canvas. ${draft.nodes.length} nodes, ${draft.edges.length} connections.`, fitView: true, children: [_jsx(Background, { variant: BackgroundVariant.Dots, gap: 18, size: 1 }), _jsx(Controls, { showInteractive: false, className: "!overflow-hidden !rounded-lg !border !border-zinc-200 !shadow-sm dark:!border-zinc-800 [&>button]:!border-none" }), _jsx(MiniMap, { pannable: true, zoomable: true, nodeColor: (node) => miniMapColor(node.data), className: "!overflow-hidden !rounded-lg !border !border-zinc-200 !shadow-sm dark:!border-zinc-800" }), _jsx(PendingWireLine, { pending: wiring.pending }), _jsx(WiringHint, { pending: wiring.pending, refusal: wiringRefusal, nodes: draft.nodes, onCancel: wiring.cancel }), nodeMenu] }) }) }))] }));
528
622
  }
529
623
  /**
530
624
  * The wiring control that lives on a node, and the menu behind it.
@@ -732,17 +826,6 @@ function storedWorkflow(list, id) {
732
826
  return undefined;
733
827
  return list?.find((workflow) => workflow.id === id);
734
828
  }
735
- /**
736
- * Whether a source node can be asked what its columns are, and why not.
737
- *
738
- * Discovery reads the node the SERVER has, so the two states it cannot run in
739
- * are "never saved" and "saved, but not like this". **Neither of them is
740
- * "unpublished"**, and that is the whole point of the route: a sink cannot
741
- * commit into a type that does not exist, so requiring a published graph would
742
- * require publishing a graph whose target type cannot be created until it is.
743
- * The reasons therefore name saving and never publishing — a reader told to
744
- * publish first would go and do it, and find they cannot.
745
- */
746
829
  function discoveryTarget(draft) {
747
830
  if (!draft.id) {
748
831
  return {
@@ -779,7 +862,7 @@ function readsDifferently(before, after) {
779
862
  before.mode !== after.mode ||
780
863
  JSON.stringify(before.config ?? {}) !== JSON.stringify(after.config ?? {}));
781
864
  }
782
- function Canvas({ title = WORKFLOW_NAME.titlePlural, eyebrow = 'Ingestion', intro = 'Wire sources through transforms into sinks. Each sink commits its own object type independently, so one expensive read can feed several outputs.', canEdit = true, }) {
865
+ function Canvas({ title = WORKFLOW_NAME.titlePlural, eyebrow = 'Ingestion', intro = 'Wire sources through transforms into sinks. Each sink commits its own object type independently, so one expensive read can feed several outputs.', canEdit = true, modelHref, }) {
783
866
  const client = useCatalogClient();
784
867
  const queryClient = useQueryClient();
785
868
  const { fitView } = useReactFlow();
@@ -959,13 +1042,18 @@ function Canvas({ title = WORKFLOW_NAME.titlePlural, eyebrow = 'Ingestion', intr
959
1042
  selected: selectedIds.has(node.id),
960
1043
  }));
961
1044
  }, [draft.nodes, draft.edges, describe, problemsFor, runFor, selectedNodeIds]);
1045
+ // `useReducedMotion` returns null until it has asked, which is neither yes nor
1046
+ // no; coerced here because every consumer of it wants the boolean, and the
1047
+ // safe reading of "has not answered yet" is "do not animate".
1048
+ const reducedMotion = useReducedMotion() !== false;
1049
+ const flowing = useMemo(() => flowingEdgeIds(draft.edges, run?.nodes ?? [], { reducedMotion }), [draft.edges, run, reducedMotion]);
962
1050
  const flowEdges = useMemo(() => {
963
1051
  const selectedIds = new Set(selectedEdgeIds);
964
- return toFlowEdges(draft.edges, draft.nodes, brokenEdgeIds).map((edge) => ({
1052
+ return toFlowEdges(draft.edges, draft.nodes, brokenEdgeIds, flowing).map((edge) => ({
965
1053
  ...edge,
966
1054
  selected: selectedIds.has(edge.id),
967
1055
  }));
968
- }, [draft.edges, draft.nodes, brokenEdgeIds, selectedEdgeIds]);
1056
+ }, [draft.edges, draft.nodes, brokenEdgeIds, selectedEdgeIds, flowing]);
969
1057
  /**
970
1058
  * React Flow's changes, applied to the stored model rather than to a second
971
1059
  * copy of the graph.
@@ -1056,6 +1144,19 @@ function Canvas({ title = WORKFLOW_NAME.titlePlural, eyebrow = 'Ingestion', intr
1056
1144
  markStarted(edge.from, edge.to);
1057
1145
  setAnnouncement('Connection removed.');
1058
1146
  }, [edit, markStarted]);
1147
+ /**
1148
+ * Put a wire on the other side of its gate.
1149
+ *
1150
+ * Announced, like every other wiring change on this screen, because the only
1151
+ * visible effect is a word on a line the reader may not be looking at — and
1152
+ * moving a wire from `then` to `else` is one of the largest changes anybody
1153
+ * can make here: it inverts which half of the pipeline runs.
1154
+ */
1155
+ const setBranch = useCallback((edge, branch) => {
1156
+ edit((current) => ({ ...current, edges: edgeOnBranch(current.edges, edge, branch) }));
1157
+ markStarted(edge.from, edge.to);
1158
+ setAnnouncement(`${nodeLabelIn(draft.nodes, edge.to)} is now on the "${branch}" branch of ${nodeLabelIn(draft.nodes, edge.from)}.`);
1159
+ }, [draft.nodes, edit, markStarted]);
1059
1160
  const connect = useCallback((from, to) => {
1060
1161
  const verdict = canConnect(draft.nodes, draft.edges, from, to);
1061
1162
  if (!verdict.ok) {
@@ -1065,7 +1166,10 @@ function Canvas({ title = WORKFLOW_NAME.titlePlural, eyebrow = 'Ingestion', intr
1065
1166
  // Appended rather than inserted anywhere else: a node with several inbound
1066
1167
  // edges receives its inputs in the order the edges appear in this array,
1067
1168
  // and that order is part of what the graph produces.
1068
- edit((current) => ({ ...current, edges: [...current.edges, { from, to }] }));
1169
+ edit((current) => ({
1170
+ ...current,
1171
+ edges: [...current.edges, newEdge(current.nodes, current.edges, from, to)],
1172
+ }));
1069
1173
  markStarted(from, to);
1070
1174
  setAnnouncement(`${nodeLabelIn(draft.nodes, from)} now feeds ${nodeLabelIn(draft.nodes, to)}.`);
1071
1175
  }, [draft.nodes, draft.edges, edit, markStarted]);
@@ -1109,6 +1213,22 @@ function Canvas({ title = WORKFLOW_NAME.titlePlural, eyebrow = 'Ingestion', intr
1109
1213
  return false;
1110
1214
  return canConnect(draft.nodes, draft.edges, candidate.source, candidate.target).ok;
1111
1215
  }, [draft.nodes, draft.edges]);
1216
+ /**
1217
+ * Wiring by clicking twice, which is the gesture people actually reach for.
1218
+ *
1219
+ * Built on the same `connect` the menu, the rail and the drag all end in, so
1220
+ * there is one place a connection is made and one place it is refused. Why
1221
+ * React Flow's own `connectOnClick` is turned off in favour of this — it
1222
+ * connects but draws nothing, and cannot say why it refused — is written out
1223
+ * at the top of `workflow/wiring.tsx`.
1224
+ */
1225
+ const { wiring, refusal: wiringRefusal } = useClickWiring({
1226
+ canEdit,
1227
+ nodes: draft.nodes,
1228
+ edges: draft.edges,
1229
+ onConnect: connect,
1230
+ onSay: setAnnouncement,
1231
+ });
1112
1232
  const save = useMutation({
1113
1233
  mutationFn: () => client.saveWorkflow({
1114
1234
  id: draft.id,
@@ -1247,7 +1367,7 @@ function Canvas({ title = WORKFLOW_NAME.titlePlural, eyebrow = 'Ingestion', intr
1247
1367
  edit((current) => ({
1248
1368
  ...current,
1249
1369
  nodes: [...current.nodes, node],
1250
- edges: [...current.edges, { from: fromId, to: node.id }],
1370
+ edges: [...current.edges, newEdge(current.nodes, current.edges, fromId, node.id)],
1251
1371
  }));
1252
1372
  setUnstarted((current) => new Set([...current, node.id]));
1253
1373
  menu.close();
@@ -1375,10 +1495,18 @@ function Canvas({ title = WORKFLOW_NAME.titlePlural, eyebrow = 'Ingestion', intr
1375
1495
  * not save that: it fits the graph into a box, and half the box was off
1376
1496
  * screen. See `QueryConsole` for the same pattern.
1377
1497
  */
1378
- _jsxs("div", { className: "flex h-full min-h-0 flex-col", children: [_jsxs("div", { className: "shrink-0 px-6 pt-5", children: [_jsxs("div", { className: "flex flex-wrap items-baseline gap-x-3 gap-y-1", children: [_jsx("p", { className: cn('font-mono text-[11px] uppercase tracking-[0.18em]', MUTED), children: eyebrow }), _jsx("h1", { className: "text-xl font-semibold tracking-tight", children: title }), stored && _jsx(WorkflowStatusBadge, { workflow: stored }), _jsx(CommitsBadge, { produces: produces })] }), _jsx("p", { className: "mt-0.5 max-w-3xl text-xs text-zinc-500 dark:text-zinc-400", children: intro }), _jsx(DurabilityBanner, { durability: durability }), stored && _jsx(AdoptionNote, { workflow: stored }), _jsxs("div", { className: "mt-2.5 grid gap-3 sm:grid-cols-2 lg:grid-cols-3", children: [_jsx(SelectField, { label: WORKFLOW_NAME.title, ariaLabel: `Which ${WORKFLOW_NAME.singular} to edit`, value: selected, onValueChange: (value) => {
1498
+ _jsxs("div", { className: "flex h-full min-h-0 flex-col", children: [_jsxs("div", { className: "shrink-0 px-6 pt-5", children: [_jsxs("div", { className: "flex flex-wrap items-baseline gap-x-3 gap-y-1", children: [_jsx("p", { className: cn('font-mono text-[11px] uppercase tracking-[0.18em]', MUTED), children: eyebrow }), _jsx("h1", { className: "text-xl font-semibold tracking-tight", children: title }), stored && _jsx(WorkflowStatusBadge, { workflow: stored }), _jsx(CommitsBadge, { produces: produces })] }), _jsx("p", { className: "mt-0.5 max-w-3xl text-xs text-zinc-500 dark:text-zinc-400", children: intro }), _jsx(DurabilityBanner, { durability: durability }), workflows.isSuccess && workflows.data.length === 0 && _jsx(NothingDrawnYet, {}), _jsxs("div", { className: "mt-2.5 grid gap-3 sm:grid-cols-2 lg:grid-cols-3", children: [_jsx(SelectField, { label: WORKFLOW_NAME.title, ariaLabel: `Which ${WORKFLOW_NAME.singular} to edit`, value: selected, onValueChange: (value) => {
1379
1499
  loadedRef.current = null;
1380
1500
  setSelected(value);
1381
- }, options: workflowOptions, disabled: workflows.isPending }), _jsx(TextField, { label: "Name", value: draft.name, onChange: (name) => edit((current) => ({ ...current, name })), placeholder: "Fleet readiness", disabled: !canEdit }), _jsx(CanvasActions, { draft: draft, stored: stored, canEdit: canEdit, blocked: blocked, unfinished: unfinished, saving: save.isPending, running: runIt.isPending, durabilityDetail: durability.detail, acknowledging: acknowledging, onAcknowledgingChange: setAcknowledging, onSave: saveNow, onRun: runNow, onLifecycleChange: onLifecycleChange, onAskDelete: () => setConfirmingDelete(true) })] }), save.error && _jsx(RefusalNote, { lead: "The server refused it:", error: save.error }), runIt.error && _jsx(RefusalNote, { lead: "The run could not start:", error: runIt.error }), _jsx(ShrinkRefusalNote, { run: run, error: runIt.error, onAcknowledge: () => setAcknowledging(true) })] }), canEdit && (_jsx(AddNodeBar, { refreshing: workflows.isFetching && !workflows.isPending, onAdd: addNode, onTidy: tidy })), _jsxs("div", { className: "flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto px-6 pb-5 pt-3 lg:flex-row lg:overflow-hidden", children: [_jsx(GraphSurface, { loading: workflows.isPending, failed: workflows.isError, error: workflows.error, onRetry: () => workflows.refetch(), canEdit: canEdit, draft: draft, flowNodes: flowNodes, flowEdges: flowEdges, onInspect: setInspecting, onEditCode: setEditingCodeFor, onNodesChange: onNodesChange, onEdgesChange: onEdgesChange, onConnect: onConnect, isValidConnection: isValidConnection, onConnectEnd: announceRefusedDrop, onNodeEnter: menu.onNodeEnter, onNodeLeave: menu.onNodeLeave, onPaneClick: menu.close, nodeMenu: _jsx(NodeWiringMenu, { node: menu.anchor, draft: draft, canEdit: canEdit, open: menu.open, onOpenChange: menu.onOpenChange, onHoverChange: menu.onHoverChange, onConnect: connect, onConnectToNew: connectToNew, onDisconnect: disconnect }) }), _jsx(WiringRail, { draft: draft, problems: live, pending: pending, run: run, canEdit: canEdit, onInspect: setInspecting, onDisconnect: disconnect, children: stored && (_jsxs(_Fragment, { children: [_jsx(SchedulePanel, { workflow: stored, canEdit: canEdit, onScheduled: onLifecycleChange }, stored.id), _jsx(RunsAsPanel, { workflowId: stored.id, status: stored.status, transforms: graphTransforms })] })) })] }), _jsx("output", { "aria-live": "polite", className: "sr-only", children: announcement }), _jsx(NodeInspector, { node: inspectingNode, draft: draft, transforms: transforms, connections: connections, typeOptions: typeOptions, canEdit: canEdit, problems: problemsOf(problemsFor, inspectingNode), pending: problemsOf(pendingFor, inspectingNode), discovery: discovery, discoverable: discoveryTarget(draft), onDiscovered: rememberShape, onClose: () => setInspecting(null), onChange: (next) => {
1501
+ }, options: workflowOptions, disabled: workflows.isPending }), _jsx(TextField, { label: "Name", value: draft.name, onChange: (name) => edit((current) => ({ ...current, name })), placeholder: "Fleet readiness", disabled: !canEdit }), _jsx(CanvasActions, { draft: draft, stored: stored, canEdit: canEdit, blocked: blocked, unfinished: unfinished, saving: save.isPending, running: runIt.isPending, durabilityDetail: durability.detail, acknowledging: acknowledging, onAcknowledgingChange: setAcknowledging, onSave: saveNow, onRun: runNow, onLifecycleChange: onLifecycleChange, onAskDelete: () => setConfirmingDelete(true) })] }), save.error && _jsx(RefusalNote, { lead: "The server refused it:", error: save.error }), runIt.error && _jsx(RefusalNote, { lead: "The run could not start:", error: runIt.error }), _jsx(ShrinkRefusalNote, { run: run, error: runIt.error, onAcknowledge: () => setAcknowledging(true) })] }), canEdit && (_jsx(AddNodeBar, { refreshing: workflows.isFetching && !workflows.isPending, onAdd: addNode, onTidy: tidy })), _jsxs("div", { className: "flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto px-6 pb-5 pt-3 lg:flex-row lg:overflow-hidden", children: [_jsx(GraphSurface, { loading: workflows.isPending, failed: workflows.isError, error: workflows.error, onRetry: () => workflows.refetch(), canEdit: canEdit, draft: draft, flowNodes: flowNodes, flowEdges: flowEdges, onInspect: setInspecting, onEditCode: setEditingCodeFor, onNodesChange: onNodesChange, onEdgesChange: onEdgesChange, onConnect: onConnect, isValidConnection: isValidConnection, onConnectEnd: announceRefusedDrop, onNodeEnter: menu.onNodeEnter, onNodeLeave: menu.onNodeLeave,
1502
+ // Clicking empty canvas puts away everything that is half-open: the
1503
+ // wiring menu, and a wire that was started and never landed. React
1504
+ // Flow only fires this for clicks on the pane ITSELF, so finishing a
1505
+ // wire on a handle does not also cancel it on the way past.
1506
+ onPaneClick: () => {
1507
+ menu.close();
1508
+ wiring.cancel();
1509
+ }, onDisconnect: disconnect, wiring: wiring, wiringRefusal: wiringRefusal, nodeMenu: _jsx(NodeWiringMenu, { node: menu.anchor, draft: draft, canEdit: canEdit, open: menu.open, onOpenChange: menu.onOpenChange, onHoverChange: menu.onHoverChange, onConnect: connect, onConnectToNew: connectToNew, onDisconnect: disconnect }) }), _jsx(WiringRail, { draft: draft, problems: live, pending: pending, run: run, canEdit: canEdit, onInspect: setInspecting, onDisconnect: disconnect, children: stored && (_jsxs(_Fragment, { children: [_jsx(SchedulePanel, { workflow: stored, canEdit: canEdit, onScheduled: onLifecycleChange }, stored.id), _jsx(RunsAsPanel, { workflowId: stored.id, status: stored.status, transforms: graphTransforms })] })) })] }), _jsx("output", { "aria-live": "polite", className: "sr-only", children: announcement }), _jsx(NodeInspector, { node: inspectingNode, draft: draft, transforms: transforms, connections: connections, typeOptions: typeOptions, canEdit: canEdit, modelHref: modelHref, problems: problemsOf(problemsFor, inspectingNode), pending: problemsOf(pendingFor, inspectingNode), discovery: discovery, discoverable: { ...discoveryTarget(draft), onSave: saveNow, saving: save.isPending }, onDiscovered: rememberShape, onClose: () => setInspecting(null), onChange: (next) => {
1382
1510
  // Editing any field is the clearest statement there is that somebody
1383
1511
  // is working on this node rather than looking at one they just made.
1384
1512
  markStarted(next.id);
@@ -1401,7 +1529,7 @@ function Canvas({ title = WORKFLOW_NAME.titlePlural, eyebrow = 'Ingestion', intr
1401
1529
  ...current,
1402
1530
  nodes: current.nodes.map((node) => (node.id === next.id ? next : node)),
1403
1531
  }));
1404
- }, onConnect: connect, onConnectToNew: connectToNew, onDisconnect: disconnect, onCreateTransform: (nodeId) => createTransform.mutate(nodeId), creatingTransform: createTransform.isPending, createTransformError: createTransform.error, onDelete: (nodeId) => {
1532
+ }, onConnect: connect, onConnectToNew: connectToNew, onDisconnect: disconnect, onBranch: setBranch, onCreateTransform: (nodeId) => createTransform.mutate(nodeId), creatingTransform: createTransform.isPending, createTransformError: createTransform.error, onDelete: (nodeId) => {
1405
1533
  edit((current) => ({
1406
1534
  ...current,
1407
1535
  nodes: current.nodes.filter((node) => node.id !== nodeId),
@@ -1450,6 +1578,29 @@ function DurabilityBanner({ durability, }) {
1450
1578
  function CanvasSkeleton() {
1451
1579
  return (_jsx("div", { className: "flex h-full w-full items-center justify-center bg-zinc-50 dark:bg-zinc-950", children: _jsxs("div", { className: "flex items-center gap-3", children: [_jsx("div", { className: "h-16 w-48 animate-pulse rounded-lg bg-zinc-200 dark:bg-zinc-800" }), _jsx(ArrowRight, { size: 14, className: MUTED }), _jsx("div", { className: "h-16 w-48 animate-pulse rounded-lg bg-zinc-200 dark:bg-zinc-800" }), _jsx(ArrowRight, { size: 14, className: MUTED }), _jsx("div", { className: "h-16 w-48 animate-pulse rounded-lg bg-zinc-200 dark:bg-zinc-800" })] }) }));
1452
1580
  }
1581
+ /**
1582
+ * That there are none, said rather than drawn as a blank canvas.
1583
+ *
1584
+ * The zero case used to be nearly unreachable: a deployment that had connectors
1585
+ * got them wrapped into graphs at boot, so `#workflows` opened onto thirteen of
1586
+ * them. Nothing wraps anything now — a graph exists because somebody drew one —
1587
+ * so a deployment that has never drawn one opens onto an empty canvas, which is
1588
+ * pixel-identical to a workflow whose nodes have all been deleted and to a list
1589
+ * that failed to load in a way the query did not notice.
1590
+ *
1591
+ * So it says which of the three it is, and what to do about it. The distinction
1592
+ * this file already draws between {@link CanvasSkeleton} and
1593
+ * {@link CanvasFailure} is the same one, for the same reason: three states that
1594
+ * render identically and mean different things need one of them to speak.
1595
+ *
1596
+ * It carries no button. The control that creates a workflow is the `New
1597
+ * workflow` option already selected in the picker three lines below this note,
1598
+ * and a second affordance pointing at the same act is how somebody ends up
1599
+ * wondering whether the two do different things.
1600
+ */
1601
+ function NothingDrawnYet() {
1602
+ return (_jsxs("div", { className: cn('mt-2.5 flex flex-wrap items-baseline gap-x-2 rounded-md border border-dashed px-2.5 py-1.5', RULE), children: [_jsxs("p", { className: cn('font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: ["No ", WORKFLOW_NAME.plural, " yet"] }), _jsxs("p", { className: cn('text-[11px] leading-relaxed', MUTED), children: ["Nothing is missing \u2014 this deployment has never had one drawn. Add a source, wire it into a sink and save, and it becomes the first. If this deployment has connectors already loading data, they are not shown here and nothing turns them into ", WORKFLOW_NAME.plural, "automatically."] })] }));
1603
+ }
1453
1604
  function CanvasFailure({ error, onRetry, }) {
1454
1605
  return (_jsx("div", { className: "flex h-full w-full items-center justify-center bg-red-50 px-6 dark:bg-red-950/30", children: _jsxs("div", { className: "max-w-md text-center", children: [_jsx(CircleAlert, { size: 18, className: "mx-auto text-red-600" }), _jsxs("p", { className: "mt-2 text-sm text-red-700 dark:text-red-300", children: ["The ", WORKFLOW_NAME.plural, " could not be read, so nothing below is drawn. This is not an empty ", WORKFLOW_NAME.singular, "."] }), _jsx("p", { className: "mt-1 font-mono text-[11px] text-red-600 dark:text-red-400", children: error instanceof Error ? error.message : 'No reason was given.' }), _jsx("button", { type: "button", onClick: onRetry, className: "mt-3 rounded-md border border-red-300 px-3 py-1 text-xs text-red-700 dark:border-red-800 dark:text-red-300", children: "Try again" })] }) }));
1455
1606
  }
@@ -1514,8 +1665,21 @@ function PendingWork({ pending, label, onInspect, }) {
1514
1665
  * description of it. Only which end of the edge to name, and how removing it is
1515
1666
  * announced, differ; `children` carries whatever belongs under the list.
1516
1667
  */
1517
- function WiringList({ title, edges, otherEnd, describeRemoval, canEdit, onDisconnect, children, }) {
1518
- return (_jsxs("section", { children: [_jsx("h3", { className: cn('font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: title }), edges.length === 0 ? (_jsx("p", { className: cn('mt-1 text-[11px]', MUTED), children: "Nothing yet." })) : (_jsx("ul", { className: "mt-1 space-y-1", children: edges.map((edge) => (_jsxs("li", { className: "flex items-center gap-1.5 text-[11px]", children: [_jsx("span", { className: "truncate", children: otherEnd(edge) }), canEdit && (_jsx(Tooltip, { content: "Remove this connection.", children: _jsx("button", { type: "button", onClick: () => onDisconnect(edge), "aria-label": describeRemoval(otherEnd(edge)), className: "ml-auto rounded p-0.5 text-zinc-400 hover:text-red-600", children: _jsx(Unplug, { size: 11 }) }) }))] }, edgeId(edge)))) })), children] }));
1668
+ function WiringList({ title, edges, otherEnd, describeRemoval, canEdit, onDisconnect, onBranch, children, }) {
1669
+ return (_jsxs("section", { children: [_jsx("h3", { className: cn('font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: title }), edges.length === 0 ? (_jsx("p", { className: cn('mt-1 text-[11px]', MUTED), children: "Nothing yet." })) : (_jsx("ul", { className: "mt-1 space-y-1", children: edges.map((edge) => (_jsxs("li", { className: "flex items-center gap-1.5 text-[11px]", children: [_jsx("span", { className: "truncate", children: otherEnd(edge) }), onBranch && (
1670
+ // Beside the wire it belongs to rather than as two lists headed
1671
+ // "Then" and "Else", because the branch is a property of the
1672
+ // wire: splitting the list would mean a wire changing sides has
1673
+ // to move between two controls, and the order the wires were
1674
+ // drawn in — which is what the canvas draws — would be lost.
1675
+ _jsx("div", { className: "ml-auto w-28 shrink-0", children: _jsx(Select, { ariaLabel: `Which branch feeds ${otherEnd(edge)}`, value: edge.branch ?? '', onValueChange: (branch) => {
1676
+ if (!isWorkflowBranchLabel(branch))
1677
+ return;
1678
+ onBranch(edge, branch);
1679
+ }, options: WORKFLOW_BRANCH_LABELS.map((label) => ({
1680
+ value: label,
1681
+ label,
1682
+ })), placeholder: "branch?", disabled: !canEdit }) })), canEdit && (_jsx(Tooltip, { content: "Remove this connection.", children: _jsx("button", { type: "button", onClick: () => onDisconnect(edge), "aria-label": describeRemoval(otherEnd(edge)), className: "ml-auto rounded p-0.5 text-zinc-400 hover:text-red-600", children: _jsx(Unplug, { size: 11 }) }) }))] }, edgeId(edge)))) })), children] }));
1519
1683
  }
1520
1684
  /**
1521
1685
  * Which code runs here, and a way into it.
@@ -1561,9 +1725,23 @@ function TransformInspector({ node, transforms, canEdit, creating, createError,
1561
1725
  *
1562
1726
  * The type is set here, on the node that commits it, rather than once for the
1563
1727
  * whole graph — several sinks may write several types.
1728
+ *
1729
+ * ## The way out to the type
1730
+ *
1731
+ * This inspector is the one place in the whole canvas that names an object type,
1732
+ * so it is the only honest place for a link to the model screen. It sits under
1733
+ * the picker rather than in the header, and it names the type rather than saying
1734
+ * "Open the model": the destination is that type's page, and a link whose label
1735
+ * describes a screen rather than a thing gives no clue what pressing it shows.
1736
+ *
1737
+ * Rendered only when a type is actually chosen. A fresh sink's `targetType` is
1738
+ * the empty string, and `#model?type=` names nothing — it would land on the
1739
+ * model screen's first type and look, exactly, like a link that worked.
1564
1740
  */
1565
- function SinkInspector({ node, typeOptions, canEdit, onChange, }) {
1566
- return (_jsxs("div", { className: "space-y-3", children: [_jsx(SelectField, { label: "Commits", ariaLabel: "Which object type this sink writes", value: node.targetType, onValueChange: (targetType) => onChange({ ...node, targetType }), options: typeOptions, placeholder: "Choose one type\u2026", disabled: !canEdit, hint: "The type is set here, on the node that commits it, rather than once for the whole graph \u2014 several sinks may write several types." }), _jsx(SelectField, { label: "Commit mode", ariaLabel: "Whether this sink replaces the dataset or merges into it", value: node.mode ?? 'full', onValueChange: (mode) => onChange({
1741
+ function SinkInspector({ node, typeOptions, canEdit, modelHref, onChange, }) {
1742
+ const target = node.targetType.trim();
1743
+ const href = target.length > 0 ? modelHref?.(target) : undefined;
1744
+ return (_jsxs("div", { className: "space-y-3", children: [_jsx(SelectField, { label: "Commits", ariaLabel: "Which object type this sink writes", value: node.targetType, onValueChange: (targetType) => onChange({ ...node, targetType }), options: typeOptions, placeholder: "Choose one type\u2026", disabled: !canEdit, hint: "The type is set here, on the node that commits it, rather than once for the whole graph \u2014 several sinks may write several types." }), href && (_jsxs("a", { href: href, "aria-label": `Open ${target} on the model screen`, className: cn('inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-xs outline-none', RULE, 'hover:bg-zinc-50 focus-visible:ring-2 focus-visible:ring-sky-500/40 dark:hover:bg-zinc-800'), children: [_jsx(Database, { size: 12, "aria-hidden": true }), "Open ", target, _jsx(ExternalLink, { size: 12, "aria-hidden": true, className: MUTED })] })), _jsx(SelectField, { label: "Commit mode", ariaLabel: "Whether this sink replaces the dataset or merges into it", value: node.mode ?? 'full', onValueChange: (mode) => onChange({
1567
1745
  ...node,
1568
1746
  mode: mode === 'incremental' ? 'incremental' : 'full',
1569
1747
  }), options: [
@@ -1574,32 +1752,101 @@ function SinkInspector({ node, typeOptions, canEdit, onChange, }) {
1574
1752
  /**
1575
1753
  * Which workflow this node hands its step to, and what it hands it.
1576
1754
  *
1577
- * ## Two fields, typed, and no picker
1578
- *
1579
- * The obvious design is a dropdown of the workflows this deployment has, and it
1580
- * cannot be built honestly today: nothing can enumerate them. The durable
1581
- * engine answers `workflowBody(name, version)` for the process asking and
1582
- * nothing else, and a missing body means *either* "not registered" *or* "its
1583
- * body is in another SDK" *or* "it is a group resolved against a live worker" —
1584
- * so a list inferred from it would omit precisely the cross-SDK workflows this
1585
- * node exists to call, and would omit them silently. A picker that quietly
1586
- * hides the thing you are looking for is worse than a text box.
1587
- *
1588
- * So: text, and `CallableWorkflowRef` in core is the shape to hand this
1589
- * component the day a deployment can announce its registrations. One entry per
1590
- * name **and version**, never per name — a picker that chose the version for
1591
- * you would undo the pin below.
1755
+ * ## There is a picker now, and there was not before
1756
+ *
1757
+ * This used to be two text fields and a docblock explaining why a dropdown
1758
+ * could not be built honestly, and that explanation is worth keeping because it
1759
+ * is still what the picker has to be careful about. Nothing could enumerate a
1760
+ * deployment's registrations: the durable engine answered
1761
+ * `workflowBody(name, version)` for the process asking and nothing else, and a
1762
+ * missing body meant *either* "not registered" *or* "its body is in another SDK
1763
+ * behind `registerRemote`" *or* "it is a group resolved by convention against a
1764
+ * live worker". A list inferred from that would have omitted precisely the
1765
+ * cross-SDK workflows this node exists to call, and omitted them silently — a
1766
+ * picker that quietly hides the thing you are looking for is worse than a text
1767
+ * box.
1768
+ *
1769
+ * `@dudousxd/nestjs-durable-core` **0.65.0** added
1770
+ * `WorkflowEngine.announcedWorkflows()`, which is not an inference: live workers
1771
+ * publish what they can execute on the descriptor keyspace and every pod folds
1772
+ * the same statements. `GET pipeline/callable-workflows` serves it as
1773
+ * `CallableWorkflowRef`s, and the two fields below offer them. Three properties
1774
+ * of that aggregate are load-bearing here and none of them may be flattened:
1775
+ *
1776
+ * - **It lists what is runnable now, not what is known about.** The announcer is
1777
+ * always the queue's consumer, so it is neither a superset nor a subset of any
1778
+ * registry. A workflow missing from it may be perfectly real.
1779
+ * - **It is a snapshot about one heartbeat wide.** Liveness is a TTL on the
1780
+ * descriptor key, so a worker that dies takes its entries with it within about
1781
+ * half a minute. Hence the ten-second `staleTime` below, the refetch on mount,
1782
+ * and the time printed under the field. It is never cached like
1783
+ * `capabilities`, which is stale-forever and correctly so.
1784
+ * - **Disagreements are surfaced, never resolved.** Two workers claiming one
1785
+ * `name@version` from two groups mean nobody can say which queue a run would
1786
+ * land on, so `callableWorkflowBlock` — core's rule, shared with the server —
1787
+ * refuses the entry. It is still SHOWN, greyed, with the reason: an entry
1788
+ * silently dropped from a picker is the failure the old docblock was about.
1789
+ *
1790
+ * The same rule refuses a bare, unversioned announcement, which is what an
1791
+ * un-upgraded worker of any SDK publishes. A name with no version cannot satisfy
1792
+ * the pin, and offering it as though it could would be a lie the node then
1793
+ * carries.
1794
+ *
1795
+ * ## Two searchable fields, not one select over `name@version`
1796
+ *
1797
+ * The first shape of this was a single `SelectField` listing combined
1798
+ * `name@version` keys, with the two text fields left underneath it. Three things
1799
+ * were wrong with that and all three are fixed here.
1800
+ *
1801
+ * - **A popup with no search is unusable at fleet size.** A deployment
1802
+ * announcing three hundred workflows renders three hundred rows, and the only
1803
+ * gesture over them is "scroll until you see it". Both fields are `Combobox`
1804
+ * now: type to narrow, on the name, the group and the description.
1805
+ * - **Name and version are two questions and read as two.** Choosing the
1806
+ * workflow and choosing which of its versions to pin are separate decisions,
1807
+ * and a list of `billing.reconcile@1`, `billing.reconcile@2`,
1808
+ * `billing.reconcile@3` makes the *name* list three times longer to answer a
1809
+ * question about versions. The name field lists names; the version field
1810
+ * lists the versions announced for the name that was chosen.
1811
+ * - **Three controls for two values is one too many.** The select and the text
1812
+ * fields said the same two things twice, and a select that could not express
1813
+ * what somebody typed had to be shown next to a box that could.
1814
+ *
1815
+ * ## Typing something the fleet never announced still works
1816
+ *
1817
+ * That is why these are `Combobox`es and not `Select`s, and it is the property
1818
+ * the whole node depends on. A deployment whose workers have not been upgraded
1819
+ * announces little or nothing, and a picker that became the only path would make
1820
+ * this node unusable there. Base UI's `Autocomplete` has no *selected value* at
1821
+ * all — the input's text is the value and the list is a suggestion over it — so
1822
+ * both fields remain typeable at all times, including when the list is empty,
1823
+ * unavailable, or simply does not contain what somebody is pointing at.
1824
+ *
1825
+ * ## Both halves, or neither
1826
+ *
1827
+ * Splitting one select into two raised the failure the single select could not
1828
+ * have: a name committed on its own, leaving a node that looks configured and
1829
+ * runs whatever is newest on the day it runs. See {@link CallInspector}'s
1830
+ * `chooseName` — choosing a name writes the version in the SAME update whenever
1831
+ * the fleet announces exactly one, which is the common case and stays one
1832
+ * action, and blanks it rather than guessing when it does not. Blank is refused
1833
+ * by `callIsUnnamed`, and the note under the field says so before the save does.
1592
1834
  *
1593
1835
  * ## Why the version is a required field and not a convenience
1594
1836
  *
1595
1837
  * Without it the load would run whichever version is registered on the day it
1596
1838
  * runs, so the person who owns that workflow could change what this pipeline
1597
1839
  * does by deploying theirs. With it, a mismatch stops the load and says so.
1598
- * What it cannot do is *prevent* the wrong version starting: the engine starts
1599
- * the newest registered version and takes no version argument, so the check
1600
- * happens immediately after the start and cancels. The note below says that in
1601
- * the room where somebody is typing the version, rather than only in a
1602
- * docblock they will never open.
1840
+ * What it still cannot do is *prevent* the wrong version starting. `engine.start`
1841
+ * takes a pinned `version` as of durable 0.65.0, but the catalog does not pass
1842
+ * one, and that is a decision rather than an oversight: a pinned start is
1843
+ * refused outright on the two SYNTHESIZED registration paths — a child
1844
+ * inheriting a remote ancestor's routing, and convention routing to a live
1845
+ * worker group — which are exactly how a cross-SDK workflow is reached. Pinning
1846
+ * at the start would therefore break the calls this node exists for. So the
1847
+ * check still happens immediately after the start, and cancels. The note under
1848
+ * the fields says that in the room where somebody is typing the version, rather
1849
+ * than only in a docblock they will never open.
1603
1850
  */
1604
1851
  function CallInspector({ node, canEdit, onChange, }) {
1605
1852
  // Held locally, pushed up when it parses — the same rule `SourceInspector`
@@ -1608,6 +1855,22 @@ function CallInspector({ node, canEdit, onChange, }) {
1608
1855
  // that reformats mid-keystroke is unusable.
1609
1856
  const [text, setText] = useState(() => configText(node.config));
1610
1857
  const [invalid, setInvalid] = useState(false);
1858
+ const client = useCatalogClient();
1859
+ // Asked here rather than by the canvas and threaded down, because this is the
1860
+ // only component that wants it and a call node is a small minority of the
1861
+ // nodes anybody draws — a canvas-level query would ask every deployment for
1862
+ // its fleet on every page load to serve a field most graphs never open.
1863
+ const announced = useQuery({
1864
+ queryKey: catalogQueryKeys.callableWorkflows,
1865
+ queryFn: () => client.listCallableWorkflows(),
1866
+ // Ten seconds, against the descriptor TTL of about thirty-five. Long enough
1867
+ // that opening and closing the sheet does not re-ask, short enough that a
1868
+ // worker which died while somebody was reading is gone before they choose.
1869
+ // Emphatically NOT `Infinity`, which is right for `capabilities` and would
1870
+ // here pin the list to whatever the fleet looked like when the tab opened.
1871
+ staleTime: 10_000,
1872
+ retry: false,
1873
+ });
1611
1874
  const pushConfig = (next) => {
1612
1875
  setText(next);
1613
1876
  const parsed = parseConfigText(next);
@@ -1615,10 +1878,674 @@ function CallInspector({ node, canEdit, onChange, }) {
1615
1878
  if (parsed !== undefined)
1616
1879
  onChange({ ...node, config: parsed });
1617
1880
  };
1618
- return (_jsxs("div", { className: "space-y-3", children: [_jsx(TextField, { label: "Workflow", value: node.callName, onChange: (callName) => onChange({ ...node, callName }), placeholder: "billing.reconcile", disabled: !canEdit, hint: "The name it is registered under in this deployment, exactly. Its body may be in another language \u2014 that is the point of calling it rather than writing it here." }), _jsx(TextField, { label: "Version", value: node.callVersion, onChange: (callVersion) => onChange({ ...node, callVersion }), placeholder: "1", disabled: !canEdit, hint: "Pinned, and part of what this graph is. Registered without a version, a workflow is version 1. Repointing this at another version is an edit to this graph, and shows up as one." }), _jsx(TextAreaField, { label: "Parameters", value: text, onChange: pushConfig, rows: 5, mono: true, placeholder: "{}", disabled: !canEdit, hint: invalid
1881
+ const refs = announced.data?.workflows ?? [];
1882
+ const name = node.callName.trim();
1883
+ const version = node.callVersion.trim();
1884
+ // Every announcement of the name currently in the box — including the blocked
1885
+ // ones, which is the point. What the version field offers is derived from
1886
+ // this, so an entry that cannot be pinned appears there greyed rather than
1887
+ // vanishing between the two fields.
1888
+ const forName = refs.filter((ref) => ref.name === name);
1889
+ const nameOptions = callableNameOptions(refs);
1890
+ const versionOptions = callableVersionOptions(forName);
1891
+ // The one announcement this node is pinned to, when it is pinned to one at
1892
+ // all. A node pointing at something the fleet is not announcing gets no
1893
+ // confirmation line rather than a nearest match — saying "a live worker
1894
+ // announces this" about an entry nobody announced is the lie the whole
1895
+ // component is arranged against.
1896
+ //
1897
+ // A blocked entry can never be it, however exactly the two strings line up:
1898
+ // an `ambiguous-group` entry is not a pin anybody can act on, and an entry
1899
+ // with no version cannot be one at all, however empty the version field
1900
+ // happens to be.
1901
+ const chosen = forName.find((ref) => ref.version !== undefined && ref.version === version && !callableWorkflowBlock(ref));
1902
+ const blocked = refs
1903
+ .map((ref) => ({ ref, block: callableWorkflowBlock(ref) }))
1904
+ .filter((entry) => Boolean(entry.block));
1905
+ // Announced, pinnable and not yet chosen: the state where the name is settled
1906
+ // and the version is a real question. Worth a sentence of its own because it
1907
+ // is the ONLY way this pair of fields can leave a node half-pinned, and the
1908
+ // person who just picked a name is the one who can finish it.
1909
+ const undecided = name.length > 0 && version.length === 0 && versionOptions.length > 0;
1910
+ // Two different silences, and telling somebody the wrong one is worse than
1911
+ // telling them nothing. An empty aggregate is a fact about the DEPLOYMENT and
1912
+ // the server's own sentence explains it; an empty aggregate is not what a
1913
+ // search that matched none of three hundred announcements means, and printing
1914
+ // "no durable engine resolved" over that would be a diagnosis of the wrong
1915
+ // thing entirely.
1916
+ let noNames;
1917
+ if (announced.isPending)
1918
+ noNames = 'Asking the live workers what they can execute…';
1919
+ else if (refs.length > 0)
1920
+ noNames =
1921
+ 'No live worker announces a workflow by that name. Type it anyway if you know it is there — a worker too old to publish its registrations still runs the workflow.';
1922
+ else
1923
+ noNames =
1924
+ announced.data?.detail ??
1925
+ 'Nothing here could be asked what this deployment can execute, so there is no list to choose from. Type the workflow name and the version to pin.';
1926
+ /**
1927
+ * Commit a name, and the version with it whenever the fleet leaves no choice.
1928
+ *
1929
+ * Splitting one `name@version` select into two fields is what makes this
1930
+ * function necessary: a name committed on its own leaves a node that looks
1931
+ * configured and runs whatever is newest on the day it runs, which is the
1932
+ * single failure the pin exists to prevent. So the version moves in the SAME
1933
+ * update, by three rules, in order:
1934
+ *
1935
+ * 1. **The version already held is announced for the new name** — keep it.
1936
+ * Re-picking the same name must not disturb a settled node, and a version
1937
+ * two workflows share is not a coincidence worth punishing.
1938
+ * 2. **The version is blank, or was the old name's** — replace it. Blank is
1939
+ * the fresh node; the old name's version is now stale, and leaving it would
1940
+ * produce a pin nobody announced while looking like one somebody chose. It
1941
+ * becomes the one pinnable version when there is exactly one — the common
1942
+ * case, and it stays one action — and blank otherwise, because a guess
1943
+ * between two versions is the thing the pin exists to stop. Blank is
1944
+ * refused by `callIsUnnamed` and said out loud under the field.
1945
+ * 3. **Anything else** — leave it. A version somebody typed that the fleet
1946
+ * never offered is theirs, and this field has no standing to erase it.
1947
+ *
1948
+ * `callableWorkflowBlock` decides what counts as pinnable throughout, here at
1949
+ * the moment of commit and not only where rows are greyed. A disabled row is a
1950
+ * rendering decision; the rule about what may be written onto the graph is not
1951
+ * one, and a Base UI item that stopped honouring `disabled` must not be able
1952
+ * to get round it.
1953
+ */
1954
+ const chooseName = (option) => {
1955
+ const offered = pinnableVersions(refs, option.value);
1956
+ if (offered.length === 0)
1957
+ return;
1958
+ if (offered.includes(version)) {
1959
+ onChange({ ...node, callName: option.value });
1960
+ return;
1961
+ }
1962
+ const ours = version.length === 0 || pinnableVersions(refs, name).includes(version);
1963
+ const only = offered.length === 1 ? offered[0] : undefined;
1964
+ onChange({ ...node, callName: option.value, callVersion: ours ? (only ?? '') : version });
1965
+ };
1966
+ /**
1967
+ * Commit a version, against the name in the box.
1968
+ *
1969
+ * Looked up as an announcement rather than taken as a string, for the same
1970
+ * reason `chooseName` re-checks: the row carries a claim, and the claim is
1971
+ * what `callableWorkflowBlock` gets to refuse.
1972
+ */
1973
+ const chooseVersion = (option) => {
1974
+ const ref = forName.find((candidate) => candidate.version === option.value);
1975
+ if (!ref || ref.version === undefined || callableWorkflowBlock(ref))
1976
+ return;
1977
+ onChange({ ...node, callName: ref.name, callVersion: ref.version });
1978
+ };
1979
+ return (_jsxs("div", { className: "space-y-3", children: [_jsx(ComboboxField, { label: "Workflow", value: node.callName, onValueChange: (callName) => onChange({ ...node, callName }), onSelect: chooseName, options: nameOptions, placeholder: "billing.reconcile", disabled: !canEdit, emptyMessage: noNames, hint: _jsxs(_Fragment, { children: ["The name it is registered under in this deployment, exactly. Type to search what a live worker says it can execute right now, read at ", readTime(announced.data?.observedAt), " \u2014 a snapshot, not a registry, so a worker that stops beating drops off it within about half a minute and one too old to announce its registrations was never on it. Anything you type is accepted whether or not it is on the list; its body may be in another language, which is the point of calling it rather than writing it here."] }) }), _jsx(ComboboxField, { label: "Version", value: node.callVersion, onValueChange: (callVersion) => onChange({ ...node, callVersion }), onSelect: chooseVersion, options: versionOptions, placeholder: "1", disabled: !canEdit, emptyMessage: name.length === 0
1980
+ ? 'Name a workflow first, and the versions announced for it are listed here.'
1981
+ : `No live worker announces a version of "${name}". Type the one you mean.`, hint: "Pinned, and part of what this graph is. Registered without a version, a workflow is version 1. Repointing this at another version is an edit to this graph, and shows up as one." }), undecided && (_jsxs("p", { className: cn('text-[11px] leading-relaxed', MUTED), children: ["The fleet announces more than one version of \u201C", name, "\u201D, so nothing here picked one for you. Until you do, this node names half of what it needs and the graph will not save."] })), chosen && (_jsxs("p", { className: cn('text-[11px] leading-relaxed', MUTED), children: ["This exact pin is announced right now: ", chosen.name, "@", chosen.version, chosen.group ? `, on group ${chosen.group}` : '', chosen.workers === 1 ? ' — by one worker, so it is a single point of failure.' : '.'] })), blocked.length > 0 && (_jsx("div", { className: cn('space-y-1 text-[11px] leading-relaxed', MUTED), children: blocked.map(({ ref, block }) => (_jsx("p", { children: block.message }, callableKey(ref)))) })), _jsx(TextAreaField, { label: "Parameters", value: text, onChange: pushConfig, rows: 5, mono: true, placeholder: "{}", disabled: !canEdit, hint: invalid
1619
1982
  ? 'That is not valid JSON yet, so it has not been saved onto the node.'
1620
1983
  : 'A JSON object, handed to the workflow as `input`. Beside it, under `catalog`, it also gets this run’s id and the staged rows of whatever feeds this node — handles, never the rows themselves. Not a place for a password: name an env var the callee already reads.' }), _jsx("p", { className: cn('text-[11px] leading-relaxed', MUTED), children: "This runs as a child of the load, with its own retries, and the load waits for it. If it fails, this node fails and nothing after it runs. Cancelling the load cancels it; letting the load time out does not, so a workflow you call should carry its own execution timeout." }), _jsxs("p", { className: cn('text-[11px] leading-relaxed', MUTED), children: ["Whether two loads calling it can overlap is decided by how ", _jsx("em", { children: "it" }), " was registered, not by this graph \u2014 and on the path a workflow in another language is reached by, that declaration may not be visible to the engine at all, so assume it can run alongside itself."] })] }));
1621
1984
  }
1985
+ /**
1986
+ * What identifies one announced entry among the others.
1987
+ *
1988
+ * `name@version`, and the bare name when nobody announced a version — the same
1989
+ * key the durable aggregate sorts on, and the reason it can identify a row at
1990
+ * all: the fleet reports one entry per `name@version`, so two entries can never
1991
+ * collide. A key of the name alone would collapse the versions into one, which
1992
+ * is the picker undoing the pin.
1993
+ */
1994
+ function callableKey(ref) {
1995
+ return ref.version === undefined ? ref.name : `${ref.name}@${ref.version}`;
1996
+ }
1997
+ /**
1998
+ * The announced names, one row each, for the workflow field.
1999
+ *
2000
+ * One row per NAME here and one row per version in the field below, which is the
2001
+ * split this pair of fields exists to make. A single list of `name@version` keys
2002
+ * answers the version question inside the name question: a workflow with eight
2003
+ * versions takes eight rows of a list somebody is scanning for a name, and the
2004
+ * name they want is eight times harder to find because of versions they have not
2005
+ * been asked about yet.
2006
+ *
2007
+ * A name is refused only when EVERY announcement under it is refused — one
2008
+ * unpinnable version among four pinnable ones says nothing about the name. The
2009
+ * refusals themselves are per entry and belong to the version field, which shows
2010
+ * them; this line only reports that there is nothing pinnable left.
2011
+ */
2012
+ function callableNameOptions(refs) {
2013
+ const names = [...new Set(refs.map((ref) => ref.name))].sort();
2014
+ return names.map((name) => callableNameOption(name, refs.filter((ref) => ref.name === name)));
2015
+ }
2016
+ /** One name, folded across every announcement of it. */
2017
+ function callableNameOption(name, forName) {
2018
+ const pinnable = forName.filter((ref) => callableWorkflowBlock(ref) === undefined);
2019
+ const groups = [...new Set(forName.flatMap(groupsOf))].sort();
2020
+ const description = forName.find((ref) => ref.description !== undefined)?.description;
2021
+ const workers = forName.reduce((most, ref) => Math.max(most, ref.workers ?? 0), 0);
2022
+ const facts = pinnable.length === 0 ? refusalFacts(forName) : [countOf(pinnable.length, 'version')];
2023
+ // The group is the single most useful fact here — the only signal
2024
+ // distinguishing "this body lives in another process, in another language"
2025
+ // from "this one is local", which is precisely what a missing `workflowBody`
2026
+ // could never tell apart.
2027
+ if (groups.length === 1)
2028
+ facts.push(`group ${groups[0]}`);
2029
+ if (groups.length > 1)
2030
+ facts.push(`groups ${groups.join(', ')}`);
2031
+ if (description)
2032
+ facts.push(description);
2033
+ // One worker is a single point of failure, and a graph built on it should say
2034
+ // so before the day it matters.
2035
+ if (workers > 0)
2036
+ facts.push(countOf(workers, 'worker'));
2037
+ return {
2038
+ value: name,
2039
+ label: name,
2040
+ hint: facts.join(' · '),
2041
+ // Searched but not shown. Somebody hunting the Python half of the fleet
2042
+ // types the group, and somebody who half-remembers what a workflow does
2043
+ // types that — a search over the name alone answers both with "nothing".
2044
+ keywords: [...groups, description ?? ''].join(' '),
2045
+ disabled: pinnable.length === 0,
2046
+ };
2047
+ }
2048
+ /**
2049
+ * Why nothing under a name can be pinned, in the few words a popup row has.
2050
+ *
2051
+ * Short deliberately: this line truncates inside the popup, and the full
2052
+ * sentences `callableWorkflowBlock` writes are printed under the fields, where
2053
+ * nothing truncates them.
2054
+ */
2055
+ function refusalFacts(forName) {
2056
+ const codes = new Set(forName.map((ref) => callableWorkflowBlock(ref)?.code));
2057
+ const facts = [];
2058
+ if (codes.has('no-version'))
2059
+ facts.push('no version announced — cannot be pinned');
2060
+ if (codes.has('ambiguous-group'))
2061
+ facts.push('claimed by two groups — ambiguous');
2062
+ return facts;
2063
+ }
2064
+ /**
2065
+ * The versions announced for one name, one row each.
2066
+ *
2067
+ * Every announcement of that name, including the ones that cannot be chosen. A
2068
+ * bare, unversioned announcement — what an un-upgraded worker of any SDK
2069
+ * publishes — is a row here too, greyed and labelled as having no version: it is
2070
+ * a real thing the fleet said about this name, and the alternative is a picker
2071
+ * that quietly disagrees with the sentence printed underneath it.
2072
+ */
2073
+ function callableVersionOptions(forName) {
2074
+ return forName
2075
+ .map(callableVersionOption)
2076
+ .sort((left, right) => left.label.localeCompare(right.label, undefined, { numeric: true }));
2077
+ }
2078
+ function callableVersionOption(ref) {
2079
+ const block = callableWorkflowBlock(ref);
2080
+ const facts = [];
2081
+ if (block?.code === 'no-version')
2082
+ facts.push('no version announced — cannot be pinned');
2083
+ if (block?.code === 'ambiguous-group')
2084
+ facts.push(`two groups (${groupsOf(ref).join(', ')}) — ambiguous`);
2085
+ if (ref.group)
2086
+ facts.push(`group ${ref.group}`);
2087
+ if (ref.description)
2088
+ facts.push(ref.description);
2089
+ if (ref.workers !== undefined)
2090
+ facts.push(countOf(ref.workers, 'worker'));
2091
+ return {
2092
+ // The fleet folds one entry per `name@version`, so within one name the
2093
+ // versions are distinct and at most one entry is bare — which makes the
2094
+ // empty string a safe identity for that one rather than a collision.
2095
+ value: ref.version ?? '',
2096
+ label: ref.version ?? 'no version announced',
2097
+ hint: facts.join(' · '),
2098
+ keywords: [ref.group ?? '', ref.description ?? ''].join(' '),
2099
+ disabled: block !== undefined,
2100
+ };
2101
+ }
2102
+ /** "1 worker" / "3 workers". A count whose plural is not left to the reader. */
2103
+ function countOf(count, noun) {
2104
+ return count === 1 ? `1 ${noun}` : `${count} ${noun}s`;
2105
+ }
2106
+ /**
2107
+ * The versions of one name that may actually be pinned.
2108
+ *
2109
+ * `callableWorkflowBlock` is the authority, not the presence of a version
2110
+ * string: an `ambiguous-group` entry has a perfectly good version and still may
2111
+ * not be committed.
2112
+ */
2113
+ function pinnableVersions(refs, name) {
2114
+ const versions = [];
2115
+ for (const ref of refs) {
2116
+ if (ref.name !== name || ref.version === undefined)
2117
+ continue;
2118
+ if (callableWorkflowBlock(ref) === undefined)
2119
+ versions.push(ref.version);
2120
+ }
2121
+ return versions;
2122
+ }
2123
+ /**
2124
+ * Every group named in one announcement.
2125
+ *
2126
+ * `group` is set when the announcers agree on exactly one, and left unset when
2127
+ * they disagree — in which case the values are in `disagreements` and both are
2128
+ * worth showing. Silence contributes nothing, because silence is not a claim.
2129
+ */
2130
+ function groupsOf(ref) {
2131
+ if (ref.group !== undefined)
2132
+ return [ref.group];
2133
+ return ref.disagreements?.find((entry) => entry.axis === 'group')?.values ?? [];
2134
+ }
2135
+ /**
2136
+ * When the fleet was asked, as a clock time.
2137
+ *
2138
+ * Printed at all because this list is a snapshot roughly one heartbeat wide, and
2139
+ * a screen that showed it with no time attached would be presenting a moment as
2140
+ * a standing fact. Falls back to the plain string rather than to nothing when
2141
+ * the server sends something unparseable — a server that answered is a server
2142
+ * that answered, and hiding its timestamp because the format surprised us would
2143
+ * remove the one caveat this field is here to carry.
2144
+ */
2145
+ function readTime(observedAt) {
2146
+ if (!observedAt)
2147
+ return 'an unknown time';
2148
+ const at = new Date(observedAt);
2149
+ return Number.isNaN(at.getTime()) ? observedAt : at.toLocaleTimeString();
2150
+ }
2151
+ /**
2152
+ * What this gate decides on, and what the decision costs.
2153
+ *
2154
+ * ## The kind of test comes first, and switching it replaces the test
2155
+ *
2156
+ * A gate tests one thing — a variable where the load runs, or how many rows
2157
+ * reached it — and the model says so with a union rather than with two sets of
2158
+ * optional fields. The form is built the same way round: pick the kind, then
2159
+ * fill in the fields that kind has. Switching the picker hands back a whole new
2160
+ * predicate rather than merging the old one's fields into it, which does discard
2161
+ * a variable name somebody typed — deliberately, because the alternative is a
2162
+ * node quietly carrying the leftovers of a test it is no longer making, and the
2163
+ * next reader cannot tell which of the two it will actually do.
2164
+ *
2165
+ * ## No picker for the variable, for a different reason than the call node's
2166
+ *
2167
+ * A call node has no picker because nothing can enumerate the workflows. This
2168
+ * one has no picker because the list would be *wrong*: the variables that matter
2169
+ * are the ones this deployment has and the other one does not, so a list built
2170
+ * from what the console's own process can see would offer exactly the wrong set
2171
+ * — the ones present everywhere — and quietly omit the one somebody is looking
2172
+ * for. Text, and the graph is refused until it is filled in.
2173
+ *
2174
+ * ## What is said out loud here and nowhere else
2175
+ *
2176
+ * That the value never leaves the machine, because somebody typing
2177
+ * `CLICKHOUSE_URL` into a form is entitled to know whether they have just put a
2178
+ * password on a screen. That the test runs where the *load* runs rather than
2179
+ * here, because a variable set in the console's pod and not in the worker's is
2180
+ * the way this goes wrong. And that the branch is decided once and recorded, so
2181
+ * a resumed run cannot change its mind — which is the sentence that makes the
2182
+ * run panel's "took the then branch" trustworthy.
2183
+ */
2184
+ function IfInspector({ node, canEdit, onChange, }) {
2185
+ const setPredicate = (predicate) => onChange({ ...node, predicate });
2186
+ return (_jsxs("div", { className: "space-y-3", children: [_jsx(SelectField, { label: "Decide on", ariaLabel: "What this gate branches on", value: node.predicate.kind, onValueChange: (kind) => {
2187
+ // Narrowed rather than trusted, because `onValueChange` hands back a
2188
+ // string and the model wants one of two. An unrecognised one is
2189
+ // dropped: a gate is never left holding a test nothing can evaluate.
2190
+ if (!isWorkflowPredicateKind(kind))
2191
+ return;
2192
+ setPredicate(freshPredicate(kind));
2193
+ }, options: [
2194
+ { value: 'env', label: 'An environment variable', hint: 'where the load runs' },
2195
+ {
2196
+ value: 'rowCount',
2197
+ label: 'How many rows reached it',
2198
+ hint: 'off the run’s own record',
2199
+ },
2200
+ ], disabled: !canEdit, hint: "A variable tells one deployment apart from another. A row count tells a load that found data apart from one that found none \u2014 which is how a sink is kept from committing an empty snapshot over what is live." }), _jsx(PredicateFields, { predicate: node.predicate, canEdit: canEdit, onChange: setPredicate }), _jsxs("p", { className: cn('text-[11px] leading-relaxed', MUTED), children: ["The wires out of this node are labelled ", _jsx("strong", { children: "then" }), " and ", _jsx("strong", { children: "else" }), ", under \u201CFeeds\u201D below. To invert the test, swap which one is which \u2014 there is no \u201Cnot\u201D, because two ways to say one thing is two places to look when a load goes the way you did not expect."] }), _jsxs("p", { className: cn('text-[11px] leading-relaxed', MUTED), children: ["Everything reachable only through the branch that is not taken is ", _jsx("em", { children: "skipped" }), ", never failed. A sink on that side commits nothing, so whatever it publishes stays exactly as it was \u2014 that is the point, and the run panel says so rather than leaving a blank."] }), _jsx("p", { className: cn('text-[11px] leading-relaxed', MUTED), children: "The branch is decided once, at the moment this node runs, and recorded on the run. A load that is resumed after a crash reads the decision back instead of asking again, so it cannot take one branch on the way in and the other on the way back." })] }));
2201
+ }
2202
+ /**
2203
+ * The test a freshly picked kind starts as.
2204
+ *
2205
+ * An env test starts blank, so the graph refuses to publish until somebody names
2206
+ * a variable — there is nothing to guess. A row-count test starts at 1, which is
2207
+ * not a guess but the *only* threshold that means "did anything arrive at all",
2208
+ * which is the case the predicate was built for; a bigger number is a claim
2209
+ * about a particular pipeline and is typed.
2210
+ */
2211
+ function freshPredicate(kind) {
2212
+ if (kind === 'env')
2213
+ return { kind: 'env', envVar: '' };
2214
+ if (kind === 'rowCount')
2215
+ return { kind: 'rowCount', atLeast: 1 };
2216
+ return unreachablePredicateKind(kind, 'freshPredicate');
2217
+ }
2218
+ /**
2219
+ * The fields one kind of test has, and none of the fields the other has.
2220
+ *
2221
+ * Split per kind and ending in a refusal, so a predicate kind added to the model
2222
+ * without a form here stops the build naming this file — the same rule
2223
+ * `KindInspector` follows for node kinds, and for the same reason: the failure
2224
+ * it prevents is a node somebody can select, that shows nothing to configure,
2225
+ * and that runs anyway.
2226
+ */
2227
+ function PredicateFields({ predicate, canEdit, onChange, }) {
2228
+ if (predicate.kind === 'env') {
2229
+ return _jsx(EnvPredicateFields, { predicate: predicate, canEdit: canEdit, onChange: onChange });
2230
+ }
2231
+ if (predicate.kind === 'rowCount') {
2232
+ return _jsx(RowCountPredicateFields, { predicate: predicate, canEdit: canEdit, onChange: onChange });
2233
+ }
2234
+ return unreachablePredicateKind(predicate, 'PredicateFields');
2235
+ }
2236
+ function EnvPredicateFields({ predicate, canEdit, onChange, }) {
2237
+ // Whether to compare against a value at all is a *mode*, not an empty text
2238
+ // box: `equals: ''` is a real test ("set, but blank") and `equals: undefined`
2239
+ // is a different one ("set to anything"), and a single field could not express
2240
+ // both — clearing the box would silently switch which question is being asked.
2241
+ const comparing = predicate.equals !== undefined;
2242
+ return (_jsxs(_Fragment, { children: [_jsx(TextField, { label: "Environment variable", value: predicate.envVar, onChange: (envVar) => onChange({ ...predicate, envVar }), placeholder: "CLICKHOUSE_URL", disabled: !canEdit, hint: "The name of a variable on the machine that runs the load \u2014 not on this one. Only its name is stored, and only \u201Cset\u201D or \u201Cnot set\u201D is ever written to the run log, so naming one that holds a credential is safe." }), _jsx(SelectField, { label: "Test", ariaLabel: "What this gate tests the variable for", value: comparing ? 'equals' : 'set', onValueChange: (mode) => onChange(mode === 'equals' ? { ...predicate, equals: '' } : { ...predicate, equals: undefined }), options: [
2243
+ { value: 'set', label: 'Is set to anything' },
2244
+ { value: 'equals', label: 'Equals a particular value' },
2245
+ ], disabled: !canEdit, hint: "\u201CIs set\u201D is the deployment test: a deployment that has a ClickHouse has its URL and one that does not has nothing. Compare against a value when the variable exists everywhere and only its contents differ." }), comparing && (_jsx(TextField, { label: "Equals", value: predicate.equals ?? '', onChange: (equals) => onChange({ ...predicate, equals }), placeholder: "local", disabled: !canEdit, hint: "Compared exactly, with no trimming. An empty value here means \u201Cset, but blank\u201D, which is a different test from \u201Cis set to anything\u201D." }))] }));
2246
+ }
2247
+ /**
2248
+ * One threshold, and the sentence that says what it is for.
2249
+ *
2250
+ * A text box with a numeric keypad rather than `type="number"`, which is the
2251
+ * rule `ObjectExplorer` already writes down: that control drops what it cannot
2252
+ * parse and answers a scroll wheel, so a number somebody typed can change while
2253
+ * they are reading the form. Non-digits are stripped here instead, and an empty
2254
+ * box is stored as 0 — which the validator refuses by name, so a half-filled
2255
+ * gate says so on the canvas rather than publishing a test that always passes.
2256
+ */
2257
+ function RowCountPredicateFields({ predicate, canEdit, onChange, }) {
2258
+ const digits = Number.isInteger(predicate.atLeast) && predicate.atLeast > 0;
2259
+ return (_jsxs(_Fragment, { children: [_jsx(TextField, { label: "At least this many rows", value: digits ? String(predicate.atLeast) : '', onChange: (typed) => {
2260
+ const cleaned = typed.replace(/[^0-9]/g, '');
2261
+ onChange({
2262
+ ...predicate,
2263
+ atLeast: cleaned.length === 0 ? 0 : Number.parseInt(cleaned, 10),
2264
+ });
2265
+ }, inputMode: "numeric", placeholder: "1", disabled: !canEdit, hint: "1 is \u201Cdid anything arrive at all\u201D. A larger number is for a load whose export is never legitimately small \u2014 under it, treat the upstream as broken rather than as data." }), _jsx("p", { className: cn('text-[11px] leading-relaxed', MUTED), children: "The count is the one on the single wire feeding this node, taken from what that node recorded \u2014 nothing is re-counted, and nothing is read out of the staged rows." })] }));
2266
+ }
2267
+ /**
2268
+ * Building a filter's predicate, and acknowledging what it shrinks.
2269
+ *
2270
+ * Two halves, and the second one is the reason this inspector is not just a form
2271
+ * over a tree. The predicate editor is the ordinary part: a recursive tree of
2272
+ * conditions with "and"/"or" groups, built from the vocabulary core exports so a
2273
+ * form that offered an operator the runner cannot evaluate is a build failure
2274
+ * rather than a graph somebody saves and a step that throws mid-load.
2275
+ *
2276
+ * The acknowledgement is the part that matters. If this filter is the only thing
2277
+ * feeding a sink that *replaces* what a type publishes, then whatever it drops
2278
+ * disappears from that type — silently, because the run succeeds. The graph
2279
+ * cannot tell that apart from filtering to derive something new (see
2280
+ * `WorkflowFilterNode.narrows`: they are structurally identical graphs), so the
2281
+ * screen asks, per type, and the server refuses the graph until it is answered.
2282
+ * The switches below are that question, and they are shown *only* when the
2283
+ * question is live — offering them on a filter that narrows nothing would train
2284
+ * people to flip them.
2285
+ */
2286
+ function FilterInspector({ node, graph, canEdit, onChange, }) {
2287
+ // Core's answer, not this file's. A canvas that worked out its own set would
2288
+ // offer acknowledgements the server then refuses, which is a person ticking a
2289
+ // box to be told no.
2290
+ const narrowable = workflowNarrowedTypes(graph, node.id);
2291
+ const acknowledged = node.narrows ?? [];
2292
+ const setPredicate = (predicate) => onChange({ ...node, predicate });
2293
+ const setNarrows = (type, on) => {
2294
+ const next = on ? [...acknowledged, type] : acknowledged.filter((named) => named !== type);
2295
+ // Stored as absent rather than as `[]`, so "acknowledged nothing" has one
2296
+ // spelling. The boundary normalises the same way.
2297
+ onChange({ ...node, narrows: next.length === 0 ? undefined : next });
2298
+ };
2299
+ return (_jsxs("div", { className: "space-y-3", children: [_jsx(FilterPredicateEditor, { predicate: node.predicate, depth: 0, canEdit: canEdit, onChange: setPredicate, onRemove: undefined }), _jsxs("p", { className: cn('font-mono text-[10px] leading-relaxed', MUTED), children: ["keeps ", describeFilterPredicate(node.predicate)] }), _jsxs("p", { className: cn('text-[11px] leading-relaxed', MUTED), children: ["Rows that match are passed on; the rest are dropped here. The run records", ' ', _jsx("strong", { children: "how many went in and how many came out" }), ", so the panel can say what this node removed \u2014 a filter whose effect is invisible is how data goes missing quietly."] }), _jsxs("p", { className: cn('text-[11px] leading-relaxed', MUTED), children: ["A column with no value never matches, not even a \u201Cdoes not equal\u201D test \u2014 that is what a database would answer, and it is what keeps this test meaning the same thing if it is ever pushed into the source query. Use ", _jsx("em", { children: "is empty" }), " to find those rows. A value the test cannot compare against \u2014 text where the test names a number \u2014 does not match either, and the run says how many of those there were."] }), narrowable.length > 0 && (_jsx(FieldGroup, { title: "What this shrinks", hint: _jsxs(_Fragment, { children: ["This filter is the only thing feeding", ' ', narrowable.length === 1 ? 'a sink that replaces' : 'sinks that replace', " what", ' ', narrowable.length === 1 ? 'a type publishes' : 'these types publish', ". So everything it drops disappears from ", narrowable.length === 1 ? 'that type' : 'those types', " the next time this graph runs, and the run reports success while doing it. Say so here if that is what you mean. If you meant to build something new out of a subset, point the sink at a different object type; if you meant to add rows rather than replace them, set the sink to incremental."] }), children: narrowable.map((type) => (_jsx(Switch, { checked: acknowledged.includes(type), onCheckedChange: (on) => setNarrows(type, on), disabled: !canEdit, label: `Replace what ${type} publishes with the rows that pass`, hint: `The published snapshot of ${type} will hold only what this filter keeps. The type's row-count bound still applies and can still refuse the commit.` }, type))) })), acknowledged.some((type) => !narrowable.includes(type)) && (_jsxs("p", { className: "text-[11px] leading-relaxed text-amber-600 dark:text-amber-400", children: ["This filter says it narrows", ' ', acknowledged
2300
+ .filter((type) => !narrowable.includes(type))
2301
+ .map((type) => `“${type}”`)
2302
+ .join(', '), ", and it no longer does \u2014 rows now reach that sink another way, or it merges rather than replaces. Turn it off: an acknowledgement nothing reads is worse than none, because the next reader believes it."] }))] }));
2303
+ }
2304
+ /**
2305
+ * One node of the predicate tree: a group, or a single condition.
2306
+ *
2307
+ * Recursive rather than flattened, because the model is a tree and a flat list
2308
+ * of conditions with a single and/or toggle cannot express "A and (B or C)" —
2309
+ * which is the second thing anybody wants after "A and B".
2310
+ *
2311
+ * `onRemove` is absent exactly at the root, which is what makes the root
2312
+ * unremovable without a separate flag: a predicate is required, so there is
2313
+ * always at least one condition and the button that would delete the last one
2314
+ * does not exist.
2315
+ */
2316
+ function FilterPredicateEditor({ predicate, depth, canEdit, onChange, onRemove, }) {
2317
+ if (predicate.kind === 'all' || predicate.kind === 'any') {
2318
+ return (_jsx(FilterGroupEditor, { predicate: predicate, depth: depth, canEdit: canEdit, onChange: onChange, onRemove: onRemove }));
2319
+ }
2320
+ return (_jsx(FilterConditionEditor, { predicate: predicate, depth: depth, canEdit: canEdit, onChange: onChange, onRemove: onRemove }));
2321
+ }
2322
+ /** The word between a group's conditions, and the two ways to add another one. */
2323
+ function FilterGroupEditor({ predicate, depth, canEdit, onChange, onRemove, }) {
2324
+ const replaceChild = (index, child) => onChange({
2325
+ ...predicate,
2326
+ children: predicate.children.map((existing, at) => (at === index ? child : existing)),
2327
+ });
2328
+ // Removing the last child would leave an empty group, which keeps every row
2329
+ // (`all`) or drops every row (`any`) and is refused by the validator. Rather
2330
+ // than let somebody build one and then be told, removing the second-to-last
2331
+ // child collapses the group into the one that is left.
2332
+ const removeChild = (index) => {
2333
+ const left = predicate.children.filter((_, at) => at !== index);
2334
+ onChange(left.length === 1 ? left[0] : { ...predicate, children: left });
2335
+ };
2336
+ return (_jsxs("div", { className: cn('space-y-2 rounded-md border px-2 py-2', RULE), children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("div", { className: "min-w-0 flex-1", children: _jsx(SelectField, { label: "Match", ariaLabel: "Whether every condition in this group has to match, or any one of them", value: predicate.kind, onValueChange: (kind) => {
2337
+ if (kind !== 'all' && kind !== 'any')
2338
+ return;
2339
+ onChange({ ...predicate, kind });
2340
+ }, options: [
2341
+ { value: 'all', label: 'Every condition', hint: 'and' },
2342
+ { value: 'any', label: 'Any one condition', hint: 'or' },
2343
+ ], disabled: !canEdit }) }), onRemove && canEdit && (_jsx(Button, { variant: "ghost", size: "sm", onClick: onRemove, className: "mt-4 shrink-0", children: "Remove group" }))] }), predicate.children.map((child, index) => (_jsx(FilterPredicateEditor
2344
+ // Positional keys, because a condition has no id and nothing in this
2345
+ // tree is reordered — the only edits are replace-in-place, append and
2346
+ // remove, and a removal re-renders the whole subtree from the model
2347
+ // anyway. There is no draft state below this point to be preserved.
2348
+ // biome-ignore lint/suspicious/noArrayIndexKey: see above
2349
+ , { predicate: child, depth: depth + 1, canEdit: canEdit, onChange: (next) => replaceChild(index, next), onRemove: () => removeChild(index) }, index))), canEdit && (_jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { variant: "outline", size: "sm", onClick: () => onChange({ ...predicate, children: [...predicate.children, freshFilterCondition()] }), children: "Add condition" }), depth + 1 < WORKFLOW_FILTER_MAX_DEPTH && (_jsx(Button, { variant: "outline", size: "sm", onClick: () => onChange({
2350
+ ...predicate,
2351
+ children: [
2352
+ ...predicate.children,
2353
+ { kind: 'any', children: [freshFilterCondition()] },
2354
+ ],
2355
+ }), children: "Add group" }))] }))] }));
2356
+ }
2357
+ /** One condition: a column, a test, and whatever that test compares against. */
2358
+ function FilterConditionEditor({ predicate, depth, canEdit, onChange, onRemove, }) {
2359
+ return (_jsxs("div", { className: cn('space-y-2 rounded-md border px-2 py-2', RULE), children: [_jsx(TextField, { label: "Column", value: predicate.column, onChange: (column) => onChange({ ...predicate, column }), placeholder: "status", disabled: !canEdit, hint: "The bare name as the rows carry it \u2014 letters, digits and underscore, starting with a letter or underscore. No table prefix and no expression: the name has to be usable as an identifier so this test can one day be handed to the source as a WHERE. Rename anything else in a transform first." }), _jsx(SelectField, { label: "Test", ariaLabel: "What kind of test this condition makes", value: predicate.kind, onValueChange: (kind) => {
2360
+ if (!isWorkflowFilterPredicateKind(kind))
2361
+ return;
2362
+ onChange(retargetFilterCondition(predicate, kind));
2363
+ }, options: [
2364
+ { value: 'compare', label: 'Compare against a value' },
2365
+ { value: 'oneOf', label: 'Is one of a list' },
2366
+ { value: 'present', label: 'Is empty, or has a value' },
2367
+ ], disabled: !canEdit }), _jsx(FilterConditionFields, { predicate: predicate, canEdit: canEdit, onChange: onChange }), onRemove && canEdit && (_jsx("div", { className: "flex justify-end", children: _jsx(Button, { variant: "ghost", size: "sm", onClick: onRemove, children: "Remove condition" }) })), depth === 0 && canEdit && (
2368
+ // The root starts as a single condition, so the only way to reach a
2369
+ // group is from here. Wrapping rather than offering a group at the top
2370
+ // level keeps a one-condition filter looking like a one-condition
2371
+ // filter, which is what nearly all of them are.
2372
+ _jsx("div", { className: "flex justify-end", children: _jsx(Button, { variant: "outline", size: "sm", onClick: () => onChange({ kind: 'all', children: [predicate, freshFilterCondition()] }), children: "Add another condition" }) }))] }));
2373
+ }
2374
+ /**
2375
+ * The fields one kind of condition has, and none of the fields the others have.
2376
+ *
2377
+ * Split per kind and ending in a refusal, for the reason `PredicateFields`
2378
+ * gives about gates: a kind added to the model without a form here would be a
2379
+ * condition somebody can select, that shows nothing to fill in, and that decides
2380
+ * which rows a published type contains.
2381
+ */
2382
+ function FilterConditionFields({ predicate, canEdit, onChange, }) {
2383
+ if (predicate.kind === 'present') {
2384
+ return (_jsx(SelectField, { label: "Has a value?", ariaLabel: "Whether the column has to be empty or has to hold something", value: predicate.operator, onValueChange: (operator) => {
2385
+ if (operator !== 'isNull' && operator !== 'isNotNull')
2386
+ return;
2387
+ onChange({ ...predicate, operator });
2388
+ }, options: [
2389
+ { value: 'isNotNull', label: 'Has a value' },
2390
+ { value: 'isNull', label: 'Is empty' },
2391
+ ], disabled: !canEdit, hint: "The only test that can see an empty column. Every other test here treats an empty value as \u201Ccannot say\u201D, which never matches." }));
2392
+ }
2393
+ if (predicate.kind === 'oneOf') {
2394
+ return (_jsxs(_Fragment, { children: [_jsx(SelectField, { label: "In the list?", ariaLabel: "Whether the column has to be in the list or out of it", value: predicate.operator, onValueChange: (operator) => {
2395
+ if (operator !== 'in' && operator !== 'notIn')
2396
+ return;
2397
+ onChange({ ...predicate, operator });
2398
+ }, options: [
2399
+ { value: 'in', label: 'Is one of these' },
2400
+ { value: 'notIn', label: 'Is none of these' },
2401
+ ], disabled: !canEdit }), _jsx(FilterValueTypeField, { value: predicate.values[0], canEdit: canEdit, onChange: (sample) => onChange({
2402
+ ...predicate,
2403
+ values: predicate.values.map((existing) => castFilterValue(existing, sample)),
2404
+ }) }), _jsx(TextAreaField, { label: "Values", value: predicate.values.map((value) => String(value)).join('\n'), onChange: (text) => onChange({ ...predicate, values: parseFilterValues(text, predicate.values[0]) }), rows: 4, mono: true, disabled: !canEdit, hint: `One per line. At most ${WORKFLOW_FILTER_MAX_VALUES} — past that this is a join against another dataset rather than a filter, and the thing to do is read that dataset in as a second source.` })] }));
2405
+ }
2406
+ if (predicate.kind === 'compare') {
2407
+ return (_jsxs(_Fragment, { children: [_jsx(SelectField, { label: "Comparison", ariaLabel: "How the column is compared against the value", value: predicate.operator, onValueChange: (operator) => {
2408
+ if (!isWorkflowFilterOperator(operator))
2409
+ return;
2410
+ onChange({ ...predicate, operator });
2411
+ }, options: WORKFLOW_FILTER_OPERATORS.map((operator) => ({
2412
+ value: operator,
2413
+ label: FILTER_OPERATOR_LABELS[operator],
2414
+ })), disabled: !canEdit }), _jsx(FilterValueTypeField, { value: predicate.value, canEdit: canEdit, onChange: (sample) => onChange({ ...predicate, value: castFilterValue(predicate.value, sample) }) }), _jsx(FilterValueField, { value: predicate.value, canEdit: canEdit, onChange: (value) => onChange({ ...predicate, value }) })] }));
2415
+ }
2416
+ return unreachableFilterPredicateKind(predicate, 'FilterConditionFields');
2417
+ }
2418
+ /**
2419
+ * Each operator, spelled out in a sentence rather than in symbols.
2420
+ *
2421
+ * The node's face uses `>` and `≥` because it has 224 pixels; a dropdown has
2422
+ * room, and "is after / greater than" is what somebody scanning a list of ten
2423
+ * options is actually reading for. A `Record` keyed by the union, so an operator
2424
+ * added to core without a label here stops the build rather than rendering an
2425
+ * empty row in a select.
2426
+ */
2427
+ const FILTER_OPERATOR_LABELS = {
2428
+ equals: 'equals',
2429
+ notEquals: 'does not equal',
2430
+ greaterThan: 'is greater than',
2431
+ greaterThanOrEqual: 'is greater than or equal to',
2432
+ lessThan: 'is less than',
2433
+ lessThanOrEqual: 'is less than or equal to',
2434
+ contains: 'contains',
2435
+ notContains: 'does not contain',
2436
+ startsWith: 'starts with',
2437
+ notStartsWith: 'does not start with',
2438
+ };
2439
+ /**
2440
+ * Whether the value is text, a number, or true/false.
2441
+ *
2442
+ * A visible choice rather than something inferred from what was typed, and this
2443
+ * is the field most likely to be mistaken for clutter. It is not: `"10"` and
2444
+ * `10` are different values here and neither matches the other, exactly as a
2445
+ * strongly-typed column would answer, and a form that guessed from the
2446
+ * characters would silently flip a text column's test to numeric the moment
2447
+ * somebody filtered on an order number. The run log reports those rows as
2448
+ * incomparable; this field is how they are avoided in the first place.
2449
+ */
2450
+ function FilterValueTypeField({ value, canEdit, onChange, }) {
2451
+ return (_jsx(SelectField, { label: "Value type", ariaLabel: "Whether the value is text, a number, or true/false", value: typeof value === 'number' ? 'number' : typeof value === 'boolean' ? 'boolean' : 'text', onValueChange: (type) => {
2452
+ if (type === 'number')
2453
+ return onChange(0);
2454
+ if (type === 'boolean')
2455
+ return onChange(true);
2456
+ onChange('');
2457
+ }, options: [
2458
+ { value: 'text', label: 'Text' },
2459
+ { value: 'number', label: 'A number' },
2460
+ { value: 'boolean', label: 'True or false' },
2461
+ ], disabled: !canEdit, hint: "Text and numbers are never equal to each other here, and neither is greater or less than the other \u2014 a row whose column holds the wrong one of the two is reported on the run rather than quietly matching. Dates are text: ISO-8601 sorts correctly." }));
2462
+ }
2463
+ /** The value itself, in whichever control the chosen type deserves. */
2464
+ function FilterValueField({ value, canEdit, onChange, }) {
2465
+ if (typeof value === 'boolean') {
2466
+ return (_jsx(SelectField, { label: "Value", ariaLabel: "The true or false value this column is compared against", value: value ? 'true' : 'false', onValueChange: (chosen) => onChange(chosen === 'true'), options: [
2467
+ { value: 'true', label: 'True' },
2468
+ { value: 'false', label: 'False' },
2469
+ ], disabled: !canEdit }));
2470
+ }
2471
+ if (typeof value === 'number') {
2472
+ return (_jsx(TextField, { label: "Value",
2473
+ // A text box with a numeric keypad rather than `type="number"`, which is
2474
+ // the rule the row-count threshold above already writes down: that
2475
+ // control drops what it cannot parse and answers a scroll wheel.
2476
+ value: Number.isFinite(value) ? String(value) : '', onChange: (typed) => {
2477
+ const cleaned = typed.replace(/[^0-9.-]/g, '');
2478
+ const parsed = Number.parseFloat(cleaned);
2479
+ // An unparseable box stores 0 rather than `NaN`: every comparison
2480
+ // against `NaN` is false, so a filter holding one drops every row
2481
+ // while looking perfectly well configured — and the model refuses to
2482
+ // store it, so the graph could not be saved to find that out.
2483
+ onChange(Number.isFinite(parsed) ? parsed : 0);
2484
+ }, inputMode: "numeric", placeholder: "0", disabled: !canEdit }));
2485
+ }
2486
+ return (_jsx(TextField, { label: "Value", value: value, onChange: onChange, placeholder: "OPEN", disabled: !canEdit, hint: "Compared exactly, with no trimming and no case folding. Collation is a property of the column in every database this runs against, so a case-insensitive test evaluated here and the same one evaluated in the source would legitimately disagree \u2014 normalise in a transform instead." }));
2487
+ }
2488
+ /** A condition somebody has not filled in yet. Refused by the validator until they do. */
2489
+ function freshFilterCondition() {
2490
+ return { kind: 'compare', column: '', operator: 'equals', value: '' };
2491
+ }
2492
+ /**
2493
+ * The same condition, asked to be a different kind of test.
2494
+ *
2495
+ * The **column is carried across** and nothing else is, which is the split worth
2496
+ * arguing: the column is what somebody typed and is the expensive half to
2497
+ * retype, while an operator and a value belong to the test that is being left
2498
+ * behind — `greaterThan` has no meaning for a presence check and a value has
2499
+ * none either.
2500
+ */
2501
+ function retargetFilterCondition(predicate, kind) {
2502
+ if (kind === 'compare') {
2503
+ return { kind: 'compare', column: predicate.column, operator: 'equals', value: '' };
2504
+ }
2505
+ if (kind === 'oneOf') {
2506
+ return { kind: 'oneOf', column: predicate.column, operator: 'in', values: [''] };
2507
+ }
2508
+ if (kind === 'present') {
2509
+ return { kind: 'present', column: predicate.column, operator: 'isNotNull' };
2510
+ }
2511
+ // The two group kinds are reachable from the select's type but never from its
2512
+ // options, because a group is added by its own button and is not a *test* a
2513
+ // condition can be switched to. Refusing rather than building one keeps the
2514
+ // exhaustiveness honest without pretending this is a conversion.
2515
+ if (kind === 'all' || kind === 'any')
2516
+ return predicate;
2517
+ return unreachableFilterPredicateKind(kind, 'retargetFilterCondition');
2518
+ }
2519
+ /** One value, moved to the type of a sample, keeping whatever survives the move. */
2520
+ function castFilterValue(value, sample) {
2521
+ if (typeof sample === 'number') {
2522
+ const parsed = typeof value === 'number' ? value : Number.parseFloat(String(value));
2523
+ return Number.isFinite(parsed) ? parsed : 0;
2524
+ }
2525
+ if (typeof sample === 'boolean')
2526
+ return value === true || value === 'true';
2527
+ return String(value);
2528
+ }
2529
+ /**
2530
+ * A textarea of values, one per line, in the type the list is already in.
2531
+ *
2532
+ * Blank lines are dropped rather than kept as empty strings, because a trailing
2533
+ * newline is what a textarea has after every entry and a list ending in `""`
2534
+ * would filter for a value nobody typed. An entirely empty box keeps one blank
2535
+ * entry: the model refuses an empty list, and clearing the box should leave a
2536
+ * condition to finish rather than a graph that cannot be saved with no visible
2537
+ * cause.
2538
+ */
2539
+ function parseFilterValues(text, sample) {
2540
+ const lines = text
2541
+ .split('\n')
2542
+ .map((line) => line.trim())
2543
+ .filter((line) => line.length > 0);
2544
+ if (lines.length === 0)
2545
+ return [''];
2546
+ const cast = sample ?? '';
2547
+ return lines.slice(0, WORKFLOW_FILTER_MAX_VALUES).map((line) => castFilterValue(line, cast));
2548
+ }
1622
2549
  /**
1623
2550
  * The parameter box's two directions, kept together because they are inverses.
1624
2551
  *
@@ -1660,7 +2587,7 @@ function parseConfigText(text) {
1660
2587
  * a kind added without a branch here shows up as a node with a name and nothing
1661
2588
  * to configure, which is visible on the screen rather than silent.
1662
2589
  */
1663
- function KindInspector({ node, transforms, connections, typeOptions, canEdit, discovery, discoverable, onDiscovered, onChange, onEditCode, onCreateTransform, creatingTransform, createTransformError, }) {
2590
+ function KindInspector({ node, graph, transforms, connections, typeOptions, canEdit, modelHref, discovery, discoverable, onDiscovered, onChange, onEditCode, onCreateTransform, creatingTransform, createTransformError, }) {
1664
2591
  if (node.kind === 'transform') {
1665
2592
  return (_jsx(TransformInspector, { node: node, transforms: transforms, canEdit: canEdit, creating: creatingTransform, createError: createTransformError, onChange: onChange, onEditCode: onEditCode, onCreate: onCreateTransform }));
1666
2593
  }
@@ -1677,9 +2604,26 @@ function KindInspector({ node, transforms, connections, typeOptions, canEdit, di
1677
2604
  // being pointed at a different node.
1678
2605
  return _jsx(CallInspector, { node: node, canEdit: canEdit, onChange: onChange }, node.id);
1679
2606
  }
1680
- return (_jsx(SinkInspector, { node: node, typeOptions: typeOptions, canEdit: canEdit, onChange: onChange }));
2607
+ if (node.kind === 'if') {
2608
+ return _jsx(IfInspector, { node: node, canEdit: canEdit, onChange: onChange }, node.id);
2609
+ }
2610
+ if (node.kind === 'filter') {
2611
+ // Given the whole graph, not only the node, because the one question this
2612
+ // inspector cannot answer from the node alone is the important one: which
2613
+ // published types this filter stands in front of. See
2614
+ // `WorkflowFilterNode.narrows`.
2615
+ return (_jsx(FilterInspector, { node: node, graph: graph, canEdit: canEdit, onChange: onChange }, node.id));
2616
+ }
2617
+ if (node.kind === 'sink') {
2618
+ return (_jsx(SinkInspector, { node: node, typeOptions: typeOptions, canEdit: canEdit, modelHref: modelHref, onChange: onChange }));
2619
+ }
2620
+ // The chain ends in a refusal rather than a fallthrough, so a kind added to
2621
+ // core without a form here is a type error naming this file — which is the
2622
+ // whole reason the docblock above says a missing branch shows up as "a node
2623
+ // with a name and nothing to configure". It no longer can.
2624
+ return unreachableNodeKind(node, 'KindInspector');
1681
2625
  }
1682
- function NodeInspector({ node, draft, transforms, connections, typeOptions, canEdit, problems, pending, discovery, discoverable, onDiscovered, onClose, onChange, onConnect, onConnectToNew, onDisconnect, onDelete, onEditCode, onCreateTransform, creatingTransform, createTransformError, }) {
2626
+ function NodeInspector({ node, draft, transforms, connections, typeOptions, canEdit, modelHref, problems, pending, discovery, discoverable, onDiscovered, onClose, onChange, onConnect, onConnectToNew, onDisconnect, onBranch, onDelete, onEditCode, onCreateTransform, creatingTransform, createTransformError, }) {
1683
2627
  const [pendingTarget, setPendingTarget] = useState('');
1684
2628
  const label = (id) => {
1685
2629
  const found = draft.nodes.find((n) => n.id === id);
@@ -1720,7 +2664,11 @@ function NodeInspector({ node, draft, transforms, connections, typeOptions, canE
1720
2664
  return (_jsx(Sheet, { open: node !== null, onOpenChange: (open) => {
1721
2665
  if (!open)
1722
2666
  onClose();
1723
- }, title: node ? nodeName(node) : '', description: node ? `${node.kind} node` : undefined, children: node && (_jsxs("div", { className: "space-y-4", children: [problems.length > 0 && (_jsx("ul", { className: "space-y-1.5 rounded-md border border-red-200 bg-red-50 p-2 dark:border-red-900 dark:bg-red-950/40", children: problems.map((problem) => (_jsx("li", { className: "text-[11px] leading-relaxed text-red-700 dark:text-red-300", children: problem.message }, problem.code))) })), pending.length > 0 && (_jsxs("div", { className: cn('rounded-md border p-2', RULE), children: [_jsx("p", { className: cn('font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: "Still to do" }), _jsx("ul", { className: "mt-1 space-y-0.5", children: pending.map((problem) => (_jsx("li", { className: "text-[11px] leading-relaxed", children: todoFor(problem) }, problem.code))) })] })), _jsx(TextField, { label: "Name", value: node.name, onChange: (name) => onChange({ ...node, name }), placeholder: node.kind, disabled: !canEdit, hint: "What it is called on the canvas and in the wiring list. Renaming it does not change what the graph does, so it does not bump the version." }), _jsx(KindInspector, { node: node, transforms: transforms, connections: connections, typeOptions: typeOptions, canEdit: canEdit, discovery: discovery, discoverable: discoverable, onDiscovered: onDiscovered, onChange: onChange, onEditCode: onEditCode, onCreateTransform: onCreateTransform, creatingTransform: creatingTransform, createTransformError: createTransformError }), _jsx(WiringList, { title: "Fed by", edges: incoming, otherEnd: (edge) => label(edge.from), describeRemoval: (name) => `Stop ${name} feeding this node`, canEdit: canEdit, onDisconnect: onDisconnect, children: incoming.length > 1 && (_jsx("p", { className: cn('mt-1 text-[11px] leading-relaxed', MUTED), children: "Inputs arrive in this order, and the order is part of what the graph produces \u2014 a transform joining two feeds sees them exactly like this." })) }), _jsxs(WiringList, { title: "Feeds", edges: outgoing, otherEnd: (edge) => label(edge.to), describeRemoval: (name) => `Stop this node feeding ${name}`, canEdit: canEdit, onDisconnect: onDisconnect, children: [canEdit && (_jsxs("div", { className: "mt-2 flex items-end gap-2", children: [_jsx("div", { className: "min-w-0 flex-1", children: _jsx(Select, { ariaLabel: "Send this node's output to", value: pendingTarget, onValueChange: setPendingTarget, options: eligible, placeholder: eligible.length === 0
2667
+ }, title: node ? nodeName(node) : '', description: node ? `${node.kind} node` : undefined, children: node && (_jsxs("div", { className: "space-y-4", children: [problems.length > 0 && (_jsx("ul", { className: "space-y-1.5 rounded-md border border-red-200 bg-red-50 p-2 dark:border-red-900 dark:bg-red-950/40", children: problems.map((problem) => (_jsx("li", { className: "text-[11px] leading-relaxed text-red-700 dark:text-red-300", children: problem.message }, problem.code))) })), pending.length > 0 && (_jsxs("div", { className: cn('rounded-md border p-2', RULE), children: [_jsx("p", { className: cn('font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: "Still to do" }), _jsx("ul", { className: "mt-1 space-y-0.5", children: pending.map((problem) => (_jsx("li", { className: "text-[11px] leading-relaxed", children: todoFor(problem) }, problem.code))) })] })), _jsx(TextField, { label: "Name", value: node.name, onChange: (name) => onChange({ ...node, name }), placeholder: node.kind, disabled: !canEdit, hint: "What it is called on the canvas and in the wiring list. Renaming it does not change what the graph does, so it does not bump the version." }), _jsx(KindInspector, { node: node, graph: draft, transforms: transforms, connections: connections, typeOptions: typeOptions, canEdit: canEdit, modelHref: modelHref, discovery: discovery, discoverable: discoverable, onDiscovered: onDiscovered, onChange: onChange, onEditCode: onEditCode, onCreateTransform: onCreateTransform, creatingTransform: creatingTransform, createTransformError: createTransformError }), _jsx(WiringList, { title: "Fed by", edges: incoming, otherEnd: (edge) => label(edge.from), describeRemoval: (name) => `Stop ${name} feeding this node`, canEdit: canEdit, onDisconnect: onDisconnect, children: incoming.length > 1 && (_jsx("p", { className: cn('mt-1 text-[11px] leading-relaxed', MUTED), children: "Inputs arrive in this order, and the order is part of what the graph produces \u2014 a transform joining two feeds sees them exactly like this." })) }), _jsxs(WiringList, { title: "Feeds", edges: outgoing, otherEnd: (edge) => label(edge.to), describeRemoval: (name) => `Stop this node feeding ${name}`, canEdit: canEdit, onDisconnect: onDisconnect,
2668
+ // Only a gate's wires have a side to be on. `validateWorkflow`
2669
+ // refuses a label on any other wire, so offering the control there
2670
+ // would be offering a change the server will not take.
2671
+ onBranch: node.kind === 'if' ? onBranch : undefined, children: [canEdit && (_jsxs("div", { className: "mt-2 flex items-end gap-2", children: [_jsx("div", { className: "min-w-0 flex-1", children: _jsx(Select, { ariaLabel: "Send this node's output to", value: pendingTarget, onValueChange: setPendingTarget, options: eligible, placeholder: eligible.length === 0
1724
2672
  ? 'Nothing can be wired from here'
1725
2673
  : 'Send its output to…', disabled: eligible.length === 0 }) }), _jsx("button", { type: "button", onClick: () => {
1726
2674
  if (!pendingTarget)
@@ -1781,21 +2729,21 @@ function SourceInspector({ node, connections, canEdit, discovery, discoverable,
1781
2729
  // The connection goes with the kind it belonged to. Keeping it would
1782
2730
  // point an S3 source at a SQL address.
1783
2731
  push(source, { sourceKind, connectionId: undefined });
1784
- }, options: KIND_OPTIONS, disabled: !canEdit }), usesConnection(kind) && (_jsx(SelectField, { label: "Read through", ariaLabel: "Connection", value: chosen, onValueChange: (value) => push(source, {
1785
- // Omitted, never sent empty: an empty string is a connection id
1786
- // the server would look up and fail to find, where absent means
1787
- // "this source carries its own address".
1788
- connectionId: value === INLINE_CONNECTION ? undefined : value,
1789
- }), options: [
1790
- {
1791
- value: INLINE_CONNECTION,
1792
- label: 'Configure the address here',
1793
- hint: 'This source alone',
1794
- },
1795
- ...options,
1796
- ], disabled: !canEdit, hint: options.length === 0
1797
- ? 'No connections of this kind yet. One is worth making when a second source needs the same address.'
1798
- : viaConnection
1799
- ? 'The connection supplies the address and the credential. What stays below is only what is specific to this load.'
1800
- : undefined })), _jsx(SourceFields, { kind: kind, draft: source, onChange: update, viaConnection: viaConnection, disabled: !canEdit }), _jsx(ReadModeFields, { kind: kind, mode: mode, onModeChange: (next) => push(source, { mode: next }), draft: source, onChange: update, disabled: !canEdit }), incremental && (_jsx("p", { className: cn('text-[11px] leading-relaxed', MUTED), children: "A watermark is kept per node, so two sources in the same graph reading incrementally do not overwrite each other's position." })), _jsx(SchemaDiscoveryPanel, { workflowId: discoverable.workflowId ?? '', nodeId: node.id, bridge: discovery, onDiscovered: onDiscovered, ...(discoverable.workflowId === undefined ? { disabledReason: discoverable.because } : {}) })] }));
2732
+ }, options: KIND_OPTIONS, disabled: !canEdit }), usesConnection(kind) && (_jsxs(_Fragment, { children: [_jsx(SelectField, { label: "Read through", ariaLabel: "Connection", value: chosen, onValueChange: (value) => push(source, {
2733
+ // Omitted, never sent empty: an empty string is a connection id
2734
+ // the server would look up and fail to find, where absent means
2735
+ // "this source carries its own address".
2736
+ connectionId: value === INLINE_CONNECTION ? undefined : value,
2737
+ }), options: [
2738
+ {
2739
+ value: INLINE_CONNECTION,
2740
+ label: 'Configure the address here',
2741
+ hint: 'This source alone',
2742
+ },
2743
+ ...options,
2744
+ ], disabled: !canEdit, hint: options.length === 0
2745
+ ? 'No connections of this kind yet. One is worth making when a second source needs the same address.'
2746
+ : viaConnection
2747
+ ? 'The connection supplies the address and the credential. What stays below is only what is specific to this load.'
2748
+ : undefined }), _jsx(SourceConnectionCreator, { kind: kind, canEdit: canEdit, hasOptions: options.length > 0, onCreated: (connection) => push(source, { connectionId: connection.id }) })] })), _jsx(SourceFields, { kind: kind, draft: source, onChange: update, viaConnection: viaConnection, disabled: !canEdit }), _jsx(ReadModeFields, { kind: kind, mode: mode, onModeChange: (next) => push(source, { mode: next }), draft: source, onChange: update, disabled: !canEdit }), incremental && (_jsx("p", { className: cn('text-[11px] leading-relaxed', MUTED), children: "A watermark is kept per node, so two sources in the same graph reading incrementally do not overwrite each other's position." })), _jsx(SchemaDiscoveryPanel, { workflowId: discoverable.workflowId ?? '', nodeId: node.id, bridge: discovery, onDiscovered: onDiscovered, onSave: discoverable.onSave, saving: discoverable.saving, ...(discoverable.workflowId === undefined ? { disabledReason: discoverable.because } : {}) })] }));
1801
2749
  }