@objectstack/formula 4.0.4
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.
- package/.turbo/turbo-build.log +22 -0
- package/LICENSE +202 -0
- package/README.md +9 -0
- package/dist/index.d.mts +240 -0
- package/dist/index.d.ts +240 -0
- package/dist/index.js +335 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +300 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +45 -0
- package/src/cel-engine.test.ts +85 -0
- package/src/cel-engine.ts +123 -0
- package/src/index.ts +18 -0
- package/src/normalize.test.ts +99 -0
- package/src/normalize.ts +103 -0
- package/src/registry.test.ts +47 -0
- package/src/registry.ts +94 -0
- package/src/seed-eval.test.ts +83 -0
- package/src/seed-eval.ts +81 -0
- package/src/stdlib.ts +81 -0
- package/src/types.ts +91 -0
- package/tsconfig.json +9 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
// src/cel-engine.ts
|
|
2
|
+
import { Environment } from "@marcbachmann/cel-js";
|
|
3
|
+
|
|
4
|
+
// src/stdlib.ts
|
|
5
|
+
function startOfDayUtc(d) {
|
|
6
|
+
const out = new Date(d.getTime());
|
|
7
|
+
out.setUTCHours(0, 0, 0, 0);
|
|
8
|
+
return out;
|
|
9
|
+
}
|
|
10
|
+
function addDaysUtc(d, n) {
|
|
11
|
+
const out = new Date(d.getTime());
|
|
12
|
+
out.setUTCDate(out.getUTCDate() + n);
|
|
13
|
+
return out;
|
|
14
|
+
}
|
|
15
|
+
function registerStdLib(env, now) {
|
|
16
|
+
return env.registerFunction("now(): google.protobuf.Timestamp", () => now()).registerFunction(
|
|
17
|
+
"today(): google.protobuf.Timestamp",
|
|
18
|
+
() => startOfDayUtc(now())
|
|
19
|
+
).registerFunction(
|
|
20
|
+
"daysFromNow(int): google.protobuf.Timestamp",
|
|
21
|
+
(n) => addDaysUtc(now(), Number(n))
|
|
22
|
+
).registerFunction(
|
|
23
|
+
"daysAgo(int): google.protobuf.Timestamp",
|
|
24
|
+
(n) => addDaysUtc(now(), -Number(n))
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
function buildScope(ctx) {
|
|
28
|
+
const scope = {};
|
|
29
|
+
if (ctx.record !== void 0) scope.record = ctx.record;
|
|
30
|
+
if (ctx.previous !== void 0) scope.previous = ctx.previous;
|
|
31
|
+
if (ctx.input !== void 0) scope.input = ctx.input;
|
|
32
|
+
const os = {};
|
|
33
|
+
if (ctx.user !== void 0) os.user = ctx.user;
|
|
34
|
+
if (ctx.org !== void 0) os.org = ctx.org;
|
|
35
|
+
if (ctx.env !== void 0) os.env = ctx.env;
|
|
36
|
+
if (Object.keys(os).length > 0) scope.os = os;
|
|
37
|
+
if (ctx.extra !== void 0) Object.assign(scope, ctx.extra);
|
|
38
|
+
return scope;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// src/cel-engine.ts
|
|
42
|
+
var DEFAULT_LIMITS = {
|
|
43
|
+
maxAstNodes: 256,
|
|
44
|
+
maxDepth: 32,
|
|
45
|
+
maxListElements: 64,
|
|
46
|
+
maxMapEntries: 64,
|
|
47
|
+
maxCallArguments: 16
|
|
48
|
+
};
|
|
49
|
+
function buildEnv(now) {
|
|
50
|
+
const env = new Environment({
|
|
51
|
+
unlistedVariablesAreDyn: true,
|
|
52
|
+
enableOptionalTypes: true,
|
|
53
|
+
limits: DEFAULT_LIMITS
|
|
54
|
+
});
|
|
55
|
+
return registerStdLib(env, now);
|
|
56
|
+
}
|
|
57
|
+
function coerce(value) {
|
|
58
|
+
if (typeof value === "bigint") {
|
|
59
|
+
if (value >= BigInt(Number.MIN_SAFE_INTEGER) && value <= BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
60
|
+
return Number(value);
|
|
61
|
+
}
|
|
62
|
+
return value.toString();
|
|
63
|
+
}
|
|
64
|
+
if (Array.isArray(value)) return value.map(coerce);
|
|
65
|
+
if (value && typeof value === "object" && !(value instanceof Date)) {
|
|
66
|
+
const out = {};
|
|
67
|
+
for (const [k, v] of Object.entries(value)) out[k] = coerce(v);
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
return value;
|
|
71
|
+
}
|
|
72
|
+
function classifyError(err) {
|
|
73
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
74
|
+
let kind = "runtime";
|
|
75
|
+
if (/Exceeded max/i.test(message)) kind = "bounds";
|
|
76
|
+
else if (/parse|unexpected|syntax/i.test(message)) kind = "parse";
|
|
77
|
+
else if (/type|unknown variable|undeclared/i.test(message)) kind = "type";
|
|
78
|
+
return { ok: false, error: { kind, message } };
|
|
79
|
+
}
|
|
80
|
+
var celEngine = {
|
|
81
|
+
dialect: "cel",
|
|
82
|
+
compile(source) {
|
|
83
|
+
try {
|
|
84
|
+
const env = buildEnv(() => /* @__PURE__ */ new Date(0));
|
|
85
|
+
const compiled = env.parse(source);
|
|
86
|
+
const checkErrors = compiled.check?.();
|
|
87
|
+
if (checkErrors && Array.isArray(checkErrors) && checkErrors.length > 0) {
|
|
88
|
+
return {
|
|
89
|
+
ok: false,
|
|
90
|
+
error: { kind: "type", message: checkErrors.join("; ") }
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
return { ok: true, value: compiled.ast };
|
|
94
|
+
} catch (err) {
|
|
95
|
+
return classifyError(err);
|
|
96
|
+
}
|
|
97
|
+
},
|
|
98
|
+
evaluate(expr, ctx) {
|
|
99
|
+
if (expr.dialect !== "cel") {
|
|
100
|
+
return {
|
|
101
|
+
ok: false,
|
|
102
|
+
error: { kind: "dialect", message: `celEngine cannot evaluate dialect '${expr.dialect}'` }
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
const source = expr.source;
|
|
106
|
+
if (typeof source !== "string" || source.length === 0) {
|
|
107
|
+
return {
|
|
108
|
+
ok: false,
|
|
109
|
+
error: { kind: "parse", message: "AST-only evaluation not yet supported; persist `source`" }
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
const now = () => ctx.now ?? /* @__PURE__ */ new Date();
|
|
113
|
+
try {
|
|
114
|
+
const env = buildEnv(now);
|
|
115
|
+
const scope = buildScope(ctx);
|
|
116
|
+
const raw = env.evaluate(source, scope);
|
|
117
|
+
return { ok: true, value: coerce(raw) };
|
|
118
|
+
} catch (err) {
|
|
119
|
+
return classifyError(err);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
// src/registry.ts
|
|
125
|
+
var registry = /* @__PURE__ */ new Map();
|
|
126
|
+
function register(engine) {
|
|
127
|
+
registry.set(engine.dialect, engine);
|
|
128
|
+
}
|
|
129
|
+
function getEngine(dialect) {
|
|
130
|
+
return registry.get(dialect);
|
|
131
|
+
}
|
|
132
|
+
function hasDialect(dialect) {
|
|
133
|
+
return registry.has(dialect) && !registry.get(dialect).dialect.startsWith("stub:");
|
|
134
|
+
}
|
|
135
|
+
function makeStub(dialect, reason) {
|
|
136
|
+
return {
|
|
137
|
+
dialect,
|
|
138
|
+
compile: () => ({ ok: false, error: { kind: "dialect", message: reason } }),
|
|
139
|
+
evaluate: () => ({ ok: false, error: { kind: "dialect", message: reason } })
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
register(celEngine);
|
|
143
|
+
register(makeStub("js", "dialect 'js' not registered. Install @objectstack/plugin-js-vm"));
|
|
144
|
+
register(makeStub("cron", "dialect 'cron' not registered. Install @objectstack/plugin-cron"));
|
|
145
|
+
var ExpressionEngine = {
|
|
146
|
+
register,
|
|
147
|
+
getEngine,
|
|
148
|
+
hasDialect,
|
|
149
|
+
/**
|
|
150
|
+
* Compile-only — parse + type-check, returning the engine-native AST. Used
|
|
151
|
+
* by `objectstack compile` to normalize source into AST in artifacts.
|
|
152
|
+
*/
|
|
153
|
+
compile(expr) {
|
|
154
|
+
const engine = registry.get(expr.dialect);
|
|
155
|
+
if (!engine) {
|
|
156
|
+
return {
|
|
157
|
+
ok: false,
|
|
158
|
+
error: { kind: "dialect", message: `No engine registered for dialect '${expr.dialect}'` }
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
if (typeof expr.source !== "string") {
|
|
162
|
+
return {
|
|
163
|
+
ok: false,
|
|
164
|
+
error: { kind: "parse", message: "Expression.source required for compile()" }
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
return engine.compile(expr.source);
|
|
168
|
+
},
|
|
169
|
+
/**
|
|
170
|
+
* Evaluate an expression in the given context. Never throws — branch on
|
|
171
|
+
* `result.ok`. Errors carry a `kind` for caller-side classification.
|
|
172
|
+
*/
|
|
173
|
+
evaluate(expr, ctx) {
|
|
174
|
+
const engine = registry.get(expr.dialect);
|
|
175
|
+
if (!engine) {
|
|
176
|
+
return {
|
|
177
|
+
ok: false,
|
|
178
|
+
error: { kind: "dialect", message: `No engine registered for dialect '${expr.dialect}'` }
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
return engine.evaluate(expr, ctx);
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
// src/seed-eval.ts
|
|
186
|
+
import { ExpressionSchema } from "@objectstack/spec";
|
|
187
|
+
function isExpressionLike(value) {
|
|
188
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
189
|
+
const v = value;
|
|
190
|
+
if (typeof v.dialect !== "string") return false;
|
|
191
|
+
return ExpressionSchema.safeParse(v).success;
|
|
192
|
+
}
|
|
193
|
+
function resolveSeed(value, ctx) {
|
|
194
|
+
if (value === null || value === void 0) {
|
|
195
|
+
return { ok: true, value };
|
|
196
|
+
}
|
|
197
|
+
const t = typeof value;
|
|
198
|
+
if (t === "string" || t === "number" || t === "boolean") {
|
|
199
|
+
return { ok: true, value };
|
|
200
|
+
}
|
|
201
|
+
if (value instanceof Date) {
|
|
202
|
+
return { ok: true, value };
|
|
203
|
+
}
|
|
204
|
+
if (Array.isArray(value)) {
|
|
205
|
+
const out2 = [];
|
|
206
|
+
for (const item of value) {
|
|
207
|
+
const r = resolveSeed(item, ctx);
|
|
208
|
+
if (!r.ok) return r;
|
|
209
|
+
out2.push(r.value);
|
|
210
|
+
}
|
|
211
|
+
return { ok: true, value: out2 };
|
|
212
|
+
}
|
|
213
|
+
if (isExpressionLike(value)) {
|
|
214
|
+
return ExpressionEngine.evaluate(value, ctx);
|
|
215
|
+
}
|
|
216
|
+
const out = {};
|
|
217
|
+
for (const [k, v] of Object.entries(value)) {
|
|
218
|
+
const r = resolveSeed(v, ctx);
|
|
219
|
+
if (!r.ok) return r;
|
|
220
|
+
out[k] = r.value;
|
|
221
|
+
}
|
|
222
|
+
return { ok: true, value: out };
|
|
223
|
+
}
|
|
224
|
+
function resolveSeedRecord(record, ctx) {
|
|
225
|
+
const pinnedCtx = { ...ctx, now: ctx.now ?? /* @__PURE__ */ new Date() };
|
|
226
|
+
const result = resolveSeed(record, pinnedCtx);
|
|
227
|
+
return result;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// src/normalize.ts
|
|
231
|
+
import {
|
|
232
|
+
ExpressionInputSchema,
|
|
233
|
+
ExpressionSchema as ExpressionSchema2
|
|
234
|
+
} from "@objectstack/spec";
|
|
235
|
+
function normalizeExpression(input) {
|
|
236
|
+
const parsed = ExpressionInputSchema.safeParse(input);
|
|
237
|
+
if (!parsed.success) {
|
|
238
|
+
return {
|
|
239
|
+
ok: false,
|
|
240
|
+
error: { kind: "parse", message: parsed.error.message }
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
const expr = parsed.data;
|
|
244
|
+
if (expr.ast !== void 0 && expr.source === void 0) {
|
|
245
|
+
return { ok: true, value: expr };
|
|
246
|
+
}
|
|
247
|
+
const compiled = ExpressionEngine.compile(expr);
|
|
248
|
+
if (!compiled.ok) {
|
|
249
|
+
return compiled;
|
|
250
|
+
}
|
|
251
|
+
return {
|
|
252
|
+
ok: true,
|
|
253
|
+
value: {
|
|
254
|
+
...expr,
|
|
255
|
+
ast: compiled.value
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
function normalizeExpressionTree(root, path = []) {
|
|
260
|
+
if (root === null || typeof root !== "object") return null;
|
|
261
|
+
if (looksLikeExpression(root)) {
|
|
262
|
+
const r = normalizeExpression(root);
|
|
263
|
+
if (!r.ok) return { path: path.join("."), error: r.error };
|
|
264
|
+
Object.assign(root, r.value);
|
|
265
|
+
return null;
|
|
266
|
+
}
|
|
267
|
+
if (Array.isArray(root)) {
|
|
268
|
+
for (let i = 0; i < root.length; i++) {
|
|
269
|
+
const r = normalizeExpressionTree(root[i], [...path, String(i)]);
|
|
270
|
+
if (r) return r;
|
|
271
|
+
}
|
|
272
|
+
return null;
|
|
273
|
+
}
|
|
274
|
+
for (const [k, v] of Object.entries(root)) {
|
|
275
|
+
const r = normalizeExpressionTree(v, [...path, k]);
|
|
276
|
+
if (r) return r;
|
|
277
|
+
}
|
|
278
|
+
return null;
|
|
279
|
+
}
|
|
280
|
+
function looksLikeExpression(value) {
|
|
281
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
282
|
+
const v = value;
|
|
283
|
+
if (typeof v.dialect !== "string") return false;
|
|
284
|
+
return ExpressionSchema2.safeParse(v).success;
|
|
285
|
+
}
|
|
286
|
+
export {
|
|
287
|
+
DEFAULT_LIMITS,
|
|
288
|
+
ExpressionEngine,
|
|
289
|
+
buildScope,
|
|
290
|
+
celEngine,
|
|
291
|
+
getEngine,
|
|
292
|
+
hasDialect,
|
|
293
|
+
normalizeExpression,
|
|
294
|
+
normalizeExpressionTree,
|
|
295
|
+
register,
|
|
296
|
+
registerStdLib,
|
|
297
|
+
resolveSeed,
|
|
298
|
+
resolveSeedRecord
|
|
299
|
+
};
|
|
300
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cel-engine.ts","../src/stdlib.ts","../src/registry.ts","../src/seed-eval.ts","../src/normalize.ts"],"sourcesContent":["/**\n * CEL dialect engine — wraps `@marcbachmann/cel-js` with the ObjectStack\n * stdlib, bounded execution limits, and result coercion.\n *\n * Why a thin wrapper:\n *\n * - cel-js returns `BigInt` for ints. The kernel and CRM expect plain\n * numbers, so we coerce at the boundary.\n * - cel-js parses dotted names as receiver-typed methods; we register\n * `now()`, `today()`, `daysFromNow()` as bare functions and let `os.*`\n * refer to context data only (see {@link buildScope}).\n * - Bounds (`maxAstNodes`, `maxDepth`, …) are enforced spec-wide so\n * third-party plugins can't ship runaway predicates.\n */\n\nimport { Environment } from '@marcbachmann/cel-js';\nimport type { Expression } from '@objectstack/spec';\n\nimport { buildScope, registerStdLib } from './stdlib';\nimport type { DialectEngine, EvalContext, EvalResult } from './types';\n\n/**\n * Default execution bounds. Picked conservatively — every metadata-authored\n * expression we've seen is well under these. If you hit them, the expression\n * is too complex for ObjectStack and should be moved to a hook (`dialect: js`).\n */\nexport const DEFAULT_LIMITS = {\n maxAstNodes: 256,\n maxDepth: 32,\n maxListElements: 64,\n maxMapEntries: 64,\n maxCallArguments: 16,\n} as const;\n\nfunction buildEnv(now: () => Date): Environment {\n const env = new Environment({\n unlistedVariablesAreDyn: true,\n enableOptionalTypes: true,\n limits: DEFAULT_LIMITS,\n });\n return registerStdLib(env, now);\n}\n\n/** Coerce cel-js's BigInt-flavored return into spec-friendly JS values. */\nfunction coerce(value: unknown): unknown {\n if (typeof value === 'bigint') {\n // BigInt → number when safe, else string to avoid silent truncation.\n if (value >= BigInt(Number.MIN_SAFE_INTEGER) && value <= BigInt(Number.MAX_SAFE_INTEGER)) {\n return Number(value);\n }\n return value.toString();\n }\n if (Array.isArray(value)) return value.map(coerce);\n if (value && typeof value === 'object' && !(value instanceof Date)) {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) out[k] = coerce(v);\n return out;\n }\n return value;\n}\n\nfunction classifyError(err: unknown): EvalResult<never> {\n const message = err instanceof Error ? err.message : String(err);\n let kind: 'parse' | 'type' | 'runtime' | 'bounds' = 'runtime';\n if (/Exceeded max/i.test(message)) kind = 'bounds';\n else if (/parse|unexpected|syntax/i.test(message)) kind = 'parse';\n else if (/type|unknown variable|undeclared/i.test(message)) kind = 'type';\n return { ok: false, error: { kind, message } };\n}\n\nexport const celEngine: DialectEngine = {\n dialect: 'cel',\n\n compile(source: string): EvalResult<unknown> {\n try {\n // We use a wall-clock now() here purely for parse-time stdlib\n // type-checking; the function is never actually called.\n const env = buildEnv(() => new Date(0));\n const compiled = env.parse(source);\n // Surface check errors eagerly.\n const checkErrors = compiled.check?.();\n if (checkErrors && Array.isArray(checkErrors) && checkErrors.length > 0) {\n return {\n ok: false,\n error: { kind: 'type', message: checkErrors.join('; ') },\n };\n }\n return { ok: true, value: compiled.ast };\n } catch (err) {\n return classifyError(err);\n }\n },\n\n evaluate<T = unknown>(expr: Expression, ctx: EvalContext): EvalResult<T> {\n if (expr.dialect !== 'cel') {\n return {\n ok: false,\n error: { kind: 'dialect', message: `celEngine cannot evaluate dialect '${expr.dialect}'` },\n };\n }\n const source = expr.source;\n if (typeof source !== 'string' || source.length === 0) {\n // AST-only inputs: cel-js does not currently expose a public API to\n // re-execute a parsed AST without re-serializing. We persist `source`\n // as the canonical form during M9.1 and revisit AST-only execution in\n // M9.7 when we cut the spec persistence over.\n return {\n ok: false,\n error: { kind: 'parse', message: 'AST-only evaluation not yet supported; persist `source`' },\n };\n }\n\n const now = () => ctx.now ?? new Date();\n try {\n const env = buildEnv(now);\n const scope = buildScope(ctx);\n const raw = env.evaluate(source, scope);\n return { ok: true, value: coerce(raw) as T };\n } catch (err) {\n return classifyError(err);\n }\n },\n};\n","/**\n * ObjectStack standard CEL function library.\n *\n * Registered into the per-evaluation `Environment` by the CEL engine. All\n * functions are pure given a pinned `now` — that determinism is what makes\n * `objectstack build` artifacts byte-stable across runs.\n *\n * Function naming intentionally avoids the `os.` prefix because cel-js binds\n * dotted names to receiver types. Instead, the `os` namespace in CEL holds\n * *data* (`os.user`, `os.org`, `os.env`) supplied by the caller's\n * {@link EvalContext}.\n */\n\nimport type { Environment } from '@marcbachmann/cel-js';\n\nimport type { EvalContext } from './types';\n\n/** Truncate a Date to start-of-day in UTC. */\nfunction startOfDayUtc(d: Date): Date {\n const out = new Date(d.getTime());\n out.setUTCHours(0, 0, 0, 0);\n return out;\n}\n\n/** Add `n` days to a Date in UTC; returns a new Date. */\nfunction addDaysUtc(d: Date, n: number): Date {\n const out = new Date(d.getTime());\n out.setUTCDate(out.getUTCDate() + n);\n return out;\n}\n\n/**\n * Register the ObjectStack standard library into a CEL environment.\n *\n * The `now` resolver is closed over so each call uses the pinned\n * `EvalContext.now` (or wall-clock fallback). Implementations are kept tiny\n * and dependency-free — they're the contract surface for AI authors and must\n * stay legible.\n */\nexport function registerStdLib(\n env: Environment,\n now: () => Date,\n): Environment {\n return env\n .registerFunction('now(): google.protobuf.Timestamp', () => now())\n .registerFunction(\n 'today(): google.protobuf.Timestamp',\n () => startOfDayUtc(now()),\n )\n .registerFunction(\n 'daysFromNow(int): google.protobuf.Timestamp',\n (n: bigint | number) => addDaysUtc(now(), Number(n)),\n )\n .registerFunction(\n 'daysAgo(int): google.protobuf.Timestamp',\n (n: bigint | number) => addDaysUtc(now(), -Number(n)),\n );\n}\n\n/**\n * Build the variable scope for a single evaluation. Absent fields are simply\n * not bound — CEL macros (`has(record.foo)`) handle missing-key safely.\n */\nexport function buildScope(ctx: EvalContext): Record<string, unknown> {\n const scope: Record<string, unknown> = {};\n\n if (ctx.record !== undefined) scope.record = ctx.record;\n if (ctx.previous !== undefined) scope.previous = ctx.previous;\n if (ctx.input !== undefined) scope.input = ctx.input;\n\n // Namespaced data — written as `os.user.id`, `os.env`, etc. in CEL.\n const os: Record<string, unknown> = {};\n if (ctx.user !== undefined) os.user = ctx.user;\n if (ctx.org !== undefined) os.org = ctx.org;\n if (ctx.env !== undefined) os.env = ctx.env;\n if (Object.keys(os).length > 0) scope.os = os;\n\n if (ctx.extra !== undefined) Object.assign(scope, ctx.extra);\n\n return scope;\n}\n","/**\n * Dialect-pluggable Expression engine registry.\n *\n * Replaces the per-call-site `compileFormula` / `evaluateFormula` direct\n * imports of the deleted custom engine. Call sites now ask the registry to\n * dispatch by `expression.dialect`.\n *\n * Stub dialects (`js`, `cron`) are registered at module load with explicit\n * `dialect`-error responses so call sites get a clear message instead of\n * silent `undefined` (the old engine's anti-pattern).\n */\n\nimport type { Expression } from '@objectstack/spec';\n\nimport { celEngine } from './cel-engine';\nimport type { DialectEngine, EvalContext, EvalResult } from './types';\n\nconst registry = new Map<string, DialectEngine>();\n\n/** Register or replace a dialect engine. */\nexport function register(engine: DialectEngine): void {\n registry.set(engine.dialect, engine);\n}\n\n/** Look up a dialect engine without dispatching. */\nexport function getEngine(dialect: string): DialectEngine | undefined {\n return registry.get(dialect);\n}\n\n/** Whether a dialect has a real (non-stub) implementation registered. */\nexport function hasDialect(dialect: string): boolean {\n return registry.has(dialect) && !registry.get(dialect)!.dialect.startsWith('stub:');\n}\n\nfunction makeStub(dialect: string, reason: string): DialectEngine {\n return {\n dialect,\n compile: () => ({ ok: false, error: { kind: 'dialect', message: reason } }),\n evaluate: () => ({ ok: false, error: { kind: 'dialect', message: reason } }),\n };\n}\n\n// Real engines.\nregister(celEngine);\n\n// Stubs — phased in by later milestones (M9.5+ for `js`, M9.6 for `cron`).\nregister(makeStub('js', \"dialect 'js' not registered. Install @objectstack/plugin-js-vm\"));\nregister(makeStub('cron', \"dialect 'cron' not registered. Install @objectstack/plugin-cron\"));\n\n/**\n * The unified evaluation entry point. Replaces the old direct calls to\n * `evaluateFormula` from the deleted custom engine.\n */\nexport const ExpressionEngine = {\n register,\n getEngine,\n hasDialect,\n\n /**\n * Compile-only — parse + type-check, returning the engine-native AST. Used\n * by `objectstack compile` to normalize source into AST in artifacts.\n */\n compile(expr: Expression): EvalResult<unknown> {\n const engine = registry.get(expr.dialect);\n if (!engine) {\n return {\n ok: false,\n error: { kind: 'dialect', message: `No engine registered for dialect '${expr.dialect}'` },\n };\n }\n if (typeof expr.source !== 'string') {\n return {\n ok: false,\n error: { kind: 'parse', message: 'Expression.source required for compile()' },\n };\n }\n return engine.compile(expr.source);\n },\n\n /**\n * Evaluate an expression in the given context. Never throws — branch on\n * `result.ok`. Errors carry a `kind` for caller-side classification.\n */\n evaluate<T = unknown>(expr: Expression, ctx: EvalContext): EvalResult<T> {\n const engine = registry.get(expr.dialect);\n if (!engine) {\n return {\n ok: false,\n error: { kind: 'dialect', message: `No engine registered for dialect '${expr.dialect}'` },\n };\n }\n return engine.evaluate<T>(expr, ctx);\n },\n};\n","/**\n * Seed-value resolver.\n *\n * `Dataset.records` accepts {@link SeedValue} = primitive | Expression | array\n * | object — install-time resolution walks the tree and replaces any\n * Expression node with its evaluated result. This is what makes\n * `close_date: cel\\`now() + duration(\"P30D\")\\`` resolve to *the customer's*\n * \"today + 30 days\" instead of the developer's compile-time clock.\n */\n\nimport { ExpressionSchema, type Expression } from '@objectstack/spec';\n\nimport type { EvalContext, EvalResult } from './types';\nimport { ExpressionEngine } from './registry';\n\nexport type SeedPrimitive = string | number | boolean | null | Date;\nexport type SeedValue = SeedPrimitive | Expression | SeedValue[] | { [key: string]: SeedValue };\n\n/** Detect an Expression-shaped object without throwing on unrelated shapes. */\nfunction isExpressionLike(value: unknown): value is Expression {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false;\n const v = value as Record<string, unknown>;\n if (typeof v.dialect !== 'string') return false;\n return ExpressionSchema.safeParse(v).success;\n}\n\n/**\n * Recursively resolve a SeedValue. Records that contain Expression leaves are\n * evaluated with `ctx`; other values are passed through unchanged.\n *\n * Returns the first failure encountered. Callers (seed loader) typically\n * abort the whole record on failure rather than silently writing partial data.\n */\nexport function resolveSeed(\n value: SeedValue,\n ctx: EvalContext,\n): EvalResult<unknown> {\n if (value === null || value === undefined) {\n return { ok: true, value };\n }\n const t = typeof value;\n if (t === 'string' || t === 'number' || t === 'boolean') {\n return { ok: true, value };\n }\n if (value instanceof Date) {\n return { ok: true, value };\n }\n if (Array.isArray(value)) {\n const out: unknown[] = [];\n for (const item of value) {\n const r = resolveSeed(item, ctx);\n if (!r.ok) return r;\n out.push(r.value);\n }\n return { ok: true, value: out };\n }\n if (isExpressionLike(value)) {\n return ExpressionEngine.evaluate(value, ctx);\n }\n // Plain object — recurse field-by-field.\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, SeedValue>)) {\n const r = resolveSeed(v, ctx);\n if (!r.ok) return r;\n out[k] = r.value;\n }\n return { ok: true, value: out };\n}\n\n/**\n * Resolve a single record (object of fields), pinning `ctx.now` so all\n * expressions within see one logical clock.\n */\nexport function resolveSeedRecord(\n record: Record<string, SeedValue>,\n ctx: EvalContext,\n): EvalResult<Record<string, unknown>> {\n const pinnedCtx: EvalContext = { ...ctx, now: ctx.now ?? new Date() };\n const result = resolveSeed(record, pinnedCtx) as EvalResult<Record<string, unknown>>;\n return result;\n}\n","/**\n * Build-time normalization helpers.\n *\n * The CLI `objectstack compile` step walks the assembled `objectstack.json`\n * artifact and rewrites every Expression so that:\n *\n * 1. String shorthand input is replaced by `{ dialect: 'cel', source }`.\n * 2. The persisted envelope carries an `ast` field produced by the dialect\n * engine (M9.2 deliverable). Source is retained for round-trip / debug.\n *\n * Spec layer cannot do step 2 because it must remain dependency-free; this\n * package owns the engine import and therefore the AST step.\n */\n\nimport {\n ExpressionInputSchema,\n ExpressionSchema,\n type Expression,\n type ExpressionInput,\n} from '@objectstack/spec';\n\nimport { ExpressionEngine } from './registry';\nimport type { EvalResult } from './types';\n\n/**\n * Normalize an {@link ExpressionInput} (string shorthand OR full envelope) into\n * a fully-resolved {@link Expression} carrying both `source` and `ast`.\n *\n * Returns an EvalResult so the caller can render a structured compile error\n * pointing at the offending metadata path.\n */\nexport function normalizeExpression(input: ExpressionInput): EvalResult<Expression> {\n const parsed = ExpressionInputSchema.safeParse(input);\n if (!parsed.success) {\n return {\n ok: false,\n error: { kind: 'parse', message: parsed.error.message },\n };\n }\n\n const expr = parsed.data as Expression;\n\n // Already AST-only — accept as-is.\n if (expr.ast !== undefined && expr.source === undefined) {\n return { ok: true, value: expr };\n }\n\n // Source-bearing: ask the dialect engine to compile. Failures surface here\n // as part of the build (no silent skip).\n const compiled = ExpressionEngine.compile(expr);\n if (!compiled.ok) {\n return compiled;\n }\n\n return {\n ok: true,\n value: {\n ...expr,\n ast: compiled.value,\n },\n };\n}\n\n/**\n * Walk an arbitrary JSON tree and normalize every embedded Expression in\n * place. Used by the build pipeline to traverse the assembled metadata\n * artifact. Returns the first error encountered (paired with the dotted path\n * for diagnostics) or `null` when fully clean.\n */\nexport function normalizeExpressionTree(\n root: unknown,\n path: string[] = [],\n): { path: string; error: import('./types').EvalError } | null {\n if (root === null || typeof root !== 'object') return null;\n\n if (looksLikeExpression(root)) {\n const r = normalizeExpression(root as ExpressionInput);\n if (!r.ok) return { path: path.join('.'), error: r.error };\n Object.assign(root as Record<string, unknown>, r.value);\n return null;\n }\n\n if (Array.isArray(root)) {\n for (let i = 0; i < root.length; i++) {\n const r = normalizeExpressionTree(root[i], [...path, String(i)]);\n if (r) return r;\n }\n return null;\n }\n\n for (const [k, v] of Object.entries(root as Record<string, unknown>)) {\n const r = normalizeExpressionTree(v, [...path, k]);\n if (r) return r;\n }\n return null;\n}\n\nfunction looksLikeExpression(value: unknown): boolean {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false;\n const v = value as Record<string, unknown>;\n if (typeof v.dialect !== 'string') return false;\n return ExpressionSchema.safeParse(v).success;\n}\n"],"mappings":";AAeA,SAAS,mBAAmB;;;ACG5B,SAAS,cAAc,GAAe;AACpC,QAAM,MAAM,IAAI,KAAK,EAAE,QAAQ,CAAC;AAChC,MAAI,YAAY,GAAG,GAAG,GAAG,CAAC;AAC1B,SAAO;AACT;AAGA,SAAS,WAAW,GAAS,GAAiB;AAC5C,QAAM,MAAM,IAAI,KAAK,EAAE,QAAQ,CAAC;AAChC,MAAI,WAAW,IAAI,WAAW,IAAI,CAAC;AACnC,SAAO;AACT;AAUO,SAAS,eACd,KACA,KACa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3
|
+
"version": "4.0.4",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"description": "ObjectStack canonical expression engine — CEL (cel-js) + ObjectStack stdlib + dialect registry",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.mjs",
|
|
12
|
+
"require": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"dependencies": {
|
|
16
|
+
"@marcbachmann/cel-js": "^7.6.1",
|
|
17
|
+
"@objectstack/spec": "4.0.4"
|
|
18
|
+
},
|
|
19
|
+
"devDependencies": {
|
|
20
|
+
"typescript": "^6.0.3",
|
|
21
|
+
"vitest": "^4.1.5"
|
|
22
|
+
},
|
|
23
|
+
"keywords": [
|
|
24
|
+
"objectstack",
|
|
25
|
+
"formula",
|
|
26
|
+
"expression",
|
|
27
|
+
"cel",
|
|
28
|
+
"predicate"
|
|
29
|
+
],
|
|
30
|
+
"author": "ObjectStack",
|
|
31
|
+
"repository": {
|
|
32
|
+
"type": "git",
|
|
33
|
+
"url": "https://github.com/objectstack-ai/framework.git",
|
|
34
|
+
"directory": "packages/formula"
|
|
35
|
+
},
|
|
36
|
+
"homepage": "https://objectstack.ai/docs",
|
|
37
|
+
"bugs": "https://github.com/objectstack-ai/framework/issues",
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public"
|
|
40
|
+
},
|
|
41
|
+
"scripts": {
|
|
42
|
+
"build": "tsup --config ../../tsup.config.ts",
|
|
43
|
+
"test": "vitest run"
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { celEngine } from './cel-engine';
|
|
4
|
+
import type { Expression } from '@objectstack/spec';
|
|
5
|
+
|
|
6
|
+
const cel = (source: string): Expression => ({ dialect: 'cel', source });
|
|
7
|
+
|
|
8
|
+
describe('celEngine', () => {
|
|
9
|
+
it('evaluates simple arithmetic, coercing BigInt to number', () => {
|
|
10
|
+
const r = celEngine.evaluate(cel('1 + 2'), {});
|
|
11
|
+
expect(r).toEqual({ ok: true, value: 3 });
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
it('evaluates predicates against record context', () => {
|
|
15
|
+
const r = celEngine.evaluate(cel('record.amount > 1000'), {
|
|
16
|
+
record: { amount: 1500 },
|
|
17
|
+
});
|
|
18
|
+
expect(r).toEqual({ ok: true, value: true });
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it('exposes os.* namespace from EvalContext', () => {
|
|
22
|
+
const r = celEngine.evaluate(cel('os.user.role == "manager"'), {
|
|
23
|
+
user: { id: 'u1', role: 'manager' },
|
|
24
|
+
});
|
|
25
|
+
expect(r).toEqual({ ok: true, value: true });
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it('uses pinned now() for determinism', () => {
|
|
29
|
+
const pinned = new Date('2026-01-15T10:00:00Z');
|
|
30
|
+
const r = celEngine.evaluate(cel('now()'), { now: pinned });
|
|
31
|
+
expect(r.ok).toBe(true);
|
|
32
|
+
if (r.ok) expect((r.value as Date).toISOString()).toBe(pinned.toISOString());
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('today() truncates to UTC start-of-day', () => {
|
|
36
|
+
const pinned = new Date('2026-01-15T10:30:45.123Z');
|
|
37
|
+
const r = celEngine.evaluate(cel('today()'), { now: pinned });
|
|
38
|
+
expect(r.ok).toBe(true);
|
|
39
|
+
if (r.ok) expect((r.value as Date).toISOString()).toBe('2026-01-15T00:00:00.000Z');
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('daysFromNow(n) advances by n days from pinned now', () => {
|
|
43
|
+
const pinned = new Date('2026-01-15T10:00:00Z');
|
|
44
|
+
const r = celEngine.evaluate(cel('daysFromNow(30)'), { now: pinned });
|
|
45
|
+
expect(r.ok).toBe(true);
|
|
46
|
+
if (r.ok) expect((r.value as Date).toISOString()).toBe('2026-02-14T10:00:00.000Z');
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('classifies parse errors with kind=parse', () => {
|
|
50
|
+
const r = celEngine.evaluate(cel('1 +'), {});
|
|
51
|
+
expect(r.ok).toBe(false);
|
|
52
|
+
if (!r.ok) expect(['parse', 'type', 'runtime']).toContain(r.error.kind);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('enforces AST size bounds (kind=bounds)', () => {
|
|
56
|
+
const huge = Array.from({ length: 500 }, (_, i) => i.toString()).join(' + ');
|
|
57
|
+
const r = celEngine.evaluate(cel(huge), {});
|
|
58
|
+
expect(r.ok).toBe(false);
|
|
59
|
+
if (!r.ok) expect(r.error.kind).toBe('bounds');
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('rejects evaluation when dialect mismatches', () => {
|
|
63
|
+
const r = celEngine.evaluate({ dialect: 'js', source: 'x' } as Expression, {});
|
|
64
|
+
expect(r.ok).toBe(false);
|
|
65
|
+
if (!r.ok) expect(r.error.kind).toBe('dialect');
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('compile() returns AST on success', () => {
|
|
69
|
+
const r = celEngine.compile('record.amount > 1000');
|
|
70
|
+
expect(r.ok).toBe(true);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('handles timestamp + duration arithmetic', () => {
|
|
74
|
+
const pinned = new Date('2026-01-01T00:00:00Z');
|
|
75
|
+
const r = celEngine.evaluate(cel('now() + duration("720h")'), { now: pinned });
|
|
76
|
+
expect(r.ok).toBe(true);
|
|
77
|
+
if (r.ok) expect((r.value as Date).toISOString()).toBe('2026-01-31T00:00:00.000Z');
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it('coerces large BigInt to string to avoid silent truncation', () => {
|
|
81
|
+
const r = celEngine.evaluate(cel('9999999999999999999'), {});
|
|
82
|
+
expect(r.ok).toBe(true);
|
|
83
|
+
if (r.ok) expect(typeof r.value === 'string' || typeof r.value === 'number').toBe(true);
|
|
84
|
+
});
|
|
85
|
+
});
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CEL dialect engine — wraps `@marcbachmann/cel-js` with the ObjectStack
|
|
3
|
+
* stdlib, bounded execution limits, and result coercion.
|
|
4
|
+
*
|
|
5
|
+
* Why a thin wrapper:
|
|
6
|
+
*
|
|
7
|
+
* - cel-js returns `BigInt` for ints. The kernel and CRM expect plain
|
|
8
|
+
* numbers, so we coerce at the boundary.
|
|
9
|
+
* - cel-js parses dotted names as receiver-typed methods; we register
|
|
10
|
+
* `now()`, `today()`, `daysFromNow()` as bare functions and let `os.*`
|
|
11
|
+
* refer to context data only (see {@link buildScope}).
|
|
12
|
+
* - Bounds (`maxAstNodes`, `maxDepth`, …) are enforced spec-wide so
|
|
13
|
+
* third-party plugins can't ship runaway predicates.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { Environment } from '@marcbachmann/cel-js';
|
|
17
|
+
import type { Expression } from '@objectstack/spec';
|
|
18
|
+
|
|
19
|
+
import { buildScope, registerStdLib } from './stdlib';
|
|
20
|
+
import type { DialectEngine, EvalContext, EvalResult } from './types';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Default execution bounds. Picked conservatively — every metadata-authored
|
|
24
|
+
* expression we've seen is well under these. If you hit them, the expression
|
|
25
|
+
* is too complex for ObjectStack and should be moved to a hook (`dialect: js`).
|
|
26
|
+
*/
|
|
27
|
+
export const DEFAULT_LIMITS = {
|
|
28
|
+
maxAstNodes: 256,
|
|
29
|
+
maxDepth: 32,
|
|
30
|
+
maxListElements: 64,
|
|
31
|
+
maxMapEntries: 64,
|
|
32
|
+
maxCallArguments: 16,
|
|
33
|
+
} as const;
|
|
34
|
+
|
|
35
|
+
function buildEnv(now: () => Date): Environment {
|
|
36
|
+
const env = new Environment({
|
|
37
|
+
unlistedVariablesAreDyn: true,
|
|
38
|
+
enableOptionalTypes: true,
|
|
39
|
+
limits: DEFAULT_LIMITS,
|
|
40
|
+
});
|
|
41
|
+
return registerStdLib(env, now);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Coerce cel-js's BigInt-flavored return into spec-friendly JS values. */
|
|
45
|
+
function coerce(value: unknown): unknown {
|
|
46
|
+
if (typeof value === 'bigint') {
|
|
47
|
+
// BigInt → number when safe, else string to avoid silent truncation.
|
|
48
|
+
if (value >= BigInt(Number.MIN_SAFE_INTEGER) && value <= BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
49
|
+
return Number(value);
|
|
50
|
+
}
|
|
51
|
+
return value.toString();
|
|
52
|
+
}
|
|
53
|
+
if (Array.isArray(value)) return value.map(coerce);
|
|
54
|
+
if (value && typeof value === 'object' && !(value instanceof Date)) {
|
|
55
|
+
const out: Record<string, unknown> = {};
|
|
56
|
+
for (const [k, v] of Object.entries(value)) out[k] = coerce(v);
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
return value;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function classifyError(err: unknown): EvalResult<never> {
|
|
63
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
64
|
+
let kind: 'parse' | 'type' | 'runtime' | 'bounds' = 'runtime';
|
|
65
|
+
if (/Exceeded max/i.test(message)) kind = 'bounds';
|
|
66
|
+
else if (/parse|unexpected|syntax/i.test(message)) kind = 'parse';
|
|
67
|
+
else if (/type|unknown variable|undeclared/i.test(message)) kind = 'type';
|
|
68
|
+
return { ok: false, error: { kind, message } };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export const celEngine: DialectEngine = {
|
|
72
|
+
dialect: 'cel',
|
|
73
|
+
|
|
74
|
+
compile(source: string): EvalResult<unknown> {
|
|
75
|
+
try {
|
|
76
|
+
// We use a wall-clock now() here purely for parse-time stdlib
|
|
77
|
+
// type-checking; the function is never actually called.
|
|
78
|
+
const env = buildEnv(() => new Date(0));
|
|
79
|
+
const compiled = env.parse(source);
|
|
80
|
+
// Surface check errors eagerly.
|
|
81
|
+
const checkErrors = compiled.check?.();
|
|
82
|
+
if (checkErrors && Array.isArray(checkErrors) && checkErrors.length > 0) {
|
|
83
|
+
return {
|
|
84
|
+
ok: false,
|
|
85
|
+
error: { kind: 'type', message: checkErrors.join('; ') },
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
return { ok: true, value: compiled.ast };
|
|
89
|
+
} catch (err) {
|
|
90
|
+
return classifyError(err);
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
|
|
94
|
+
evaluate<T = unknown>(expr: Expression, ctx: EvalContext): EvalResult<T> {
|
|
95
|
+
if (expr.dialect !== 'cel') {
|
|
96
|
+
return {
|
|
97
|
+
ok: false,
|
|
98
|
+
error: { kind: 'dialect', message: `celEngine cannot evaluate dialect '${expr.dialect}'` },
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
const source = expr.source;
|
|
102
|
+
if (typeof source !== 'string' || source.length === 0) {
|
|
103
|
+
// AST-only inputs: cel-js does not currently expose a public API to
|
|
104
|
+
// re-execute a parsed AST without re-serializing. We persist `source`
|
|
105
|
+
// as the canonical form during M9.1 and revisit AST-only execution in
|
|
106
|
+
// M9.7 when we cut the spec persistence over.
|
|
107
|
+
return {
|
|
108
|
+
ok: false,
|
|
109
|
+
error: { kind: 'parse', message: 'AST-only evaluation not yet supported; persist `source`' },
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const now = () => ctx.now ?? new Date();
|
|
114
|
+
try {
|
|
115
|
+
const env = buildEnv(now);
|
|
116
|
+
const scope = buildScope(ctx);
|
|
117
|
+
const raw = env.evaluate(source, scope);
|
|
118
|
+
return { ok: true, value: coerce(raw) as T };
|
|
119
|
+
} catch (err) {
|
|
120
|
+
return classifyError(err);
|
|
121
|
+
}
|
|
122
|
+
},
|
|
123
|
+
};
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @objectstack/formula
|
|
3
|
+
*
|
|
4
|
+
* Canonical expression engine for ObjectStack. CEL (Common Expression
|
|
5
|
+
* Language) is the default dialect; `js` and `cron` are dispatched to
|
|
6
|
+
* dedicated plugin engines.
|
|
7
|
+
*
|
|
8
|
+
* @see content/docs/concepts/north-star.mdx §8 "No private expression DSL"
|
|
9
|
+
* @see ROADMAP.md M9 "Expression Unification"
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export { ExpressionEngine, getEngine, hasDialect, register } from './registry';
|
|
13
|
+
export { celEngine, DEFAULT_LIMITS } from './cel-engine';
|
|
14
|
+
export { registerStdLib, buildScope } from './stdlib';
|
|
15
|
+
export { resolveSeed, resolveSeedRecord } from './seed-eval';
|
|
16
|
+
export { normalizeExpression, normalizeExpressionTree } from './normalize';
|
|
17
|
+
export type { SeedValue, SeedPrimitive } from './seed-eval';
|
|
18
|
+
export type { DialectEngine, EvalContext, EvalResult, EvalError } from './types';
|