@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
package/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # @reopt-ai/opt-workflow
2
+
3
+ ## 0.1.0
4
+
5
+ Initial release.
6
+
7
+ - Keyboard-first workflow editor (`WorkflowEditor`) and read-only run viewer (`WorkflowViewer`) on a cell-grid canvas. Every action has a key; the canvas, action menu, config panel, connections, node picker, outline and template picker hand focus to each other without dropping a keystroke.
8
+ - Host contract (`WorkflowHost`): save, run with an event stream, run history and per-step metrics, templates, custom config fields, an extension hook for variables and checks, and notices. The editor knows no backend.
9
+ - Node contracts and a catalog (`/nodes`): hosts register their own triggers and actions; nodes passed through the editor's `nodes` prop are scoped to that editor.
10
+ - Pure, server-safe layer: `/core` (document model, grid rules, preflight, proposal preview) and `/simulate` (test executor).
11
+ - `/mock`: an in-memory host, sample documents, and a product-sized sample (45 node contracts, 34 templates).
12
+ - AI proposal preview: a proposed definition is shown as a diff on the canvas and applied as one undo step.
13
+ - One scoped `styles.css` (no Tailwind needed in the host) and `shadcn-bridge.css` for hosts on shadcn tokens. Korean and English are built in (`locale`, `messages`).
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) reopt Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,214 @@
1
- # Temporary Holding Version
1
+ # @reopt-ai/opt-workflow
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 키보드 우선 워크플로우 에디터. 셀 그리드 캔버스에 스텝을 놓고 잇고, 실행이 지나간 길을
4
+ 같은 캔버스에서 읽는다. 저장소·실행 엔진·인증은 모른다 — 필요한 일은 **호스트 계약**으로만
5
+ 부탁한다.
6
+
7
+ > 0.x다 — 리옵트 스튜디오가 첫 소비자이고, 1.0 전에는 minor에서 API가 바뀔 수 있다.
8
+
9
+ ## 설치
10
+
11
+ ```sh
12
+ npm install @reopt-ai/opt-workflow
13
+ ```
14
+
15
+ `react`·`react-dom` 19와 `zod` 4가 peer다. 스타일은 한 장이고 Tailwind가 없어도 된다.
16
+
17
+ ```tsx
18
+ import "@reopt-ai/opt-workflow/styles.css";
19
+ ```
20
+
21
+ ## 5분 시작 — 메모리 호스트
22
+
23
+ ```tsx
24
+ "use client";
25
+
26
+ import { useMemo, useSyncExternalStore } from "react";
27
+ import { WorkflowEditor } from "@reopt-ai/opt-workflow";
28
+ import {
29
+ createMockWorkflowHost,
30
+ sampleOrderDefinition,
31
+ sampleWorkflowTemplates,
32
+ } from "@reopt-ai/opt-workflow/mock";
33
+
34
+ export function Workspace() {
35
+ const mock = useMemo(
36
+ () =>
37
+ createMockWorkflowHost({
38
+ workflowId: "wf_sample",
39
+ name: "주문 금액별 처리",
40
+ definition: sampleOrderDefinition,
41
+ templates: sampleWorkflowTemplates,
42
+ }),
43
+ [],
44
+ );
45
+ const host = useSyncExternalStore(mock.subscribe, mock.getHost, mock.getHost);
46
+
47
+ return (
48
+ <div style={{ height: "100dvh" }}>
49
+ <WorkflowEditor
50
+ host={host}
51
+ workflowId={host.workflowId}
52
+ initialName="주문 금액별 처리"
53
+ initialDefinition={sampleOrderDefinition}
54
+ onSave={mock.save}
55
+ />
56
+ </div>
57
+ );
58
+ }
59
+ ```
60
+
61
+ 에디터는 부모의 높이를 채운다. 부모에 높이가 있어야 한다.
62
+
63
+ ## 엔트리
64
+
65
+ | 엔트리 | 내용 | 환경 |
66
+ | -------------- | ------------------------------------------------------------------------------ | ---------- |
67
+ | `.` | `WorkflowEditor`·`WorkflowViewer`, 호스트 계약 타입, AI 제안 브리지, 조립용 훅 | 클라이언트 |
68
+ | `./core` | 문서 모델·zod 스키마·그리드 규칙·점검·**조건 평가·분기 판정·변수 해석** | 서버 안전 |
69
+ | `./nodes` | 노드 계약 타입, 카탈로그 등록, 내장 범용 노드 | 서버 안전 |
70
+ | `./simulate` | 시뮬레이션 실행기(핸들러를 부르지 않는다) | 서버 안전 |
71
+ | `./mock` | 메모리 호스트와 예시 문서 | 어디서나 |
72
+ | `./styles.css` | 스타일 한 장 | — |
73
+
74
+ ## 호스트 계약
75
+
76
+ `WorkflowHost`의 모든 칸은 선택이다. **주지 않은 능력은 화면에서 사라진다.**
77
+
78
+ | 칸 | 하는 일 | 없으면 |
79
+ | ----------------------------- | ------------------------------------------------ | --------------------------------- |
80
+ | `onSave`(에디터 prop) | 문서 저장. 성공하면 `true` | 편집은 되지만 저장이 안 된다 |
81
+ | `runner` | 실행 예약·시작·재개, 이벤트 스트림 | 실행·디버그가 없다(테스트는 남음) |
82
+ | `runs` | 지난 런 상세, 스텝별 누적 지표의 표본 | 재생·지표가 없다 |
83
+ | `fields` | 커스텀 설정 필드 렌더러(필드 `type`이 키) | 그 타입은 글자 입력으로 열린다 |
84
+ | `templates`·`prepareTemplate` | 빈 캔버스의 시작 템플릿 | 빈 캔버스로 시작한다 |
85
+ | `useExtension` | 변수·점검·안내를 더하는 **훅**(참조를 고정할 것) | 내장 것만 |
86
+ | `saveContext` | 문서와 함께 저장되는 호스트 값(소속 등) | — |
87
+ | `onNotify` | 알림을 호스트 토스터로 | 에디터가 자기 알림 줄에 그린다 |
88
+ | `onDirtyChange` | 미저장 변경 유무 — 호스트 라우터의 이탈 확인에 | 탭 닫기·새로고침만 묻는다 |
89
+
90
+ ### 실행 — 순서가 계약이다
91
+
92
+ 1. 에디터가 `runner.start()`로 runId를 받는다.
93
+ 2. `runner.openEventStream()`으로 스트림을 연다.
94
+ 3. 스트림이 `connected`를 보내면 그때 `runner.run()`을 부른다.
95
+
96
+ 스트림 구현은 **구독이 실제로 성립한 뒤에** `connected`를 보내야 한다(HTTP 연결이 열린 시점이
97
+ 아니다). 먼저 보내면 빠른 스텝의 결과가 구독 전에 지나가 사라진다.
98
+
99
+ `openEventStream`이 돌려주는 값은 브라우저 `EventSource`와 같은 모양이다. 서버가 있으면
100
+ `new EventSource(url)`을 그대로 돌려주면 된다. `startIndex`는 이어받기다 — 끊겼다 다시 붙을 때
101
+ 에디터가 마지막으로 받은 순번 + 1을 준다.
102
+
103
+ ## 노드
104
+
105
+ 에디터는 내장 범용 노드(수동·일정·웹훅 트리거, 대기·HTTP·데이터 변환, 반복·병렬)를 갖고,
106
+ 제품 고유 노드는 호스트가 계약으로 더한다.
107
+
108
+ ```tsx
109
+ import type { NodeContract } from "@reopt-ai/opt-workflow/nodes";
110
+
111
+ const sendEmail: NodeContract = {
112
+ id: "sendEmail",
113
+ name: "이메일 보내기",
114
+ description: "고객에게 이메일을 보냅니다",
115
+ icon: MailIcon, // className을 받는 컴포넌트면 된다
116
+ color: "bg-blue-500",
117
+ category: "communication",
118
+ editorCategory: "발송",
119
+ fields: [
120
+ { key: "to", label: "받는 사람", type: "email", required: true },
121
+ {
122
+ key: "templateId",
123
+ label: "템플릿",
124
+ type: "emailTemplate",
125
+ required: true,
126
+ },
127
+ ],
128
+ };
129
+
130
+ const NODES = { actions: [sendEmail] }; // 모듈 최상위 — 참조를 고정한다
131
+
132
+ <WorkflowEditor
133
+ nodes={NODES}
134
+ host={{ fields: { emailTemplate: TemplatePicker } }}
135
+ />;
136
+ ```
137
+
138
+ - 필드 `type`이 내장(`text`·`email`·`number`·`select`·`textarea`·`boolean`)이 아니면 `host.fields`에서
139
+ 같은 이름의 렌더러를 찾는다.
140
+ - 피커에 보이는 순서까지 정하려면 `nodes={{ ..., mode: "replace" }}`로 목록 전체를 준다
141
+ (`builtInActionContracts`·`builtInTriggerContracts`에서 골라 함께 넣는다).
142
+ - 변수 픽커에 노드의 출력을 보이려면 `nodes.outputs`·`nodes.triggerPayloads`에 스키마를 준다.
143
+ - `color`는 Tailwind 색 클래스 문자열이다. 22색 × 400~700 단계가 스타일에 미리 들어 있다.
144
+
145
+ ## 키보드
146
+
147
+ 캔버스에 포커스를 두고 쓴다. `?`가 전체 표를 연다.
148
+
149
+ | 키 | 동작 |
150
+ | ------------------------- | --------------------------------------------------------------------- |
151
+ | 방향키 / Shift+방향키 | 한 칸 이동 / 그 방향의 다음 스텝으로 |
152
+ | PageUp·PageDown, Home·End | 흐름 순서로 이전·다음, 처음·끝 |
153
+ | Enter | 스텝이면 액션 메뉴, 빈 칸이면 스텝 추가 |
154
+ | Space | 연결 모드 시작 → 대상에서 완료 |
155
+ | C / Shift+C | 선택 스텝의 연결을 하나 고른다(Enter 따라가기, Delete 그 연결만 삭제) |
156
+ | Alt+방향키 | 스텝 이동(옆 칸에 스텝이 있으면 맞바꿈) |
157
+ | Mod+C / V / D | 복사 / 붙여넣기 / 복제 |
158
+ | Mod+Z / Mod+Shift+Z | 되돌리기 / 다시하기 |
159
+ | Mod+S | 저장(입력 중에도) |
160
+ | A / L / F / `[` `]` | 스텝 추가 / 구조 / 전체 보기 / 좌우 도구 |
161
+ | Escape | 연결 모드 → 고른 연결 → 선택 → 실행 결과 순으로 한 단계씩 |
162
+
163
+ Tab은 가로채지 않는다. 입력창·열린 메뉴·대화상자 안의 키는 그쪽 것이다.
164
+
165
+ ## 테마
166
+
167
+ 색은 `--opt-wf-*` 변수에서 온다. 기본값은 opt-palette 토큰(`--opt-*`)을 읽고, 없으면 중립
168
+ 팔레트다. 호스트는 에디터를 감싼 요소에서 필요한 것만 덮는다.
169
+
170
+ ```css
171
+ .my-app [data-opt-workflow],
172
+ .my-app [data-opt-workflow-layer] {
173
+ --opt-wf-primary: #4f46e5;
174
+ --opt-wf-primary-foreground: #ffffff;
175
+ --opt-wf-background: #ffffff;
176
+ --opt-wf-border: #e5e7eb;
177
+ }
178
+ ```
179
+
180
+ `[data-opt-workflow-layer]`는 에디터 밖으로 포털되는 층(대화상자·팝오버·메뉴·툴팁)이다.
181
+ 스타일은 `@scope`로 에디터 안에만 적용되어 호스트의 클래스와 서로 간섭하지 않는다.
182
+
183
+ ## AI 제안
184
+
185
+ 브리지에 편집을 올리면 캔버스가 문서를 바꾸지 않은 채 미리보기를 그리고, 적용은 되돌리기 한
186
+ 건이다. 한 화면에 에디터가 여럿이면 에디터마다 브리지를 만든다.
187
+
188
+ ```tsx
189
+ const bridge = useMemo(() => createWorkflowEditorBridge(), []);
190
+ bridge
191
+ .getState()
192
+ .stageOp({ kind: "update", stepId: "hold", label: "30분 대기" });
193
+
194
+ <WorkflowEditor bridge={bridge} />;
195
+ ```
196
+
197
+ ## 개발
198
+
199
+ ```bash
200
+ bun run --filter @reopt-ai/opt-workflow dev # 단독 화면 (127.0.0.1:5231)
201
+ bun run --filter @reopt-ai/opt-workflow test
202
+ bun run --filter @reopt-ai/opt-workflow build:styles # styles.tailwind.css → styles.css
203
+ ```
204
+
205
+ ## 화면 언어
206
+
207
+ 기본은 한국어다. `locale="en"`을 주면 영어 사전을 쓰고, `messages`로 문구 일부를 바꾼다(원문이 키).
208
+
209
+ ```tsx
210
+ <WorkflowEditor locale="en" messages={{ 저장: "Publish" }} />
211
+ ```
212
+
213
+ 사전에 없는 글은 원문 그대로 나온다 — 호스트가 등록한 노드의 이름·설명은 호스트의 언어로 적는다.
214
+ 언어는 마운트 때 정한다. 떠 있는 동안 바꾸려면 `key`로 에디터를 다시 세운다.
@@ -0,0 +1,389 @@
1
+ import { r as _objectSpread2 } from "./end-node-ids-p85jFEcP.js";
2
+ import { z } from "zod";
3
+ // src/types/grid-workflow-dto.ts
4
+ const GRID_SIZE = 9;
5
+ const CELL_WIDTH = 248;
6
+ const CELL_HEIGHT = 136;
7
+ const CELL_GAP = 40;
8
+ const CELL_PITCH_X = 288;
9
+ const CELL_PITCH_Y = 176;
10
+ const MAX_STEPS = 200;
11
+ const MAX_GRID_ROWS = 64;
12
+ const MAX_GRID_COLS = 16;
13
+ const BRANCH_TYPE_COLORS = {
14
+ true: {
15
+ stroke: "stroke-green-500",
16
+ fill: "fill-green-500",
17
+ label: "참"
18
+ },
19
+ false: {
20
+ stroke: "stroke-red-500",
21
+ fill: "fill-red-500",
22
+ label: "거짓"
23
+ },
24
+ case: {
25
+ stroke: "stroke-blue-500",
26
+ fill: "fill-blue-500",
27
+ label: "Case"
28
+ },
29
+ default: {
30
+ stroke: "stroke-gray-500",
31
+ fill: "fill-gray-500",
32
+ label: "기본"
33
+ }
34
+ };
35
+ const STEP_TYPE_COLORS = {
36
+ trigger: {
37
+ bg: "bg-green-100 dark:bg-green-900/30",
38
+ border: "border-green-500",
39
+ text: "text-green-700 dark:text-green-300"
40
+ },
41
+ condition: {
42
+ bg: "bg-yellow-100 dark:bg-yellow-900/30",
43
+ border: "border-yellow-500",
44
+ text: "text-yellow-700 dark:text-yellow-300"
45
+ },
46
+ action: {
47
+ bg: "bg-blue-100 dark:bg-blue-900/30",
48
+ border: "border-blue-500",
49
+ text: "text-blue-700 dark:text-blue-300"
50
+ },
51
+ end: {
52
+ bg: "bg-red-100 dark:bg-red-900/30",
53
+ border: "border-red-500",
54
+ text: "text-red-700 dark:text-red-300"
55
+ },
56
+ parallel: {
57
+ bg: "bg-purple-100 dark:bg-purple-900/30",
58
+ border: "border-purple-500",
59
+ text: "text-purple-700 dark:text-purple-300"
60
+ },
61
+ join: {
62
+ bg: "bg-purple-100 dark:bg-purple-900/30",
63
+ border: "border-purple-500",
64
+ text: "text-purple-700 dark:text-purple-300"
65
+ },
66
+ forEach: {
67
+ bg: "bg-cyan-100 dark:bg-cyan-900/30",
68
+ border: "border-cyan-500",
69
+ text: "text-cyan-700 dark:text-cyan-300"
70
+ },
71
+ while: {
72
+ bg: "bg-cyan-100 dark:bg-cyan-900/30",
73
+ border: "border-cyan-500",
74
+ text: "text-cyan-700 dark:text-cyan-300"
75
+ },
76
+ repeat: {
77
+ bg: "bg-cyan-100 dark:bg-cyan-900/30",
78
+ border: "border-cyan-500",
79
+ text: "text-cyan-700 dark:text-cyan-300"
80
+ },
81
+ loopEnd: {
82
+ bg: "bg-cyan-100 dark:bg-cyan-900/30",
83
+ border: "border-cyan-400 border-dashed",
84
+ text: "text-cyan-700 dark:text-cyan-300"
85
+ },
86
+ tryCatch: {
87
+ bg: "bg-orange-100 dark:bg-orange-900/30",
88
+ border: "border-orange-500",
89
+ text: "text-orange-700 dark:text-orange-300"
90
+ },
91
+ errorHandler: {
92
+ bg: "bg-orange-100 dark:bg-orange-900/30",
93
+ border: "border-orange-500",
94
+ text: "text-orange-700 dark:text-orange-300"
95
+ }
96
+ };
97
+ function positionToIndex(position) {
98
+ return position.row * 9 + position.col;
99
+ }
100
+ function indexToPosition(index) {
101
+ return {
102
+ row: Math.floor(index / 9),
103
+ col: index % 9
104
+ };
105
+ }
106
+ function isSamePosition(a, b) {
107
+ if (!a || !b) return false;
108
+ return a.row === b.row && a.col === b.col;
109
+ }
110
+ /** 절대 상한(하드캡) 검사 — 렌더 바운드 검사는 lib/grid-bounds.isWithinBounds */
111
+ function isValidPosition(position) {
112
+ return position.row >= 0 && position.row < 64 && position.col >= 0 && position.col < 16;
113
+ }
114
+ function getAdjacentPosition(position, direction) {
115
+ const newPosition = _objectSpread2({}, position);
116
+ switch (direction) {
117
+ case "up":
118
+ newPosition.row -= 1;
119
+ break;
120
+ case "down":
121
+ newPosition.row += 1;
122
+ break;
123
+ case "left":
124
+ newPosition.col -= 1;
125
+ break;
126
+ case "right": newPosition.col += 1;
127
+ }
128
+ return isValidPosition(newPosition) ? newPosition : null;
129
+ }
130
+ function getConnectionDirection(from, to) {
131
+ const rowDiff = to.row - from.row;
132
+ const colDiff = to.col - from.col;
133
+ if (Math.abs(rowDiff) + Math.abs(colDiff) !== 1) return null;
134
+ if (rowDiff === -1) return "up";
135
+ if (rowDiff === 1) return "down";
136
+ if (colDiff === -1) return "left";
137
+ if (colDiff === 1) return "right";
138
+ return null;
139
+ }
140
+ function hasCycle(connections, newConnection) {
141
+ const allConnections = newConnection ? [...connections, _objectSpread2(_objectSpread2({}, newConnection), {}, {
142
+ id: "temp",
143
+ fromPosition: {
144
+ row: 0,
145
+ col: 0
146
+ },
147
+ toPosition: {
148
+ row: 0,
149
+ col: 0
150
+ }
151
+ })] : connections;
152
+ const adjacencyList = /* @__PURE__ */ new Map();
153
+ for (const conn of allConnections) {
154
+ const existing = adjacencyList.get(conn.fromStepId) || [];
155
+ adjacencyList.set(conn.fromStepId, [...existing, conn.toStepId]);
156
+ }
157
+ const visited = /* @__PURE__ */ new Set();
158
+ const recursionStack = /* @__PURE__ */ new Set();
159
+ function dfs(nodeId) {
160
+ visited.add(nodeId);
161
+ recursionStack.add(nodeId);
162
+ const neighbors = adjacencyList.get(nodeId) || [];
163
+ for (const neighbor of neighbors) if (!visited.has(neighbor)) {
164
+ if (dfs(neighbor)) return true;
165
+ } else if (recursionStack.has(neighbor)) return true;
166
+ recursionStack.delete(nodeId);
167
+ return false;
168
+ }
169
+ const allNodes = /* @__PURE__ */ new Set();
170
+ for (const conn of allConnections) {
171
+ allNodes.add(conn.fromStepId);
172
+ allNodes.add(conn.toStepId);
173
+ }
174
+ for (const node of allNodes) if (!visited.has(node)) {
175
+ if (dfs(node)) return true;
176
+ }
177
+ return false;
178
+ }
179
+ // src/lib/grid-bounds.ts
180
+ const MIN_COLS = 3;
181
+ const MIN_ROWS = 6;
182
+ const MAX_COLS = 16;
183
+ const MAX_ROWS = 64;
184
+ function clamp(value, min, max) {
185
+ return Math.min(Math.max(value, min), max);
186
+ }
187
+ /**
188
+ * 스텝 배치에서 렌더 바운드를 파생한다.
189
+ * 행은 항상 콘텐츠 아래 1행 성장 마진을 포함한다 (세로 흐름 기본).
190
+ */
191
+ function deriveGridBounds(steps) {
192
+ let maxRow = -1;
193
+ let maxCol = -1;
194
+ for (const step of steps) {
195
+ if (step.position.row > maxRow) maxRow = step.position.row;
196
+ if (step.position.col > maxCol) maxCol = step.position.col;
197
+ }
198
+ return {
199
+ rows: clamp(maxRow + 2, 6, MAX_ROWS),
200
+ cols: clamp(maxCol + 1, 3, MAX_COLS)
201
+ };
202
+ }
203
+ /** 두 바운드의 축별 최대값 (파생 바운드 + 수동 확장 floor 병합용) */
204
+ function mergeBounds(a, b) {
205
+ return {
206
+ rows: clamp(Math.max(a.rows, b.rows), 1, MAX_ROWS),
207
+ cols: clamp(Math.max(a.cols, b.cols), 1, MAX_COLS)
208
+ };
209
+ }
210
+ function isWithinBounds(position, bounds) {
211
+ return position.row >= 0 && position.row < bounds.rows && position.col >= 0 && position.col < bounds.cols;
212
+ }
213
+ /** 하드캡 검사 — 저장/임포트 검증용 (렌더 바운드와 무관한 절대 상한) */
214
+ function isWithinHardCap(position) {
215
+ return position.row >= 0 && position.row < MAX_ROWS && position.col >= 0 && position.col < MAX_COLS;
216
+ }
217
+ // src/schemas/grid-workflow-schema.ts
218
+ /**
219
+ * 그리드 워크플로우 JSON 스키마 및 유효성 검사
220
+ */
221
+ const gridPositionSchema = z.object({
222
+ row: z.number().int().min(0).max(63),
223
+ col: z.number().int().min(0).max(15)
224
+ });
225
+ const gridStepTypeSchema = z.enum([
226
+ "trigger",
227
+ "condition",
228
+ "action",
229
+ "end",
230
+ "parallel",
231
+ "join",
232
+ "forEach",
233
+ "while",
234
+ "repeat",
235
+ "loopEnd",
236
+ "tryCatch",
237
+ "errorHandler"
238
+ ]);
239
+ const branchTypeSchema = z.enum([
240
+ "true",
241
+ "false",
242
+ "case",
243
+ "default"
244
+ ]);
245
+ const gridStepConfigSchema = z.record(z.string(), z.json());
246
+ const gridStepSchema = z.object({
247
+ id: z.string().min(1, "스텝 ID는 필수입니다"),
248
+ position: gridPositionSchema,
249
+ type: gridStepTypeSchema,
250
+ label: z.string().min(1, "스텝 라벨은 필수입니다"),
251
+ nodeDefinitionId: z.string().optional(),
252
+ nodeDefinition: z.unknown().optional(),
253
+ config: gridStepConfigSchema.default({}),
254
+ /**
255
+ * 실패해도 다음 스텝으로 진행.
256
+ * ⚠️ `.default(false)`가 아니라 `.optional()`이다 — "선언 없음"과 "끔"을 구분해야
257
+ * 옛 정의를 읽을 때 의미가 바뀌지 않는다(루트 CLAUDE.md 규율 7).
258
+ */
259
+ continueOnError: z.boolean().optional()
260
+ });
261
+ const gridConnectionSchema = z.object({
262
+ id: z.string().min(1, "연결 ID는 필수입니다"),
263
+ fromStepId: z.string().min(1, "시작 스텝 ID는 필수입니다"),
264
+ toStepId: z.string().min(1, "종료 스텝 ID는 필수입니다"),
265
+ fromPosition: gridPositionSchema,
266
+ toPosition: gridPositionSchema,
267
+ label: z.string().optional(),
268
+ condition: z.string().optional(),
269
+ branchType: branchTypeSchema.optional(),
270
+ branchValue: z.string().optional()
271
+ });
272
+ const gridWorkflowDefinitionSchema = z.object({
273
+ gridSize: z.number().int().min(1).max(99).default(9),
274
+ steps: z.array(gridStepSchema).max(200),
275
+ connections: z.array(gridConnectionSchema),
276
+ /** 테스트 실행용 트리거 샘플 페이로드 — 선언 없음은 `.optional()`(기본값 주입 금지) */
277
+ testParams: z.record(z.string(), z.unknown()).optional()
278
+ });
279
+ const exportTemplateSchema = z.object({
280
+ version: z.string().default("1.0"),
281
+ exportedAt: z.string().datetime(),
282
+ metadata: z.object({
283
+ name: z.string().min(1, "템플릿 이름은 필수입니다"),
284
+ description: z.string().optional(),
285
+ category: z.enum([
286
+ "basic",
287
+ "ai",
288
+ "marketing"
289
+ ]).optional(),
290
+ icon: z.string().optional(),
291
+ author: z.string().optional()
292
+ }),
293
+ definition: gridWorkflowDefinitionSchema
294
+ });
295
+ // src/lib/parse-workflow-definition.ts
296
+ /** 파싱 실패 시의 안전값 — 뷰어는 빈 캔버스를 렌더한다 */
297
+ const EMPTY_GRID_WORKFLOW_DEFINITION = {
298
+ gridSize: 9,
299
+ steps: [],
300
+ connections: []
301
+ };
302
+ /**
303
+ * Strict persistence/execution parser. Unlike the display parser below, this
304
+ * never turns corrupt stored JSON into an empty workflow.
305
+ */
306
+ function parseGridWorkflowDefinitionStrict(raw) {
307
+ return gridWorkflowDefinitionSchema.parse(raw);
308
+ }
309
+ /**
310
+ * 저장된 정의를 **표시용**으로 안전하게 읽는다. 읽지 못하면 빈 캔버스를 돌려주고, 왜 못
311
+ * 읽었는지는 `onFallback`으로 알린다(호스트가 로그에 남긴다).
312
+ *
313
+ * ⚠️ 표시 경로(뷰어·목록) 전용 — 실행 경로는 손상된 정의를 빈 정의로 조용히 바꾸면 안 된다
314
+ * (오실행 위험). 그쪽은 `parseGridWorkflowDefinitionStrict`의 실패를 에러로 다룬다.
315
+ */
316
+ function parseGridWorkflowDefinition(raw, onFallback) {
317
+ try {
318
+ return parseGridWorkflowDefinitionStrict(raw);
319
+ } catch (error) {
320
+ onFallback === null || onFallback === void 0 || onFallback(error);
321
+ return EMPTY_GRID_WORKFLOW_DEFINITION;
322
+ }
323
+ }
324
+ // src/lib/ai-stream.ts
325
+ /**
326
+ * AI 생성 스텝의 **부분 출력 스트리밍** 계약 — 서버(핸들러)와 클라이언트(캔버스)가 같은
327
+ * 이름·모양을 쓴다(클라이언트 안전, 순수).
328
+ *
329
+ * 핸들러는 `context.emit(data, { namespace: AI_TEXT_STREAM_NAMESPACE })`로 지금까지의
330
+ * 전체 텍스트를 보내고(조각이 아니라 누적 — 이벤트가 하나 빠져도 화면이 어긋나지 않는다),
331
+ * 캔버스는 실행 중인 카드에 그 텍스트를 흘려 보여 준다. 참조 구현(100ms 스로틀)과 같다.
332
+ */
333
+ const AI_TEXT_STREAM_NAMESPACE = "ai-text";
334
+ function isAiTextStreamData(data) {
335
+ return typeof data === "object" && data !== null && data.kind === "ai-text" && typeof data.text === "string";
336
+ }
337
+ /**
338
+ * 스로틀 방출기 — 마지막 값만 기억했다가 간격마다 한 번 보내고, `flush`가 남은 값을
339
+ * 반드시 보낸다(끝 조각이 사라지면 "완료 직전에서 멈춘" 것처럼 보인다).
340
+ */
341
+ function createThrottledEmitter(send, intervalMs, now = () => Date.now()) {
342
+ let pending;
343
+ let hasPending = false;
344
+ let lastSentAt = -Infinity;
345
+ let chain = Promise.resolve();
346
+ const dispatch = (value) => {
347
+ chain = chain.then(() => send(value)).catch(() => void 0);
348
+ };
349
+ return {
350
+ push(value) {
351
+ const at = now();
352
+ if (at - lastSentAt >= intervalMs) {
353
+ lastSentAt = at;
354
+ hasPending = false;
355
+ pending = void 0;
356
+ dispatch(value);
357
+ return;
358
+ }
359
+ pending = value;
360
+ hasPending = true;
361
+ },
362
+ async flush() {
363
+ if (hasPending) {
364
+ hasPending = false;
365
+ const value = pending;
366
+ pending = void 0;
367
+ lastSentAt = now();
368
+ dispatch(value);
369
+ }
370
+ await chain;
371
+ }
372
+ };
373
+ }
374
+ /**
375
+ * 선택지 분류의 후보 목록 — 한 줄에 하나. 공백 줄·중복은 버린다(모델이 고를 수 없는
376
+ * 값이 목록에 남으면 구조화 출력이 거절된다).
377
+ */
378
+ function parseChoiceList(text) {
379
+ const seen = /* @__PURE__ */ new Set();
380
+ const result = [];
381
+ for (const raw of (text !== null && text !== void 0 ? text : "").split(/\r?\n/)) {
382
+ const value = raw.trim();
383
+ if (!value || seen.has(value)) continue;
384
+ seen.add(value);
385
+ result.push(value);
386
+ }
387
+ return result;
388
+ }
389
+ export { MAX_GRID_COLS as A, positionToIndex as B, BRANCH_TYPE_COLORS as C, CELL_PITCH_Y as D, CELL_PITCH_X as E, getConnectionDirection as F, hasCycle as I, indexToPosition as L, MAX_STEPS as M, STEP_TYPE_COLORS as N, CELL_WIDTH as O, getAdjacentPosition as P, isSamePosition as R, mergeBounds as S, CELL_HEIGHT as T, MIN_COLS as _, EMPTY_GRID_WORKFLOW_DEFINITION as a, isWithinBounds as b, branchTypeSchema as c, gridPositionSchema as d, gridStepSchema as f, MAX_ROWS as g, MAX_COLS as h, parseChoiceList as i, MAX_GRID_ROWS as j, GRID_SIZE as k, exportTemplateSchema as l, gridWorkflowDefinitionSchema as m, createThrottledEmitter as n, parseGridWorkflowDefinition as o, gridStepTypeSchema as p, isAiTextStreamData as r, parseGridWorkflowDefinitionStrict as s, AI_TEXT_STREAM_NAMESPACE as t, gridConnectionSchema as u, MIN_ROWS as v, CELL_GAP as w, isWithinHardCap as x, deriveGridBounds as y, isValidPosition as z };