@manifesto-ai/compiler 1.6.2 → 1.7.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 (201) hide show
  1. package/README.md +64 -16
  2. package/dist/chunk-DJY6BFGK.js +74 -0
  3. package/dist/chunk-DJY6BFGK.js.map +1 -0
  4. package/dist/chunk-QP2LGMBA.js +4522 -0
  5. package/dist/chunk-QP2LGMBA.js.map +1 -0
  6. package/dist/chunk-QXLPDCLA.js +33 -0
  7. package/dist/chunk-QXLPDCLA.js.map +1 -0
  8. package/dist/esbuild.d.ts +8 -0
  9. package/dist/esbuild.js +14 -0
  10. package/dist/esbuild.js.map +1 -0
  11. package/dist/index.d.ts +2710 -11
  12. package/dist/index.js +2189 -43
  13. package/dist/index.js.map +1 -1
  14. package/dist/node-loader.d.ts +18 -0
  15. package/dist/node-loader.js +47 -0
  16. package/dist/node-loader.js.map +1 -0
  17. package/dist/rollup.d.ts +8 -0
  18. package/dist/rollup.js +14 -0
  19. package/dist/rollup.js.map +1 -0
  20. package/dist/rspack.d.ts +7 -0
  21. package/dist/rspack.js +14 -0
  22. package/dist/rspack.js.map +1 -0
  23. package/dist/unplugin-6wnvFiEo.d.ts +17 -0
  24. package/dist/vite.d.ts +8 -17
  25. package/dist/vite.js +13 -33
  26. package/dist/vite.js.map +1 -1
  27. package/dist/webpack.d.ts +8 -0
  28. package/dist/webpack.js +14 -0
  29. package/dist/webpack.js.map +1 -0
  30. package/package.json +39 -21
  31. package/dist/analyzer/index.d.ts +0 -6
  32. package/dist/analyzer/index.d.ts.map +0 -1
  33. package/dist/analyzer/index.js +0 -6
  34. package/dist/analyzer/index.js.map +0 -1
  35. package/dist/analyzer/scope.d.ts +0 -77
  36. package/dist/analyzer/scope.d.ts.map +0 -1
  37. package/dist/analyzer/scope.js +0 -296
  38. package/dist/analyzer/scope.js.map +0 -1
  39. package/dist/analyzer/validator.d.ts +0 -60
  40. package/dist/analyzer/validator.d.ts.map +0 -1
  41. package/dist/analyzer/validator.js +0 -439
  42. package/dist/analyzer/validator.js.map +0 -1
  43. package/dist/api/compile-mel-patch-collector.d.ts +0 -32
  44. package/dist/api/compile-mel-patch-collector.d.ts.map +0 -1
  45. package/dist/api/compile-mel-patch-collector.js +0 -425
  46. package/dist/api/compile-mel-patch-collector.js.map +0 -1
  47. package/dist/api/compile-mel-patch-expr.d.ts +0 -9
  48. package/dist/api/compile-mel-patch-expr.d.ts.map +0 -1
  49. package/dist/api/compile-mel-patch-expr.js +0 -179
  50. package/dist/api/compile-mel-patch-expr.js.map +0 -1
  51. package/dist/api/compile-mel-patch-location.d.ts +0 -10
  52. package/dist/api/compile-mel-patch-location.d.ts.map +0 -1
  53. package/dist/api/compile-mel-patch-location.js +0 -48
  54. package/dist/api/compile-mel-patch-location.js.map +0 -1
  55. package/dist/api/compile-mel-patch.d.ts +0 -6
  56. package/dist/api/compile-mel-patch.d.ts.map +0 -1
  57. package/dist/api/compile-mel-patch.js +0 -244
  58. package/dist/api/compile-mel-patch.js.map +0 -1
  59. package/dist/api/compile-mel.d.ts +0 -126
  60. package/dist/api/compile-mel.d.ts.map +0 -1
  61. package/dist/api/compile-mel.js +0 -114
  62. package/dist/api/compile-mel.js.map +0 -1
  63. package/dist/api/index.d.ts +0 -10
  64. package/dist/api/index.d.ts.map +0 -1
  65. package/dist/api/index.js +0 -9
  66. package/dist/api/index.js.map +0 -1
  67. package/dist/diagnostics/codes.d.ts +0 -25
  68. package/dist/diagnostics/codes.d.ts.map +0 -1
  69. package/dist/diagnostics/codes.js +0 -154
  70. package/dist/diagnostics/codes.js.map +0 -1
  71. package/dist/diagnostics/index.d.ts +0 -6
  72. package/dist/diagnostics/index.d.ts.map +0 -1
  73. package/dist/diagnostics/index.js +0 -6
  74. package/dist/diagnostics/index.js.map +0 -1
  75. package/dist/diagnostics/types.d.ts +0 -67
  76. package/dist/diagnostics/types.d.ts.map +0 -1
  77. package/dist/diagnostics/types.js +0 -58
  78. package/dist/diagnostics/types.js.map +0 -1
  79. package/dist/evaluation/context.d.ts +0 -91
  80. package/dist/evaluation/context.d.ts.map +0 -1
  81. package/dist/evaluation/context.js +0 -53
  82. package/dist/evaluation/context.js.map +0 -1
  83. package/dist/evaluation/evaluate-expr.d.ts +0 -24
  84. package/dist/evaluation/evaluate-expr.d.ts.map +0 -1
  85. package/dist/evaluation/evaluate-expr.js +0 -577
  86. package/dist/evaluation/evaluate-expr.js.map +0 -1
  87. package/dist/evaluation/evaluate-patch.d.ts +0 -123
  88. package/dist/evaluation/evaluate-patch.d.ts.map +0 -1
  89. package/dist/evaluation/evaluate-patch.js +0 -202
  90. package/dist/evaluation/evaluate-patch.js.map +0 -1
  91. package/dist/evaluation/evaluate-runtime-patch.d.ts +0 -86
  92. package/dist/evaluation/evaluate-runtime-patch.d.ts.map +0 -1
  93. package/dist/evaluation/evaluate-runtime-patch.js +0 -185
  94. package/dist/evaluation/evaluate-runtime-patch.js.map +0 -1
  95. package/dist/evaluation/index.d.ts +0 -15
  96. package/dist/evaluation/index.d.ts.map +0 -1
  97. package/dist/evaluation/index.js +0 -13
  98. package/dist/evaluation/index.js.map +0 -1
  99. package/dist/generator/index.d.ts +0 -7
  100. package/dist/generator/index.d.ts.map +0 -1
  101. package/dist/generator/index.js +0 -7
  102. package/dist/generator/index.js.map +0 -1
  103. package/dist/generator/ir.d.ts +0 -348
  104. package/dist/generator/ir.d.ts.map +0 -1
  105. package/dist/generator/ir.js +0 -715
  106. package/dist/generator/ir.js.map +0 -1
  107. package/dist/generator/lowering.d.ts +0 -11
  108. package/dist/generator/lowering.d.ts.map +0 -1
  109. package/dist/generator/lowering.js +0 -369
  110. package/dist/generator/lowering.js.map +0 -1
  111. package/dist/generator/normalizer.d.ts +0 -16
  112. package/dist/generator/normalizer.d.ts.map +0 -1
  113. package/dist/generator/normalizer.js +0 -181
  114. package/dist/generator/normalizer.js.map +0 -1
  115. package/dist/index.d.ts.map +0 -1
  116. package/dist/lexer/index.d.ts +0 -7
  117. package/dist/lexer/index.d.ts.map +0 -1
  118. package/dist/lexer/index.js +0 -7
  119. package/dist/lexer/index.js.map +0 -1
  120. package/dist/lexer/lexer.d.ts +0 -59
  121. package/dist/lexer/lexer.d.ts.map +0 -1
  122. package/dist/lexer/lexer.js +0 -433
  123. package/dist/lexer/lexer.js.map +0 -1
  124. package/dist/lexer/source-location.d.ts +0 -41
  125. package/dist/lexer/source-location.d.ts.map +0 -1
  126. package/dist/lexer/source-location.js +0 -33
  127. package/dist/lexer/source-location.js.map +0 -1
  128. package/dist/lexer/tokens.d.ts +0 -47
  129. package/dist/lexer/tokens.d.ts.map +0 -1
  130. package/dist/lexer/tokens.js +0 -73
  131. package/dist/lexer/tokens.js.map +0 -1
  132. package/dist/loader.d.ts +0 -23
  133. package/dist/loader.d.ts.map +0 -1
  134. package/dist/loader.js +0 -62
  135. package/dist/loader.js.map +0 -1
  136. package/dist/lowering/context.d.ts +0 -96
  137. package/dist/lowering/context.d.ts.map +0 -1
  138. package/dist/lowering/context.js +0 -42
  139. package/dist/lowering/context.js.map +0 -1
  140. package/dist/lowering/errors.d.ts +0 -84
  141. package/dist/lowering/errors.d.ts.map +0 -1
  142. package/dist/lowering/errors.js +0 -81
  143. package/dist/lowering/errors.js.map +0 -1
  144. package/dist/lowering/index.d.ts +0 -20
  145. package/dist/lowering/index.d.ts.map +0 -1
  146. package/dist/lowering/index.js +0 -13
  147. package/dist/lowering/index.js.map +0 -1
  148. package/dist/lowering/lower-expr.d.ts +0 -76
  149. package/dist/lowering/lower-expr.d.ts.map +0 -1
  150. package/dist/lowering/lower-expr.js +0 -366
  151. package/dist/lowering/lower-expr.js.map +0 -1
  152. package/dist/lowering/lower-patch.d.ts +0 -231
  153. package/dist/lowering/lower-patch.d.ts.map +0 -1
  154. package/dist/lowering/lower-patch.js +0 -146
  155. package/dist/lowering/lower-patch.js.map +0 -1
  156. package/dist/lowering/lower-runtime-patch.d.ts +0 -100
  157. package/dist/lowering/lower-runtime-patch.d.ts.map +0 -1
  158. package/dist/lowering/lower-runtime-patch.js +0 -49
  159. package/dist/lowering/lower-runtime-patch.js.map +0 -1
  160. package/dist/mel-module.d.ts +0 -13
  161. package/dist/mel-module.d.ts.map +0 -1
  162. package/dist/mel-module.js +0 -33
  163. package/dist/mel-module.js.map +0 -1
  164. package/dist/parser/ast.d.ts +0 -344
  165. package/dist/parser/ast.d.ts.map +0 -1
  166. package/dist/parser/ast.js +0 -24
  167. package/dist/parser/ast.js.map +0 -1
  168. package/dist/parser/index.d.ts +0 -7
  169. package/dist/parser/index.d.ts.map +0 -1
  170. package/dist/parser/index.js +0 -7
  171. package/dist/parser/index.js.map +0 -1
  172. package/dist/parser/parser.d.ts +0 -92
  173. package/dist/parser/parser.d.ts.map +0 -1
  174. package/dist/parser/parser.js +0 -892
  175. package/dist/parser/parser.js.map +0 -1
  176. package/dist/parser/precedence.d.ts +0 -44
  177. package/dist/parser/precedence.d.ts.map +0 -1
  178. package/dist/parser/precedence.js +0 -69
  179. package/dist/parser/precedence.js.map +0 -1
  180. package/dist/renderer/expr-node.d.ts +0 -172
  181. package/dist/renderer/expr-node.d.ts.map +0 -1
  182. package/dist/renderer/expr-node.js +0 -218
  183. package/dist/renderer/expr-node.js.map +0 -1
  184. package/dist/renderer/fragment.d.ts +0 -84
  185. package/dist/renderer/fragment.d.ts.map +0 -1
  186. package/dist/renderer/fragment.js +0 -172
  187. package/dist/renderer/fragment.js.map +0 -1
  188. package/dist/renderer/index.d.ts +0 -23
  189. package/dist/renderer/index.d.ts.map +0 -1
  190. package/dist/renderer/index.js +0 -27
  191. package/dist/renderer/index.js.map +0 -1
  192. package/dist/renderer/patch-op.d.ts +0 -82
  193. package/dist/renderer/patch-op.d.ts.map +0 -1
  194. package/dist/renderer/patch-op.js +0 -204
  195. package/dist/renderer/patch-op.js.map +0 -1
  196. package/dist/renderer/type-expr.d.ts +0 -61
  197. package/dist/renderer/type-expr.d.ts.map +0 -1
  198. package/dist/renderer/type-expr.js +0 -131
  199. package/dist/renderer/type-expr.js.map +0 -1
  200. package/dist/vite.d.ts.map +0 -1
  201. package/loader.cjs +0 -22
