@reopt-ai/opt-workflow 0.0.0-stage → 0.1.1

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 +20 -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 +11899 -0
  23. package/dist/index.d.cts +803 -0
  24. package/dist/index.d.ts +803 -0
  25. package/dist/index.js +11852 -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,589 @@
1
+ import { n as _objectWithoutProperties, r as _objectSpread2 } from "./end-node-ids-p85jFEcP.js";
2
+ // src/lib/message.ts
3
+ const MAX_RECORDS = 2e3;
4
+ const records = /* @__PURE__ */ new Map();
5
+ /** `{이름}` 자리에 값을 끼운다. 모르는 자리는 그대로 둔다(`{{변수}}` 같은 글의 일부). */
6
+ function formatMessage(template, params) {
7
+ if (!params) return template;
8
+ return template.replace(/\{(\w+)\}/g, (match, name) => name in params ? String(params[name]) : match);
9
+ }
10
+ /**
11
+ * 틀에 값을 끼운 한국어 문장을 돌려주고, 번역할 수 있게 틀과 값을 적어 둔다.
12
+ * 이 표식(`msgf("…")`)이 있어야 번역 누락 검사가 그 틀을 찾는다.
13
+ */
14
+ function msgf(source, params, options) {
15
+ const formatted = formatMessage(source, params);
16
+ records.delete(formatted);
17
+ records.set(formatted, {
18
+ source,
19
+ params,
20
+ translate: options === null || options === void 0 ? void 0 : options.translate
21
+ });
22
+ if (records.size > MAX_RECORDS) {
23
+ const oldest = records.keys().next().value;
24
+ if (oldest !== void 0) records.delete(oldest);
25
+ }
26
+ return formatted;
27
+ }
28
+ /** 그 문자열이 `msgf`로 만든 것이면 틀과 값을 돌려준다. */
29
+ function lookupFormattedMessage(formatted) {
30
+ return records.get(formatted);
31
+ }
32
+ // src/engine/variable-resolver.ts
33
+ const VARIABLE_PATTERN = /\{\{([^}]+)\}\}/g;
34
+ const FORBIDDEN_KEYS = /* @__PURE__ */ new Set([
35
+ "__proto__",
36
+ "prototype",
37
+ "constructor"
38
+ ]);
39
+ /**
40
+ * 중첩 객체에서 경로로 값 조회
41
+ * @example getValueByPath({ a: { b: 1 } }, 'a.b') => 1
42
+ *
43
+ * 안전 규칙:
44
+ * - __proto__/prototype/constructor 키는 접근 거부 (prototype pollution 방지)
45
+ * - 자체 속성(hasOwnProperty)만 허용 (상속 속성 우회 방지)
46
+ * - Map/Set 등 내장 컨테이너는 인덱싱 대상에서 제외
47
+ */
48
+ function getValueByPath(obj, path) {
49
+ const keys = path.split(".");
50
+ let current = obj;
51
+ for (const key of keys) {
52
+ if (current === null || current === void 0) return;
53
+ if (typeof current !== "object") return;
54
+ if (FORBIDDEN_KEYS.has(key)) return;
55
+ const container = current;
56
+ if (!Object.prototype.hasOwnProperty.call(container, key)) return;
57
+ current = container[key];
58
+ }
59
+ return current;
60
+ }
61
+ /**
62
+ * 변수 소스에서 값 조회
63
+ * 우선순위: variables > params > previousResults
64
+ */
65
+ function resolveVariable(variablePath, context) {
66
+ const trimmedPath = variablePath.trim();
67
+ const fromVariables = getValueByPath(context.variables, trimmedPath);
68
+ if (fromVariables !== void 0) return fromVariables;
69
+ if (trimmedPath.startsWith("variables.")) {
70
+ const namespaced = getValueByPath(context.variables, trimmedPath.slice(10));
71
+ if (namespaced !== void 0) return namespaced;
72
+ }
73
+ const fromParams = getValueByPath(context.params, trimmedPath);
74
+ if (fromParams !== void 0) return fromParams;
75
+ if (trimmedPath.startsWith("params.")) {
76
+ const namespaced = getValueByPath(context.params, trimmedPath.slice(7));
77
+ if (namespaced !== void 0) return namespaced;
78
+ }
79
+ const parts = trimmedPath.split(".");
80
+ if (parts.length >= 2) {
81
+ const stepId = parts[0];
82
+ const result = context.previousResults.get(stepId);
83
+ if (result === null || result === void 0 ? void 0 : result.output) {
84
+ const outputPath = parts.slice(1).join(".");
85
+ const fromOutput = getValueByPath({ output: result.output }, outputPath);
86
+ if (fromOutput !== void 0) return fromOutput;
87
+ }
88
+ }
89
+ if (trimmedPath === "runId") return context.runId;
90
+ if (trimmedPath === "workflowId") return context.workflowId;
91
+ if (trimmedPath === "workspaceId") return context.workspaceId;
92
+ if (trimmedPath === "userId") return context.userId;
93
+ if (trimmedPath === "triggeredBy") return context.triggeredBy;
94
+ if (trimmedPath === "now") return (/* @__PURE__ */ new Date()).toISOString();
95
+ if (trimmedPath === "timestamp") return Date.now();
96
+ }
97
+ /**
98
+ * 문자열 내 모든 변수를 치환
99
+ * @example resolveVariables('Hello {{name}}!', context) => 'Hello John!'
100
+ */
101
+ function resolveVariables(template, context) {
102
+ return replaceVariables(template, context, (text) => text);
103
+ }
104
+ /**
105
+ * AI 프롬프트용 치환 — 작성자가 쓴 프롬프트 문장은 그대로 두고 **치환된 값**의 꺾쇠괄호만
106
+ * `‹` `›`로 바꾼다. 폼 응답·고객 데이터 같은 값이 프롬프트의 `<inquiry>` 같은 데이터 블록을
107
+ * 닫고 지시를 끼워 넣지 못하게 한다.
108
+ */
109
+ function resolvePromptVariables(template, context) {
110
+ return replaceVariables(template, context, neutralizeUntrusted);
111
+ }
112
+ /** 내용 속 꺾쇠괄호를 `‹` `›`로 바꾼다 — 데이터 블록을 닫거나 열 수 없게. */
113
+ function neutralizeUntrusted(text) {
114
+ return text.replace(/[<>]/g, (bracket) => bracket === "<" ? "‹" : "›");
115
+ }
116
+ function replaceVariables(template, context, formatValue) {
117
+ return template.replace(VARIABLE_PATTERN, (match, variablePath) => {
118
+ const value = resolveVariable(variablePath, context);
119
+ if (value === void 0) return "";
120
+ if (typeof value === "object") return formatValue(JSON.stringify(value));
121
+ return formatValue(String(value));
122
+ });
123
+ }
124
+ /**
125
+ * 문자열 내 변수 패턴 존재 여부 확인
126
+ */
127
+ function hasVariables(template) {
128
+ VARIABLE_PATTERN.lastIndex = 0;
129
+ return VARIABLE_PATTERN.test(template);
130
+ }
131
+ /**
132
+ * 문자열에서 모든 변수 경로 추출
133
+ */
134
+ function extractVariablePaths(template) {
135
+ const paths = [];
136
+ let match;
137
+ VARIABLE_PATTERN.lastIndex = 0;
138
+ while ((match = VARIABLE_PATTERN.exec(template)) !== null) paths.push(match[1].trim());
139
+ return paths;
140
+ }
141
+ /**
142
+ * "값을 가리키는 칸"(데이터 변환 입력·반복 대상 컬렉션)의 참조를 **값 그대로** 해석한다.
143
+ *
144
+ * 🔴 그 칸들은 변수 픽커가 붙어 있어 `{{step-2.output.data}}`가 들어가는데, 실행부는
145
+ * `context.variables[입력]`을 이름 그대로 읽어 **항상** "입력 변수를 찾을 수 없습니다"였다
146
+ * (트리거 페이로드·스텝 출력도 못 읽었다). 문자열로 치환하면 배열·객체가 JSON 문자열이
147
+ * 되므로 `resolveVariables`가 아니라 경로 조회를 쓴다. 토큰 없는 옛 값(`items`)은
148
+ * 같은 조회의 첫 단계(variables)가 그대로 받는다.
149
+ */
150
+ function resolveValueReference(reference, context) {
151
+ var _whole$;
152
+ const trimmed = reference.trim();
153
+ const whole = /^\{\{([^}]+)\}\}$/.exec(trimmed);
154
+ return resolveVariable((_whole$ = whole === null || whole === void 0 ? void 0 : whole[1]) !== null && _whole$ !== void 0 ? _whole$ : trimmed, context);
155
+ }
156
+ /**
157
+ * 단일 변수 값 해석 (객체 형태로 반환)
158
+ */
159
+ function resolveVariableValue(variablePath, context) {
160
+ return resolveVariable(variablePath, context);
161
+ }
162
+ /**
163
+ * 객체 안에서 **해석되지 않은** 변수 경로를 모은다.
164
+ *
165
+ * 미해석 토큰은 빈 문자열로 치환된다(그 동작 자체는 의도적이다 — 선택 변수를
166
+ * 쓰는 워크플로우가 많다). 문제는 **그것이 아무 데도 안 남는다**는 점이다:
167
+ * 수신자가 빈 이메일이 나가도 실행은 초록불이고 런 상세에도 흔적이 없다.
168
+ * 그래서 치환은 그대로 두고, 무엇이 비었는지를 기록으로 남긴다.
169
+ */
170
+ function collectUnresolvedVariables(value, context, seen = /* @__PURE__ */ new Set()) {
171
+ if (typeof value === "string") {
172
+ for (const path of extractVariablePaths(value)) if (resolveVariableValue(path, context) === void 0) seen.add(path);
173
+ } else if (Array.isArray(value)) for (const item of value) collectUnresolvedVariables(item, context, seen);
174
+ else if (value && typeof value === "object") for (const item of Object.values(value)) collectUnresolvedVariables(item, context, seen);
175
+ return [...seen];
176
+ }
177
+ /**
178
+ * 객체 내 모든 문자열 필드의 변수 치환
179
+ */
180
+ function resolveObjectVariables(obj, context) {
181
+ const result = {};
182
+ for (const [key, value] of Object.entries(obj)) if (typeof value === "string") result[key] = resolveVariables(value, context);
183
+ else if (value && typeof value === "object" && !Array.isArray(value)) result[key] = resolveObjectVariables(value, context);
184
+ else if (Array.isArray(value)) result[key] = value.map((item) => {
185
+ if (typeof item === "string") return resolveVariables(item, context);
186
+ if (item && typeof item === "object") return resolveObjectVariables(item, context);
187
+ return item;
188
+ });
189
+ else result[key] = value;
190
+ return result;
191
+ }
192
+ // src/engine/condition-evaluator.ts
193
+ /**
194
+ * 조건 평가기
195
+ * 조건 스텝의 표현식을 평가하여 분기를 결정합니다.
196
+ */
197
+ const _excluded = ["condition"];
198
+ /**
199
+ * 저장된 조건 설정을 런타임 계약(`ConditionConfig`)으로 정규화한다 — **한 벌**.
200
+ *
201
+ * 🔴 조건의 키가 세 곳에서 갈려 있었다: 카탈로그(`condition-if-else`)는 `condition`,
202
+ * 템플릿도 `condition`, 실행기·검증기는 `expression`/`switchValue`만 읽었다. 그래서
203
+ * 에디터로 만든 조건은 실행 전 점검이 거절하고 실행기는 항상 false로 갔다(2026-09-23 실측).
204
+ * 지금은 카탈로그 키가 런타임 키와 같고, 옛 행·템플릿의 `condition`은 여기서 흡수한다.
205
+ * 평가·검증·화면 요약·설정 패널이 전부 이 함수를 거친다 — 두 곳에 적지 말 것.
206
+ */
207
+ function normalizeConditionConfig(raw) {
208
+ const config = raw !== null && raw !== void 0 ? raw : {};
209
+ const legacyExpression = typeof config.condition === "string" ? config.condition : void 0;
210
+ const expression = typeof config.expression === "string" ? config.expression : void 0;
211
+ const switchValue = typeof config.switchValue === "string" ? config.switchValue : void 0;
212
+ const conditionType = config.conditionType === "switch" || config.conditionType === void 0 && switchValue !== void 0 ? "switch" : "if-else";
213
+ const { condition: _legacy } = config, rest = _objectWithoutProperties(config, _excluded);
214
+ return _objectSpread2(_objectSpread2({}, rest), {}, {
215
+ conditionType,
216
+ expression: conditionType === "if-else" ? expression !== null && expression !== void 0 ? expression : legacyExpression : expression,
217
+ switchValue: conditionType === "switch" ? switchValue !== null && switchValue !== void 0 ? switchValue : expression : switchValue
218
+ });
219
+ }
220
+ /**
221
+ * 조건 평가
222
+ */
223
+ async function evaluateCondition(config, context) {
224
+ const conditionConfig = normalizeConditionConfig(config);
225
+ if (conditionConfig.conditionType === "switch") return evaluateSwitchCondition(conditionConfig, context);
226
+ return evaluateIfElseCondition(conditionConfig, context);
227
+ }
228
+ /**
229
+ * if-else 조건 평가
230
+ */
231
+ function evaluateIfElseCondition(config, context) {
232
+ if (config.conditionGroup) return evaluateConditionGroup(config.conditionGroup, context);
233
+ if (config.expression) return evaluateExpression(config.expression, context);
234
+ if (config.leftOperand && config.operator) return evaluateComparison(config.leftOperand, config.operator, config.rightOperand, context);
235
+ return false;
236
+ }
237
+ /**
238
+ * switch 조건 평가
239
+ */
240
+ function evaluateSwitchCondition(config, context) {
241
+ if (!config.switchValue) return "default";
242
+ return resolveVariables(config.switchValue, context) || "default";
243
+ }
244
+ /**
245
+ * 조건식이 **지원 형식**인가 — 치환 전 원문으로 판정한다. 점검(`validateConditionConfig`)과
246
+ * 평가(`evaluateExpression`)가 같은 이 함수를 본다.
247
+ *
248
+ * 🔴 왜 필요한가(2026-09-23, 에이전트 실모델 프로브): "이메일이 @acme.com으로 끝나면"을
249
+ * 받은 모델이 `{{email}} endsWith '@acme.com'`을 썼다. 비교 연산자(`===`·`>` 등)가 없어
250
+ * 평가기의 "단일 값 참/거짓" 폴백으로 떨어졌고, 치환된 문자열은 비어 있지 않으니 **항상
251
+ * 참**이었다 — 모든 고객에게 태그가 붙는다. 점검도 "문제 없음"이었다(키가 채워졌는지만
252
+ * 봤다). 사람이 손으로 적어도 같은 구멍이다. 단일 값은 **`{{변수}}` 하나**일 때만 허용한다.
253
+ */
254
+ function findUnsupportedConditionExpression(expression) {
255
+ const trimmed = expression.trim();
256
+ if (!trimmed) return null;
257
+ if (/^(true|false)$/i.test(trimmed)) return null;
258
+ if (/^\{\{[^}]+\}\}$/.test(trimmed)) return null;
259
+ if (!/\{\{[^}]+\}\}/.test(trimmed)) return msgf("조건식에 변수가 없습니다: \"{expression}\". 값은 {{변수}}로 적어야 합니다(예: {{count}} < 10) — 그대로 두면 결과가 늘 같습니다.", { expression: trimmed });
260
+ if (/^(.+?)\s*(===?|!==?)\s*(['"]).*\3$/.test(trimmed)) return null;
261
+ if (/^(.+?)\s*(>=|<=|>|<|===?|!==?)\s*-?\d+(?:\.\d+)?$/.test(trimmed)) return null;
262
+ return msgf("지원하지 않는 조건식입니다: \"{expression}\". {{변수}} === '값' · {{변수}} !== '값' · {{변수}} > 10 · {{변수}}(참/거짓) 중 하나로 적으세요. 포함·시작·끝 비교와 &&·||는 지원하지 않습니다.", { expression: trimmed });
263
+ }
264
+ /**
265
+ * 표현식 평가 (안전한 방식)
266
+ * 지원 형식:
267
+ * - {{variable}} === 'value'
268
+ * - {{variable}} > 10
269
+ * - 단일 값(truthy 판정)
270
+ *
271
+ * 🔴 **인식하지 못한 표현식은 거짓이 아니라 예외다.** 예전에는 어느 패턴에도
272
+ * 맞지 않으면 truthy 폴백으로 `true`를 돌려줬다 — 조건은 게이트인데 오타 하나가
273
+ * "항상 통과"로 열리는 fail-open이었다(`{{a}} === {{b}}`처럼 따옴표가 없는 흔한
274
+ * 형태가 여기 걸린다). 이제 던져서 스텝을 실패시킨다: 사용자가 즉시 알게 되고,
275
+ * 잘못된 분기로 메일이 나가지 않는다.
276
+ */
277
+ function evaluateExpression(expression, context) {
278
+ const unsupported = findUnsupportedConditionExpression(expression);
279
+ if (unsupported) throw new Error(unsupported);
280
+ const resolvedExpression = resolveVariables(expression, context);
281
+ if (/^true$/i.test(resolvedExpression)) return true;
282
+ if (/^false$/i.test(resolvedExpression)) return false;
283
+ const equalityMatch = resolvedExpression.match(/^(.+?)\s*(===?|!==?)\s*['"](.+?)['"]$/);
284
+ if (equalityMatch) {
285
+ const [, left, op, right] = equalityMatch;
286
+ const leftValue = left.trim();
287
+ if (op === "===" || op === "==") return leftValue === right;
288
+ if (op === "!==" || op === "!=") return leftValue !== right;
289
+ }
290
+ const numericMatch = resolvedExpression.match(/^(.+?)\s*(>|<|>=|<=|===?|!==?)\s*(\d+(?:\.\d+)?)$/);
291
+ if (numericMatch) {
292
+ const [, left, op, right] = numericMatch;
293
+ const leftNum = parseFloat(left.trim());
294
+ const rightNum = parseFloat(right);
295
+ if (isNaN(leftNum) || isNaN(rightNum)) return false;
296
+ switch (op) {
297
+ case ">": return leftNum > rightNum;
298
+ case "<": return leftNum < rightNum;
299
+ case ">=": return leftNum >= rightNum;
300
+ case "<=": return leftNum <= rightNum;
301
+ case "===":
302
+ case "==": return leftNum === rightNum;
303
+ case "!==":
304
+ case "!=": return leftNum !== rightNum;
305
+ }
306
+ }
307
+ const trimmed = resolvedExpression.trim();
308
+ if (!trimmed || trimmed === "0" || trimmed === "null" || trimmed === "undefined" || trimmed === "false") return false;
309
+ if (/(===?|!==?|>=?|<=?|&&|\|\|)/.test(trimmed)) throw new Error(msgf("조건 표현식을 해석할 수 없습니다: \"{expression}\" (치환 결과: \"{resolved}\"). 지원 형식: {{변수}} === '값', {{변수}} > 10, {{변수}}", {
310
+ expression,
311
+ resolved: trimmed
312
+ }));
313
+ return true;
314
+ }
315
+ /**
316
+ * 비교 연산 수행
317
+ */
318
+ function evaluateComparison(leftOperand, operator, rightOperand, context) {
319
+ let leftValue;
320
+ if (leftOperand.startsWith("{{") && leftOperand.endsWith("}}")) leftValue = resolveVariableValue(leftOperand.slice(2, -2).trim(), context);
321
+ else leftValue = resolveVariables(leftOperand, context);
322
+ let rightValue = rightOperand;
323
+ if (typeof rightOperand === "string") {
324
+ if (rightOperand.startsWith("{{") && rightOperand.endsWith("}}")) rightValue = resolveVariableValue(rightOperand.slice(2, -2).trim(), context);
325
+ else rightValue = resolveVariables(rightOperand, context);
326
+ }
327
+ switch (operator) {
328
+ case "equals": return looseEquals(leftValue, rightValue);
329
+ case "notEquals": return !looseEquals(leftValue, rightValue);
330
+ case "contains": return String(leftValue).includes(String(rightValue));
331
+ case "notContains": return !String(leftValue).includes(String(rightValue));
332
+ case "startsWith": return String(leftValue).startsWith(String(rightValue));
333
+ case "endsWith": return String(leftValue).endsWith(String(rightValue));
334
+ case "greaterThan": return Number(leftValue) > Number(rightValue);
335
+ case "lessThan": return Number(leftValue) < Number(rightValue);
336
+ case "greaterThanOrEquals": return Number(leftValue) >= Number(rightValue);
337
+ case "lessThanOrEquals": return Number(leftValue) <= Number(rightValue);
338
+ case "isEmpty": return !leftValue || typeof leftValue === "string" && leftValue.trim() === "";
339
+ case "isNotEmpty": return Boolean(leftValue) && (typeof leftValue !== "string" || leftValue.trim() !== "");
340
+ case "isNull": return leftValue === null || leftValue === void 0;
341
+ case "isNotNull": return leftValue !== null && leftValue !== void 0;
342
+ case "matches": try {
343
+ return new RegExp(String(rightValue)).test(String(leftValue));
344
+ } catch (_unused) {
345
+ return false;
346
+ }
347
+ default: return false;
348
+ }
349
+ }
350
+ /**
351
+ * 같음 비교 — 타입이 갈려도 사람이 기대하는 대로 판정한다.
352
+ *
353
+ * UI는 모든 입력을 **문자열로 저장**하는데 변수 값은 숫자·불린인 경우가 흔하다.
354
+ * 엄격 비교만 쓰면 `10 === "10"`이 false여서 "값이 같은데 왜 false냐"가 된다.
355
+ * 숫자/불린으로 해석 가능한 쌍만 정규화하고, 그 외에는 엄격 비교를 유지한다.
356
+ */
357
+ function looseEquals(left, right) {
358
+ if (left === right) return true;
359
+ if (left == null || right == null) return false;
360
+ const leftNum = typeof left === "number" ? left : toFiniteNumber(left);
361
+ const rightNum = typeof right === "number" ? right : toFiniteNumber(right);
362
+ if (leftNum !== void 0 && rightNum !== void 0) return leftNum === rightNum;
363
+ const leftBool = toBoolean(left);
364
+ const rightBool = toBoolean(right);
365
+ if (leftBool !== void 0 && rightBool !== void 0) return leftBool === rightBool;
366
+ return false;
367
+ }
368
+ function toFiniteNumber(value) {
369
+ if (typeof value !== "string") return void 0;
370
+ const trimmed = value.trim();
371
+ if (trimmed === "") return void 0;
372
+ const parsed = Number(trimmed);
373
+ return Number.isFinite(parsed) ? parsed : void 0;
374
+ }
375
+ function toBoolean(value) {
376
+ if (typeof value === "boolean") return value;
377
+ if (typeof value !== "string") return void 0;
378
+ const lower = value.trim().toLowerCase();
379
+ if (lower === "true") return true;
380
+ if (lower === "false") return false;
381
+ }
382
+ /**
383
+ * 조건 설정 검증
384
+ */
385
+ function validateConditionConfig(raw) {
386
+ const config = normalizeConditionConfig(raw);
387
+ const errors = [];
388
+ if (!config.conditionType) errors.push("조건 유형이 지정되지 않았습니다");
389
+ if (config.conditionType === "if-else" && !config.conditionGroup) {
390
+ if (!config.expression && !config.leftOperand) errors.push("조건 표현식 또는 비교 대상이 필요합니다");
391
+ if (config.expression) {
392
+ const unsupported = findUnsupportedConditionExpression(config.expression);
393
+ if (unsupported) errors.push(unsupported);
394
+ }
395
+ if (config.leftOperand && !config.operator) errors.push("비교 연산자가 지정되지 않았습니다");
396
+ }
397
+ if (config.conditionType === "switch") {
398
+ if (!config.switchValue) errors.push("switch 대상 값이 지정되지 않았습니다");
399
+ }
400
+ return {
401
+ valid: errors.length === 0,
402
+ errors
403
+ };
404
+ }
405
+ /**
406
+ * 조건 그룹 재귀 평가 (AND/OR)
407
+ */
408
+ function evaluateConditionGroup(group, context) {
409
+ const results = group.conditions.map((condition) => {
410
+ if ("logic" in condition) return evaluateConditionGroup(condition, context);
411
+ return evaluateSingleCondition(condition, context);
412
+ });
413
+ if (group.logic === "and") return results.every(Boolean);
414
+ return results.some(Boolean);
415
+ }
416
+ /**
417
+ * 단일 조건 평가
418
+ */
419
+ function evaluateSingleCondition(condition, context) {
420
+ return evaluateComparison(condition.leftOperand, condition.operator, condition.rightOperand, context);
421
+ }
422
+ /**
423
+ * 조건 평가 + 상세 정보 반환 (디버깅용)
424
+ */
425
+ async function evaluateConditionWithDetails(config, context) {
426
+ const conditionConfig = normalizeConditionConfig(config);
427
+ if (conditionConfig.conditionType === "switch") {
428
+ var _conditionConfig$swit;
429
+ const result = evaluateSwitchCondition(conditionConfig, context);
430
+ return {
431
+ result,
432
+ details: {
433
+ conditionType: "switch",
434
+ leftValue: conditionConfig.switchValue,
435
+ result,
436
+ expression: conditionConfig.switchValue,
437
+ resolvedExpression: resolveVariables((_conditionConfig$swit = conditionConfig.switchValue) !== null && _conditionConfig$swit !== void 0 ? _conditionConfig$swit : "", context)
438
+ }
439
+ };
440
+ }
441
+ if (conditionConfig.conditionGroup) {
442
+ const result = evaluateConditionGroup(conditionConfig.conditionGroup, context);
443
+ return {
444
+ result,
445
+ details: {
446
+ conditionType: "group",
447
+ result,
448
+ expression: JSON.stringify(conditionConfig.conditionGroup)
449
+ }
450
+ };
451
+ }
452
+ if (conditionConfig.expression) {
453
+ const resolved = resolveVariables(conditionConfig.expression, context);
454
+ const result = evaluateExpression(conditionConfig.expression, context);
455
+ return {
456
+ result,
457
+ details: {
458
+ conditionType: "if-else",
459
+ result,
460
+ expression: conditionConfig.expression,
461
+ resolvedExpression: resolved
462
+ }
463
+ };
464
+ }
465
+ if (conditionConfig.leftOperand && conditionConfig.operator) {
466
+ let leftValue;
467
+ if (conditionConfig.leftOperand.startsWith("{{") && conditionConfig.leftOperand.endsWith("}}")) leftValue = resolveVariableValue(conditionConfig.leftOperand.slice(2, -2).trim(), context);
468
+ else leftValue = resolveVariables(conditionConfig.leftOperand, context);
469
+ let rightValue = conditionConfig.rightOperand;
470
+ if (typeof conditionConfig.rightOperand === "string") {
471
+ if (conditionConfig.rightOperand.startsWith("{{") && conditionConfig.rightOperand.endsWith("}}")) rightValue = resolveVariableValue(conditionConfig.rightOperand.slice(2, -2).trim(), context);
472
+ else rightValue = resolveVariables(conditionConfig.rightOperand, context);
473
+ }
474
+ const result = evaluateComparison(conditionConfig.leftOperand, conditionConfig.operator, conditionConfig.rightOperand, context);
475
+ return {
476
+ result,
477
+ details: {
478
+ conditionType: "if-else",
479
+ leftValue,
480
+ operator: conditionConfig.operator,
481
+ rightValue,
482
+ result,
483
+ expression: `${conditionConfig.leftOperand} ${conditionConfig.operator} ${String(conditionConfig.rightOperand)}`
484
+ }
485
+ };
486
+ }
487
+ return {
488
+ result: false,
489
+ details: {
490
+ conditionType: "if-else",
491
+ result: false,
492
+ expression: "(no condition defined)"
493
+ }
494
+ };
495
+ }
496
+ // src/engine/branch-resolver.ts
497
+ /**
498
+ * 분기 경로 결정기
499
+ * 조건 스텝에서 나가는 연결들 중 적절한 경로를 선택합니다.
500
+ */
501
+ /**
502
+ * 조건 평가 결과에 따라 다음 스텝 ID 결정
503
+ */
504
+ function resolveBranchPath(conditionStep, outgoingConnections, conditionResult) {
505
+ if (outgoingConnections.length === 0) return null;
506
+ if (conditionStep.config.conditionType === "switch") return resolveSwitchBranch(outgoingConnections, conditionResult);
507
+ return resolveIfElseBranch(outgoingConnections, conditionResult);
508
+ }
509
+ /**
510
+ * if-else 분기 해결
511
+ */
512
+ function resolveIfElseBranch(connections, conditionResult) {
513
+ var _connections$0$toStep, _connections$;
514
+ const boolResult = Boolean(conditionResult);
515
+ const wanted = boolResult ? "true" : "false";
516
+ const match = connections.find((conn) => conn.branchType === wanted);
517
+ if (match) return match.toStepId;
518
+ if (connections.some((conn) => conn.branchType)) return null;
519
+ if (connections.length >= 2) return boolResult ? connections[0].toStepId : connections[1].toStepId;
520
+ return (_connections$0$toStep = (_connections$ = connections[0]) === null || _connections$ === void 0 ? void 0 : _connections$.toStepId) !== null && _connections$0$toStep !== void 0 ? _connections$0$toStep : null;
521
+ }
522
+ /**
523
+ * switch 분기 해결
524
+ */
525
+ function resolveSwitchBranch(connections, conditionResult) {
526
+ const resultValue = String(conditionResult);
527
+ const caseConnection = connections.find((conn) => {
528
+ if (conn.branchType !== "case") return false;
529
+ return conn.branchValue === resultValue;
530
+ });
531
+ if (caseConnection) return caseConnection.toStepId;
532
+ const defaultConnection = connections.find((conn) => conn.branchType === "default");
533
+ if (defaultConnection) return defaultConnection.toStepId;
534
+ return null;
535
+ }
536
+ /**
537
+ * 분기 연결 검증
538
+ * 조건 스텝의 연결이 올바르게 구성되어 있는지 확인
539
+ */
540
+ function validateBranchConnections(conditionStep, connections) {
541
+ const errors = [];
542
+ const warnings = [];
543
+ if (conditionStep.config.conditionType === "switch") {
544
+ const caseConnections = connections.filter((c) => c.branchType === "case");
545
+ const defaultConnection = connections.find((c) => c.branchType === "default");
546
+ if (caseConnections.length === 0 && !defaultConnection) errors.push("switch 조건에 case 또는 default 분기가 없습니다");
547
+ if (!defaultConnection) warnings.push("default 분기가 없으면 매칭되지 않는 값은 처리되지 않습니다");
548
+ const caseValues = caseConnections.map((c) => c.branchValue);
549
+ const duplicates = caseValues.filter((v, i) => caseValues.indexOf(v) !== i);
550
+ if (duplicates.length > 0) errors.push(msgf("중복된 case 값이 있습니다: {values}", { values: duplicates.join(", ") }));
551
+ } else {
552
+ const trueConnections = connections.filter((c) => c.branchType === "true");
553
+ const falseConnections = connections.filter((c) => c.branchType === "false");
554
+ if (trueConnections.length === 0 && falseConnections.length === 0) warnings.push("분기 타입이 지정되지 않았습니다. 조건 결과에 따라 순서대로 선택됩니다.");
555
+ if (trueConnections.length > 1) errors.push("true 분기가 여러 개 있습니다");
556
+ if (falseConnections.length > 1) errors.push("false 분기가 여러 개 있습니다");
557
+ if (trueConnections.length === 0 && falseConnections.length > 0) warnings.push("참 분기가 없습니다. 조건이 참이면 여기서 흐름이 끝납니다.");
558
+ if (falseConnections.length === 0 && trueConnections.length > 0) warnings.push("거짓 분기가 없습니다. 조건이 거짓이면 여기서 흐름이 끝납니다.");
559
+ }
560
+ return {
561
+ valid: errors.length === 0,
562
+ warnings,
563
+ errors
564
+ };
565
+ }
566
+ /**
567
+ * 분기 타입별 레이블 생성
568
+ */
569
+ function getBranchLabel(branchType, branchValue) {
570
+ switch (branchType) {
571
+ case "true": return "참 (True)";
572
+ case "false": return "거짓 (False)";
573
+ case "case": return branchValue ? `Case: ${branchValue}` : "Case";
574
+ case "default": return "기본 (Default)";
575
+ default: return "";
576
+ }
577
+ }
578
+ /**
579
+ * 연결에서 분기 정보 추출
580
+ */
581
+ function extractBranchInfo(connection) {
582
+ var _connection$label;
583
+ return {
584
+ type: connection.branchType,
585
+ value: connection.branchValue,
586
+ label: connection.branchType ? getBranchLabel(connection.branchType, connection.branchValue) : (_connection$label = connection.label) !== null && _connection$label !== void 0 ? _connection$label : ""
587
+ };
588
+ }
589
+ export { resolveVariableValue as _, evaluateCondition as a, lookupFormattedMessage as b, findUnsupportedConditionExpression as c, collectUnresolvedVariables as d, extractVariablePaths as f, resolveValueReference as g, resolvePromptVariables as h, validateBranchConnections as i, normalizeConditionConfig as l, resolveObjectVariables as m, getBranchLabel as n, evaluateConditionGroup as o, hasVariables as p, resolveBranchPath as r, evaluateConditionWithDetails as s, extractBranchInfo as t, validateConditionConfig as u, resolveVariables as v, msgf as x, formatMessage as y };