@reopt-ai/opt-workflow 0.0.0-stage → 0.1.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 (54) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/LICENSE +21 -0
  3. package/README.md +213 -2
  4. package/dist/ai-stream-APc3uCiQ.js +389 -0
  5. package/dist/ai-stream-B_lk9_Rf.cjs +628 -0
  6. package/dist/branch-resolver-BDi6Wu6m.js +589 -0
  7. package/dist/branch-resolver-D_wM183Q.cjs +714 -0
  8. package/dist/core-CtqBb-6v.d.cts +919 -0
  9. package/dist/core-z3nXmUBj.d.ts +919 -0
  10. package/dist/core.cjs +301 -0
  11. package/dist/core.d.cts +5 -0
  12. package/dist/core.d.ts +5 -0
  13. package/dist/core.js +184 -0
  14. package/dist/define-template-Bmn96lF_.cjs +74 -0
  15. package/dist/define-template-BvGNB5Tv.js +69 -0
  16. package/dist/end-node-ids-D6WBaCLm.cjs +109 -0
  17. package/dist/end-node-ids-p85jFEcP.js +86 -0
  18. package/dist/execution-context-DVeybULC.d.cts +258 -0
  19. package/dist/execution-context-YFTRCj0y.d.ts +258 -0
  20. package/dist/grid-workflow-dto-C86EArJP.d.cts +300 -0
  21. package/dist/grid-workflow-dto-C86EArJP.d.ts +300 -0
  22. package/dist/index.cjs +11873 -0
  23. package/dist/index.d.cts +794 -0
  24. package/dist/index.d.ts +794 -0
  25. package/dist/index.js +11828 -0
  26. package/dist/mock.cjs +7295 -0
  27. package/dist/mock.d.cts +88 -0
  28. package/dist/mock.d.ts +88 -0
  29. package/dist/mock.js +7287 -0
  30. package/dist/node-definitions-C-GMfjMm.js +797 -0
  31. package/dist/node-definitions-pS1Zp1dK.cjs +940 -0
  32. package/dist/nodes-D_a8ZkRp.d.cts +50 -0
  33. package/dist/nodes-myp8R2zo.d.ts +50 -0
  34. package/dist/nodes.cjs +36 -0
  35. package/dist/nodes.d.cts +3 -0
  36. package/dist/nodes.d.ts +3 -0
  37. package/dist/nodes.js +4 -0
  38. package/dist/shadcn-bridge.css +72 -0
  39. package/dist/simulate.cjs +6 -0
  40. package/dist/simulate.d.cts +111 -0
  41. package/dist/simulate.d.ts +111 -0
  42. package/dist/simulate.js +1 -0
  43. package/dist/step-type-for-node-Blf5DKrp.js +228 -0
  44. package/dist/step-type-for-node-D9sdHfWA.cjs +281 -0
  45. package/dist/styles.css +4 -0
  46. package/dist/test-executor-C2AvI73G.cjs +342 -0
  47. package/dist/test-executor-DpT3qXIT.js +313 -0
  48. package/dist/types-Bj0VWFny.d.cts +126 -0
  49. package/dist/types-C5744w6f.d.cts +184 -0
  50. package/dist/types-DQcmIuAl.d.ts +126 -0
  51. package/dist/types-dVHX2CyI.d.ts +184 -0
  52. package/dist/workflow-preview-B0kul6f-.js +1742 -0
  53. package/dist/workflow-preview-CZzXKXqK.cjs +2065 -0
  54. package/package.json +119 -4