package/dist/index.js CHANGED
@@ -1,44 +1,2190 @@
1
- /**
2
- * @manifesto-ai/compiler
3
- *
4
- * MEL (Manifesto Expression Language) compiler.
5
- * Provides lexer, parser, analyzer, lowering, evaluation, and rendering.
6
- */
7
- // ════════════════════════════════════════════════════════════════════════════
8
- // Lexer (MEL source → tokens)
9
- // ════════════════════════════════════════════════════════════════════════════
10
- export * from "./lexer/index.js";
11
- // ════════════════════════════════════════════════════════════════════════════
12
- // Parser (tokens → AST)
13
- // ════════════════════════════════════════════════════════════════════════════
14
- export * from "./parser/index.js";
15
- // ════════════════════════════════════════════════════════════════════════════
16
- // Analyzer (AST validation and scope analysis)
17
- // ════════════════════════════════════════════════════════════════════════════
18
- export * from "./analyzer/index.js";
19
- // ════════════════════════════════════════════════════════════════════════════
20
- // Diagnostics
21
- // ════════════════════════════════════════════════════════════════════════════
22
- export * from "./diagnostics/index.js";
23
- // ════════════════════════════════════════════════════════════════════════════
24
- // Generator (AST → IR)
25
- // ════════════════════════════════════════════════════════════════════════════
26
- export * from "./generator/index.js";
27
- // ════════════════════════════════════════════════════════════════════════════
28
- // MEL Renderer (PatchFragment → MEL text)
29
- // Re-export with namespace to avoid ExprNode conflict with parser
30
- // ════════════════════════════════════════════════════════════════════════════
31
- export { renderTypeExpr, renderTypeField, renderValue, renderExprNode, renderPatchOp, extractTypeName, renderFragment, renderFragments, renderFragmentsByKind, renderAsDomain, } from "./renderer/index.js";
32
- // ════════════════════════════════════════════════════════════════════════════
33
- // Lowering (MEL IR → Core IR)
34
- // ════════════════════════════════════════════════════════════════════════════
35
- export * from "./lowering/index.js";
36
- // ════════════════════════════════════════════════════════════════════════════
37
- // Evaluation (Core IR → Concrete Values)
38
- // ════════════════════════════════════════════════════════════════════════════
39
- export * from "./evaluation/index.js";
40
- // ════════════════════════════════════════════════════════════════════════════
41
- // Compile API (MEL Text Ingest)
42
- // ════════════════════════════════════════════════════════════════════════════
43
- export * from "./api/index.js";
1
+ import {
2
+ KEYWORDS,
3
+ Lexer,
4
+ LoweringError,
5
+ Parser,
6
+ Precedence,
7
+ RESERVED_KEYWORDS,
8
+ Scope,
9
+ ScopeAnalyzer,
10
+ SemanticValidator,
11
+ analyzeScope,
12
+ compileMelDomain,
13
+ compileMelPatch,
14
+ createError,
15
+ createInfo,
16
+ createLocation,
17
+ createPointLocation,
18
+ createPosition,
19
+ createToken,
20
+ createWarning,
21
+ filterBySeverity,
22
+ generate,
23
+ getBinaryPrecedence,
24
+ getKeywordKind,
25
+ hasErrors,
26
+ invalidKindForContext,
27
+ invalidShape,
28
+ invalidSysPath,
29
+ isBinaryOp,
30
+ isError,
31
+ isExprNode,
32
+ isKeyword,
33
+ isReserved,
34
+ isRightAssociative,
35
+ isStmtNode,
36
+ isUnaryOp,
37
+ lowerExprNode,
38
+ lowerRuntimePatch,
39
+ lowerRuntimePatches,
40
+ mergeLocations,
41
+ normalizeExpr,
42
+ normalizeFunctionCall,
43
+ parse,
44
+ tokenToBinaryOp,
45
+ tokenize,
46
+ unknownCallFn,
47
+ unknownNodeKind,
48
+ unsupportedBase,
49
+ validateSemantics
50
+ } from "./chunk-QP2LGMBA.js";
51
+
52
+ // src/diagnostics/codes.ts
53
+ var DIAGNOSTIC_CODES = {
54
+ // ============ Syntax Errors (E0xx) ============
55
+ E001: {
56
+ code: "E001",
57
+ message: "$system.* cannot be used in computed expressions (non-deterministic)",
58
+ category: "semantic"
59
+ },
60
+ E002: {
61
+ code: "E002",
62
+ message: "$system.* cannot be used in state initializers",
63
+ category: "semantic"
64
+ },
65
+ E003: {
66
+ code: "E003",
67
+ message: "Invalid $system reference",
68
+ category: "semantic"
69
+ },
70
+ E004: {
71
+ code: "E004",
72
+ message: "Identifier starts with reserved prefix '__sys__'",
73
+ category: "syntax"
74
+ },
75
+ // ============ v0.3.3 Errors (E0xx) ============
76
+ E005: {
77
+ code: "E005",
78
+ message: "available expression must be pure (no Effects, no $system.*)",
79
+ category: "semantic"
80
+ },
81
+ E006: {
82
+ code: "E006",
83
+ message: "fail must be inside a guard (when or once)",
84
+ category: "semantic"
85
+ },
86
+ E007: {
87
+ code: "E007",
88
+ message: "stop must be inside a guard (when or once)",
89
+ category: "semantic"
90
+ },
91
+ E008: {
92
+ code: "E008",
93
+ message: "stop message suggests waiting/pending - use 'Already processed' style instead",
94
+ category: "semantic"
95
+ },
96
+ E009: {
97
+ code: "E009",
98
+ message: "Primitive aggregation (sum, min, max) only allowed in computed",
99
+ category: "semantic"
100
+ },
101
+ E010: {
102
+ code: "E010",
103
+ message: "Primitive aggregation does not allow composition - use direct reference only",
104
+ category: "semantic"
105
+ },
106
+ E011: {
107
+ code: "E011",
108
+ message: "reduce/fold/scan is forbidden - use sum, min, max for aggregation",
109
+ category: "semantic"
110
+ },
111
+ // ============ Scope Errors (E1xx) ============
112
+ E_UNDEFINED: {
113
+ code: "E_UNDEFINED",
114
+ message: "Undefined identifier",
115
+ category: "semantic"
116
+ },
117
+ E_DUPLICATE: {
118
+ code: "E_DUPLICATE",
119
+ message: "Duplicate identifier",
120
+ category: "semantic"
121
+ },
122
+ E_INVALID_ACCESS: {
123
+ code: "E_INVALID_ACCESS",
124
+ message: "Invalid access to identifier in this context",
125
+ category: "semantic"
126
+ },
127
+ // ============ Statement Errors (E2xx) ============
128
+ E_UNGUARDED_STMT: {
129
+ code: "E_UNGUARDED_STMT",
130
+ message: "Statement must be inside a guard (when or once)",
131
+ category: "semantic"
132
+ },
133
+ E_UNGUARDED_PATCH: {
134
+ code: "E_UNGUARDED_PATCH",
135
+ message: "Patch must be inside a guard",
136
+ category: "semantic"
137
+ },
138
+ E_UNGUARDED_EFFECT: {
139
+ code: "E_UNGUARDED_EFFECT",
140
+ message: "Effect must be inside a guard",
141
+ category: "semantic"
142
+ },
143
+ // ============ Type Errors (E3xx) ============
144
+ E_ARG_COUNT: {
145
+ code: "E_ARG_COUNT",
146
+ message: "Wrong number of arguments",
147
+ category: "type"
148
+ },
149
+ E_TYPE_MISMATCH: {
150
+ code: "E_TYPE_MISMATCH",
151
+ message: "Type mismatch",
152
+ category: "type"
153
+ },
154
+ // ============ Warnings (W0xx) ============
155
+ W_NON_BOOL_COND: {
156
+ code: "W_NON_BOOL_COND",
157
+ message: "Condition may not be boolean",
158
+ category: "semantic"
159
+ },
160
+ W_UNUSED: {
161
+ code: "W_UNUSED",
162
+ message: "Unused identifier",
163
+ category: "semantic"
164
+ },
165
+ W012: {
166
+ code: "W012",
167
+ message: "Anonymous object type in state field - use named type declaration instead",
168
+ category: "type"
169
+ },
170
+ // ============ Lexer Errors ============
171
+ MEL_LEXER: {
172
+ code: "MEL_LEXER",
173
+ message: "Lexer error",
174
+ category: "syntax"
175
+ },
176
+ // ============ Parser Errors ============
177
+ MEL_PARSER: {
178
+ code: "MEL_PARSER",
179
+ message: "Parser error",
180
+ category: "syntax"
181
+ }
182
+ };
183
+ function getDiagnosticInfo(code) {
184
+ return DIAGNOSTIC_CODES[code];
185
+ }
186
+ function formatDiagnosticCode(code) {
187
+ const info = DIAGNOSTIC_CODES[code];
188
+ if (info) {
189
+ return `${code}: ${info.message}`;
190
+ }
191
+ return code;
192
+ }
193
+
194
+ // src/diagnostics/format.ts
195
+ function formatDiagnostic(diagnostic, source) {
196
+ const { code, message, location } = diagnostic;
197
+ if (!location || location.start.line === 0 && location.start.column === 0) {
198
+ return `[${code}] ${message}`;
199
+ }
200
+ const { line, column } = location.start;
201
+ const header = `[${code}] ${message} (${line}:${column})`;
202
+ if (!source) {
203
+ return header;
204
+ }
205
+ const sourceLines = source.split("\n");
206
+ const lineContent = sourceLines[line - 1];
207
+ if (!lineContent) {
208
+ return header;
209
+ }
210
+ const lineNumStr = String(line).padStart(4, " ");
211
+ const sourceLine = `${lineNumStr} | ${lineContent}`;
212
+ const underlineLen = Math.max(
213
+ 1,
214
+ location.end.line === location.start.line ? Math.min(location.end.column - column, lineContent.length - column + 1) : 1
215
+ );
216
+ const padding = " ".repeat(lineNumStr.length + 3 + column - 1);
217
+ const underline = `${padding}${"^".repeat(underlineLen)}`;
218
+ return `${header}
219
+ ${sourceLine}
220
+ ${underline}`;
221
+ }
222
+ function formatDiagnostics(diagnostics, source) {
223
+ return diagnostics.map((d) => formatDiagnostic(d, source)).join("\n\n");
224
+ }
225
+
226
+ // src/generator/lowering.ts
227
+ import {
228
+ hashSchemaSync,
229
+ semanticPathToPatchPath
230
+ } from "@manifesto-ai/core";
231
+ function lowerSystemValues(schema) {
232
+ const result = structuredClone(schema);
233
+ let lowered = false;
234
+ for (const [actionName, action] of Object.entries(result.actions)) {
235
+ const ctx = createContext(actionName);
236
+ collectSystemRefs(action.flow, ctx);
237
+ if (ctx.slots.size === 0) {
238
+ continue;
239
+ }
240
+ lowered = true;
241
+ for (const slot of ctx.slots.values()) {
242
+ result.state.fields[slot.valueSlot] = {
243
+ type: systemValueType(slot.key),
244
+ required: true,
245
+ default: null
246
+ };
247
+ result.state.fields[slot.intentSlot] = {
248
+ type: "string",
249
+ required: true,
250
+ default: null
251
+ };
252
+ }
253
+ result.actions[actionName] = {
254
+ ...action,
255
+ flow: lowerFlow(action.flow, ctx)
256
+ };
257
+ }
258
+ if (!lowered) {
259
+ return result;
260
+ }
261
+ const { hash: _hash, ...schemaWithoutHash } = result;
262
+ const nextHash = hashSchemaSync(schemaWithoutHash);
263
+ return {
264
+ ...schemaWithoutHash,
265
+ hash: nextHash
266
+ };
267
+ }
268
+ function createContext(actionName) {
269
+ return {
270
+ actionName,
271
+ slots: /* @__PURE__ */ new Map()
272
+ };
273
+ }
274
+ function systemValueType(key) {
275
+ switch (key) {
276
+ case "timestamp":
277
+ case "time.now":
278
+ return "number";
279
+ default:
280
+ return "string";
281
+ }
282
+ }
283
+ function normalizeSystemKeyForSlot(key) {
284
+ return key.replaceAll(".", "_");
285
+ }
286
+ function toPatchPath(path) {
287
+ return semanticPathToPatchPath(path);
288
+ }
289
+ function collectSystemRefs(flow, ctx) {
290
+ switch (flow.kind) {
291
+ case "seq":
292
+ for (const step of flow.steps) {
293
+ collectSystemRefs(step, ctx);
294
+ }
295
+ break;
296
+ case "if":
297
+ collectSystemRefsFromExpr(flow.cond, ctx);
298
+ collectSystemRefs(flow.then, ctx);
299
+ if (flow.else) {
300
+ collectSystemRefs(flow.else, ctx);
301
+ }
302
+ break;
303
+ case "patch":
304
+ if (flow.value) {
305
+ collectSystemRefsFromExpr(flow.value, ctx);
306
+ }
307
+ break;
308
+ case "effect":
309
+ for (const param of Object.values(flow.params)) {
310
+ collectSystemRefsFromExpr(param, ctx);
311
+ }
312
+ break;
313
+ case "fail":
314
+ if (flow.message) {
315
+ collectSystemRefsFromExpr(flow.message, ctx);
316
+ }
317
+ break;
318
+ }
319
+ }
320
+ function collectSystemRefsFromExpr(expr, ctx) {
321
+ if (expr.kind === "get" && expr.path.startsWith("$system.")) {
322
+ const key = expr.path.slice("$system.".length);
323
+ if (!ctx.slots.has(key)) {
324
+ const normalizedKey = normalizeSystemKeyForSlot(key);
325
+ ctx.slots.set(key, {
326
+ key,
327
+ valueSlot: `__sys__${ctx.actionName}_${normalizedKey}_value`,
328
+ intentSlot: `__sys__${ctx.actionName}_${normalizedKey}_intent`
329
+ });
330
+ }
331
+ return;
332
+ }
333
+ if (expr.kind === "object") {
334
+ for (const value of Object.values(expr.fields)) {
335
+ if (value && typeof value === "object" && "kind" in value) {
336
+ collectSystemRefsFromExpr(value, ctx);
337
+ }
338
+ }
339
+ return;
340
+ }
341
+ for (const value of Object.values(expr)) {
342
+ if (typeof value === "object" && value !== null) {
343
+ if (Array.isArray(value)) {
344
+ for (const item of value) {
345
+ if (typeof item === "object" && item !== null && "kind" in item) {
346
+ collectSystemRefsFromExpr(item, ctx);
347
+ }
348
+ }
349
+ } else if ("kind" in value) {
350
+ collectSystemRefsFromExpr(value, ctx);
351
+ }
352
+ }
353
+ }
354
+ }
355
+ function lowerFlow(flow, ctx) {
356
+ if (ctx.slots.size === 0) {
357
+ return flow;
358
+ }
359
+ const acquisitionSteps = [];
360
+ for (const slot of ctx.slots.values()) {
361
+ const acquisitionFlow = {
362
+ kind: "if",
363
+ cond: {
364
+ kind: "neq",
365
+ left: { kind: "get", path: slot.intentSlot },
366
+ right: { kind: "get", path: "meta.intentId" }
367
+ },
368
+ then: {
369
+ kind: "seq",
370
+ steps: [
371
+ {
372
+ kind: "patch",
373
+ op: "set",
374
+ path: toPatchPath(slot.intentSlot),
375
+ value: { kind: "get", path: "meta.intentId" }
376
+ },
377
+ {
378
+ kind: "effect",
379
+ type: "system.get",
380
+ params: {
381
+ key: { kind: "lit", value: slot.key },
382
+ into: { kind: "lit", value: slot.valueSlot }
383
+ }
384
+ }
385
+ ]
386
+ }
387
+ };
388
+ acquisitionSteps.push(acquisitionFlow);
389
+ }
390
+ const readinessConditions = [];
391
+ for (const slot of ctx.slots.values()) {
392
+ readinessConditions.push({
393
+ kind: "eq",
394
+ left: { kind: "get", path: slot.intentSlot },
395
+ right: { kind: "get", path: "meta.intentId" }
396
+ });
397
+ }
398
+ const readinessCond = readinessConditions.length === 1 ? readinessConditions[0] : { kind: "and", args: readinessConditions };
399
+ const transformedFlow = transformFlow(flow, ctx);
400
+ const guardedFlow = {
401
+ kind: "if",
402
+ cond: readinessCond,
403
+ then: transformedFlow
404
+ };
405
+ return {
406
+ kind: "seq",
407
+ steps: [...acquisitionSteps, guardedFlow]
408
+ };
409
+ }
410
+ function transformFlow(flow, ctx) {
411
+ switch (flow.kind) {
412
+ case "seq":
413
+ return {
414
+ kind: "seq",
415
+ steps: flow.steps.map((s) => transformFlow(s, ctx))
416
+ };
417
+ case "if":
418
+ return {
419
+ kind: "if",
420
+ cond: transformExpr(flow.cond, ctx),
421
+ then: transformFlow(flow.then, ctx),
422
+ else: flow.else ? transformFlow(flow.else, ctx) : void 0
423
+ };
424
+ case "patch":
425
+ return {
426
+ kind: "patch",
427
+ op: flow.op,
428
+ path: flow.path,
429
+ value: flow.value ? transformExpr(flow.value, ctx) : void 0
430
+ };
431
+ case "effect":
432
+ const params = {};
433
+ for (const [key, value] of Object.entries(flow.params)) {
434
+ params[key] = transformExpr(value, ctx);
435
+ }
436
+ return {
437
+ kind: "effect",
438
+ type: flow.type,
439
+ params
440
+ };
441
+ case "fail":
442
+ return {
443
+ kind: "fail",
444
+ code: flow.code,
445
+ message: flow.message ? transformExpr(flow.message, ctx) : void 0
446
+ };
447
+ default:
448
+ return flow;
449
+ }
450
+ }
451
+ function transformExpr(expr, ctx) {
452
+ if (expr.kind === "get" && expr.path.startsWith("$system.")) {
453
+ const key = expr.path.slice("$system.".length);
454
+ const slot = ctx.slots.get(key);
455
+ if (slot) {
456
+ return { kind: "get", path: slot.valueSlot };
457
+ }
458
+ }
459
+ switch (expr.kind) {
460
+ case "eq":
461
+ case "neq":
462
+ case "gt":
463
+ case "gte":
464
+ case "lt":
465
+ case "lte":
466
+ case "add":
467
+ case "sub":
468
+ case "mul":
469
+ case "div":
470
+ case "mod":
471
+ return {
472
+ kind: expr.kind,
473
+ left: transformExpr(expr.left, ctx),
474
+ right: transformExpr(expr.right, ctx)
475
+ };
476
+ case "and":
477
+ case "or":
478
+ case "coalesce":
479
+ case "concat":
480
+ case "min":
481
+ case "max":
482
+ case "merge":
483
+ return {
484
+ kind: expr.kind,
485
+ args: expr.args.map((a) => transformExpr(a, ctx))
486
+ };
487
+ case "not":
488
+ case "neg":
489
+ case "abs":
490
+ case "floor":
491
+ case "ceil":
492
+ case "round":
493
+ case "isNull":
494
+ case "typeof":
495
+ case "toString":
496
+ case "len":
497
+ case "keys":
498
+ case "values":
499
+ case "entries":
500
+ case "first":
501
+ case "last":
502
+ return {
503
+ kind: expr.kind,
504
+ arg: transformExpr(expr.arg, ctx)
505
+ };
506
+ case "trim":
507
+ case "toLowerCase":
508
+ case "toUpperCase":
509
+ case "strLen":
510
+ return {
511
+ kind: expr.kind,
512
+ str: transformExpr(expr.str, ctx)
513
+ };
514
+ case "at":
515
+ case "includes":
516
+ return {
517
+ kind: expr.kind,
518
+ array: transformExpr(expr.array, ctx),
519
+ index: transformExpr(expr.index ?? expr.item, ctx)
520
+ };
521
+ case "filter":
522
+ case "map":
523
+ case "find":
524
+ case "every":
525
+ case "some":
526
+ return {
527
+ kind: expr.kind,
528
+ array: transformExpr(expr.array, ctx),
529
+ predicate: transformExpr(expr.predicate ?? expr.mapper, ctx)
530
+ };
531
+ case "if":
532
+ return {
533
+ kind: "if",
534
+ cond: transformExpr(expr.cond, ctx),
535
+ then: transformExpr(expr.then, ctx),
536
+ else: transformExpr(expr.else, ctx)
537
+ };
538
+ case "field":
539
+ return {
540
+ kind: "field",
541
+ object: transformExpr(expr.object, ctx),
542
+ property: expr.property
543
+ };
544
+ case "object":
545
+ const fields = {};
546
+ for (const [key, value] of Object.entries(expr.fields)) {
547
+ fields[key] = transformExpr(value, ctx);
548
+ }
549
+ return { kind: "object", fields };
550
+ case "append":
551
+ return {
552
+ kind: "append",
553
+ array: transformExpr(expr.array, ctx),
554
+ items: expr.items.map((i) => transformExpr(i, ctx))
555
+ };
556
+ default:
557
+ return expr;
558
+ }
559
+ }
560
+
561
+ // src/renderer/type-expr.ts
562
+ function renderTypeExpr(typeExpr) {
563
+ switch (typeExpr.kind) {
564
+ case "primitive":
565
+ return typeExpr.name;
566
+ case "literal":
567
+ return renderLiteralValue(typeExpr.value);
568
+ case "ref":
569
+ return typeExpr.name;
570
+ case "array":
571
+ return `Array<${renderTypeExpr(typeExpr.element)}>`;
572
+ case "record":
573
+ return `Record<${renderTypeExpr(typeExpr.key)}, ${renderTypeExpr(typeExpr.value)}>`;
574
+ case "union":
575
+ return renderUnion(typeExpr.members);
576
+ case "object":
577
+ return renderObjectType(typeExpr.fields);
578
+ }
579
+ }
580
+ function renderLiteralValue(value) {
581
+ if (value === null) {
582
+ return "null";
583
+ }
584
+ if (typeof value === "string") {
585
+ return `"${escapeString(value)}"`;
586
+ }
587
+ if (typeof value === "boolean") {
588
+ return value ? "true" : "false";
589
+ }
590
+ return String(value);
591
+ }
592
+ function renderUnion(members) {
593
+ if (members.length === 0) {
594
+ return "never";
595
+ }
596
+ return members.map(renderTypeExpr).join(" | ");
597
+ }
598
+ function renderObjectType(fields) {
599
+ if (fields.length === 0) {
600
+ return "{}";
601
+ }
602
+ const fieldStrings = fields.map((field) => {
603
+ const optional = field.optional ? "?" : "";
604
+ return `${field.name}${optional}: ${renderTypeExpr(field.type)}`;
605
+ });
606
+ return `{ ${fieldStrings.join(", ")} }`;
607
+ }
608
+ function renderTypeField(field, defaultValue) {
609
+ const typeStr = renderTypeExpr(field.type);
610
+ if (defaultValue !== void 0) {
611
+ return `${field.name}: ${typeStr} = ${renderValue(defaultValue)}`;
612
+ }
613
+ if (field.optional) {
614
+ return `${field.name}?: ${typeStr}`;
615
+ }
616
+ return `${field.name}: ${typeStr}`;
617
+ }
618
+ function renderValue(value) {
619
+ if (value === null) {
620
+ return "null";
621
+ }
622
+ if (value === void 0) {
623
+ return "null";
624
+ }
625
+ if (typeof value === "string") {
626
+ return `"${escapeString(value)}"`;
627
+ }
628
+ if (typeof value === "number") {
629
+ return String(value);
630
+ }
631
+ if (typeof value === "boolean") {
632
+ return value ? "true" : "false";
633
+ }
634
+ if (Array.isArray(value)) {
635
+ const items = value.map(renderValue).join(", ");
636
+ return `[${items}]`;
637
+ }
638
+ if (typeof value === "object") {
639
+ const entries = Object.entries(value).map(([k, v]) => `${k}: ${renderValue(v)}`).join(", ");
640
+ return `{ ${entries} }`;
641
+ }
642
+ return String(value);
643
+ }
644
+ function escapeString(str) {
645
+ return str.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
646
+ }
647
+
648
+ // src/renderer/expr-node.ts
649
+ function renderExprNode(expr) {
650
+ switch (expr.kind) {
651
+ // Literals
652
+ case "lit":
653
+ return renderLiteral(expr.value);
654
+ case "get":
655
+ return renderPath(expr.path);
656
+ // Comparison (binary)
657
+ case "eq":
658
+ return `eq(${renderExprNode(expr.left)}, ${renderExprNode(expr.right)})`;
659
+ case "neq":
660
+ return `neq(${renderExprNode(expr.left)}, ${renderExprNode(expr.right)})`;
661
+ case "gt":
662
+ return `gt(${renderExprNode(expr.left)}, ${renderExprNode(expr.right)})`;
663
+ case "gte":
664
+ return `gte(${renderExprNode(expr.left)}, ${renderExprNode(expr.right)})`;
665
+ case "lt":
666
+ return `lt(${renderExprNode(expr.left)}, ${renderExprNode(expr.right)})`;
667
+ case "lte":
668
+ return `lte(${renderExprNode(expr.left)}, ${renderExprNode(expr.right)})`;
669
+ // Logical
670
+ case "and":
671
+ if (!expr.args || !Array.isArray(expr.args)) {
672
+ return `and(/* malformed: args undefined */)`;
673
+ }
674
+ return `and(${expr.args.map(renderExprNode).join(", ")})`;
675
+ case "or":
676
+ if (!expr.args || !Array.isArray(expr.args)) {
677
+ return `or(/* malformed: args undefined */)`;
678
+ }
679
+ return `or(${expr.args.map(renderExprNode).join(", ")})`;
680
+ case "not":
681
+ if (!expr.arg) {
682
+ return `not(/* malformed: arg undefined */)`;
683
+ }
684
+ return `not(${renderExprNode(expr.arg)})`;
685
+ // Conditional
686
+ case "if":
687
+ return `if(${renderExprNode(expr.cond)}, ${renderExprNode(expr.then)}, ${renderExprNode(expr.else)})`;
688
+ // Arithmetic
689
+ case "add":
690
+ return `add(${renderExprNode(expr.left)}, ${renderExprNode(expr.right)})`;
691
+ case "sub":
692
+ return `sub(${renderExprNode(expr.left)}, ${renderExprNode(expr.right)})`;
693
+ case "mul":
694
+ return `mul(${renderExprNode(expr.left)}, ${renderExprNode(expr.right)})`;
695
+ case "div":
696
+ return `div(${renderExprNode(expr.left)}, ${renderExprNode(expr.right)})`;
697
+ case "mod":
698
+ return `mod(${renderExprNode(expr.left)}, ${renderExprNode(expr.right)})`;
699
+ // String
700
+ case "concat":
701
+ if (!expr.args || !Array.isArray(expr.args)) {
702
+ return `concat(/* malformed: args undefined */)`;
703
+ }
704
+ return `concat(${expr.args.map(renderExprNode).join(", ")})`;
705
+ case "substring":
706
+ if (expr.end !== void 0) {
707
+ return `substring(${renderExprNode(expr.str)}, ${renderExprNode(expr.start)}, ${renderExprNode(expr.end)})`;
708
+ }
709
+ return `substring(${renderExprNode(expr.str)}, ${renderExprNode(expr.start)})`;
710
+ case "trim":
711
+ return `trim(${renderExprNode(expr.str)})`;
712
+ // Collection
713
+ case "len":
714
+ return `len(${renderExprNode(expr.arg)})`;
715
+ case "at":
716
+ return `at(${renderExprNode(expr.array)}, ${renderExprNode(expr.index)})`;
717
+ case "first":
718
+ return `first(${renderExprNode(expr.array)})`;
719
+ case "last":
720
+ return `last(${renderExprNode(expr.array)})`;
721
+ case "slice":
722
+ if (expr.end !== void 0) {
723
+ return `slice(${renderExprNode(expr.array)}, ${renderExprNode(expr.start)}, ${renderExprNode(expr.end)})`;
724
+ }
725
+ return `slice(${renderExprNode(expr.array)}, ${renderExprNode(expr.start)})`;
726
+ case "includes":
727
+ return `includes(${renderExprNode(expr.array)}, ${renderExprNode(expr.item)})`;
728
+ case "filter":
729
+ return `filter(${renderExprNode(expr.array)}, ${renderExprNode(expr.predicate)})`;
730
+ case "map":
731
+ return `map(${renderExprNode(expr.array)}, ${renderExprNode(expr.mapper)})`;
732
+ case "find":
733
+ return `find(${renderExprNode(expr.array)}, ${renderExprNode(expr.predicate)})`;
734
+ case "every":
735
+ return `every(${renderExprNode(expr.array)}, ${renderExprNode(expr.predicate)})`;
736
+ case "some":
737
+ return `some(${renderExprNode(expr.array)}, ${renderExprNode(expr.predicate)})`;
738
+ case "append":
739
+ if (!expr.items || !Array.isArray(expr.items)) {
740
+ return `append(${renderExprNode(expr.array)}, /* malformed: items undefined */)`;
741
+ }
742
+ return `append(${renderExprNode(expr.array)}, ${expr.items.map(renderExprNode).join(", ")})`;
743
+ // Object
744
+ case "object":
745
+ return renderObjectExpr(expr.fields);
746
+ case "field":
747
+ return `${renderExprNode(expr.object)}.${expr.property}`;
748
+ case "keys":
749
+ return `keys(${renderExprNode(expr.obj)})`;
750
+ case "values":
751
+ return `values(${renderExprNode(expr.obj)})`;
752
+ case "entries":
753
+ return `entries(${renderExprNode(expr.obj)})`;
754
+ case "merge":
755
+ if (!expr.objects || !Array.isArray(expr.objects)) {
756
+ return `merge(/* malformed: objects undefined */)`;
757
+ }
758
+ return `merge(${expr.objects.map(renderExprNode).join(", ")})`;
759
+ // Type
760
+ case "typeof":
761
+ return `typeof(${renderExprNode(expr.arg)})`;
762
+ case "isNull":
763
+ return `isNull(${renderExprNode(expr.arg)})`;
764
+ case "coalesce":
765
+ if (!expr.args || !Array.isArray(expr.args)) {
766
+ return `coalesce(/* malformed: args undefined */)`;
767
+ }
768
+ return `coalesce(${expr.args.map(renderExprNode).join(", ")})`;
769
+ default:
770
+ return `/* unknown: ${JSON.stringify(expr)} */`;
771
+ }
772
+ }
773
+ function renderLiteral(value) {
774
+ if (value === null) {
775
+ return "null";
776
+ }
777
+ if (value === void 0) {
778
+ return "null";
779
+ }
780
+ if (typeof value === "string") {
781
+ return `"${escapeString2(value)}"`;
782
+ }
783
+ if (typeof value === "number") {
784
+ return String(value);
785
+ }
786
+ if (typeof value === "boolean") {
787
+ return value ? "true" : "false";
788
+ }
789
+ if (Array.isArray(value)) {
790
+ const items = value.map(renderLiteral).join(", ");
791
+ return `[${items}]`;
792
+ }
793
+ if (typeof value === "object") {
794
+ const entries = Object.entries(value).map(([k, v]) => `${k}: ${renderLiteral(v)}`).join(", ");
795
+ return `{ ${entries} }`;
796
+ }
797
+ return String(value);
798
+ }
799
+ function renderPath(path) {
800
+ if (path.startsWith("$meta.")) {
801
+ return path;
802
+ }
803
+ if (path.startsWith("$system.")) {
804
+ return path;
805
+ }
806
+ if (path.startsWith("$input.")) {
807
+ return path;
808
+ }
809
+ if (path.startsWith("data.")) {
810
+ return path.slice(5);
811
+ }
812
+ return path;
813
+ }
814
+ function renderObjectExpr(fields) {
815
+ const entries = Object.entries(fields).map(([key, value]) => `${key}: ${renderExprNode(value)}`).join(", ");
816
+ return `{ ${entries} }`;
817
+ }
818
+ function escapeString2(str) {
819
+ return str.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
820
+ }
821
+
822
+ // src/renderer/patch-op.ts
823
+ import { parsePath } from "@manifesto-ai/core";
824
+ var DEFAULT_OPTIONS = {
825
+ indent: " ",
826
+ includeComments: false,
827
+ commentPrefix: "// "
828
+ };
829
+ function renderPatchOp(op, options) {
830
+ const opts = { ...DEFAULT_OPTIONS, ...options };
831
+ switch (op.kind) {
832
+ case "addType":
833
+ return renderAddType(op, opts);
834
+ case "addField":
835
+ return renderAddField(op, opts);
836
+ case "setFieldType":
837
+ return renderSetFieldType(op, opts);
838
+ case "setDefaultValue":
839
+ return renderSetDefaultValue(op, opts);
840
+ case "addConstraint":
841
+ return renderAddConstraint(op, opts);
842
+ case "addComputed":
843
+ return renderAddComputed(op, opts);
844
+ case "addActionAvailable":
845
+ return renderAddActionAvailable(op, opts);
846
+ default:
847
+ return `// Unknown operation: ${JSON.stringify(op)}`;
848
+ }
849
+ }
850
+ function renderAddType(op, opts) {
851
+ const { indent } = opts;
852
+ if (op.typeExpr.kind === "object") {
853
+ const fields = op.typeExpr.fields.map((field) => `${indent}${renderTypeField(field)}`).join("\n");
854
+ return `type ${op.typeName} {
855
+ ${fields}
856
+ }`;
857
+ }
858
+ return `type ${op.typeName} = ${renderTypeExpr(op.typeExpr)}`;
859
+ }
860
+ function renderAddField(op, _opts) {
861
+ const field = op.field;
862
+ if ("defaultValue" in field && field.defaultValue !== void 0) {
863
+ return renderTypeField(field, field.defaultValue);
864
+ }
865
+ return renderTypeField(field);
866
+ }
867
+ function renderSetFieldType(op, opts) {
868
+ const typeStr = renderTypeExpr(op.typeExpr);
869
+ const fieldName = extractFieldName(op.path);
870
+ const lines = [];
871
+ if (opts.includeComments) {
872
+ lines.push(`${opts.commentPrefix}Change ${op.path} type to: ${typeStr}`);
873
+ }
874
+ lines.push(`${fieldName}: ${typeStr}`);
875
+ return lines.join("\n");
876
+ }
877
+ function renderSetDefaultValue(op, opts) {
878
+ const fieldName = extractFieldName(op.path);
879
+ const valueStr = renderValue(op.value);
880
+ const lines = [];
881
+ if (opts.includeComments) {
882
+ lines.push(`${opts.commentPrefix}Set default value for ${op.path}`);
883
+ }
884
+ lines.push(`${fieldName} = ${valueStr}`);
885
+ return lines.join("\n");
886
+ }
887
+ function renderAddConstraint(op, opts) {
888
+ const exprStr = renderExprNode(op.rule);
889
+ const messageStr = op.message ? ` - "${op.message}"` : "";
890
+ return `${opts.commentPrefix}Constraint on ${op.targetPath}: ${exprStr}${messageStr}`;
891
+ }
892
+ function renderAddComputed(op, opts) {
893
+ const exprStr = renderExprNode(op.expr);
894
+ const lines = [];
895
+ if (opts.includeComments && op.deps && op.deps.length > 0) {
896
+ lines.push(`${opts.commentPrefix}Dependencies: ${op.deps.join(", ")}`);
897
+ }
898
+ lines.push(`computed ${op.name} = ${exprStr}`);
899
+ return lines.join("\n");
900
+ }
901
+ function renderAddActionAvailable(op, opts) {
902
+ const exprStr = renderExprNode(op.expr);
903
+ const lines = [];
904
+ if (opts.includeComments) {
905
+ lines.push(`${opts.commentPrefix}Add availability condition to ${op.actionName}`);
906
+ }
907
+ lines.push(`action ${op.actionName}() available when ${exprStr} {`);
908
+ lines.push(`${opts.indent}// action body...`);
909
+ lines.push(`}`);
910
+ return lines.join("\n");
911
+ }
912
+ function extractFieldName(path) {
913
+ const parts = parsePath(path);
914
+ return parts[parts.length - 1] ?? "";
915
+ }
916
+ function extractTypeName(path) {
917
+ const parts = parsePath(path);
918
+ if (parts.length >= 2) {
919
+ return parts[0];
920
+ }
921
+ return void 0;
922
+ }
923
+
924
+ // src/renderer/fragment.ts
925
+ var DEFAULT_FRAGMENT_OPTIONS = {
926
+ indent: " ",
927
+ includeComments: true,
928
+ commentPrefix: "// ",
929
+ includeMetadata: true,
930
+ includeEvidence: false,
931
+ includeConfidence: true,
932
+ includeFragmentId: false
933
+ };
934
+ function renderFragment(fragment, options) {
935
+ const opts = { ...DEFAULT_FRAGMENT_OPTIONS, ...options };
936
+ const lines = [];
937
+ if (opts.includeMetadata) {
938
+ if (opts.includeFragmentId) {
939
+ lines.push(`${opts.commentPrefix}Fragment: ${fragment.fragmentId}`);
940
+ }
941
+ if (opts.includeConfidence) {
942
+ const confidencePercent = (fragment.confidence * 100).toFixed(0);
943
+ lines.push(`${opts.commentPrefix}Confidence: ${confidencePercent}%`);
944
+ }
945
+ if (opts.includeEvidence && fragment.evidence.length > 0) {
946
+ lines.push(`${opts.commentPrefix}Evidence:`);
947
+ for (const evidence of fragment.evidence) {
948
+ lines.push(`${opts.commentPrefix} - ${evidence}`);
949
+ }
950
+ }
951
+ }
952
+ const opStr = renderPatchOp(fragment.op, {
953
+ indent: opts.indent,
954
+ includeComments: opts.includeComments,
955
+ commentPrefix: opts.commentPrefix
956
+ });
957
+ lines.push(opStr);
958
+ return lines.join("\n");
959
+ }
960
+ function renderFragments(fragments, options) {
961
+ const opts = { ...DEFAULT_FRAGMENT_OPTIONS, ...options };
962
+ const renderedFragments = fragments.map(
963
+ (fragment) => renderFragment(fragment, opts)
964
+ );
965
+ return renderedFragments.join("\n\n");
966
+ }
967
+ function renderFragmentsByKind(fragments, options) {
968
+ const opts = { ...DEFAULT_FRAGMENT_OPTIONS, ...options };
969
+ const grouped = {};
970
+ for (const fragment of fragments) {
971
+ const kind = fragment.op.kind;
972
+ if (!grouped[kind]) {
973
+ grouped[kind] = [];
974
+ }
975
+ grouped[kind].push(fragment);
976
+ }
977
+ const result = {};
978
+ for (const [kind, kindFragments] of Object.entries(grouped)) {
979
+ result[kind] = renderFragments(kindFragments, opts);
980
+ }
981
+ return result;
982
+ }
983
+ function renderAsDomain(domainName, fragments, options) {
984
+ const opts = { ...DEFAULT_FRAGMENT_OPTIONS, ...options };
985
+ const indent = opts.indent ?? " ";
986
+ const types = [];
987
+ const fields = [];
988
+ const defaults = [];
989
+ const computed = [];
990
+ const constraints = [];
991
+ const actions = [];
992
+ for (const fragment of fragments) {
993
+ switch (fragment.op.kind) {
994
+ case "addType":
995
+ types.push(fragment);
996
+ break;
997
+ case "addField":
998
+ case "setFieldType":
999
+ fields.push(fragment);
1000
+ break;
1001
+ case "setDefaultValue":
1002
+ defaults.push(fragment);
1003
+ break;
1004
+ case "addComputed":
1005
+ computed.push(fragment);
1006
+ break;
1007
+ case "addConstraint":
1008
+ constraints.push(fragment);
1009
+ break;
1010
+ case "addActionAvailable":
1011
+ actions.push(fragment);
1012
+ break;
1013
+ }
1014
+ }
1015
+ const lines = [];
1016
+ lines.push(`domain ${domainName} {`);
1017
+ if (fields.length > 0 || defaults.length > 0) {
1018
+ lines.push(`${indent}state {`);
1019
+ for (const fragment of [...fields, ...defaults]) {
1020
+ const rendered = renderPatchOp(fragment.op, { indent: indent + indent, includeComments: false });
1021
+ lines.push(`${indent}${indent}${rendered}`);
1022
+ }
1023
+ lines.push(`${indent}}`);
1024
+ lines.push("");
1025
+ }
1026
+ for (const fragment of types) {
1027
+ const rendered = renderPatchOp(fragment.op, { indent, includeComments: false });
1028
+ const indented = rendered.split("\n").map((line) => `${indent}${line}`).join("\n");
1029
+ lines.push(indented);
1030
+ lines.push("");
1031
+ }
1032
+ for (const fragment of computed) {
1033
+ const rendered = renderPatchOp(fragment.op, { indent, includeComments: false });
1034
+ lines.push(`${indent}${rendered}`);
1035
+ }
1036
+ if (computed.length > 0) lines.push("");
1037
+ for (const fragment of constraints) {
1038
+ const rendered = renderPatchOp(fragment.op, { indent, includeComments: true });
1039
+ lines.push(`${indent}${rendered}`);
1040
+ }
1041
+ if (constraints.length > 0) lines.push("");
1042
+ for (const fragment of actions) {
1043
+ const rendered = renderPatchOp(fragment.op, { indent, includeComments: false });
1044
+ const indented = rendered.split("\n").map((line) => `${indent}${line}`).join("\n");
1045
+ lines.push(indented);
1046
+ lines.push("");
1047
+ }
1048
+ lines.push("}");
1049
+ return lines.join("\n");
1050
+ }
1051
+
1052
+ // src/lowering/context.ts
1053
+ var DEFAULT_SCHEMA_CONTEXT = {
1054
+ mode: "schema",
1055
+ allowSysPaths: { prefixes: ["meta", "input"] },
1056
+ fnTableVersion: "1.0",
1057
+ allowItem: false
1058
+ };
1059
+ var DEFAULT_ACTION_CONTEXT = {
1060
+ mode: "action",
1061
+ allowSysPaths: { prefixes: ["meta", "input"] },
1062
+ fnTableVersion: "1.0",
1063
+ allowItem: false
1064
+ };
1065
+ var EFFECT_ARGS_CONTEXT = {
1066
+ mode: "action",
1067
+ allowSysPaths: { prefixes: ["meta", "input"] },
1068
+ fnTableVersion: "1.0",
1069
+ allowItem: true
1070
+ };
1071
+ var DEFAULT_PATCH_CONTEXT = {
1072
+ allowSysPaths: { prefixes: ["meta", "input"] },
1073
+ fnTableVersion: "1.0"
1074
+ };
1075
+
1076
+ // src/lowering/lower-patch.ts
1077
+ function lowerPatchFragments(fragments, ctx) {
1078
+ return fragments.map((fragment) => lowerPatchFragment(fragment, ctx));
1079
+ }
1080
+ function lowerPatchFragment(fragment, ctx) {
1081
+ const condition = fragment.condition ? lowerExprNode(fragment.condition, createExprContext(ctx, "action")) : void 0;
1082
+ const op = lowerPatchOp(fragment.op, ctx);
1083
+ return {
1084
+ fragmentId: fragment.fragmentId,
1085
+ condition,
1086
+ op,
1087
+ confidence: fragment.confidence
1088
+ };
1089
+ }
1090
+ function lowerPatchOp(op, ctx) {
1091
+ switch (op.kind) {
1092
+ case "addType":
1093
+ return {
1094
+ kind: "addType",
1095
+ typeName: op.typeName,
1096
+ typeExpr: lowerTypeExpr(op.typeExpr)
1097
+ };
1098
+ case "addField":
1099
+ return {
1100
+ kind: "addField",
1101
+ typeName: op.typeName,
1102
+ field: {
1103
+ name: op.field.name,
1104
+ type: lowerTypeExpr(op.field.type),
1105
+ optional: op.field.optional,
1106
+ defaultValue: op.field.defaultValue
1107
+ }
1108
+ };
1109
+ case "setFieldType":
1110
+ return {
1111
+ kind: "setFieldType",
1112
+ path: op.path,
1113
+ typeExpr: lowerTypeExpr(op.typeExpr)
1114
+ };
1115
+ case "setDefaultValue":
1116
+ return {
1117
+ kind: "setDefaultValue",
1118
+ path: op.path,
1119
+ value: op.value
1120
+ };
1121
+ case "addConstraint":
1122
+ return {
1123
+ kind: "addConstraint",
1124
+ targetPath: op.targetPath,
1125
+ rule: lowerExprNode(op.rule, createExprContext(ctx, "schema")),
1126
+ message: op.message
1127
+ };
1128
+ case "addComputed":
1129
+ return {
1130
+ kind: "addComputed",
1131
+ name: op.name,
1132
+ expr: lowerExprNode(op.expr, createExprContext(ctx, "schema")),
1133
+ deps: op.deps
1134
+ };
1135
+ case "addActionAvailable":
1136
+ return {
1137
+ kind: "addActionAvailable",
1138
+ actionName: op.actionName,
1139
+ expr: lowerExprNode(op.expr, createExprContext(ctx, "schema"))
1140
+ };
1141
+ }
1142
+ }
1143
+ function lowerTypeExpr(typeExpr) {
1144
+ switch (typeExpr.kind) {
1145
+ case "primitive":
1146
+ return { kind: "primitive", name: typeExpr.name };
1147
+ case "array":
1148
+ return { kind: "array", element: lowerTypeExpr(typeExpr.element) };
1149
+ case "object":
1150
+ return {
1151
+ kind: "object",
1152
+ fields: typeExpr.fields.map((f) => ({
1153
+ name: f.name,
1154
+ type: lowerTypeExpr(f.type),
1155
+ optional: f.optional
1156
+ }))
1157
+ };
1158
+ case "union":
1159
+ return {
1160
+ kind: "union",
1161
+ members: typeExpr.members.map(lowerTypeExpr)
1162
+ };
1163
+ case "literal":
1164
+ return { kind: "literal", value: typeExpr.value };
1165
+ case "ref":
1166
+ return { kind: "ref", name: typeExpr.name };
1167
+ }
1168
+ }
1169
+ function createExprContext(patchCtx, mode) {
1170
+ return {
1171
+ mode,
1172
+ allowSysPaths: patchCtx.allowSysPaths,
1173
+ fnTableVersion: patchCtx.fnTableVersion,
1174
+ actionName: patchCtx.actionName,
1175
+ allowItem: false
1176
+ // Only true for effect.args (not in schema ops)
1177
+ };
1178
+ }
1179
+
1180
+ // src/evaluation/context.ts
1181
+ import { parsePath as parsePath2 } from "@manifesto-ai/core";
1182
+ function createEvaluationContext(options) {
1183
+ return {
1184
+ snapshot: options.snapshot ?? { data: {}, computed: {} },
1185
+ meta: options.meta,
1186
+ input: options.input ?? {},
1187
+ item: options.item
1188
+ };
1189
+ }
1190
+ function applyPatchToWorkingSnapshot(snapshot, path, value) {
1191
+ const newData = structuredClone(snapshot.data);
1192
+ setValueAtPath(newData, path, value);
1193
+ return {
1194
+ data: newData,
1195
+ computed: snapshot.computed
1196
+ };
1197
+ }
1198
+ function setValueAtPath(obj, path, value) {
1199
+ const parts = parsePath2(path);
1200
+ let current = obj;
1201
+ for (let i = 0; i < parts.length - 1; i++) {
1202
+ const part = parts[i];
1203
+ if (!(part in current) || typeof current[part] !== "object") {
1204
+ current[part] = {};
1205
+ }
1206
+ current = current[part];
1207
+ }
1208
+ const lastPart = parts[parts.length - 1];
1209
+ current[lastPart] = value;
1210
+ }
1211
+
1212
+ // src/evaluation/evaluate-expr.ts
1213
+ import { parsePath as parsePath3 } from "@manifesto-ai/core";
1214
+ function evaluateExpr(expr, ctx) {
1215
+ try {
1216
+ return evaluateNode(expr, ctx);
1217
+ } catch {
1218
+ return null;
1219
+ }
1220
+ }
1221
+ function evaluateNode(expr, ctx) {
1222
+ switch (expr.kind) {
1223
+ // Literals
1224
+ case "lit":
1225
+ return expr.value;
1226
+ case "get":
1227
+ return resolvePath(expr.path, ctx);
1228
+ // Comparison
1229
+ case "eq":
1230
+ return evaluateEq(expr.left, expr.right, ctx);
1231
+ case "neq":
1232
+ return evaluateNeq(expr.left, expr.right, ctx);
1233
+ case "gt":
1234
+ return evaluateComparison(expr.left, expr.right, ctx, (a, b) => a > b);
1235
+ case "gte":
1236
+ return evaluateComparison(expr.left, expr.right, ctx, (a, b) => a >= b);
1237
+ case "lt":
1238
+ return evaluateComparison(expr.left, expr.right, ctx, (a, b) => a < b);
1239
+ case "lte":
1240
+ return evaluateComparison(expr.left, expr.right, ctx, (a, b) => a <= b);
1241
+ // Logical
1242
+ case "and":
1243
+ return evaluateAnd(expr.args, ctx);
1244
+ case "or":
1245
+ return evaluateOr(expr.args, ctx);
1246
+ case "not":
1247
+ return evaluateNot(expr.arg, ctx);
1248
+ // Conditional
1249
+ case "if":
1250
+ return evaluateIf(expr.cond, expr.then, expr.else, ctx);
1251
+ // Arithmetic
1252
+ case "add":
1253
+ return evaluateArithmetic(expr.left, expr.right, ctx, (a, b) => a + b);
1254
+ case "sub":
1255
+ return evaluateArithmetic(expr.left, expr.right, ctx, (a, b) => a - b);
1256
+ case "mul":
1257
+ return evaluateArithmetic(expr.left, expr.right, ctx, (a, b) => a * b);
1258
+ case "div":
1259
+ return evaluateDiv(expr.left, expr.right, ctx);
1260
+ case "mod":
1261
+ return evaluateMod(expr.left, expr.right, ctx);
1262
+ // String
1263
+ case "concat":
1264
+ return evaluateConcat(expr.args, ctx);
1265
+ case "substring":
1266
+ return evaluateSubstring(expr.str, expr.start, expr.end, ctx);
1267
+ case "trim":
1268
+ return evaluateTrim(expr.str, ctx);
1269
+ // Collection
1270
+ case "len":
1271
+ return evaluateLen(expr.arg, ctx);
1272
+ case "at":
1273
+ return evaluateAt(expr.array, expr.index, ctx);
1274
+ case "first":
1275
+ return evaluateFirst(expr.array, ctx);
1276
+ case "last":
1277
+ return evaluateLast(expr.array, ctx);
1278
+ case "slice":
1279
+ return evaluateSlice(expr.array, expr.start, expr.end, ctx);
1280
+ case "includes":
1281
+ return evaluateIncludes(expr.array, expr.item, ctx);
1282
+ case "filter":
1283
+ return evaluateFilter(expr.array, expr.predicate, ctx);
1284
+ case "map":
1285
+ return evaluateMap(expr.array, expr.mapper, ctx);
1286
+ case "find":
1287
+ return evaluateFind(expr.array, expr.predicate, ctx);
1288
+ case "every":
1289
+ return evaluateEvery(expr.array, expr.predicate, ctx);
1290
+ case "some":
1291
+ return evaluateSome(expr.array, expr.predicate, ctx);
1292
+ case "append":
1293
+ return evaluateAppend(expr.array, expr.items, ctx);
1294
+ // Object
1295
+ case "object":
1296
+ return evaluateObject(expr.fields, ctx);
1297
+ case "field":
1298
+ return evaluateFieldAccess(expr.object, expr.property, ctx);
1299
+ case "keys":
1300
+ return evaluateKeys(expr.obj, ctx);
1301
+ case "values":
1302
+ return evaluateValues(expr.obj, ctx);
1303
+ case "entries":
1304
+ return evaluateEntries(expr.obj, ctx);
1305
+ case "merge":
1306
+ return evaluateMerge(expr.objects, ctx);
1307
+ // Type
1308
+ case "typeof":
1309
+ return evaluateTypeof(expr.arg, ctx);
1310
+ case "isNull":
1311
+ return evaluateIsNull(expr.arg, ctx);
1312
+ case "coalesce":
1313
+ return evaluateCoalesce(expr.args, ctx);
1314
+ default:
1315
+ return null;
1316
+ }
1317
+ }
1318
+ function resolvePath(path, ctx) {
1319
+ const parts = parsePath3(path);
1320
+ if (parts[0] === "meta") {
1321
+ return getValueAtPath(ctx.meta, parts.slice(1));
1322
+ }
1323
+ if (parts[0] === "input") {
1324
+ return getValueAtPath(ctx.input, parts.slice(1));
1325
+ }
1326
+ if (parts[0] === "$item") {
1327
+ if (ctx.item === void 0) {
1328
+ return null;
1329
+ }
1330
+ if (parts.length === 1) {
1331
+ return ctx.item;
1332
+ }
1333
+ return getValueAtPath(ctx.item, parts.slice(1));
1334
+ }
1335
+ if (path in ctx.snapshot.computed) {
1336
+ return ctx.snapshot.computed[path];
1337
+ }
1338
+ return getValueAtPath(ctx.snapshot.data, parts);
1339
+ }
1340
+ function getValueAtPath(obj, parts) {
1341
+ if (parts.length === 0) {
1342
+ return obj;
1343
+ }
1344
+ if (obj === null || obj === void 0) {
1345
+ return null;
1346
+ }
1347
+ if (typeof obj !== "object") {
1348
+ return null;
1349
+ }
1350
+ const [head, ...rest] = parts;
1351
+ const next = obj[head];
1352
+ if (rest.length === 0) {
1353
+ return next === void 0 ? null : next;
1354
+ }
1355
+ return getValueAtPath(next, rest);
1356
+ }
1357
+ function evaluateEq(left, right, ctx) {
1358
+ const l = evaluateNode(left, ctx);
1359
+ const r = evaluateNode(right, ctx);
1360
+ return deepEqual(l, r);
1361
+ }
1362
+ function evaluateNeq(left, right, ctx) {
1363
+ const result = evaluateEq(left, right, ctx);
1364
+ if (result === null) return null;
1365
+ return !result;
1366
+ }
1367
+ function evaluateComparison(left, right, ctx, compare) {
1368
+ const l = evaluateNode(left, ctx);
1369
+ const r = evaluateNode(right, ctx);
1370
+ if (typeof l !== "number" || typeof r !== "number") {
1371
+ return null;
1372
+ }
1373
+ return compare(l, r);
1374
+ }
1375
+ function deepEqual(a, b) {
1376
+ if (a === b) return true;
1377
+ if (a === null || b === null) return a === b;
1378
+ if (typeof a !== typeof b) return false;
1379
+ if (Array.isArray(a) && Array.isArray(b)) {
1380
+ if (a.length !== b.length) return false;
1381
+ return a.every((item, i) => deepEqual(item, b[i]));
1382
+ }
1383
+ if (typeof a === "object" && typeof b === "object") {
1384
+ const aKeys = Object.keys(a);
1385
+ const bKeys = Object.keys(b);
1386
+ if (aKeys.length !== bKeys.length) return false;
1387
+ return aKeys.every(
1388
+ (key) => Object.prototype.hasOwnProperty.call(b, key) && deepEqual(
1389
+ a[key],
1390
+ b[key]
1391
+ )
1392
+ );
1393
+ }
1394
+ return false;
1395
+ }
1396
+ function evaluateAnd(args, ctx) {
1397
+ for (const arg of args) {
1398
+ const result = evaluateNode(arg, ctx);
1399
+ if (result !== true) {
1400
+ return result === false ? false : null;
1401
+ }
1402
+ }
1403
+ return true;
1404
+ }
1405
+ function evaluateOr(args, ctx) {
1406
+ for (const arg of args) {
1407
+ const result = evaluateNode(arg, ctx);
1408
+ if (result === true) {
1409
+ return true;
1410
+ }
1411
+ if (result !== false) {
1412
+ return null;
1413
+ }
1414
+ }
1415
+ return false;
1416
+ }
1417
+ function evaluateNot(arg, ctx) {
1418
+ const result = evaluateNode(arg, ctx);
1419
+ if (typeof result !== "boolean") {
1420
+ return null;
1421
+ }
1422
+ return !result;
1423
+ }
1424
+ function evaluateIf(cond, thenExpr, elseExpr, ctx) {
1425
+ const condResult = evaluateNode(cond, ctx);
1426
+ if (condResult === true) {
1427
+ return evaluateNode(thenExpr, ctx);
1428
+ }
1429
+ if (condResult === false) {
1430
+ return evaluateNode(elseExpr, ctx);
1431
+ }
1432
+ return null;
1433
+ }
1434
+ function evaluateArithmetic(left, right, ctx, op) {
1435
+ const l = evaluateNode(left, ctx);
1436
+ const r = evaluateNode(right, ctx);
1437
+ if (typeof l !== "number" || typeof r !== "number") {
1438
+ return null;
1439
+ }
1440
+ const result = op(l, r);
1441
+ if (!Number.isFinite(result)) {
1442
+ return null;
1443
+ }
1444
+ return result;
1445
+ }
1446
+ function evaluateDiv(left, right, ctx) {
1447
+ const l = evaluateNode(left, ctx);
1448
+ const r = evaluateNode(right, ctx);
1449
+ if (typeof l !== "number" || typeof r !== "number") {
1450
+ return null;
1451
+ }
1452
+ if (r === 0) {
1453
+ return null;
1454
+ }
1455
+ return l / r;
1456
+ }
1457
+ function evaluateMod(left, right, ctx) {
1458
+ const l = evaluateNode(left, ctx);
1459
+ const r = evaluateNode(right, ctx);
1460
+ if (typeof l !== "number" || typeof r !== "number") {
1461
+ return null;
1462
+ }
1463
+ if (r === 0) {
1464
+ return null;
1465
+ }
1466
+ return l % r;
1467
+ }
1468
+ function evaluateConcat(args, ctx) {
1469
+ const values = [];
1470
+ for (const arg of args) {
1471
+ const val = evaluateNode(arg, ctx);
1472
+ if (typeof val !== "string") {
1473
+ return null;
1474
+ }
1475
+ values.push(val);
1476
+ }
1477
+ return values.join("");
1478
+ }
1479
+ function evaluateSubstring(str, start, end, ctx) {
1480
+ const s = evaluateNode(str, ctx);
1481
+ const startIdx = evaluateNode(start, ctx);
1482
+ if (typeof s !== "string" || typeof startIdx !== "number") {
1483
+ return null;
1484
+ }
1485
+ if (end === void 0) {
1486
+ return s.substring(startIdx);
1487
+ }
1488
+ const endIdx = evaluateNode(end, ctx);
1489
+ if (typeof endIdx !== "number") {
1490
+ return null;
1491
+ }
1492
+ return s.substring(startIdx, endIdx);
1493
+ }
1494
+ function evaluateTrim(str, ctx) {
1495
+ const s = evaluateNode(str, ctx);
1496
+ if (typeof s !== "string") {
1497
+ return null;
1498
+ }
1499
+ return s.trim();
1500
+ }
1501
+ function evaluateLen(arg, ctx) {
1502
+ const val = evaluateNode(arg, ctx);
1503
+ if (Array.isArray(val)) {
1504
+ return val.length;
1505
+ }
1506
+ if (typeof val === "string") {
1507
+ return val.length;
1508
+ }
1509
+ if (val !== null && typeof val === "object") {
1510
+ return Object.keys(val).length;
1511
+ }
1512
+ return null;
1513
+ }
1514
+ function evaluateAt(array, index, ctx) {
1515
+ const base = evaluateNode(array, ctx);
1516
+ const key = evaluateNode(index, ctx);
1517
+ if (Array.isArray(base) && typeof key === "number") {
1518
+ if (key < 0 || key >= base.length) {
1519
+ return null;
1520
+ }
1521
+ return base[key];
1522
+ }
1523
+ if (typeof base === "object" && base !== null && !Array.isArray(base) && typeof key === "string") {
1524
+ return base[key] ?? null;
1525
+ }
1526
+ return null;
1527
+ }
1528
+ function evaluateFirst(array, ctx) {
1529
+ const arr = evaluateNode(array, ctx);
1530
+ if (!Array.isArray(arr) || arr.length === 0) {
1531
+ return null;
1532
+ }
1533
+ return arr[0];
1534
+ }
1535
+ function evaluateLast(array, ctx) {
1536
+ const arr = evaluateNode(array, ctx);
1537
+ if (!Array.isArray(arr) || arr.length === 0) {
1538
+ return null;
1539
+ }
1540
+ return arr[arr.length - 1];
1541
+ }
1542
+ function evaluateSlice(array, start, end, ctx) {
1543
+ const arr = evaluateNode(array, ctx);
1544
+ const startIdx = evaluateNode(start, ctx);
1545
+ if (!Array.isArray(arr) || typeof startIdx !== "number") {
1546
+ return null;
1547
+ }
1548
+ if (end === void 0) {
1549
+ return arr.slice(startIdx);
1550
+ }
1551
+ const endIdx = evaluateNode(end, ctx);
1552
+ if (typeof endIdx !== "number") {
1553
+ return null;
1554
+ }
1555
+ return arr.slice(startIdx, endIdx);
1556
+ }
1557
+ function evaluateIncludes(array, item, ctx) {
1558
+ const arr = evaluateNode(array, ctx);
1559
+ const val = evaluateNode(item, ctx);
1560
+ if (!Array.isArray(arr)) {
1561
+ return null;
1562
+ }
1563
+ return arr.some((el) => deepEqual(el, val));
1564
+ }
1565
+ function evaluateFilter(array, predicate, ctx) {
1566
+ const arr = evaluateNode(array, ctx);
1567
+ if (!Array.isArray(arr)) {
1568
+ return null;
1569
+ }
1570
+ const result = [];
1571
+ for (const item of arr) {
1572
+ const itemCtx = { ...ctx, item };
1573
+ const keep = evaluateNode(predicate, itemCtx);
1574
+ if (keep === true) {
1575
+ result.push(item);
1576
+ } else if (keep !== false) {
1577
+ return null;
1578
+ }
1579
+ }
1580
+ return result;
1581
+ }
1582
+ function evaluateMap(array, mapper, ctx) {
1583
+ const arr = evaluateNode(array, ctx);
1584
+ if (!Array.isArray(arr)) {
1585
+ return null;
1586
+ }
1587
+ const result = [];
1588
+ for (const item of arr) {
1589
+ const itemCtx = { ...ctx, item };
1590
+ const mapped = evaluateNode(mapper, itemCtx);
1591
+ result.push(mapped);
1592
+ }
1593
+ return result;
1594
+ }
1595
+ function evaluateFind(array, predicate, ctx) {
1596
+ const arr = evaluateNode(array, ctx);
1597
+ if (!Array.isArray(arr)) {
1598
+ return null;
1599
+ }
1600
+ for (const item of arr) {
1601
+ const itemCtx = { ...ctx, item };
1602
+ const match = evaluateNode(predicate, itemCtx);
1603
+ if (match === true) {
1604
+ return item;
1605
+ }
1606
+ if (match !== false) {
1607
+ return null;
1608
+ }
1609
+ }
1610
+ return null;
1611
+ }
1612
+ function evaluateEvery(array, predicate, ctx) {
1613
+ const arr = evaluateNode(array, ctx);
1614
+ if (!Array.isArray(arr)) {
1615
+ return null;
1616
+ }
1617
+ for (const item of arr) {
1618
+ const itemCtx = { ...ctx, item };
1619
+ const result = evaluateNode(predicate, itemCtx);
1620
+ if (result === false) {
1621
+ return false;
1622
+ }
1623
+ if (result !== true) {
1624
+ return null;
1625
+ }
1626
+ }
1627
+ return true;
1628
+ }
1629
+ function evaluateSome(array, predicate, ctx) {
1630
+ const arr = evaluateNode(array, ctx);
1631
+ if (!Array.isArray(arr)) {
1632
+ return null;
1633
+ }
1634
+ for (const item of arr) {
1635
+ const itemCtx = { ...ctx, item };
1636
+ const result = evaluateNode(predicate, itemCtx);
1637
+ if (result === true) {
1638
+ return true;
1639
+ }
1640
+ if (result !== false) {
1641
+ return null;
1642
+ }
1643
+ }
1644
+ return false;
1645
+ }
1646
+ function evaluateAppend(array, items, ctx) {
1647
+ const arr = evaluateNode(array, ctx);
1648
+ if (!Array.isArray(arr)) {
1649
+ return null;
1650
+ }
1651
+ const itemValues = items.map((item) => evaluateNode(item, ctx));
1652
+ return [...arr, ...itemValues];
1653
+ }
1654
+ function evaluateObject(fields, ctx) {
1655
+ const result = {};
1656
+ for (const [key, value] of Object.entries(fields)) {
1657
+ result[key] = evaluateNode(value, ctx);
1658
+ }
1659
+ return result;
1660
+ }
1661
+ function evaluateFieldAccess(objectExpr, property, ctx) {
1662
+ const obj = evaluateNode(objectExpr, ctx);
1663
+ if (obj === null || typeof obj !== "object" || Array.isArray(obj)) {
1664
+ return null;
1665
+ }
1666
+ return obj[property] ?? null;
1667
+ }
1668
+ function evaluateKeys(obj, ctx) {
1669
+ const o = evaluateNode(obj, ctx);
1670
+ if (o === null || typeof o !== "object" || Array.isArray(o)) {
1671
+ return null;
1672
+ }
1673
+ return Object.keys(o);
1674
+ }
1675
+ function evaluateValues(obj, ctx) {
1676
+ const o = evaluateNode(obj, ctx);
1677
+ if (o === null || typeof o !== "object" || Array.isArray(o)) {
1678
+ return null;
1679
+ }
1680
+ return Object.values(o);
1681
+ }
1682
+ function evaluateEntries(obj, ctx) {
1683
+ const o = evaluateNode(obj, ctx);
1684
+ if (o === null || typeof o !== "object" || Array.isArray(o)) {
1685
+ return null;
1686
+ }
1687
+ return Object.entries(o);
1688
+ }
1689
+ function evaluateMerge(objects, ctx) {
1690
+ const result = {};
1691
+ for (const objExpr of objects) {
1692
+ const o = evaluateNode(objExpr, ctx);
1693
+ if (o === null || typeof o !== "object" || Array.isArray(o)) {
1694
+ return null;
1695
+ }
1696
+ Object.assign(result, o);
1697
+ }
1698
+ return result;
1699
+ }
1700
+ function evaluateTypeof(arg, ctx) {
1701
+ const val = evaluateNode(arg, ctx);
1702
+ if (val === null) return "null";
1703
+ if (Array.isArray(val)) return "array";
1704
+ return typeof val;
1705
+ }
1706
+ function evaluateIsNull(arg, ctx) {
1707
+ const val = evaluateNode(arg, ctx);
1708
+ return val === null;
1709
+ }
1710
+ function evaluateCoalesce(args, ctx) {
1711
+ for (const arg of args) {
1712
+ const val = evaluateNode(arg, ctx);
1713
+ if (val !== null && val !== void 0) {
1714
+ return val;
1715
+ }
1716
+ }
1717
+ return null;
1718
+ }
1719
+
1720
+ // src/evaluation/evaluate-patch.ts
1721
+ function evaluateConditionalPatchOps(ops, ctx) {
1722
+ const patches = [];
1723
+ const skipped = [];
1724
+ let workingSnapshot = ctx.snapshot;
1725
+ for (const op of ops) {
1726
+ const evalCtx = {
1727
+ ...ctx,
1728
+ snapshot: workingSnapshot
1729
+ };
1730
+ if (op.condition !== void 0) {
1731
+ const conditionResult = evaluateExpr(op.condition, evalCtx);
1732
+ if (conditionResult !== true) {
1733
+ const reason = conditionResult === false ? "false" : conditionResult === null ? "null" : "non-boolean";
1734
+ skipped.push({ fragmentId: op.fragmentId, reason });
1735
+ continue;
1736
+ }
1737
+ }
1738
+ const evaluated = {
1739
+ fragmentId: op.fragmentId,
1740
+ op: op.op,
1741
+ confidence: op.confidence,
1742
+ conditionEvaluated: op.condition !== void 0
1743
+ };
1744
+ patches.push(evaluated);
1745
+ workingSnapshot = updateWorkingSnapshot(workingSnapshot, op.op, evalCtx);
1746
+ }
1747
+ return {
1748
+ patches,
1749
+ skipped,
1750
+ finalSnapshot: workingSnapshot
1751
+ };
1752
+ }
1753
+ function evaluatePatches(ops, ctx) {
1754
+ return ops.filter((op) => {
1755
+ if (op.condition === void 0) {
1756
+ return true;
1757
+ }
1758
+ return evaluateExpr(op.condition, ctx) === true;
1759
+ }).map((op) => ({
1760
+ fragmentId: op.fragmentId,
1761
+ op: op.op,
1762
+ confidence: op.confidence,
1763
+ conditionEvaluated: op.condition !== void 0
1764
+ }));
1765
+ }
1766
+ function updateWorkingSnapshot(snapshot, op, _ctx) {
1767
+ switch (op.kind) {
1768
+ case "setDefaultValue":
1769
+ return applyPatchToWorkingSnapshot(snapshot, op.path, op.value);
1770
+ case "addType":
1771
+ case "addField":
1772
+ case "setFieldType":
1773
+ case "addConstraint":
1774
+ case "addComputed":
1775
+ case "addActionAvailable":
1776
+ return snapshot;
1777
+ }
1778
+ }
1779
+ function evaluatePatchExpressions(op, ctx) {
1780
+ switch (op.kind) {
1781
+ case "addType":
1782
+ case "addField":
1783
+ case "setFieldType":
1784
+ case "setDefaultValue":
1785
+ return op;
1786
+ case "addConstraint":
1787
+ return {
1788
+ ...op
1789
+ // Keep rule as expression - it's evaluated at runtime by Core
1790
+ };
1791
+ case "addComputed":
1792
+ return {
1793
+ ...op
1794
+ // Keep expr as expression - it's evaluated at runtime by Core
1795
+ };
1796
+ case "addActionAvailable":
1797
+ return {
1798
+ ...op
1799
+ // Keep expr as expression - it's evaluated at runtime by Core
1800
+ };
1801
+ }
1802
+ }
1803
+ function evaluateCondition(condition, ctx) {
1804
+ if (condition === void 0) {
1805
+ return true;
1806
+ }
1807
+ const result = evaluateExpr(condition, ctx);
1808
+ return result === true;
1809
+ }
1810
+ function classifyCondition(condition, ctx) {
1811
+ if (condition === void 0) {
1812
+ return { passes: true, reason: "no-condition" };
1813
+ }
1814
+ const result = evaluateExpr(condition, ctx);
1815
+ if (result === true) {
1816
+ return { passes: true, reason: "true" };
1817
+ }
1818
+ if (result === false) {
1819
+ return { passes: false, reason: "false" };
1820
+ }
1821
+ if (result === null) {
1822
+ return { passes: false, reason: "null" };
1823
+ }
1824
+ return { passes: false, reason: "non-boolean" };
1825
+ }
1826
+
1827
+ // src/evaluation/evaluate-runtime-patch.ts
1828
+ import { mergeAtPatchPath, patchPathToDisplayString, setByPatchPath, unsetByPatchPath } from "@manifesto-ai/core";
1829
+ var UNSAFE_PROP_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1830
+ function evaluateRuntimePatches(ops, ctx) {
1831
+ const result = evaluateRuntimePatchesWithTrace(ops, ctx);
1832
+ return result.patches;
1833
+ }
1834
+ function evaluateRuntimePatchesWithTrace(ops, ctx) {
1835
+ const patches = [];
1836
+ const skipped = [];
1837
+ const warnings = [];
1838
+ let workingSnapshot = ctx.snapshot;
1839
+ const guardScopeStack = [];
1840
+ for (let i = 0; i < ops.length; i++) {
1841
+ const op = ops[i];
1842
+ const isScopedSet = op.op === "set" && isScopedMarkerPath(op.path);
1843
+ const isInScope = guardScopeStack.length > 0;
1844
+ const activeSnapshot = isScopedSet || !isInScope ? workingSnapshot : guardScopeStack[guardScopeStack.length - 1].snapshot;
1845
+ const evalCtx = {
1846
+ ...ctx,
1847
+ snapshot: activeSnapshot
1848
+ };
1849
+ if (op.condition !== void 0) {
1850
+ const conditionResult = evaluateExpr(op.condition, evalCtx);
1851
+ if (conditionResult !== true) {
1852
+ const reason = conditionResult === false ? "false" : conditionResult === null ? "null" : "non-boolean";
1853
+ skipped.push({
1854
+ index: i,
1855
+ path: irPathToDisplayString(op.path),
1856
+ reason
1857
+ });
1858
+ continue;
1859
+ }
1860
+ }
1861
+ const resolvedPath = resolveIRPath(op.path, evalCtx);
1862
+ if (!resolvedPath.ok) {
1863
+ skipped.push({
1864
+ index: i,
1865
+ path: irPathToDisplayString(op.path),
1866
+ reason: "invalid-path"
1867
+ });
1868
+ warnings.push(`Skipped runtime patch at index ${i}: ${resolvedPath.warning}`);
1869
+ continue;
1870
+ }
1871
+ const concretePath = resolvedPath.path;
1872
+ const concreteValue = op.value ? evaluateExpr(op.value, evalCtx) : void 0;
1873
+ const patch = buildConcretePatch(op.op, concretePath, concreteValue);
1874
+ if (patch === null) {
1875
+ continue;
1876
+ }
1877
+ if (op.op === "unset" && isScopedMarkerPath(op.path) && (!isInScope || !isPatchPathEqual(
1878
+ guardScopeStack[guardScopeStack.length - 1].markerPath,
1879
+ concretePath
1880
+ ))) {
1881
+ continue;
1882
+ }
1883
+ patches.push(patch);
1884
+ workingSnapshot = applyConcretePatchToWorkingSnapshot(workingSnapshot, patch);
1885
+ if (op.op === "set" && isScopedMarkerPath(op.path)) {
1886
+ guardScopeStack.push({
1887
+ markerPath: concretePath,
1888
+ snapshot: workingSnapshot
1889
+ });
1890
+ continue;
1891
+ }
1892
+ if (op.op === "unset" && isScopedMarkerPath(op.path) && guardScopeStack.length > 0 && isPatchPathEqual(
1893
+ guardScopeStack[guardScopeStack.length - 1].markerPath,
1894
+ concretePath
1895
+ )) {
1896
+ guardScopeStack.pop();
1897
+ }
1898
+ }
1899
+ return {
1900
+ patches,
1901
+ skipped,
1902
+ warnings,
1903
+ finalSnapshot: workingSnapshot
1904
+ };
1905
+ }
1906
+ function buildConcretePatch(op, path, value) {
1907
+ switch (op) {
1908
+ case "set":
1909
+ return { op: "set", path, value };
1910
+ case "unset":
1911
+ return { op: "unset", path };
1912
+ case "merge":
1913
+ if (isRecord(value)) {
1914
+ return { op: "merge", path, value };
1915
+ }
1916
+ return { op: "set", path, value: null };
1917
+ }
1918
+ }
1919
+ function applyConcretePatchToWorkingSnapshot(snapshot, patch) {
1920
+ const baseData = snapshot.data;
1921
+ const nextData = (() => {
1922
+ switch (patch.op) {
1923
+ case "set":
1924
+ return setByPatchPath(baseData, patch.path, patch.value);
1925
+ case "unset":
1926
+ return unsetByPatchPath(baseData, patch.path);
1927
+ case "merge":
1928
+ return mergeAtPatchPath(baseData, patch.path, patch.value);
1929
+ }
1930
+ })();
1931
+ return {
1932
+ data: nextData,
1933
+ computed: snapshot.computed
1934
+ };
1935
+ }
1936
+ function resolveIRPath(path, ctx) {
1937
+ if (path.length === 0) {
1938
+ return { ok: false, warning: "path is empty" };
1939
+ }
1940
+ const resolved = [];
1941
+ for (let i = 0; i < path.length; i++) {
1942
+ const segment = path[i];
1943
+ if (segment.kind === "prop") {
1944
+ if (!isValidPropSegment(segment.name)) {
1945
+ return { ok: false, warning: `invalid prop segment '${segment.name}'` };
1946
+ }
1947
+ resolved.push({ kind: "prop", name: segment.name });
1948
+ continue;
1949
+ }
1950
+ const value = evaluateExpr(segment.expr, ctx);
1951
+ const concrete = toConcreteSegment(value);
1952
+ if (concrete === null) {
1953
+ return {
1954
+ ok: false,
1955
+ warning: `expr segment at index ${i} resolved to invalid value`
1956
+ };
1957
+ }
1958
+ resolved.push(concrete);
1959
+ }
1960
+ return { ok: true, path: resolved };
1961
+ }
1962
+ function toConcreteSegment(value) {
1963
+ if (typeof value === "number" && Number.isInteger(value) && Number.isFinite(value) && value >= 0) {
1964
+ return { kind: "index", index: value };
1965
+ }
1966
+ if (typeof value === "string" && value.length > 0 && isValidPropSegment(value)) {
1967
+ return { kind: "prop", name: value };
1968
+ }
1969
+ return null;
1970
+ }
1971
+ function isValidPropSegment(name) {
1972
+ return name.length > 0 && !UNSAFE_PROP_SEGMENTS.has(name);
1973
+ }
1974
+ function isScopedMarkerPath(path) {
1975
+ return hasPropPrefix(path, ["$mel", "__whenGuards"]) || hasPropPrefix(path, ["$mel", "__onceScopeGuards"]);
1976
+ }
1977
+ function hasPropPrefix(path, prefix) {
1978
+ if (path.length < prefix.length) {
1979
+ return false;
1980
+ }
1981
+ for (let i = 0; i < prefix.length; i++) {
1982
+ const segment = path[i];
1983
+ if (segment.kind !== "prop" || segment.name !== prefix[i]) {
1984
+ return false;
1985
+ }
1986
+ }
1987
+ return true;
1988
+ }
1989
+ function isPatchPathEqual(a, b) {
1990
+ if (a.length !== b.length) {
1991
+ return false;
1992
+ }
1993
+ for (let i = 0; i < a.length; i++) {
1994
+ const left = a[i];
1995
+ const right = b[i];
1996
+ if (left.kind !== right.kind) {
1997
+ return false;
1998
+ }
1999
+ if (left.kind === "prop" && right.kind === "prop" && left.name !== right.name) {
2000
+ return false;
2001
+ }
2002
+ if (left.kind === "index" && right.kind === "index" && left.index !== right.index) {
2003
+ return false;
2004
+ }
2005
+ }
2006
+ return true;
2007
+ }
2008
+ function irPathToDisplayString(path) {
2009
+ const concretePrefix = [];
2010
+ for (const segment of path) {
2011
+ if (segment.kind === "prop") {
2012
+ concretePrefix.push({ kind: "prop", name: segment.name });
2013
+ continue;
2014
+ }
2015
+ if (concretePrefix.length === 0) {
2016
+ return "[expr]";
2017
+ }
2018
+ return `${patchPathToDisplayString(concretePrefix)}.[expr]`;
2019
+ }
2020
+ if (concretePrefix.length === 0) {
2021
+ return "";
2022
+ }
2023
+ return patchPathToDisplayString(concretePrefix);
2024
+ }
2025
+ function isRecord(value) {
2026
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2027
+ }
2028
+
2029
+ // src/index.ts
2030
+ function compile(source, options = {}) {
2031
+ const trace = [];
2032
+ const lexStart = performance.now();
2033
+ const lexResult = tokenize(source);
2034
+ trace.push({ phase: "lex", durationMs: performance.now() - lexStart, details: { tokenCount: lexResult.tokens.length } });
2035
+ if (hasErrors(lexResult.diagnostics)) {
2036
+ return {
2037
+ schema: null,
2038
+ trace,
2039
+ warnings: lexResult.diagnostics.filter((d) => d.severity === "warning"),
2040
+ errors: lexResult.diagnostics.filter((d) => d.severity === "error"),
2041
+ success: false
2042
+ };
2043
+ }
2044
+ const parseStart = performance.now();
2045
+ const parseResult = parse(lexResult.tokens);
2046
+ const parseErrors = parseResult.diagnostics;
2047
+ trace.push({ phase: "parse", durationMs: performance.now() - parseStart });
2048
+ if (hasErrors(parseErrors)) {
2049
+ return {
2050
+ schema: null,
2051
+ trace,
2052
+ warnings: parseErrors.filter((d) => d.severity === "warning"),
2053
+ errors: parseErrors.filter((d) => d.severity === "error"),
2054
+ success: false
2055
+ };
2056
+ }
2057
+ const diagnostics = [];
2058
+ if (!options.skipSemanticAnalysis && parseResult.program) {
2059
+ const scopeResult = analyzeScope(parseResult.program);
2060
+ const validateResult = validateSemantics(parseResult.program);
2061
+ diagnostics.push(...scopeResult.diagnostics, ...validateResult.diagnostics);
2062
+ }
2063
+ const generateStart = performance.now();
2064
+ const genResult = generate(parseResult.program);
2065
+ diagnostics.push(...genResult.diagnostics);
2066
+ trace.push({ phase: "generate", durationMs: performance.now() - generateStart });
2067
+ if (options.skipSemanticAnalysis) {
2068
+ diagnostics.push(...parseResult.diagnostics);
2069
+ }
2070
+ const errors = diagnostics.filter((d) => d.severity === "error");
2071
+ if (genResult.schema === null || errors.length > 0) {
2072
+ return {
2073
+ schema: null,
2074
+ trace,
2075
+ warnings: diagnostics.filter((d) => d.severity === "warning"),
2076
+ errors,
2077
+ success: false
2078
+ };
2079
+ }
2080
+ let schema = genResult.schema;
2081
+ if (options.lowerSystemValues) {
2082
+ const lowerStart = performance.now();
2083
+ schema = lowerSystemValues(schema);
2084
+ trace.push({ phase: "lower", durationMs: performance.now() - lowerStart });
2085
+ }
2086
+ const warnings = diagnostics.filter((d) => d.severity === "warning");
2087
+ return {
2088
+ schema,
2089
+ trace,
2090
+ warnings,
2091
+ errors: diagnostics.filter((d) => d.severity === "error"),
2092
+ success: errors.length === 0
2093
+ };
2094
+ }
2095
+ function parseSource(source) {
2096
+ const lexResult = tokenize(source);
2097
+ if (hasErrors(lexResult.diagnostics)) {
2098
+ return { program: null, diagnostics: lexResult.diagnostics };
2099
+ }
2100
+ return parse(lexResult.tokens);
2101
+ }
2102
+ function check(source) {
2103
+ const result = compile(source);
2104
+ return result.errors;
2105
+ }
2106
+ export {
2107
+ DEFAULT_ACTION_CONTEXT,
2108
+ DEFAULT_PATCH_CONTEXT,
2109
+ DEFAULT_SCHEMA_CONTEXT,
2110
+ DIAGNOSTIC_CODES,
2111
+ EFFECT_ARGS_CONTEXT,
2112
+ KEYWORDS,
2113
+ Lexer,
2114
+ LoweringError,
2115
+ Parser,
2116
+ Precedence,
2117
+ RESERVED_KEYWORDS,
2118
+ Scope,
2119
+ ScopeAnalyzer,
2120
+ SemanticValidator,
2121
+ analyzeScope,
2122
+ applyPatchToWorkingSnapshot,
2123
+ check,
2124
+ classifyCondition,
2125
+ compile,
2126
+ compileMelDomain,
2127
+ compileMelPatch,
2128
+ createError,
2129
+ createEvaluationContext,
2130
+ createInfo,
2131
+ createLocation,
2132
+ createPointLocation,
2133
+ createPosition,
2134
+ createToken,
2135
+ createWarning,
2136
+ evaluateCondition,
2137
+ evaluateConditionalPatchOps,
2138
+ evaluateExpr,
2139
+ evaluatePatchExpressions,
2140
+ evaluatePatches,
2141
+ evaluateRuntimePatches,
2142
+ evaluateRuntimePatchesWithTrace,
2143
+ extractTypeName,
2144
+ filterBySeverity,
2145
+ formatDiagnostic,
2146
+ formatDiagnosticCode,
2147
+ formatDiagnostics,
2148
+ generate,
2149
+ getBinaryPrecedence,
2150
+ getDiagnosticInfo,
2151
+ getKeywordKind,
2152
+ hasErrors,
2153
+ invalidKindForContext,
2154
+ invalidShape,
2155
+ invalidSysPath,
2156
+ isBinaryOp,
2157
+ isError,
2158
+ isExprNode,
2159
+ isKeyword,
2160
+ isReserved,
2161
+ isRightAssociative,
2162
+ isStmtNode,
2163
+ isUnaryOp,
2164
+ lowerExprNode,
2165
+ lowerPatchFragments,
2166
+ lowerRuntimePatch,
2167
+ lowerRuntimePatches,
2168
+ lowerSystemValues,
2169
+ mergeLocations,
2170
+ normalizeExpr,
2171
+ normalizeFunctionCall,
2172
+ parse,
2173
+ parseSource,
2174
+ renderAsDomain,
2175
+ renderExprNode,
2176
+ renderFragment,
2177
+ renderFragments,
2178
+ renderFragmentsByKind,
2179
+ renderPatchOp,
2180
+ renderTypeExpr,
2181
+ renderTypeField,
2182
+ renderValue,
2183
+ tokenToBinaryOp,
2184
+ tokenize,
2185
+ unknownCallFn,
2186
+ unknownNodeKind,
2187
+ unsupportedBase,
2188
+ validateSemantics
2189
+ };
44
2190
  //# sourceMappingURL=index.js.map