@@ -0,0 +1,2065 @@
1
+ const require_branch_resolver = require("./branch-resolver-D_wM183Q.cjs");
2
+ const require_end_node_ids = require("./end-node-ids-D6WBaCLm.cjs");
3
+ const require_node_definitions = require("./node-definitions-pS1Zp1dK.cjs");
4
+ const require_step_type_for_node = require("./step-type-for-node-D9sdHfWA.cjs");
5
+ const require_ai_stream = require("./ai-stream-B_lk9_Rf.cjs");
6
+ // src/lib/grid-geometry.ts
7
+ /** 빈 행·열을 제외한 실제 스텝 영역. 화면 맞춤이 글씨를 불필요하게 축소하지 않는다. */
8
+ function getStepsRect(steps) {
9
+ if (steps.length === 0) return void 0;
10
+ const origins = steps.map((step) => getCellOrigin(step.position));
11
+ const x = Math.min(...origins.map((point) => point.x));
12
+ const y = Math.min(...origins.map((point) => point.y));
13
+ return {
14
+ x,
15
+ y,
16
+ width: Math.max(...origins.map((point) => point.x)) - x + 248,
17
+ height: Math.max(...origins.map((point) => point.y)) - y + 136
18
+ };
19
+ }
20
+ const IDENTITY_TRANSFORM = {
21
+ translateX: 0,
22
+ translateY: 0,
23
+ scale: 1
24
+ };
25
+ /** 셀 좌상단 좌표 (콘텐츠 좌표계, padding = CELL_GAP/2) */
26
+ function getCellOrigin(position) {
27
+ const padding = 20;
28
+ return {
29
+ x: padding + position.col * 288,
30
+ y: padding + position.row * 176
31
+ };
32
+ }
33
+ /** 셀 중앙 좌표 (콘텐츠 좌표계) */
34
+ function getCellCenter(position) {
35
+ const origin = getCellOrigin(position);
36
+ return {
37
+ x: origin.x + 124,
38
+ y: origin.y + 68
39
+ };
40
+ }
41
+ /**
42
+ * 연결선이 셀 경계에서 시작/끝나도록 가장자리 좌표 계산.
43
+ * 가로/세로 정렬이 아닌 경우(비인접 대각)는 중앙에서 시작/끝.
44
+ */
45
+ function getCellEdge(from, to) {
46
+ const fromCenter = getCellCenter(from);
47
+ const toCenter = getCellCenter(to);
48
+ const dx = to.col - from.col;
49
+ const dy = to.row - from.row;
50
+ const start = require_end_node_ids._objectSpread2({}, fromCenter);
51
+ const end = require_end_node_ids._objectSpread2({}, toCenter);
52
+ if (dx !== 0 && dy === 0) {
53
+ if (dx > 0) {
54
+ start.x = fromCenter.x + 124;
55
+ end.x = toCenter.x - 124;
56
+ } else {
57
+ start.x = fromCenter.x - 124;
58
+ end.x = toCenter.x + 124;
59
+ }
60
+ } else if (dy !== 0 && dx === 0) {
61
+ if (dy > 0) {
62
+ start.y = fromCenter.y + 68;
63
+ end.y = toCenter.y - 68;
64
+ } else {
65
+ start.y = fromCenter.y - 68;
66
+ end.y = toCenter.y + 68;
67
+ }
68
+ } else if (dx !== 0 && dy !== 0) {
69
+ start.y = fromCenter.y + (dy > 0 ? 68 : -68);
70
+ end.x = toCenter.x + (dx > 0 ? -124 : 124);
71
+ }
72
+ return {
73
+ start,
74
+ end
75
+ };
76
+ }
77
+ /** 바운드 기반 콘텐츠 픽셀 크기 */
78
+ function getContentSize(bounds) {
79
+ return {
80
+ width: bounds.cols * 288,
81
+ height: bounds.rows * 176
82
+ };
83
+ }
84
+ /** 콘텐츠 좌표 → 뷰포트 좌표 */
85
+ function contentToViewport(point, t) {
86
+ return {
87
+ x: point.x * t.scale + t.translateX,
88
+ y: point.y * t.scale + t.translateY
89
+ };
90
+ }
91
+ /** 뷰포트 좌표 → 콘텐츠 좌표 */
92
+ function viewportToContent(point, t) {
93
+ return {
94
+ x: (point.x - t.translateX) / t.scale,
95
+ y: (point.y - t.translateY) / t.scale
96
+ };
97
+ }
98
+ /** 뷰포트 좌표가 가리키는 셀 (바운드 밖이면 null) */
99
+ function viewportPointToCell(point, t, bounds) {
100
+ const content = viewportToContent(point, t);
101
+ const col = Math.floor(content.x / 288);
102
+ const row = Math.floor(content.y / 176);
103
+ if (row < 0 || row >= bounds.rows || col < 0 || col >= bounds.cols) return null;
104
+ return {
105
+ row,
106
+ col
107
+ };
108
+ }
109
+ /** 셀의 뷰포트 좌표계 사각형 (액션바 앵커링용) */
110
+ function cellToViewportRect(position, t) {
111
+ const origin = contentToViewport(getCellOrigin(position), t);
112
+ return {
113
+ top: origin.y,
114
+ left: origin.x,
115
+ width: 248 * t.scale,
116
+ height: 136 * t.scale
117
+ };
118
+ }
119
+ // src/lib/grid-keyboard.ts
120
+ function byPosition(a, b) {
121
+ return a.position.row - b.position.row || a.position.col - b.position.col;
122
+ }
123
+ /**
124
+ * 흐름 순서 — 트리거(없으면 맨 위 왼쪽 스텝)부터 연결을 따라 BFS, 닿지 않는 스텝은 위치
125
+ * 순으로 뒤에 붙인다. 목록 미리보기(`orderStepsForPreview`)와 키보드 스텝 이동이 같은 순서를
126
+ * 쓴다 — 예전 키보드 이동은 행→열 순이라 분기가 있으면 흐름과 다르게 움직였다.
127
+ */
128
+ function orderStepsByFlow(steps, connections) {
129
+ var _steps$find;
130
+ const sorted = [...steps].sort(byPosition);
131
+ const start = (_steps$find = steps.find((s) => s.type === "trigger")) !== null && _steps$find !== void 0 ? _steps$find : sorted[0];
132
+ if (!start) return [];
133
+ const stepById = new Map(steps.map((s) => [s.id, s]));
134
+ const adjacency = /* @__PURE__ */ new Map();
135
+ for (const conn of connections) {
136
+ var _adjacency$get;
137
+ const list = (_adjacency$get = adjacency.get(conn.fromStepId)) !== null && _adjacency$get !== void 0 ? _adjacency$get : [];
138
+ list.push(conn.toStepId);
139
+ adjacency.set(conn.fromStepId, list);
140
+ }
141
+ const ordered = [];
142
+ const visited = /* @__PURE__ */ new Set();
143
+ const queue = [start.id];
144
+ while (queue.length > 0) {
145
+ var _adjacency$get2;
146
+ const id = queue.shift();
147
+ if (visited.has(id)) continue;
148
+ visited.add(id);
149
+ const step = stepById.get(id);
150
+ if (step) ordered.push(step);
151
+ for (const next of (_adjacency$get2 = adjacency.get(id)) !== null && _adjacency$get2 !== void 0 ? _adjacency$get2 : []) if (!visited.has(next)) queue.push(next);
152
+ }
153
+ for (const step of sorted) if (!visited.has(step.id)) {
154
+ ordered.push(step);
155
+ visited.add(step.id);
156
+ }
157
+ return ordered;
158
+ }
159
+ /** 같은 행·열에서 그 방향으로 가장 가까운 스텝의 자리 — 사이의 빈 칸을 건너뛴다. */
160
+ function findStepInDirection(steps, from, direction) {
161
+ let best = null;
162
+ let bestDistance = Infinity;
163
+ for (const { position } of steps) {
164
+ const dRow = position.row - from.row;
165
+ const dCol = position.col - from.col;
166
+ const distance = direction === "up" && dCol === 0 && dRow < 0 ? -dRow : direction === "down" && dCol === 0 && dRow > 0 ? dRow : direction === "left" && dRow === 0 && dCol < 0 ? -dCol : direction === "right" && dRow === 0 && dCol > 0 ? dCol : null;
167
+ if (distance !== null && distance < bestDistance) {
168
+ best = position;
169
+ bestDistance = distance;
170
+ }
171
+ }
172
+ return best;
173
+ }
174
+ /** 한 스텝에 붙은 연결을 키보드가 도는 순서 — 나가는 연결 먼저, 그다음 들어오는 연결. */
175
+ function listStepConnections(stepId, connections) {
176
+ return [...connections.filter((c) => c.fromStepId === stepId), ...connections.filter((c) => c.toStepId === stepId)];
177
+ }
178
+ /**
179
+ * 연결 순회의 다음 차례. 고른 연결이 없으면 첫 번째(뒤로 돌면 마지막)부터, 끝에서는 처음으로
180
+ * 돌아온다. 붙은 연결이 없으면 null.
181
+ */
182
+ function cycleStepConnection(stepId, connections, currentId, reverse) {
183
+ var _ref, _list$next;
184
+ const list = listStepConnections(stepId, connections);
185
+ if (list.length === 0) return null;
186
+ const index = currentId ? list.findIndex((c) => c.id === currentId) : -1;
187
+ if (index === -1) return (_ref = reverse ? list.at(-1) : list[0]) !== null && _ref !== void 0 ? _ref : null;
188
+ return (_list$next = list[(index + (reverse ? -1 : 1) + list.length) % list.length]) !== null && _list$next !== void 0 ? _list$next : null;
189
+ }
190
+ /** 고른 연결에서 지금 스텝의 반대편 자리 — Enter로 연결을 따라갈 때 쓴다. */
191
+ function getConnectionFarEnd(connection, fromStepId) {
192
+ return connection.fromStepId === fromStepId ? connection.toPosition : connection.fromPosition;
193
+ }
194
+ /**
195
+ * 고른 연결이 **지금도 유효한가**. 유효 조건은 셋이다: 고른 뒤로 선택이 바뀌지 않았고(같은
196
+ * 객체), 선택한 칸에 스텝이 있고, 그 연결이 아직 그 스텝에 붙어 있다.
197
+ *
198
+ * 🔴 선택을 스텝 id로 비교하면 안 된다 — 다른 칸에 갔다가 돌아오면 고른 연결이 되살아나고,
199
+ * 그 상태의 Delete는 스텝이 아니라 연결을 지운다. 선택을 다시 정하는 모든 경로는 새 객체를
200
+ * 만들므로 객체 동일성이 "선택이 한 번도 안 바뀌었다"를 뜻한다.
201
+ */
202
+ function resolveConnectionFocus(focus, selectedPosition, selectedStepId, connections) {
203
+ if (!focus || focus.selection !== selectedPosition || !selectedStepId) return null;
204
+ return connections.some((c) => c.id === focus.connectionId && (c.fromStepId === selectedStepId || c.toStepId === selectedStepId)) ? focus.connectionId : null;
205
+ }
206
+ // src/lib/order-steps-for-preview.ts
207
+ const EMPTY = {
208
+ start: null,
209
+ middle: [],
210
+ end: null,
211
+ isEmpty: true
212
+ };
213
+ /** 그리드 정의 형태(steps/connections)인지 런타임 가드 — 뷰어와 동일 패턴. */
214
+ function asGridDefinition(definition) {
215
+ if (definition && typeof definition === "object" && "steps" in definition && "connections" in definition && Array.isArray(definition.steps)) return definition;
216
+ return null;
217
+ }
218
+ /**
219
+ * 워크플로우 정의를 미리보기용 시작/중간/끝 스텝으로 정렬한다.
220
+ *
221
+ * 연결(fromStepId→toStepId)을 따라 시작 스텝부터 BFS 순회해 흐름 순서를 만들고,
222
+ * 연결이 없으면 그리드 위치 순으로 fallback한다. 레거시 nodes/edges 정의나 빈
223
+ * 정의는 `isEmpty: true`로 반환한다(미리보기에서 플레이스홀더 처리).
224
+ */
225
+ function orderStepsForPreview(definition) {
226
+ var _steps$find;
227
+ const grid = asGridDefinition(definition);
228
+ if (!grid || grid.steps.length === 0) return EMPTY;
229
+ const steps = grid.steps;
230
+ const ordered = orderStepsByFlow(steps, Array.isArray(grid.connections) ? grid.connections : []);
231
+ const start = ordered[0];
232
+ const end = (_steps$find = steps.find((s) => s.type === "end")) !== null && _steps$find !== void 0 ? _steps$find : null;
233
+ const endStep = end !== null && end !== void 0 ? end : ordered.length > 1 ? ordered[ordered.length - 1] : null;
234
+ const middle = ordered.filter((s) => s.id !== start.id && s.id !== (endStep === null || endStep === void 0 ? void 0 : endStep.id));
235
+ const toPreview = (s) => ({
236
+ id: s.id,
237
+ type: s.type,
238
+ label: s.label,
239
+ nodeDefinitionId: s.nodeDefinitionId
240
+ });
241
+ return {
242
+ start: toPreview(start),
243
+ middle: middle.map(toPreview),
244
+ end: endStep && endStep.id !== start.id ? toPreview(endStep) : null,
245
+ isEmpty: false
246
+ };
247
+ }
248
+ // src/engine/security/pii-mask.ts
249
+ /**
250
+ * 워크플로우 로그용 PII 마스킹.
251
+ *
252
+ * `logging-service.ts`가 input/output을 그대로 metadata로 저장해서
253
+ * `workflowLog.metadata`에 원본 PII가 남고 있었다. 이 모듈이 객체 트리를
254
+ * 한 번 훑어 다음을 가린다:
255
+ *
256
+ * - **키 기반**: `password`, `token`, `secret`, `apiKey`, `authorization`,
257
+ * `cookie`, `creditCard`/`cardNumber` 같은 민감 키는 값을 통째로 `***`로.
258
+ * - **값 기반 패턴**: 문자열 안의 이메일·전화번호·신용카드 번호·`Bearer ...`
259
+ * 토큰을 부분 마스킹.
260
+ *
261
+ * 완전한 PII 분류기는 아니다. 명백한 유출 케이스만 막고, 정밀한 클래스 분류는
262
+ * 별도 도메인 시스템(예: DLP)으로 미룬다.
263
+ */
264
+ const SENSITIVE_KEY_PATTERN = /(password|token|secret|api[-_]?key|authorization|cookie|credit[-_]?card|card[-_]?number|cvv|ssn|residentNumber)/i;
265
+ const EMAIL_PATTERN = /([\w.+-])[\w.+-]*(@[\w.-]+\.[a-z]{2,})/gi;
266
+ const PHONE_KR_PATTERN = /(\b01\d)[-\s]?(\d{3,4})[-\s]?(\d{4}\b)/g;
267
+ const CARD_PATTERN = /\b(\d{4})[-\s]?(\d{4})[-\s]?(\d{4})[-\s]?(\d{4})\b/g;
268
+ const BEARER_PATTERN = /\b(Bearer)\s+[A-Za-z0-9_\-.=]+/gi;
269
+ const MAX_DEPTH = 6;
270
+ /**
271
+ * 문자열 값에서 알려진 PII 패턴을 부분 마스킹.
272
+ */
273
+ function maskPiiString(input) {
274
+ return input.replace(EMAIL_PATTERN, (_match, first, domain) => `${first}***${domain}`).replace(PHONE_KR_PATTERN, (_match, head, _mid, tail) => `${head}-****-${tail}`).replace(CARD_PATTERN, (_match, _a, _b, _c, last) => `****-****-****-${last}`).replace(BEARER_PATTERN, "$1 ***");
275
+ }
276
+ /**
277
+ * 객체 트리를 깊이 우선으로 순회하며 PII를 가린다.
278
+ * 순환 참조 / Map / Set / Date 같은 비-plain 값은 안전하게 통과시킨다.
279
+ */
280
+ function maskPiiDeep(value, depth = 0, seen) {
281
+ if (depth > MAX_DEPTH) return value;
282
+ if (value === null || value === void 0) return value;
283
+ if (typeof value === "string") return maskPiiString(value);
284
+ if (typeof value !== "object") return value;
285
+ if (value instanceof Date) return value;
286
+ const visited = seen !== null && seen !== void 0 ? seen : /* @__PURE__ */ new WeakSet();
287
+ if (visited.has(value)) return value;
288
+ visited.add(value);
289
+ if (Array.isArray(value)) return value.map((item) => maskPiiDeep(item, depth + 1, visited));
290
+ const proto = Object.getPrototypeOf(value);
291
+ if (proto !== Object.prototype && proto !== null) return value;
292
+ const masked = {};
293
+ for (const [key, child] of Object.entries(value)) {
294
+ if (SENSITIVE_KEY_PATTERN.test(key)) {
295
+ masked[key] = typeof child === "string" || typeof child === "number" ? "***" : maskPiiDeep(child, depth + 1, visited);
296
+ continue;
297
+ }
298
+ masked[key] = maskPiiDeep(child, depth + 1, visited);
299
+ }
300
+ return masked;
301
+ }
302
+ // src/lib/run-path.ts
303
+ function toMillis(value) {
304
+ if (value === void 0) return void 0;
305
+ const ms = value instanceof Date ? value.getTime() : new Date(value).getTime();
306
+ return Number.isNaN(ms) ? void 0 : ms;
307
+ }
308
+ function hasRun(state) {
309
+ return state !== void 0 && state.status !== "pending";
310
+ }
311
+ function deriveRunPath({ steps, connections, stepStates, settled }) {
312
+ const connectionStatus = /* @__PURE__ */ new Map();
313
+ for (const connection of connections) {
314
+ const from = stepStates.get(connection.fromStepId);
315
+ const to = stepStates.get(connection.toStepId);
316
+ if (hasRun(from) && hasRun(to)) {
317
+ const fromAt = toMillis(from.startedAt);
318
+ const toAt = toMillis(to.startedAt);
319
+ if (fromAt === void 0 || toAt === void 0 || toAt >= fromAt) {
320
+ connectionStatus.set(connection.id, to.status === "running" ? "active" : "traversed");
321
+ continue;
322
+ }
323
+ }
324
+ if (settled) connectionStatus.set(connection.id, "muted");
325
+ }
326
+ const unreachedStepIds = /* @__PURE__ */ new Set();
327
+ if (settled) {
328
+ for (const step of steps) if (!hasRun(stepStates.get(step.id))) unreachedStepIds.add(step.id);
329
+ }
330
+ return {
331
+ connectionStatus,
332
+ unreachedStepIds
333
+ };
334
+ }
335
+ // src/lib/config-fields.ts
336
+ /** `showWhen` 조건을 만족해 화면에 그려지는 필드만 남긴다. */
337
+ function visibleConfigFields(fields, config) {
338
+ return fields.filter((field) => {
339
+ if (!field.showWhen) return true;
340
+ const current = config[field.showWhen.field];
341
+ if (typeof current !== "string" && typeof current !== "number") return false;
342
+ return String(current) === String(field.showWhen.value);
343
+ });
344
+ }
345
+ /** 값이 "비어 있다"의 정의 — `false`·`0`은 **입력된 값**이다. */
346
+ function isBlank(value) {
347
+ if (value === void 0 || value === null) return true;
348
+ if (typeof value === "string") return value.trim() === "";
349
+ if (Array.isArray(value)) return value.length === 0;
350
+ return false;
351
+ }
352
+ /** 화면에 보이면서 필수인데 비어 있는 필드 — 저장을 막는 이유가 된다. */
353
+ function missingRequiredFields(fields, config) {
354
+ return visibleConfigFields(fields, config).filter((field) => field.required === true && isBlank(config[field.key]));
355
+ }
356
+ // src/lib/step-summary.ts
357
+ function textValue(value) {
358
+ var _JSON$stringify;
359
+ if (typeof value === "string") return value;
360
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
361
+ return (_JSON$stringify = JSON.stringify(value)) !== null && _JSON$stringify !== void 0 ? _JSON$stringify : "";
362
+ }
363
+ function getStepSummary(step) {
364
+ var _getStepNodeDefinitio, _getStepNodeDefinitio2;
365
+ const config = maskPiiDeep(step.config);
366
+ if (step.type === "condition") {
367
+ var _config$leftOperand, _config$leftOperand2, _config$rightOperand;
368
+ const normalized = require_branch_resolver.normalizeConditionConfig(config);
369
+ const expression = normalized.conditionType === "switch" ? normalized.switchValue : normalized.expression;
370
+ return expression ? [{
371
+ label: normalized.conditionType === "switch" ? "분기 기준" : "조건",
372
+ value: textValue(expression)
373
+ }] : ((_config$leftOperand = config.leftOperand) !== null && _config$leftOperand !== void 0 ? _config$leftOperand : config.field) ? [{
374
+ label: "조건",
375
+ value: [
376
+ (_config$leftOperand2 = config.leftOperand) !== null && _config$leftOperand2 !== void 0 ? _config$leftOperand2 : config.field,
377
+ config.operator,
378
+ (_config$rightOperand = config.rightOperand) !== null && _config$rightOperand !== void 0 ? _config$rightOperand : config.value
379
+ ].filter((value) => value != null).map(textValue).join(" ")
380
+ }] : [];
381
+ }
382
+ const fields = visibleConfigFields((_getStepNodeDefinitio = (_getStepNodeDefinitio2 = require_step_type_for_node.getStepNodeDefinition(step)) === null || _getStepNodeDefinitio2 === void 0 || (_getStepNodeDefinitio2 = _getStepNodeDefinitio2.config) === null || _getStepNodeDefinitio2 === void 0 ? void 0 : _getStepNodeDefinitio2.fields) !== null && _getStepNodeDefinitio !== void 0 ? _getStepNodeDefinitio : [], config);
383
+ const masked = config;
384
+ return fields.filter((field) => {
385
+ const value = config[field.key];
386
+ return value != null && value !== "" && (!Array.isArray(value) || value.length > 0);
387
+ }).slice(0, 2).map((field) => {
388
+ var _field$options$find$l, _field$options;
389
+ const value = masked[field.key];
390
+ const text = (_field$options$find$l = (_field$options = field.options) === null || _field$options === void 0 || (_field$options = _field$options.find((option) => option.value === textValue(value))) === null || _field$options === void 0 ? void 0 : _field$options.label) !== null && _field$options$find$l !== void 0 ? _field$options$find$l : typeof value === "boolean" ? value ? "사용" : "사용 안 함" : Array.isArray(value) ? require_branch_resolver.msgf("{count}개 항목", { count: value.length }) : typeof value === "object" ? "설정됨" : textValue(value);
391
+ return {
392
+ label: field.label,
393
+ value: text.replace(/\s+/g, " ").slice(0, 100)
394
+ };
395
+ });
396
+ }
397
+ // src/lib/grid-route.ts
398
+ /** 모서리 반지름 — 거터 절반(20px)보다 작아야 짧은 진입 구간에서도 호가 온전히 그려진다. */
399
+ const CORNER_RADIUS = 10;
400
+ /** 돌아가는 차선이 카드 변에서 떨어진 거리 — 거터 중앙(계단 차선)과 겹치지 않게 안쪽을 쓴다. */
401
+ const DETOUR_OFFSET = 10;
402
+ function hasStepBetween(from, to, isOccupied) {
403
+ const stepRow = Math.sign(to.row - from.row);
404
+ const stepCol = Math.sign(to.col - from.col);
405
+ let row = from.row + stepRow;
406
+ let col = from.col + stepCol;
407
+ while (row !== to.row || col !== to.col) {
408
+ if (isOccupied({
409
+ row,
410
+ col
411
+ })) return true;
412
+ row += stepRow;
413
+ col += stepCol;
414
+ }
415
+ return false;
416
+ }
417
+ /** 두 셀을 잇는 꺾임점 목록(콘텐츠 좌표계). 첫 점은 출발 카드의 변, 끝 점은 도착 카드의 변. */
418
+ function routeConnection(from, to, isOccupied) {
419
+ const dRow = to.row - from.row;
420
+ const dCol = to.col - from.col;
421
+ const { start, end } = getCellEdge(from, to);
422
+ if (dRow === 0 && dCol === 0) return [start, end];
423
+ if (dRow === 0 || dCol === 0) {
424
+ if (!hasStepBetween(from, to, isOccupied)) return [start, end];
425
+ const fromCenter = getCellCenter(from);
426
+ const toCenter = getCellCenter(to);
427
+ if (dRow === 0) {
428
+ const bottom = fromCenter.y + 68;
429
+ const lane = bottom + DETOUR_OFFSET;
430
+ return [
431
+ {
432
+ x: fromCenter.x,
433
+ y: bottom
434
+ },
435
+ {
436
+ x: fromCenter.x,
437
+ y: lane
438
+ },
439
+ {
440
+ x: toCenter.x,
441
+ y: lane
442
+ },
443
+ {
444
+ x: toCenter.x,
445
+ y: bottom
446
+ }
447
+ ];
448
+ }
449
+ const right = fromCenter.x + 124;
450
+ const lane = right + DETOUR_OFFSET;
451
+ return [
452
+ {
453
+ x: right,
454
+ y: fromCenter.y
455
+ },
456
+ {
457
+ x: lane,
458
+ y: fromCenter.y
459
+ },
460
+ {
461
+ x: lane,
462
+ y: toCenter.y
463
+ },
464
+ {
465
+ x: right,
466
+ y: toCenter.y
467
+ }
468
+ ];
469
+ }
470
+ const gutterY = (dRow > 0 ? from.row + 1 : from.row) * 176;
471
+ const gutterX = (dCol > 0 ? to.col : to.col + 1) * 288;
472
+ return [
473
+ start,
474
+ {
475
+ x: start.x,
476
+ y: gutterY
477
+ },
478
+ {
479
+ x: gutterX,
480
+ y: gutterY
481
+ },
482
+ {
483
+ x: gutterX,
484
+ y: end.y
485
+ },
486
+ end
487
+ ];
488
+ }
489
+ /** 꺾임점을 직선 + 모서리 호로 잇는 SVG path. 구간이 반지름보다 짧으면 호를 줄인다. */
490
+ function roundedPath(points, radius = CORNER_RADIUS) {
491
+ const first = points[0];
492
+ if (!first) return "";
493
+ let d = `M ${first.x} ${first.y}`;
494
+ for (let index = 1; index < points.length; index++) {
495
+ const corner = points[index];
496
+ const next = points[index + 1];
497
+ if (!next) {
498
+ d += ` L ${corner.x} ${corner.y}`;
499
+ break;
500
+ }
501
+ const previous = points[index - 1];
502
+ const inLength = Math.hypot(corner.x - previous.x, corner.y - previous.y);
503
+ const outLength = Math.hypot(next.x - corner.x, next.y - corner.y);
504
+ const r = Math.min(radius, inLength / 2, outLength / 2);
505
+ if (r < .5) {
506
+ d += ` L ${corner.x} ${corner.y}`;
507
+ continue;
508
+ }
509
+ const inX = (corner.x - previous.x) / inLength;
510
+ const inY = (corner.y - previous.y) / inLength;
511
+ const outX = (next.x - corner.x) / outLength;
512
+ const outY = (next.y - corner.y) / outLength;
513
+ const sweep = inX * outY - inY * outX > 0 ? 1 : 0;
514
+ d += ` L ${corner.x - inX * r} ${corner.y - inY * r}`;
515
+ d += ` A ${r} ${r} 0 0 ${sweep} ${corner.x + outX * r} ${corner.y + outY * r}`;
516
+ }
517
+ return d;
518
+ }
519
+ function midpoint(a, b, t = .5) {
520
+ return {
521
+ x: a.x + (b.x - a.x) * t,
522
+ y: a.y + (b.y - a.y) * t
523
+ };
524
+ }
525
+ /** 가로 이웃 연결의 라벨을 선 위로 띄우는 높이 — 40px 거터에서 화살촉을 가리지 않는다. */
526
+ const LABEL_LIFT = 11;
527
+ /**
528
+ * 분기 라벨이 앉을 자리 — **실제로 그려진 선분 위**다. 예전에는 시작·끝의 직선 중점이라
529
+ * 꺾이는 연결에서는 라벨이 선에서 떨어진 허공에 놓였다.
530
+ */
531
+ function routeLabelPoint(points) {
532
+ const [a, b, c] = points;
533
+ if (!a || !b) return {
534
+ x: 0,
535
+ y: 0
536
+ };
537
+ if (!c) return a.y === b.y ? {
538
+ x: (a.x + b.x) / 2,
539
+ y: a.y - LABEL_LIFT
540
+ } : midpoint(a, b, .4);
541
+ return midpoint(b, c);
542
+ }
543
+ /**
544
+ * 라벨 자리가 다른 라벨과 겹칠 때 쓰는 두 번째 자리 — 도착 스텝 쪽 구간. 같은 조건 스텝에서
545
+ * 나간 두 분기가 첫 구간을 함께 쓰면 첫 자리가 같아진다.
546
+ */
547
+ function routeLabelFallbackPoint(points) {
548
+ const count = points.length;
549
+ if (count >= 5) return midpoint(points[count - 3], points[count - 2]);
550
+ if (count === 4) return midpoint(points[1], points[2], .8);
551
+ return routeLabelPoint(points);
552
+ }
553
+ // src/lib/variable-tree.ts
554
+ /**
555
+ * 에디터 변수 픽커의 데이터 빌더 (순수함수 — 클라이언트 안전).
556
+ *
557
+ * 그리드 연결 그래프에서 현재 스텝의 상류(조상) 스텝을 계산하고, 각 스텝의
558
+ * 출력 스키마(output-schemas.ts)·트리거 페이로드·특수 변수를 합쳐 삽입 가능한
559
+ * `{{토큰}}` 목록을 만든다. 토큰 문법은 engine/variable-resolver.ts 와 동일:
560
+ * - 트리거 페이로드: `{{key}}` (context.params 직접)
561
+ * - 스텝 출력: `{{<stepId>.output.<key>}}` (previousResults)
562
+ * - 특수 변수: `{{runId}}` 등
563
+ */
564
+ /** engine/variable-resolver.ts 의 VARIABLE_PATTERN과 동일해야 한다 (테스트로 고정) */
565
+ const VARIABLE_TOKEN_PATTERN = /\{\{([^}]+)\}\}/g;
566
+ /**
567
+ * 현재 스텝의 상류(조상) 스텝 목록 — 연결 그래프 역방향 BFS.
568
+ * 자기 자신은 제외하며, 그래프 순서(트리거에서 가까운 순)와 무관하게
569
+ * 방문 순서대로 반환한다.
570
+ */
571
+ function getUpstreamSteps(currentStepId, steps, connections) {
572
+ var _incoming$get2;
573
+ const stepById = new Map(steps.map((s) => [s.id, s]));
574
+ const incoming = /* @__PURE__ */ new Map();
575
+ for (const conn of connections) {
576
+ var _incoming$get;
577
+ const list = (_incoming$get = incoming.get(conn.toStepId)) !== null && _incoming$get !== void 0 ? _incoming$get : [];
578
+ list.push(conn.fromStepId);
579
+ incoming.set(conn.toStepId, list);
580
+ }
581
+ const visited = /* @__PURE__ */ new Set();
582
+ const queue = [...(_incoming$get2 = incoming.get(currentStepId)) !== null && _incoming$get2 !== void 0 ? _incoming$get2 : []];
583
+ const result = [];
584
+ while (queue.length > 0) {
585
+ var _incoming$get3;
586
+ const id = queue.shift();
587
+ if (visited.has(id) || id === currentStepId) continue;
588
+ visited.add(id);
589
+ const step = stepById.get(id);
590
+ if (step) result.push(step);
591
+ queue.push(...(_incoming$get3 = incoming.get(id)) !== null && _incoming$get3 !== void 0 ? _incoming$get3 : []);
592
+ }
593
+ return result;
594
+ }
595
+ /** 출력 필드를 하위 경로까지 편다 — 픽커와 AI 에이전트 프롬프트가 같은 경로를 쓴다. */
596
+ function flattenFields(fields, prefix) {
597
+ const out = [];
598
+ for (const field of fields) {
599
+ var _field$children;
600
+ const path = prefix ? `${prefix}.${field.key}` : field.key;
601
+ out.push(require_end_node_ids._objectSpread2(require_end_node_ids._objectSpread2({}, field), {}, { path }));
602
+ if ((_field$children = field.children) === null || _field$children === void 0 ? void 0 : _field$children.length) out.push(...flattenFields(field.children, path));
603
+ }
604
+ return out;
605
+ }
606
+ /**
607
+ * 변수 픽커에 보여줄 그룹 목록.
608
+ * 그룹 순서: 트리거 페이로드 → 상류 스텝 출력(가까운 순) → 특수 변수.
609
+ */
610
+ function buildVariableTree(params) {
611
+ var _params$extraGroups;
612
+ const { currentStepId, steps, connections } = params;
613
+ const groups = [];
614
+ const triggerStep = steps.find((s) => s.type === "trigger");
615
+ if (triggerStep === null || triggerStep === void 0 ? void 0 : triggerStep.nodeDefinitionId) {
616
+ const payload = require_step_type_for_node.TRIGGER_PAYLOADS[triggerStep.nodeDefinitionId];
617
+ if (payload === null || payload === void 0 ? void 0 : payload.length) groups.push({
618
+ id: "trigger",
619
+ heading: require_branch_resolver.msgf("트리거: {label}", { label: triggerStep.label }),
620
+ items: flattenFields(payload, "").map((f) => ({
621
+ token: `{{${f.path}}}`,
622
+ label: f.label,
623
+ type: f.type,
624
+ description: f.description,
625
+ example: f.example
626
+ }))
627
+ });
628
+ }
629
+ if ((_params$extraGroups = params.extraGroups) === null || _params$extraGroups === void 0 ? void 0 : _params$extraGroups.length) groups.push(...params.extraGroups);
630
+ const upstream = currentStepId ? getUpstreamSteps(currentStepId, steps, connections) : [];
631
+ for (const step of upstream) {
632
+ if (step.type === "trigger") continue;
633
+ const outputs = step.nodeDefinitionId ? require_step_type_for_node.NODE_OUTPUTS[step.nodeDefinitionId] : void 0;
634
+ if (!(outputs === null || outputs === void 0 ? void 0 : outputs.length)) continue;
635
+ groups.push({
636
+ id: `step-${step.id}`,
637
+ heading: require_branch_resolver.msgf("스텝: {label}", { label: step.label }),
638
+ items: flattenFields(outputs, "").map((f) => ({
639
+ token: `{{${step.id}.output.${f.path}}}`,
640
+ label: f.label,
641
+ type: f.type,
642
+ description: f.description,
643
+ example: f.example
644
+ }))
645
+ });
646
+ }
647
+ groups.push({
648
+ id: "special",
649
+ heading: "특수 변수",
650
+ items: require_step_type_for_node.SPECIAL_VARIABLES.map((f) => ({
651
+ token: `{{${f.key}}}`,
652
+ label: f.label,
653
+ type: f.type,
654
+ example: f.example
655
+ }))
656
+ });
657
+ return groups;
658
+ }
659
+ /**
660
+ * 문자열 config 값의 `{{stepId.output.*}}` 참조 중 상류에 없는 스텝을 가리키는
661
+ * 것을 찾는다 (스텝 삭제/재배선으로 깨진 참조의 정적 검출).
662
+ * 트리거 페이로드·런타임 변수 참조는 정적으로 판별할 수 없으므로 건드리지 않는다.
663
+ */
664
+ function findBrokenStepRefs(value, params) {
665
+ const issues = [];
666
+ const stepIds = new Set(params.steps.map((s) => s.id));
667
+ const upstreamIds = new Set(params.currentStepId ? getUpstreamSteps(params.currentStepId, params.steps, params.connections).map((s) => s.id) : []);
668
+ VARIABLE_TOKEN_PATTERN.lastIndex = 0;
669
+ let match;
670
+ while ((match = VARIABLE_TOKEN_PATTERN.exec(value)) !== null) {
671
+ const segments = match[1].trim().split(".");
672
+ if (segments.length < 2 || segments[1] !== "output") continue;
673
+ const refStepId = segments[0];
674
+ if (!stepIds.has(refStepId)) issues.push({
675
+ token: match[0],
676
+ message: "존재하지 않는 스텝을 참조합니다 (삭제됨?)"
677
+ });
678
+ else if (!upstreamIds.has(refStepId)) issues.push({
679
+ token: match[0],
680
+ message: "이 스텝보다 앞서 실행되지 않는 스텝의 출력입니다"
681
+ });
682
+ }
683
+ return issues;
684
+ }
685
+ // src/engine/failure-triage.ts
686
+ /**
687
+ * 실행 실패 트리아지 — **결정론이 먼저 답하고, 모델은 남은 것만** 본다.
688
+ *
689
+ * # 무엇을 푸는가
690
+ *
691
+ * 실패한 런에서 사용자가 보는 것은 에러 문자열 하나다("HTTP 422 Unprocessable
692
+ * Entity", "이메일 전송 실패 — 재시도 한도 초과"). 그 문장은 **무엇을 고쳐야 하는지**를
693
+ * 말하지 않는다. 내 설정이 틀린 건지, 상대 서비스가 잠깐 죽은 건지, 기다렸다 다시
694
+ * 누르면 되는 건지가 갈리지 않는다.
695
+ *
696
+ * # 왜 두 층인가
697
+ *
698
+ * 🔑 실패의 대부분은 **우리 코드가 만든 것**이고, 그것은 이미 타입으로 안다
699
+ * (`failureKind` — 던진 자리에서 기록). 거기에 실행 기록의 사실
700
+ * (`timedOut`·`retryCount`·`unresolvedVariables`)을 더하면 **모델 없이** 범주가 정해진다.
701
+ * 모델을 부르는 것은 돈과 지연이고, 결정론으로 답할 수 있는 것에 모델을 쓰면
702
+ * 느려지는 대신 틀릴 여지만 생긴다.
703
+ *
704
+ * 남는 것은 `failureKind: "unknown"` — **외부에서 온 자유 텍스트**다(상대 서비스 응답,
705
+ * 프로바이더 SDK 에러, 사용자 코드 예외). 그건 코드가 분류할 수 없는 자리이고,
706
+ * 정확히 Jev가 잘하는 모양이다(자유 텍스트 → 타입 답 + 확률).
707
+ *
708
+ * 이 모듈은 **순수**하다 — 모델을 부르지 않는다. 잔여분 판정은 호출측이
709
+ * `#/ai/lib/jev-classifier`로 이어 붙인다(그래야 이 층을 DB·네트워크 없이 테스트한다).
710
+ */
711
+ /**
712
+ * 실패 원인 범주 — 사용자가 **다음에 무엇을 할지**로 가른다.
713
+ * (기술적 분류가 아니라 행동 분류다. "SSRF 차단"은 원인이지만 사용자가 할 일은
714
+ * "주소를 고친다"이므로 `configuration`이다.)
715
+ */
716
+ const FAILURE_CAUSES = [
717
+ "configuration",
718
+ "data",
719
+ "external-service",
720
+ "transient",
721
+ "limit",
722
+ "cancelled",
723
+ "definition",
724
+ "unknown"
725
+ ];
726
+ /** `failureKind` → 범주 (우리가 던진 에러는 여기서 끝난다). */
727
+ const KIND_TO_CAUSE = {
728
+ timeout: {
729
+ cause: "transient",
730
+ userFixable: false,
731
+ retryLikelyHelps: true
732
+ },
733
+ aborted: {
734
+ cause: "cancelled",
735
+ userFixable: true,
736
+ retryLikelyHelps: true
737
+ },
738
+ "blocked-address": {
739
+ cause: "configuration",
740
+ userFixable: true,
741
+ retryLikelyHelps: false
742
+ },
743
+ "invalid-config": {
744
+ cause: "configuration",
745
+ userFixable: true,
746
+ retryLikelyHelps: false
747
+ },
748
+ "missing-handler": {
749
+ cause: "definition",
750
+ userFixable: false,
751
+ retryLikelyHelps: false
752
+ },
753
+ retryable: {
754
+ cause: "transient",
755
+ userFixable: false,
756
+ retryLikelyHelps: true
757
+ }
758
+ };
759
+ /**
760
+ * 실패한 스텝 하나를 결정론으로 판정한다.
761
+ *
762
+ * 🔑 순서가 규칙이다 — **더 구체적인 사실이 먼저** 이긴다. 예컨대 미해결 변수가 있으면
763
+ * 그것이 원인일 가능성이 압도적이므로(빈 값이 외부로 나가 422가 된다) `fatal`보다 앞선다.
764
+ */
765
+ function triageFailedStep(step) {
766
+ var _step$error, _step$nodeId;
767
+ const evidence = [];
768
+ const error = (_step$error = step.error) !== null && _step$error !== void 0 ? _step$error : "";
769
+ if (step.unresolvedVariables && step.unresolvedVariables.length > 0) return {
770
+ status: "resolved",
771
+ triage: {
772
+ cause: "configuration",
773
+ userFixable: true,
774
+ retryLikelyHelps: false,
775
+ source: "deterministic",
776
+ evidence: [require_branch_resolver.msgf("값을 찾지 못한 변수 {count}개: {names}", {
777
+ count: step.unresolvedVariables.length,
778
+ names: step.unresolvedVariables.map((v) => `{{${v}}}`).join(", ")
779
+ })]
780
+ }
781
+ };
782
+ if (step.status === "timeout" || step.failureKind === "timeout") return {
783
+ status: "resolved",
784
+ triage: {
785
+ cause: "transient",
786
+ userFixable: false,
787
+ retryLikelyHelps: true,
788
+ source: "deterministic",
789
+ evidence: [step.duration !== void 0 ? require_branch_resolver.msgf("{seconds}초 후 타임아웃", { seconds: Math.round(step.duration / 1e3) }) : "타임아웃"]
790
+ }
791
+ };
792
+ const kindMatch = step.failureKind && KIND_TO_CAUSE[step.failureKind];
793
+ if (kindMatch) {
794
+ if (step.retryCount > 0) evidence.push(require_branch_resolver.msgf("{count}회 재시도 후 실패", { count: step.retryCount }));
795
+ evidence.push(describeKind(step.failureKind));
796
+ return {
797
+ status: "resolved",
798
+ triage: require_end_node_ids._objectSpread2(require_end_node_ids._objectSpread2({}, kindMatch), {}, {
799
+ source: "deterministic",
800
+ evidence
801
+ })
802
+ };
803
+ }
804
+ const httpStatus = readHttpStatus(error);
805
+ if (httpStatus !== void 0) {
806
+ const isServerSide = httpStatus >= 500;
807
+ return {
808
+ status: "resolved",
809
+ triage: {
810
+ cause: isServerSide ? "external-service" : "configuration",
811
+ userFixable: !isServerSide,
812
+ retryLikelyHelps: isServerSide || httpStatus === 429,
813
+ source: "deterministic",
814
+ evidence: [require_branch_resolver.msgf("상대 서비스가 HTTP {status}로 응답", { status: httpStatus }), ...step.retryCount > 0 ? [require_branch_resolver.msgf("{count}회 재시도 후 실패", { count: step.retryCount })] : []]
815
+ }
816
+ };
817
+ }
818
+ return {
819
+ status: "needs-model",
820
+ residual: {
821
+ stepLabel: step.stepLabel,
822
+ stepType: step.stepType,
823
+ nodeKind: (_step$nodeId = step.nodeId) !== null && _step$nodeId !== void 0 ? _step$nodeId : step.stepType,
824
+ errorMessage: error.slice(0, 500),
825
+ retryCount: step.retryCount,
826
+ facts: [...step.retryCount > 0 ? [require_branch_resolver.msgf("{count}회 재시도했다", { count: step.retryCount })] : [], ...step.duration !== void 0 ? [require_branch_resolver.msgf("{ms}ms 실행 후 실패", { ms: step.duration })] : []]
827
+ }
828
+ };
829
+ }
830
+ /** 런 전체에서 **판정 대상 스텝**을 고른다 — 마지막 실패가 원인이다. */
831
+ function findFailedStep(stepRecords) {
832
+ for (let i = stepRecords.length - 1; i >= 0; i -= 1) {
833
+ const record = stepRecords[i];
834
+ if (record.status === "failed" || record.status === "timeout") return record;
835
+ }
836
+ }
837
+ function describeKind(kind) {
838
+ switch (kind) {
839
+ case "blocked-address": return "허용되지 않는 주소(사설망·메타데이터 서버)로의 호출이 차단됐습니다";
840
+ case "invalid-config": return "스텝 설정이 필수 조건을 만족하지 못했습니다";
841
+ case "missing-handler": return "이 스텝의 실행기를 찾지 못했습니다";
842
+ case "aborted": return "실행이 중단됐습니다";
843
+ case "retryable": return "일시적 오류로 분류돼 재시도했습니다";
844
+ case "timeout": return "제한 시간을 초과했습니다";
845
+ case "fatal": return "재시도로 회복할 수 없는 오류입니다";
846
+ default: return "원인을 특정하지 못했습니다";
847
+ }
848
+ }
849
+ /**
850
+ * 에러 문자열에서 HTTP 상태 코드를 읽는다.
851
+ *
852
+ * ⚠️ 문구가 아니라 **`HTTP <숫자>` 형태**만 본다. 우리 http-request 노드가 그 모양으로
853
+ * 만들고(`throwForStatus`), 그 외의 임의 문장에서 세 자리 숫자를 줍지 않는다 —
854
+ * "500명에게 발송 실패" 같은 문장을 서버 오류로 오독하지 않기 위해서다.
855
+ */
856
+ function readHttpStatus(message) {
857
+ const match = message.match(/\bHTTP\s(\d{3})\b/);
858
+ if (!match) return void 0;
859
+ const status = Number.parseInt(match[1], 10);
860
+ return status >= 100 && status <= 599 ? status : void 0;
861
+ }
862
+ // src/lib/failure-cause-copy.ts
863
+ /** 범주 → 사용자가 읽는 한 줄. 기술 용어가 아니라 **다음 행동**으로 적는다. */
864
+ const FAILURE_CAUSE_COPY = {
865
+ configuration: {
866
+ label: "설정을 고쳐야 합니다",
867
+ hint: "스텝 설정값(주소·수신자·필수 항목)이 실행 시점에 맞지 않았습니다.",
868
+ tone: "fix"
869
+ },
870
+ data: {
871
+ label: "데이터가 없거나 모양이 다릅니다",
872
+ hint: "참조한 고객·목록·변수가 비어 있거나 기대한 형태가 아니었습니다.",
873
+ tone: "fix"
874
+ },
875
+ "external-service": {
876
+ label: "연동한 서비스 쪽 문제입니다",
877
+ hint: "상대 서비스가 오류를 돌려줬습니다. 서비스 상태와 응답 내용을 확인해 주세요.",
878
+ tone: "wait"
879
+ },
880
+ transient: {
881
+ label: "일시적인 문제입니다",
882
+ hint: "네트워크·혼잡·제한 시간 때문일 가능성이 높습니다.",
883
+ tone: "wait"
884
+ },
885
+ limit: {
886
+ label: "한도 또는 권한에 막혔습니다",
887
+ hint: "요금제 한도·발송 잔액·접근 권한을 확인해 주세요.",
888
+ tone: "fix"
889
+ },
890
+ cancelled: {
891
+ label: "실행이 중단됐습니다",
892
+ hint: "취소 요청 또는 실행 상한으로 멈췄습니다.",
893
+ tone: "unknown"
894
+ },
895
+ definition: {
896
+ label: "워크플로우 구조 문제입니다",
897
+ hint: "스텝 연결이나 노드 구성을 확인해 주세요. 고객센터 문의가 필요할 수 있습니다.",
898
+ tone: "wait"
899
+ },
900
+ unknown: {
901
+ label: "원인을 특정하지 못했습니다",
902
+ hint: "원문 오류와 실행 입력을 확인해 주세요.",
903
+ tone: "unknown"
904
+ }
905
+ };
906
+ // src/lib/step-metrics.ts
907
+ /**
908
+ * 스텝별 누적 지표 — 최근 런들의 스텝 기록을 **지금 캔버스의 그래프**에 얹어 센다(순수).
909
+ *
910
+ * 런 한 건의 경로는 `deriveRunPath`가 이미 준다. 여기서는 그것을 여러 런에 돌려 합친다:
911
+ * 스텝마다 "몇 번 도달했고 몇 번 끝났고 몇 번 실패했나", 연결마다 "몇 번 지나갔나". 조건
912
+ * 스텝의 분기 비율은 나가는 연결들의 통과 횟수가 곧 답이다.
913
+ *
914
+ * 🔑 0과 "모름"을 가른다: 런이 한 건도 없으면 지표는 0이 아니라 **없다**(`runCount: 0`이고
915
+ * 스텝·연결 맵이 빈다) — 화면이 "0번 지나감"이라고 말하지 않게 한다. 그리고 그래프에 지금
916
+ * 없는 스텝의 기록(지워진 스텝)은 세지 않는다.
917
+ */
918
+ /** 실제로 시작된 상태 — `pending`·`skipped`는 실행된 것이 아니다. 시간 초과는 실패로 센다. */
919
+ const STARTED = /* @__PURE__ */ new Set([
920
+ "running",
921
+ "completed",
922
+ "failed",
923
+ "timeout"
924
+ ]);
925
+ const FAILED = /* @__PURE__ */ new Set(["failed", "timeout"]);
926
+ function aggregateStepMetrics({ steps, connections, runs }) {
927
+ const stepMetrics = /* @__PURE__ */ new Map();
928
+ const durations = /* @__PURE__ */ new Map();
929
+ const traversed = /* @__PURE__ */ new Map();
930
+ if (runs.length === 0) return {
931
+ runCount: 0,
932
+ steps: stepMetrics,
933
+ connections: traversed
934
+ };
935
+ const known = new Set(steps.map((step) => step.id));
936
+ for (const step of steps) stepMetrics.set(step.id, {
937
+ entered: 0,
938
+ completed: 0,
939
+ failed: 0,
940
+ averageDurationMs: null
941
+ });
942
+ for (const connection of connections) traversed.set(connection.id, 0);
943
+ for (const run of runs) {
944
+ const stepStates = /* @__PURE__ */ new Map();
945
+ for (const record of run.steps) {
946
+ if (!known.has(record.stepId)) continue;
947
+ if (!STARTED.has(record.status)) continue;
948
+ stepStates.set(record.stepId, {
949
+ status: record.status,
950
+ startedAt: record.startedAt
951
+ });
952
+ const metric = stepMetrics.get(record.stepId);
953
+ metric.entered++;
954
+ if (record.status === "completed") metric.completed++;
955
+ if (FAILED.has(record.status)) metric.failed++;
956
+ if (typeof record.duration === "number" && record.status !== "running") {
957
+ var _durations$get;
958
+ const sum = (_durations$get = durations.get(record.stepId)) !== null && _durations$get !== void 0 ? _durations$get : {
959
+ total: 0,
960
+ count: 0
961
+ };
962
+ sum.total += record.duration;
963
+ sum.count++;
964
+ durations.set(record.stepId, sum);
965
+ }
966
+ }
967
+ const { connectionStatus } = deriveRunPath({
968
+ steps,
969
+ connections,
970
+ stepStates,
971
+ settled: true
972
+ });
973
+ for (const [connectionId, status] of connectionStatus) if (status !== "muted") {
974
+ var _traversed$get;
975
+ traversed.set(connectionId, ((_traversed$get = traversed.get(connectionId)) !== null && _traversed$get !== void 0 ? _traversed$get : 0) + 1);
976
+ }
977
+ }
978
+ for (const [stepId, sum] of durations) {
979
+ const metric = stepMetrics.get(stepId);
980
+ if (metric && sum.count > 0) metric.averageDurationMs = Math.round(sum.total / sum.count);
981
+ }
982
+ return {
983
+ runCount: runs.length,
984
+ steps: stepMetrics,
985
+ connections: traversed
986
+ };
987
+ }
988
+ /** 분모가 0이면 비율은 없다(0%가 아니다). */
989
+ function formatShare(part, whole) {
990
+ if (whole <= 0) return null;
991
+ return `${Math.round(part / whole * 100)}%`;
992
+ }
993
+ function formatDurationMs(ms) {
994
+ if (ms < 1e3) return `${ms}ms`;
995
+ if (ms < 6e4) return require_branch_resolver.msgf("{value}초", { value: (ms / 1e3).toFixed(ms < 1e4 ? 1 : 0) });
996
+ return require_branch_resolver.msgf("{value}분", { value: Math.round(ms / 6e4) });
997
+ }
998
+ // src/lib/template-io.ts
999
+ /**
1000
+ * 워크플로우 템플릿 Import/Export 유틸리티
1001
+ */
1002
+ const _excluded = ["nodeDefinition"];
1003
+ /**
1004
+ * 워크플로우 정의 유효성 검사
1005
+ */
1006
+ function validateWorkflowDefinition(definition) {
1007
+ const errors = [];
1008
+ const warnings = [];
1009
+ const parseResult = require_ai_stream.gridWorkflowDefinitionSchema.safeParse(definition);
1010
+ if (!parseResult.success) {
1011
+ for (const issue of parseResult.error.issues) errors.push({
1012
+ code: "SCHEMA_ERROR",
1013
+ message: issue.message,
1014
+ path: issue.path.join(".")
1015
+ });
1016
+ return {
1017
+ valid: false,
1018
+ errors,
1019
+ warnings
1020
+ };
1021
+ }
1022
+ const def = parseResult.data;
1023
+ const stepIds = /* @__PURE__ */ new Set();
1024
+ const positionMap = /* @__PURE__ */ new Map();
1025
+ for (const step of def.steps) {
1026
+ if (stepIds.has(step.id)) errors.push({
1027
+ code: "DUPLICATE_STEP_ID",
1028
+ message: require_branch_resolver.msgf("중복된 스텝 ID: {id}", { id: step.id }),
1029
+ stepId: step.id
1030
+ });
1031
+ stepIds.add(step.id);
1032
+ if (!require_ai_stream.isValidPosition(step.position)) errors.push({
1033
+ code: "INVALID_POSITION",
1034
+ message: require_branch_resolver.msgf("유효하지 않은 위치: ({row}, {col})", {
1035
+ row: step.position.row,
1036
+ col: step.position.col
1037
+ }),
1038
+ stepId: step.id
1039
+ });
1040
+ const posKey = `${step.position.row},${step.position.col}`;
1041
+ if (positionMap.has(posKey)) errors.push({
1042
+ code: "DUPLICATE_POSITION",
1043
+ message: require_branch_resolver.msgf("같은 위치에 여러 스텝: ({row}, {col})", {
1044
+ row: step.position.row,
1045
+ col: step.position.col
1046
+ }),
1047
+ stepId: step.id
1048
+ });
1049
+ positionMap.set(posKey, step.id);
1050
+ if ((step.type === "trigger" || step.type === "action") && step.nodeDefinitionId) {
1051
+ if (!require_node_definitions.getNodeDefinition(step.nodeDefinitionId)) warnings.push({
1052
+ code: "UNKNOWN_NODE_DEFINITION",
1053
+ message: require_branch_resolver.msgf("알 수 없는 노드 정의: {id}", { id: String(step.nodeDefinitionId) }),
1054
+ stepId: step.id
1055
+ });
1056
+ }
1057
+ }
1058
+ const connectionIds = /* @__PURE__ */ new Set();
1059
+ const connectionPairs = /* @__PURE__ */ new Set();
1060
+ for (const conn of def.connections) {
1061
+ if (connectionIds.has(conn.id)) errors.push({
1062
+ code: "DUPLICATE_CONNECTION_ID",
1063
+ message: require_branch_resolver.msgf("중복된 연결 ID: {id}", { id: conn.id }),
1064
+ connectionId: conn.id
1065
+ });
1066
+ connectionIds.add(conn.id);
1067
+ if (!stepIds.has(conn.fromStepId)) errors.push({
1068
+ code: "INVALID_FROM_STEP",
1069
+ message: require_branch_resolver.msgf("존재하지 않는 시작 스텝: {id}", { id: conn.fromStepId }),
1070
+ connectionId: conn.id
1071
+ });
1072
+ if (!stepIds.has(conn.toStepId)) errors.push({
1073
+ code: "INVALID_TO_STEP",
1074
+ message: require_branch_resolver.msgf("존재하지 않는 종료 스텝: {id}", { id: conn.toStepId }),
1075
+ connectionId: conn.id
1076
+ });
1077
+ if (conn.fromStepId === conn.toStepId) errors.push({
1078
+ code: "SELF_CONNECTION",
1079
+ message: `자기 자신으로 연결할 수 없습니다`,
1080
+ connectionId: conn.id
1081
+ });
1082
+ const pairKey = `${conn.fromStepId}-${conn.toStepId}`;
1083
+ if (connectionPairs.has(pairKey)) warnings.push({
1084
+ code: "DUPLICATE_CONNECTION_PAIR",
1085
+ message: require_branch_resolver.msgf("동일한 연결이 이미 존재합니다: {from} → {to}", {
1086
+ from: conn.fromStepId,
1087
+ to: conn.toStepId
1088
+ }),
1089
+ stepId: conn.fromStepId
1090
+ });
1091
+ connectionPairs.add(pairKey);
1092
+ }
1093
+ if (require_ai_stream.hasCycle(def.connections)) errors.push({
1094
+ code: "CYCLE_DETECTED",
1095
+ message: "워크플로우에 순환이 감지되었습니다. 순환은 허용되지 않습니다."
1096
+ });
1097
+ const triggers = def.steps.filter((s) => s.type === "trigger");
1098
+ if (triggers.length === 0) warnings.push({
1099
+ code: "NO_TRIGGER",
1100
+ message: "트리거 스텝이 없습니다. 워크플로우가 시작되지 않을 수 있습니다."
1101
+ });
1102
+ if (triggers.length > 1) warnings.push({
1103
+ code: "MULTIPLE_TRIGGERS",
1104
+ message: require_branch_resolver.msgf("여러 개의 트리거가 있습니다 ({count}개). 일반적으로 하나의 트리거만 권장됩니다.", { count: triggers.length })
1105
+ });
1106
+ if (def.steps.filter((s) => s.type === "end").length === 0) warnings.push({
1107
+ code: "NO_END_STEP",
1108
+ message: "종료 스텝이 없습니다."
1109
+ });
1110
+ const connectedSteps = /* @__PURE__ */ new Set();
1111
+ for (const conn of def.connections) {
1112
+ connectedSteps.add(conn.fromStepId);
1113
+ connectedSteps.add(conn.toStepId);
1114
+ }
1115
+ for (const step of def.steps) if (!connectedSteps.has(step.id) && step.type !== "end" && def.steps.length > 1) warnings.push({
1116
+ code: "ISOLATED_STEP",
1117
+ message: require_branch_resolver.msgf("연결되지 않은 스텝: {label}", { label: step.label }),
1118
+ stepId: step.id
1119
+ });
1120
+ const loopSteps = def.steps.filter((s) => s.type === "forEach" || s.type === "while" || s.type === "repeat");
1121
+ if (loopSteps.length > 0) {
1122
+ const adjacency = /* @__PURE__ */ new Map();
1123
+ for (const conn of def.connections) {
1124
+ var _adjacency$get;
1125
+ const list = (_adjacency$get = adjacency.get(conn.fromStepId)) !== null && _adjacency$get !== void 0 ? _adjacency$get : [];
1126
+ list.push(conn.toStepId);
1127
+ adjacency.set(conn.fromStepId, list);
1128
+ }
1129
+ const typeById = new Map(def.steps.map((s) => [s.id, s.type]));
1130
+ for (const loop of loopSteps) {
1131
+ var _adjacency$get2;
1132
+ const visited = /* @__PURE__ */ new Set();
1133
+ const queue = [...(_adjacency$get2 = adjacency.get(loop.id)) !== null && _adjacency$get2 !== void 0 ? _adjacency$get2 : []];
1134
+ let hasLoopEnd = false;
1135
+ while (queue.length > 0) {
1136
+ var _adjacency$get3;
1137
+ const id = queue.shift();
1138
+ if (visited.has(id)) continue;
1139
+ visited.add(id);
1140
+ if (typeById.get(id) === "loopEnd") {
1141
+ hasLoopEnd = true;
1142
+ break;
1143
+ }
1144
+ queue.push(...(_adjacency$get3 = adjacency.get(id)) !== null && _adjacency$get3 !== void 0 ? _adjacency$get3 : []);
1145
+ }
1146
+ if (!hasLoopEnd) warnings.push({
1147
+ code: "LOOP_WITHOUT_LOOPEND",
1148
+ message: require_branch_resolver.msgf("반복 노드 \"{label}\"에 loopEnd 마커가 없습니다. body 끝에 \"반복 끝\" 노드를 연결하세요.", { label: loop.label }),
1149
+ stepId: loop.id
1150
+ });
1151
+ }
1152
+ }
1153
+ return {
1154
+ valid: errors.length === 0,
1155
+ errors,
1156
+ warnings
1157
+ };
1158
+ }
1159
+ /**
1160
+ * 템플릿 내보내기
1161
+ */
1162
+ function exportTemplate(definition, metadata) {
1163
+ const cleanedSteps = definition.steps.map((step) => {
1164
+ const { nodeDefinition: _ } = step;
1165
+ return require_end_node_ids._objectWithoutProperties(step, _excluded);
1166
+ });
1167
+ return {
1168
+ version: "1.0",
1169
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
1170
+ metadata,
1171
+ definition: require_end_node_ids._objectSpread2(require_end_node_ids._objectSpread2({}, definition), {}, { steps: cleanedSteps })
1172
+ };
1173
+ }
1174
+ /**
1175
+ * 템플릿을 JSON 문자열로 직렬화
1176
+ */
1177
+ function serializeTemplate(definition, metadata) {
1178
+ const exportData = exportTemplate(definition, metadata);
1179
+ return JSON.stringify(exportData, null, 2);
1180
+ }
1181
+ /**
1182
+ * 템플릿 가져오기
1183
+ */
1184
+ function importTemplate(jsonString) {
1185
+ let parsed;
1186
+ try {
1187
+ parsed = JSON.parse(jsonString);
1188
+ } catch (_unused) {
1189
+ return {
1190
+ success: false,
1191
+ validation: {
1192
+ valid: false,
1193
+ errors: [{
1194
+ code: "INVALID_JSON",
1195
+ message: "JSON 파싱에 실패했습니다."
1196
+ }],
1197
+ warnings: []
1198
+ },
1199
+ error: "JSON 파싱에 실패했습니다."
1200
+ };
1201
+ }
1202
+ const exportResult = require_ai_stream.exportTemplateSchema.safeParse(parsed);
1203
+ if (exportResult.success) {
1204
+ const { definition, metadata } = exportResult.data;
1205
+ const restoredSteps = definition.steps.map((step) => require_end_node_ids._objectSpread2(require_end_node_ids._objectSpread2({}, step), {}, { nodeDefinition: require_step_type_for_node.getStepNodeDefinition(step) }));
1206
+ const restoredDefinition = require_end_node_ids._objectSpread2(require_end_node_ids._objectSpread2({}, definition), {}, { steps: restoredSteps });
1207
+ const validation = validateWorkflowDefinition(restoredDefinition);
1208
+ return {
1209
+ success: validation.valid,
1210
+ definition: restoredDefinition,
1211
+ metadata: {
1212
+ name: metadata.name,
1213
+ description: metadata.description,
1214
+ category: metadata.category,
1215
+ icon: metadata.icon,
1216
+ author: metadata.author
1217
+ },
1218
+ validation
1219
+ };
1220
+ }
1221
+ const definitionResult = require_ai_stream.gridWorkflowDefinitionSchema.safeParse(parsed);
1222
+ if (definitionResult.success) {
1223
+ const definition = definitionResult.data;
1224
+ const restoredSteps = definition.steps.map((step) => require_end_node_ids._objectSpread2(require_end_node_ids._objectSpread2({}, step), {}, { nodeDefinition: require_step_type_for_node.getStepNodeDefinition(step) }));
1225
+ const restoredDefinition = require_end_node_ids._objectSpread2(require_end_node_ids._objectSpread2({}, definition), {}, { steps: restoredSteps });
1226
+ const validation = validateWorkflowDefinition(restoredDefinition);
1227
+ return {
1228
+ success: validation.valid,
1229
+ definition: restoredDefinition,
1230
+ metadata: { name: "가져온 워크플로우" },
1231
+ validation
1232
+ };
1233
+ }
1234
+ return {
1235
+ success: false,
1236
+ validation: {
1237
+ valid: false,
1238
+ errors: [{
1239
+ code: "INVALID_FORMAT",
1240
+ message: "유효한 워크플로우 템플릿 형식이 아닙니다."
1241
+ }],
1242
+ warnings: []
1243
+ },
1244
+ error: "유효한 워크플로우 템플릿 형식이 아닙니다."
1245
+ };
1246
+ }
1247
+ // src/lib/workflow-brief.ts
1248
+ /**
1249
+ * 워크플로우 요약 문서(Markdown) — 캔버스를 열지 않고도 읽을 수 있는 개요. 팀에 공유하거나
1250
+ * 문서에 붙이는 용도다(다시 가져오는 형식은 JSON 템플릿이고 이것은 읽기 전용이다).
1251
+ *
1252
+ * 스텝 순서는 흐름 순서(`orderStepsByFlow` — 키보드 이동·목록 미리보기와 한 벌), 스텝
1253
+ * 설명은 카드에 보이는 요약(`getStepSummary` — PII 마스킹된 값)이라 화면과 문서가 같은 말을 한다.
1254
+ */
1255
+ const STEP_TYPE_LABEL = {
1256
+ trigger: "트리거",
1257
+ condition: "조건",
1258
+ action: "액션",
1259
+ end: "종료"
1260
+ };
1261
+ /** 표 칸·목록 안에서 Markdown 문법으로 읽힐 문자를 눕힌다 */
1262
+ function inline(text) {
1263
+ return text.replace(/\s+/g, " ").replace(/([|*_`\\[\]])/g, "\\$1").trim();
1264
+ }
1265
+ function branchLabel(connection) {
1266
+ var _connection$label;
1267
+ if (connection.branchType === "case" && connection.branchValue) return connection.branchValue;
1268
+ if (connection.branchType) return require_ai_stream.BRANCH_TYPE_COLORS[connection.branchType].label;
1269
+ return (_connection$label = connection.label) !== null && _connection$label !== void 0 ? _connection$label : null;
1270
+ }
1271
+ function buildWorkflowBrief(definition, metadata) {
1272
+ var _metadata$description;
1273
+ const ordered = orderStepsByFlow(definition.steps, definition.connections);
1274
+ const numberOf = new Map(ordered.map((step, index) => [step.id, index + 1]));
1275
+ const lines = [`# ${inline(metadata.name) || "워크플로우"}`, ""];
1276
+ if ((_metadata$description = metadata.description) === null || _metadata$description === void 0 ? void 0 : _metadata$description.trim()) lines.push(metadata.description.trim(), "");
1277
+ lines.push(`스텝 ${definition.steps.length}개 · 연결 ${definition.connections.length}개`, "");
1278
+ if (ordered.length === 0) {
1279
+ lines.push("아직 스텝이 없습니다.", "");
1280
+ return lines.join("\n");
1281
+ }
1282
+ lines.push("## 흐름", "");
1283
+ for (const step of ordered) {
1284
+ var _ref, _getStepNodeDefinitio, _getStepNodeDefinitio2;
1285
+ const kind = (_ref = (_getStepNodeDefinitio = (_getStepNodeDefinitio2 = require_step_type_for_node.getStepNodeDefinition(step)) === null || _getStepNodeDefinitio2 === void 0 ? void 0 : _getStepNodeDefinitio2.name) !== null && _getStepNodeDefinitio !== void 0 ? _getStepNodeDefinitio : STEP_TYPE_LABEL[step.type]) !== null && _ref !== void 0 ? _ref : step.type;
1286
+ lines.push(`### ${numberOf.get(step.id)}. ${inline(step.label)} — ${inline(kind)}`, "");
1287
+ for (const item of getStepSummary(step)) lines.push(`- ${inline(item.label)}: ${inline(item.value)}`);
1288
+ if (step.continueOnError) lines.push("- 실패해도 계속 진행");
1289
+ const outgoing = definition.connections.filter((connection) => connection.fromStepId === step.id);
1290
+ if (outgoing.length === 0) lines.push("- 다음: 없음 (흐름이 여기서 끝납니다)");
1291
+ for (const connection of outgoing) {
1292
+ const target = definition.steps.find((candidate) => candidate.id === connection.toStepId);
1293
+ if (!target) continue;
1294
+ const branch = branchLabel(connection);
1295
+ lines.push(`- 다음${branch ? ` (${inline(branch)})` : ""}: ${numberOf.get(target.id)}. ${inline(target.label)}`);
1296
+ }
1297
+ lines.push("");
1298
+ }
1299
+ return lines.join("\n");
1300
+ }
1301
+ // src/lib/run-blockers.ts
1302
+ function findRunBlockers(definition) {
1303
+ const errors = [];
1304
+ const triggerSteps = definition.steps.filter((s) => s.type === "trigger");
1305
+ if (triggerSteps.length === 0) errors.push("트리거 스텝이 없습니다");
1306
+ if (triggerSteps.length > 1) errors.push("트리거 스텝은 하나만 있어야 합니다");
1307
+ if (triggerSteps.some((step) => {
1308
+ var _step$config;
1309
+ return step.nodeDefinitionId === "formSubmitted" && ((_step$config = step.config) === null || _step$config === void 0 ? void 0 : _step$config.formId) === null;
1310
+ })) errors.push("폼 제출 트리거에 대상 폼을 연결하거나 모든 폼을 선택하세요.");
1311
+ if (require_ai_stream.hasCycle(definition.connections)) errors.push("연결이 순환합니다. 워크플로우는 순환할 수 없습니다(무한 실행 방지).");
1312
+ return errors;
1313
+ }
1314
+ // src/lib/setup-problems.ts
1315
+ /**
1316
+ * "이 자동화는 지금 상태로 돌지 않는다" — 저장된 정의에서 **미완성 설정**을 찾는다.
1317
+ *
1318
+ * 🔴 왜 필요한가: 에디터가 필수 미입력 저장을 막게 됐지만(`lib/config-fields`),
1319
+ * **이미 저장된 정의는 그대로 남는다.** 일정 트리거에 실행 시각이 없는 워크플로우는
1320
+ * 실행되지 않고, 실행되지 않으므로 실패 기록도 남지 않는다 — 사용자 눈에는 아무 일도
1321
+ * 일어나지 않는 자동화로만 보인다. 목록에서 그 사실을 먼저 말해 줘야 한다.
1322
+ *
1323
+ * 🔑 판정은 **카탈로그 선언에서 파생**한다(`required` + `showWhen`). 여기에 "일정에는
1324
+ * 시각이 있어야 한다" 같은 규칙을 다시 적으면 선언과 갈린다.
1325
+ */
1326
+ /**
1327
+ * 정의 전체에서 "채워야 할 것이 남은" 스텝을 모은다(없으면 빈 배열).
1328
+ *
1329
+ * ⚠️ 인자가 `unknown`인 것은 의도다 — 이 값은 **DB에 저장된 JSON**이고, 목록·상세가
1330
+ * 서로 다른 DTO 타입으로 들고 있다. 모양을 여기서 확인하고 아니면 조용히 빈 배열.
1331
+ */
1332
+ function findWorkflowSetupProblems(definition) {
1333
+ var _ref;
1334
+ const steps = definition === null || definition === void 0 ? void 0 : definition.steps;
1335
+ if (!Array.isArray(steps)) return [];
1336
+ const connections = (_ref = definition === null || definition === void 0 ? void 0 : definition.connections) !== null && _ref !== void 0 ? _ref : [];
1337
+ const problems = [];
1338
+ for (const step of steps) {
1339
+ var _step$nodeDefinitionI, _step$nodeDefinition, _entry$config, _step$config;
1340
+ if (step.type === "condition") {
1341
+ const outgoing = connections.filter((connection) => connection.fromStepId === step.id);
1342
+ const { errors } = require_branch_resolver.validateBranchConnections(step, outgoing);
1343
+ if (errors.length > 0) problems.push({
1344
+ stepId: step.id,
1345
+ stepLabel: step.label,
1346
+ missingLabels: [],
1347
+ issues: errors
1348
+ });
1349
+ continue;
1350
+ }
1351
+ if (!((_step$nodeDefinitionI = step.nodeDefinitionId) !== null && _step$nodeDefinitionI !== void 0 ? _step$nodeDefinitionI : (_step$nodeDefinition = step.nodeDefinition) === null || _step$nodeDefinition === void 0 ? void 0 : _step$nodeDefinition.id)) continue;
1352
+ const entry = require_step_type_for_node.getStepNodeDefinition(step);
1353
+ const fields = entry === null || entry === void 0 || (_entry$config = entry.config) === null || _entry$config === void 0 ? void 0 : _entry$config.fields;
1354
+ if (!fields || fields.length === 0) continue;
1355
+ const missing = missingRequiredFields(fields, (_step$config = step.config) !== null && _step$config !== void 0 ? _step$config : {});
1356
+ if (missing.length === 0) continue;
1357
+ problems.push({
1358
+ stepId: step.id,
1359
+ stepLabel: step.label,
1360
+ missingLabels: missing.map((field) => field.label)
1361
+ });
1362
+ }
1363
+ return problems;
1364
+ }
1365
+ // src/lib/workflow-preflight.ts
1366
+ /**
1367
+ * 나가는 연결을 여럿 가질 수 있는 스텝 — 조건은 분기 타입으로, 병렬은 브랜치로 갈래를
1368
+ * 나눈다. 그 밖의 스텝은 실행기가 **첫 번째 연결만** 따라간다(`engine/graph-traversal.ts`).
1369
+ * 에디터는 두 번째 연결을 막지 않으므로, 그린 연결이 조용히 무시되는 자리를 점검이 말해야 한다.
1370
+ */
1371
+ const MULTI_OUTGOING_STEP_TYPES = /* @__PURE__ */ new Set(["condition", "parallel"]);
1372
+ /** 임포트의 구조 검사와 목록의 설정 검사를 편집 중 정의에도 적용한다. */
1373
+ function getWorkflowPreflight(definition) {
1374
+ const validation = validateWorkflowDefinition(definition);
1375
+ const issues = [];
1376
+ for (const [severity, items] of [["error", validation.errors], ["warning", validation.warnings]]) for (const item of items) {
1377
+ var _item$stepId, _ref, _ref2;
1378
+ if (item.code === "NO_END_STEP" || item.code === "ISOLATED_STEP") continue;
1379
+ const connectionId = "connectionId" in item ? item.connectionId : void 0;
1380
+ const connection = definition.connections.find((entry) => entry.id === connectionId);
1381
+ const stepId = (_item$stepId = item.stepId) !== null && _item$stepId !== void 0 ? _item$stepId : connection === null || connection === void 0 ? void 0 : connection.fromStepId;
1382
+ issues.push({
1383
+ id: `${item.code}:${(_ref = (_ref2 = stepId !== null && stepId !== void 0 ? stepId : connectionId) !== null && _ref2 !== void 0 ? _ref2 : item.path) !== null && _ref !== void 0 ? _ref : "workflow"}`,
1384
+ severity: item.code === "NO_TRIGGER" ? "error" : severity,
1385
+ message: item.message,
1386
+ stepId,
1387
+ target: connection ? "connections" : "canvas"
1388
+ });
1389
+ }
1390
+ const seen = new Set(issues.map((issue) => issue.message));
1391
+ for (const message of findRunBlockers(definition)) {
1392
+ if (seen.has(message)) continue;
1393
+ issues.push({
1394
+ id: `run-blocker:${message}`,
1395
+ severity: "error",
1396
+ message,
1397
+ target: "canvas"
1398
+ });
1399
+ }
1400
+ for (const problem of findWorkflowSetupProblems(definition)) {
1401
+ var _problem$issues;
1402
+ if (problem.missingLabels.length > 0) issues.push({
1403
+ id: `config:${problem.stepId}`,
1404
+ severity: "error",
1405
+ message: require_branch_resolver.msgf("{fields}을(를) 입력해 주세요.", { fields: problem.missingLabels.join(" · ") }),
1406
+ stepId: problem.stepId,
1407
+ target: "config"
1408
+ });
1409
+ (_problem$issues = problem.issues) === null || _problem$issues === void 0 || _problem$issues.forEach((message, index) => issues.push({
1410
+ id: `branch:${problem.stepId}:${index}`,
1411
+ severity: "error",
1412
+ message,
1413
+ stepId: problem.stepId,
1414
+ target: "connections"
1415
+ }));
1416
+ }
1417
+ for (const step of definition.steps) {
1418
+ if (step.type === "condition") for (const [index, message] of require_branch_resolver.validateConditionConfig(step.config).errors.entries()) issues.push({
1419
+ id: `condition:${step.id}:${index}`,
1420
+ severity: "error",
1421
+ message,
1422
+ stepId: step.id,
1423
+ target: "config"
1424
+ });
1425
+ if ((step.type === "action" || step.type === "trigger") && !step.nodeDefinitionId && !step.nodeDefinition) issues.push({
1426
+ id: `node:${step.id}`,
1427
+ severity: "error",
1428
+ message: "실행할 노드 종류를 선택해 주세요.",
1429
+ stepId: step.id,
1430
+ target: "config"
1431
+ });
1432
+ }
1433
+ for (const step of definition.steps) {
1434
+ if (MULTI_OUTGOING_STEP_TYPES.has(step.type)) continue;
1435
+ const outgoing = definition.connections.filter((connection) => connection.fromStepId === step.id);
1436
+ if (outgoing.length > 1) issues.push({
1437
+ id: `multi-outgoing:${step.id}`,
1438
+ severity: "warning",
1439
+ message: require_branch_resolver.msgf("나가는 연결이 {count}개인데 이 스텝은 첫 번째 연결만 따라갑니다. 갈래를 나누려면 조건 또는 병렬 스텝을 사이에 두세요.", { count: outgoing.length }),
1440
+ stepId: step.id,
1441
+ target: "connections"
1442
+ });
1443
+ }
1444
+ const triggers = definition.steps.filter((step) => step.type === "trigger");
1445
+ const reached = /* @__PURE__ */ new Set();
1446
+ const pending = triggers.map((step) => step.id);
1447
+ while (pending.length) {
1448
+ const id = pending.pop();
1449
+ if (reached.has(id)) continue;
1450
+ reached.add(id);
1451
+ for (const connection of definition.connections) if (connection.fromStepId === id) pending.push(connection.toStepId);
1452
+ }
1453
+ if (triggers.length > 0) {
1454
+ for (const step of definition.steps) if (!reached.has(step.id)) issues.push({
1455
+ id: `unreachable:${step.id}`,
1456
+ severity: "warning",
1457
+ message: "시작 트리거에서 이 스텝으로 이어지는 연결이 없습니다.",
1458
+ stepId: step.id,
1459
+ target: "connections"
1460
+ });
1461
+ }
1462
+ return [...issues].sort((a, b) => Number(a.severity === "warning") - Number(b.severity === "warning"));
1463
+ }
1464
+ // src/lib/grid-placement.ts
1465
+ const PLACEMENT_ORDER = [
1466
+ "right",
1467
+ "down",
1468
+ "left",
1469
+ "up"
1470
+ ];
1471
+ function isOccupied(position, steps) {
1472
+ return steps.some((s) => s.position.row === position.row && s.position.col === position.col);
1473
+ }
1474
+ /** `anchor`에 인접한(4-이웃) 첫 빈 셀. 사방이 막혀 있으면 null. */
1475
+ function findFreeAdjacentCell(anchor, steps) {
1476
+ for (const dir of PLACEMENT_ORDER) {
1477
+ const pos = require_ai_stream.getAdjacentPosition(anchor, dir);
1478
+ if (pos && !isOccupied(pos, steps)) return pos;
1479
+ }
1480
+ return null;
1481
+ }
1482
+ /**
1483
+ * 여러 앵커 **모두의** 이웃인 첫 빈 셀 — 합류 스텝(두 갈래가 모이는 join·종료) 자리.
1484
+ * 이웃이 아니어도 연결은 되지만, 합류 스텝이 모든 앞 스텝 옆에 있으면 선이 가장 짧다.
1485
+ * 그런 칸이 없으면 null(호출부가 첫 앵커 기준 배치로 물러난다).
1486
+ */
1487
+ function findFreeCommonNeighbor(anchors, steps) {
1488
+ const [first, ...rest] = anchors;
1489
+ if (!first) return null;
1490
+ for (const dir of PLACEMENT_ORDER) {
1491
+ const pos = require_ai_stream.getAdjacentPosition(first, dir);
1492
+ if (!pos || !require_ai_stream.isValidPosition(pos) || isOccupied(pos, steps)) continue;
1493
+ if (rest.every((anchor) => require_ai_stream.getConnectionDirection(anchor, pos) !== null)) return pos;
1494
+ }
1495
+ return null;
1496
+ }
1497
+ /** 인접 셀이 모두 찼을 때 `anchor`에서 바깥으로 BFS 하며 가장 가까운 빈 셀. */
1498
+ function findNearestFreeCell(anchor, steps) {
1499
+ const occupied = new Set(steps.map((s) => `${s.position.row},${s.position.col}`));
1500
+ const seen = /* @__PURE__ */ new Set([`${anchor.row},${anchor.col}`]);
1501
+ let frontier = [anchor];
1502
+ while (frontier.length > 0) {
1503
+ const next = [];
1504
+ for (const cell of frontier) for (const dir of PLACEMENT_ORDER) {
1505
+ const pos = require_ai_stream.getAdjacentPosition(cell, dir);
1506
+ if (!pos || !require_ai_stream.isValidPosition(pos)) continue;
1507
+ const key = `${pos.row},${pos.col}`;
1508
+ if (seen.has(key)) continue;
1509
+ seen.add(key);
1510
+ if (!occupied.has(key)) return pos;
1511
+ next.push(pos);
1512
+ }
1513
+ frontier = next;
1514
+ }
1515
+ return null;
1516
+ }
1517
+ /**
1518
+ * 연결 유효성 검사 — 자기 자신·중복·순환. 유효하면 null, 아니면 사용자용 사유 문자열.
1519
+ *
1520
+ * 🔑 **이웃 칸이 아니어도 연결된다.** 예전에는 이 함수만 이웃 칸을 요구했는데, 사람이 쓰는
1521
+ * 연결 모드는 원래 그 검사가 없었고 스텝을 옮기면 떨어진 연결이 그대로 남았다(템플릿 연결의
1522
+ * 41%가 비인접이다) — AI 제안 경로만 "이웃이 아니라 연결 못 함"으로 스텝을 연결 없이 남겼다.
1523
+ * 떨어진 연결은 `lib/grid-route`가 거터로 돌려 그린다. 사람(연결 모드)과 AI(제안 미리보기·
1524
+ * 세션)가 이 함수 **한 벌**을 쓴다.
1525
+ */
1526
+ function validateConnection(from, to, connections) {
1527
+ if (from.id === to.id) return "자기 자신에는 연결할 수 없습니다.";
1528
+ if (connections.some((c) => c.fromStepId === from.id && c.toStepId === to.id)) return "이미 연결되어 있습니다.";
1529
+ if (require_ai_stream.hasCycle(connections, {
1530
+ fromStepId: from.id,
1531
+ toStepId: to.id
1532
+ })) return "순환 연결은 허용되지 않습니다.";
1533
+ return null;
1534
+ }
1535
+ // src/lib/workflow-preview.ts
1536
+ /**
1537
+ * AI 제안 미리보기 — committed 그래프 + 제안 op 목록을 합쳐 "적용하면 이렇게 된다"를
1538
+ * 계산하는 순수 함수.
1539
+ *
1540
+ * 에이전트는 그래프 용어로만 op을 보내고(좌표 없음), 여기서 클라이언트가 그리드 배치·
1541
+ * 자동 연결·중복/순환 검증을 해결한다. 결과는 캔버스가 diff 스타일로 렌더하고(추가/수정/
1542
+ * 삭제 태깅), 사용자가 [적용]하면 `selectAppliedGraph`로 deleted를 거른 최종 그래프를
1543
+ * 단일 undo로 commit한다.
1544
+ *
1545
+ * 결정론적: 같은 입력이면 같은 출력(연결 id를 stepId 쌍에서 파생 — 매 렌더 uuid 재생성
1546
+ * 으로 인한 key churn 방지).
1547
+ */
1548
+ /** trigger/action 카탈로그 + condition/end 제어 정의를 합쳐 노드 정의를 찾는다. */
1549
+ function resolveNodeDef(id) {
1550
+ var _ref, _getNodeDefinition;
1551
+ if (!id) return void 0;
1552
+ return (_ref = (_getNodeDefinition = require_node_definitions.getNodeDefinition(id)) !== null && _getNodeDefinition !== void 0 ? _getNodeDefinition : require_step_type_for_node.conditionDefinitions.find((d) => d.id === id)) !== null && _ref !== void 0 ? _ref : require_step_type_for_node.endDefinitions.find((d) => d.id === id);
1553
+ }
1554
+ function makeConnection(from, to, branchType, branchValue) {
1555
+ return require_end_node_ids._objectSpread2(require_end_node_ids._objectSpread2({
1556
+ id: `c_${from.id}__${to.id}`,
1557
+ fromStepId: from.id,
1558
+ toStepId: to.id,
1559
+ fromPosition: from.position,
1560
+ toPosition: to.position
1561
+ }, branchType ? { branchType } : {}), branchValue ? {
1562
+ branchValue,
1563
+ label: branchValue
1564
+ } : {});
1565
+ }
1566
+ /** 새 스텝의 그리드 셀 결정 — 앵커 인접 → 트리거 인접 → 빈 그래프 시드. */
1567
+ function resolveAddCell(anchorStep, steps) {
1568
+ if (anchorStep) {
1569
+ var _findFreeAdjacentCell;
1570
+ return (_findFreeAdjacentCell = findFreeAdjacentCell(anchorStep.position, steps)) !== null && _findFreeAdjacentCell !== void 0 ? _findFreeAdjacentCell : findNearestFreeCell(anchorStep.position, steps);
1571
+ }
1572
+ const trigger = steps.find((s) => s.type === "trigger");
1573
+ if (trigger) {
1574
+ var _findFreeAdjacentCell2;
1575
+ return (_findFreeAdjacentCell2 = findFreeAdjacentCell(trigger.position, steps)) !== null && _findFreeAdjacentCell2 !== void 0 ? _findFreeAdjacentCell2 : findNearestFreeCell(trigger.position, steps);
1576
+ }
1577
+ const seed = {
1578
+ row: 1,
1579
+ col: 1
1580
+ };
1581
+ return steps.every((s) => s.position.row !== seed.row || s.position.col !== seed.col) ? seed : findNearestFreeCell(seed, steps);
1582
+ }
1583
+ function removeStepFromWorking(steps, connections, stepStatus, connStatus, stepId) {
1584
+ const idx = steps.findIndex((s) => s.id === stepId);
1585
+ if (idx >= 0) steps.splice(idx, 1);
1586
+ stepStatus.delete(stepId);
1587
+ for (let i = connections.length - 1; i >= 0; i--) {
1588
+ const c = connections[i];
1589
+ if (!c) continue;
1590
+ if (c.fromStepId === stepId || c.toStepId === stepId) {
1591
+ connStatus.delete(c.id);
1592
+ connections.splice(i, 1);
1593
+ }
1594
+ }
1595
+ }
1596
+ /** 삭제 표시가 없는 연결 — 연결 가능 판정(중복·순환)은 이것만 본다. */
1597
+ function liveConnections(connections, status) {
1598
+ return connections.filter((c) => status.get(c.id) !== "deleted");
1599
+ }
1600
+ function computePreviewGraph(committedSteps, committedConnections, ops) {
1601
+ const steps = committedSteps.map((s) => require_end_node_ids._objectSpread2({}, s));
1602
+ const connections = committedConnections.map((c) => require_end_node_ids._objectSpread2({}, c));
1603
+ const statusByStepId = /* @__PURE__ */ new Map();
1604
+ const statusByConnectionId = /* @__PURE__ */ new Map();
1605
+ const warnings = [];
1606
+ const findStep = (id) => steps.find((s) => s.id === id);
1607
+ for (const op of ops) switch (op.kind) {
1608
+ case "add": {
1609
+ var _op$mergeFromStepIds, _op$config;
1610
+ if (findStep(op.stepId)) break;
1611
+ const anchorStep = op.afterStepId ? findStep(op.afterStepId) : void 0;
1612
+ const mergeSteps = ((_op$mergeFromStepIds = op.mergeFromStepIds) !== null && _op$mergeFromStepIds !== void 0 ? _op$mergeFromStepIds : []).filter((id) => id !== op.afterStepId).map(findStep).filter((step) => step !== void 0);
1613
+ const beforeStep = op.insertBeforeStepId ? findStep(op.insertBeforeStepId) : void 0;
1614
+ const replaced = anchorStep && beforeStep ? liveConnections(connections, statusByConnectionId).find((c) => c.fromStepId === anchorStep.id && c.toStepId === beforeStep.id) : void 0;
1615
+ const commonAnchors = [...mergeSteps, ...beforeStep ? [beforeStep] : []];
1616
+ const commonCell = anchorStep && commonAnchors.length > 0 ? findFreeCommonNeighbor([anchorStep, ...commonAnchors].map((step) => step.position), steps) : null;
1617
+ const cell = commonCell !== null && commonCell !== void 0 ? commonCell : resolveAddCell(anchorStep, steps);
1618
+ if (!cell) {
1619
+ warnings.push(require_branch_resolver.msgf("\"{label}\" 배치 실패 — 그리드에 빈 칸이 없습니다.", { label: op.label }));
1620
+ break;
1621
+ }
1622
+ const step = require_end_node_ids._objectSpread2(require_end_node_ids._objectSpread2(require_end_node_ids._objectSpread2({
1623
+ id: op.stepId,
1624
+ position: cell,
1625
+ type: op.stepType,
1626
+ label: op.label
1627
+ }, op.nodeDefinitionId ? { nodeDefinitionId: op.nodeDefinitionId } : {}), resolveNodeDef(op.nodeDefinitionId) ? { nodeDefinition: resolveNodeDef(op.nodeDefinitionId) } : {}), {}, { config: (_op$config = op.config) !== null && _op$config !== void 0 ? _op$config : {} });
1628
+ steps.push(step);
1629
+ statusByStepId.set(step.id, "added");
1630
+ if (replaced) {
1631
+ if (statusByConnectionId.get(replaced.id) === "added") {
1632
+ connections.splice(connections.indexOf(replaced), 1);
1633
+ statusByConnectionId.delete(replaced.id);
1634
+ } else statusByConnectionId.set(replaced.id, "deleted");
1635
+ }
1636
+ if (anchorStep) {
1637
+ const reason = validateConnection(anchorStep, step, liveConnections(connections, statusByConnectionId));
1638
+ if (reason === null) {
1639
+ var _op$branchType, _op$branchValue;
1640
+ const conn = makeConnection(anchorStep, step, (_op$branchType = op.branchType) !== null && _op$branchType !== void 0 ? _op$branchType : replaced === null || replaced === void 0 ? void 0 : replaced.branchType, (_op$branchValue = op.branchValue) !== null && _op$branchValue !== void 0 ? _op$branchValue : replaced === null || replaced === void 0 ? void 0 : replaced.branchValue);
1641
+ connections.push(conn);
1642
+ statusByConnectionId.set(conn.id, "added");
1643
+ } else warnings.push(require_branch_resolver.msgf("\"{label}\"을(를) 추가했지만 \"{anchor}\" 뒤에 자동 연결하지 못했습니다({reason}). 캔버스에서 직접 연결하세요.", {
1644
+ label: op.label,
1645
+ anchor: anchorStep.label,
1646
+ reason
1647
+ }, { translate: ["reason"] }));
1648
+ }
1649
+ if (beforeStep && replaced) {
1650
+ const conn = makeConnection(step, beforeStep);
1651
+ connections.push(conn);
1652
+ statusByConnectionId.set(conn.id, "added");
1653
+ }
1654
+ for (const mergeStep of mergeSteps) {
1655
+ const reason = validateConnection(mergeStep, step, liveConnections(connections, statusByConnectionId));
1656
+ if (reason === null) {
1657
+ const conn = makeConnection(mergeStep, step);
1658
+ connections.push(conn);
1659
+ statusByConnectionId.set(conn.id, "added");
1660
+ } else warnings.push(require_branch_resolver.msgf("\"{label}\"을(를) \"{merge}\"에서 합류 연결하지 못했습니다({reason}). 캔버스에서 직접 연결하세요.", {
1661
+ label: op.label,
1662
+ merge: mergeStep.label,
1663
+ reason
1664
+ }, { translate: ["reason"] }));
1665
+ }
1666
+ break;
1667
+ }
1668
+ case "update": {
1669
+ const step = findStep(op.stepId);
1670
+ if (!step) {
1671
+ warnings.push("수정할 스텝을 찾지 못했습니다.");
1672
+ break;
1673
+ }
1674
+ if (op.label !== void 0) step.label = op.label;
1675
+ if (op.nodeDefinitionId !== void 0) {
1676
+ var _op$config2;
1677
+ step.nodeDefinitionId = op.nodeDefinitionId;
1678
+ const nodeDefinition = resolveNodeDef(op.nodeDefinitionId);
1679
+ if (nodeDefinition) step.nodeDefinition = nodeDefinition;
1680
+ else delete step.nodeDefinition;
1681
+ if (op.stepType) step.type = op.stepType;
1682
+ step.config = (_op$config2 = op.config) !== null && _op$config2 !== void 0 ? _op$config2 : {};
1683
+ } else if (op.config !== void 0) step.config = require_end_node_ids._objectSpread2(require_end_node_ids._objectSpread2({}, step.config), op.config);
1684
+ if (statusByStepId.get(op.stepId) !== "added") statusByStepId.set(op.stepId, "updated");
1685
+ break;
1686
+ }
1687
+ case "delete":
1688
+ if (!findStep(op.stepId)) break;
1689
+ if (statusByStepId.get(op.stepId) === "added") removeStepFromWorking(steps, connections, statusByStepId, statusByConnectionId, op.stepId);
1690
+ else {
1691
+ statusByStepId.set(op.stepId, "deleted");
1692
+ for (const c of connections) if (c.fromStepId === op.stepId || c.toStepId === op.stepId) statusByConnectionId.set(c.id, "deleted");
1693
+ }
1694
+ break;
1695
+ case "connect": {
1696
+ const from = findStep(op.fromStepId);
1697
+ const to = findStep(op.toStepId);
1698
+ if (!from || !to) {
1699
+ warnings.push("연결할 스텝을 찾지 못했습니다.");
1700
+ break;
1701
+ }
1702
+ const revived = connections.find((c) => c.fromStepId === from.id && c.toStepId === to.id && statusByConnectionId.get(c.id) === "deleted");
1703
+ if (revived) {
1704
+ statusByConnectionId.delete(revived.id);
1705
+ break;
1706
+ }
1707
+ const reason = validateConnection(from, to, liveConnections(connections, statusByConnectionId));
1708
+ if (reason) {
1709
+ warnings.push(reason);
1710
+ break;
1711
+ }
1712
+ const conn = makeConnection(from, to, op.branchType, op.branchValue);
1713
+ connections.push(conn);
1714
+ statusByConnectionId.set(conn.id, "added");
1715
+ break;
1716
+ }
1717
+ case "deleteConnection": {
1718
+ const idx = connections.findIndex((c) => c.id === op.connectionId);
1719
+ if (idx < 0) break;
1720
+ if (statusByConnectionId.get(op.connectionId) === "added") {
1721
+ connections.splice(idx, 1);
1722
+ statusByConnectionId.delete(op.connectionId);
1723
+ } else statusByConnectionId.set(op.connectionId, "deleted");
1724
+ break;
1725
+ }
1726
+ }
1727
+ return {
1728
+ previewSteps: steps,
1729
+ previewConnections: connections,
1730
+ statusByStepId,
1731
+ statusByConnectionId,
1732
+ warnings
1733
+ };
1734
+ }
1735
+ /** [적용] 시 commit 할 최종 그래프 — deleted 태깅 대상 제거. */
1736
+ function selectAppliedGraph(preview) {
1737
+ return {
1738
+ steps: preview.previewSteps.filter((s) => preview.statusByStepId.get(s.id) !== "deleted"),
1739
+ connections: preview.previewConnections.filter((c) => preview.statusByConnectionId.get(c.id) !== "deleted")
1740
+ };
1741
+ }
1742
+ Object.defineProperty(exports, "FAILURE_CAUSES", {
1743
+ enumerable: true,
1744
+ get: function() {
1745
+ return FAILURE_CAUSES;
1746
+ }
1747
+ });
1748
+ Object.defineProperty(exports, "FAILURE_CAUSE_COPY", {
1749
+ enumerable: true,
1750
+ get: function() {
1751
+ return FAILURE_CAUSE_COPY;
1752
+ }
1753
+ });
1754
+ Object.defineProperty(exports, "IDENTITY_TRANSFORM", {
1755
+ enumerable: true,
1756
+ get: function() {
1757
+ return IDENTITY_TRANSFORM;
1758
+ }
1759
+ });
1760
+ Object.defineProperty(exports, "MULTI_OUTGOING_STEP_TYPES", {
1761
+ enumerable: true,
1762
+ get: function() {
1763
+ return MULTI_OUTGOING_STEP_TYPES;
1764
+ }
1765
+ });
1766
+ Object.defineProperty(exports, "VARIABLE_TOKEN_PATTERN", {
1767
+ enumerable: true,
1768
+ get: function() {
1769
+ return VARIABLE_TOKEN_PATTERN;
1770
+ }
1771
+ });
1772
+ Object.defineProperty(exports, "aggregateStepMetrics", {
1773
+ enumerable: true,
1774
+ get: function() {
1775
+ return aggregateStepMetrics;
1776
+ }
1777
+ });
1778
+ Object.defineProperty(exports, "buildVariableTree", {
1779
+ enumerable: true,
1780
+ get: function() {
1781
+ return buildVariableTree;
1782
+ }
1783
+ });
1784
+ Object.defineProperty(exports, "buildWorkflowBrief", {
1785
+ enumerable: true,
1786
+ get: function() {
1787
+ return buildWorkflowBrief;
1788
+ }
1789
+ });
1790
+ Object.defineProperty(exports, "cellToViewportRect", {
1791
+ enumerable: true,
1792
+ get: function() {
1793
+ return cellToViewportRect;
1794
+ }
1795
+ });
1796
+ Object.defineProperty(exports, "computePreviewGraph", {
1797
+ enumerable: true,
1798
+ get: function() {
1799
+ return computePreviewGraph;
1800
+ }
1801
+ });
1802
+ Object.defineProperty(exports, "contentToViewport", {
1803
+ enumerable: true,
1804
+ get: function() {
1805
+ return contentToViewport;
1806
+ }
1807
+ });
1808
+ Object.defineProperty(exports, "cycleStepConnection", {
1809
+ enumerable: true,
1810
+ get: function() {
1811
+ return cycleStepConnection;
1812
+ }
1813
+ });
1814
+ Object.defineProperty(exports, "deriveRunPath", {
1815
+ enumerable: true,
1816
+ get: function() {
1817
+ return deriveRunPath;
1818
+ }
1819
+ });
1820
+ Object.defineProperty(exports, "exportTemplate", {
1821
+ enumerable: true,
1822
+ get: function() {
1823
+ return exportTemplate;
1824
+ }
1825
+ });
1826
+ Object.defineProperty(exports, "findBrokenStepRefs", {
1827
+ enumerable: true,
1828
+ get: function() {
1829
+ return findBrokenStepRefs;
1830
+ }
1831
+ });
1832
+ Object.defineProperty(exports, "findFailedStep", {
1833
+ enumerable: true,
1834
+ get: function() {
1835
+ return findFailedStep;
1836
+ }
1837
+ });
1838
+ Object.defineProperty(exports, "findFreeAdjacentCell", {
1839
+ enumerable: true,
1840
+ get: function() {
1841
+ return findFreeAdjacentCell;
1842
+ }
1843
+ });
1844
+ Object.defineProperty(exports, "findFreeCommonNeighbor", {
1845
+ enumerable: true,
1846
+ get: function() {
1847
+ return findFreeCommonNeighbor;
1848
+ }
1849
+ });
1850
+ Object.defineProperty(exports, "findNearestFreeCell", {
1851
+ enumerable: true,
1852
+ get: function() {
1853
+ return findNearestFreeCell;
1854
+ }
1855
+ });
1856
+ Object.defineProperty(exports, "findRunBlockers", {
1857
+ enumerable: true,
1858
+ get: function() {
1859
+ return findRunBlockers;
1860
+ }
1861
+ });
1862
+ Object.defineProperty(exports, "findStepInDirection", {
1863
+ enumerable: true,
1864
+ get: function() {
1865
+ return findStepInDirection;
1866
+ }
1867
+ });
1868
+ Object.defineProperty(exports, "findWorkflowSetupProblems", {
1869
+ enumerable: true,
1870
+ get: function() {
1871
+ return findWorkflowSetupProblems;
1872
+ }
1873
+ });
1874
+ Object.defineProperty(exports, "flattenFields", {
1875
+ enumerable: true,
1876
+ get: function() {
1877
+ return flattenFields;
1878
+ }
1879
+ });
1880
+ Object.defineProperty(exports, "formatDurationMs", {
1881
+ enumerable: true,
1882
+ get: function() {
1883
+ return formatDurationMs;
1884
+ }
1885
+ });
1886
+ Object.defineProperty(exports, "formatShare", {
1887
+ enumerable: true,
1888
+ get: function() {
1889
+ return formatShare;
1890
+ }
1891
+ });
1892
+ Object.defineProperty(exports, "getCellCenter", {
1893
+ enumerable: true,
1894
+ get: function() {
1895
+ return getCellCenter;
1896
+ }
1897
+ });
1898
+ Object.defineProperty(exports, "getCellEdge", {
1899
+ enumerable: true,
1900
+ get: function() {
1901
+ return getCellEdge;
1902
+ }
1903
+ });
1904
+ Object.defineProperty(exports, "getCellOrigin", {
1905
+ enumerable: true,
1906
+ get: function() {
1907
+ return getCellOrigin;
1908
+ }
1909
+ });
1910
+ Object.defineProperty(exports, "getConnectionFarEnd", {
1911
+ enumerable: true,
1912
+ get: function() {
1913
+ return getConnectionFarEnd;
1914
+ }
1915
+ });
1916
+ Object.defineProperty(exports, "getContentSize", {
1917
+ enumerable: true,
1918
+ get: function() {
1919
+ return getContentSize;
1920
+ }
1921
+ });
1922
+ Object.defineProperty(exports, "getStepSummary", {
1923
+ enumerable: true,
1924
+ get: function() {
1925
+ return getStepSummary;
1926
+ }
1927
+ });
1928
+ Object.defineProperty(exports, "getStepsRect", {
1929
+ enumerable: true,
1930
+ get: function() {
1931
+ return getStepsRect;
1932
+ }
1933
+ });
1934
+ Object.defineProperty(exports, "getUpstreamSteps", {
1935
+ enumerable: true,
1936
+ get: function() {
1937
+ return getUpstreamSteps;
1938
+ }
1939
+ });
1940
+ Object.defineProperty(exports, "getWorkflowPreflight", {
1941
+ enumerable: true,
1942
+ get: function() {
1943
+ return getWorkflowPreflight;
1944
+ }
1945
+ });
1946
+ Object.defineProperty(exports, "importTemplate", {
1947
+ enumerable: true,
1948
+ get: function() {
1949
+ return importTemplate;
1950
+ }
1951
+ });
1952
+ Object.defineProperty(exports, "listStepConnections", {
1953
+ enumerable: true,
1954
+ get: function() {
1955
+ return listStepConnections;
1956
+ }
1957
+ });
1958
+ Object.defineProperty(exports, "maskPiiDeep", {
1959
+ enumerable: true,
1960
+ get: function() {
1961
+ return maskPiiDeep;
1962
+ }
1963
+ });
1964
+ Object.defineProperty(exports, "maskPiiString", {
1965
+ enumerable: true,
1966
+ get: function() {
1967
+ return maskPiiString;
1968
+ }
1969
+ });
1970
+ Object.defineProperty(exports, "missingRequiredFields", {
1971
+ enumerable: true,
1972
+ get: function() {
1973
+ return missingRequiredFields;
1974
+ }
1975
+ });
1976
+ Object.defineProperty(exports, "orderStepsByFlow", {
1977
+ enumerable: true,
1978
+ get: function() {
1979
+ return orderStepsByFlow;
1980
+ }
1981
+ });
1982
+ Object.defineProperty(exports, "orderStepsForPreview", {
1983
+ enumerable: true,
1984
+ get: function() {
1985
+ return orderStepsForPreview;
1986
+ }
1987
+ });
1988
+ Object.defineProperty(exports, "resolveConnectionFocus", {
1989
+ enumerable: true,
1990
+ get: function() {
1991
+ return resolveConnectionFocus;
1992
+ }
1993
+ });
1994
+ Object.defineProperty(exports, "roundedPath", {
1995
+ enumerable: true,
1996
+ get: function() {
1997
+ return roundedPath;
1998
+ }
1999
+ });
2000
+ Object.defineProperty(exports, "routeConnection", {
2001
+ enumerable: true,
2002
+ get: function() {
2003
+ return routeConnection;
2004
+ }
2005
+ });
2006
+ Object.defineProperty(exports, "routeLabelFallbackPoint", {
2007
+ enumerable: true,
2008
+ get: function() {
2009
+ return routeLabelFallbackPoint;
2010
+ }
2011
+ });
2012
+ Object.defineProperty(exports, "routeLabelPoint", {
2013
+ enumerable: true,
2014
+ get: function() {
2015
+ return routeLabelPoint;
2016
+ }
2017
+ });
2018
+ Object.defineProperty(exports, "selectAppliedGraph", {
2019
+ enumerable: true,
2020
+ get: function() {
2021
+ return selectAppliedGraph;
2022
+ }
2023
+ });
2024
+ Object.defineProperty(exports, "serializeTemplate", {
2025
+ enumerable: true,
2026
+ get: function() {
2027
+ return serializeTemplate;
2028
+ }
2029
+ });
2030
+ Object.defineProperty(exports, "triageFailedStep", {
2031
+ enumerable: true,
2032
+ get: function() {
2033
+ return triageFailedStep;
2034
+ }
2035
+ });
2036
+ Object.defineProperty(exports, "validateConnection", {
2037
+ enumerable: true,
2038
+ get: function() {
2039
+ return validateConnection;
2040
+ }
2041
+ });
2042
+ Object.defineProperty(exports, "validateWorkflowDefinition", {
2043
+ enumerable: true,
2044
+ get: function() {
2045
+ return validateWorkflowDefinition;
2046
+ }
2047
+ });
2048
+ Object.defineProperty(exports, "viewportPointToCell", {
2049
+ enumerable: true,
2050
+ get: function() {
2051
+ return viewportPointToCell;
2052
+ }
2053
+ });
2054
+ Object.defineProperty(exports, "viewportToContent", {
2055
+ enumerable: true,
2056
+ get: function() {
2057
+ return viewportToContent;
2058
+ }
2059
+ });
2060
+ Object.defineProperty(exports, "visibleConfigFields", {
2061
+ enumerable: true,
2062
+ get: function() {
2063
+ return visibleConfigFields;
2064
+ }
2065
+ });