@coldsmirk/abacus-core 0.2.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.
- package/LICENSE +201 -0
- package/README.md +375 -0
- package/dist/index.cjs +762 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +495 -0
- package/dist/index.d.ts +495 -0
- package/dist/index.js +730 -0
- package/dist/index.js.map +1 -0
- package/package.json +59 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Venus
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
# @coldsmirk/abacus-core
|
|
2
|
+
|
|
3
|
+
Framework-agnostic [ZEN expression](https://gorules.io/docs/rules-engine/expression-language/) engine for the frontend. Compile, evaluate, and type-analyze ZEN expressions on top of the [GoRules ZEN](https://github.com/gorules/zen) WebAssembly engine. Pure TypeScript — no React, no DOM, no UI framework.
|
|
4
|
+
|
|
5
|
+
Part of [abacus](https://github.com/coldsmirk/abacus). To edit expressions in an editor, add [`@coldsmirk/abacus-codemirror`](https://www.npmjs.com/package/@coldsmirk/abacus-codemirror) (any framework) or [`@coldsmirk/abacus-react`](https://www.npmjs.com/package/@coldsmirk/abacus-react) (a ready-made `<ExpressionInput>`).
|
|
6
|
+
|
|
7
|
+
## What you get
|
|
8
|
+
|
|
9
|
+
- **Evaluate** ZEN expressions against a data context, sync or async.
|
|
10
|
+
- **Compile** a structured, UI-authored condition tree into a single ZEN boolean expression, and **select** a matching branch by priority.
|
|
11
|
+
- **Type-analyze** an expression against a variable-context type tree — the inferred type of every span, autocomplete metadata, and positioned diagnostics that power an editor.
|
|
12
|
+
- **Localize** all editor-produced text through a typed, extensible message catalog.
|
|
13
|
+
- **Strong typing** end to end, dual ESM / CJS, and a single lazily-loaded WebAssembly engine instance.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pnpm add @coldsmirk/abacus-core
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
The ZEN WebAssembly engine (`@gorules/zen-engine-wasm`) is a regular dependency and installs automatically. Node.js >= 22; browsers need ES2023 support (Chrome/Edge 111+, Safari 16.2+, Firefox 115+) — the bundles ship untranspiled.
|
|
22
|
+
|
|
23
|
+
## Quick start
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { evaluate, evaluateUnary, loadEngine } from "@coldsmirk/abacus-core";
|
|
27
|
+
|
|
28
|
+
// The engine loads on first use; await it (or any async helper) once up front.
|
|
29
|
+
await loadEngine();
|
|
30
|
+
|
|
31
|
+
// A standard expression evaluates to any value.
|
|
32
|
+
await evaluate("amount * 1.2", { amount: 100 }); // 120
|
|
33
|
+
|
|
34
|
+
// A unary (test) expression is a boolean condition whose implicit subject is `$`.
|
|
35
|
+
await evaluateUnary("$ > 1000", { $: 1500 }); // true
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Core concepts
|
|
39
|
+
|
|
40
|
+
### Standard vs unary expressions
|
|
41
|
+
|
|
42
|
+
ZEN has two expression flavours, selected throughout this package by a `mode: "standard" | "unary"`:
|
|
43
|
+
|
|
44
|
+
- **standard** — computes a value of any type, e.g. `amount * 1.2`, `customer.name`, `upper(code)`.
|
|
45
|
+
- **unary** — a boolean _test_ against an implicit subject `$`, e.g. `$ > 1000`, `$ in ['BJ', 'SH']`. Used for conditions.
|
|
46
|
+
|
|
47
|
+
### The engine loads once, lazily
|
|
48
|
+
|
|
49
|
+
The multi-megabyte WebAssembly binary is fetched on first use via a dynamic `import()`, then cached as a single frozen instance for the lifetime of the page. Every helper comes in two forms:
|
|
50
|
+
|
|
51
|
+
- **async** (`evaluate`, `analyzeTypes`, …) — loads the engine on demand, then runs. Safe to call any time.
|
|
52
|
+
- **sync** (`evaluateSync`, `analyzeTypesSync`, …) — run immediately, but throw `ExpressionNotReadyError` if the engine has not loaded yet. Use them only behind a readiness check (`isEngineReady()`) or after `await loadEngine()`. They exist for hot paths like an editor's per-keystroke type-checking, where awaiting a promise each call is not an option.
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
import { evaluateSync, isEngineReady, loadEngine } from "@coldsmirk/abacus-core";
|
|
56
|
+
|
|
57
|
+
await loadEngine();
|
|
58
|
+
if (isEngineReady()) {
|
|
59
|
+
evaluateSync<number>("a + b", { a: 1, b: 2 }); // 3
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Evaluating expressions
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
function evaluate<T = unknown>(expression: string, context?: ExpressionContext): Promise<T>;
|
|
67
|
+
function evaluateSync<T = unknown>(expression: string, context?: ExpressionContext): T;
|
|
68
|
+
function evaluateUnary(expression: string, context?: ExpressionContext): Promise<boolean>;
|
|
69
|
+
function evaluateUnarySync(expression: string, context?: ExpressionContext): boolean;
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
`ExpressionContext` is just `Record<string, unknown>` — the object property paths in the expression resolve against. `evaluate("customer.age", { customer: { age: 30 } })` → `30`.
|
|
73
|
+
|
|
74
|
+
The `T` type parameter on `evaluate` / `evaluateSync` is an **unchecked assertion** — the value is returned as `T` with no runtime validation, since a ZEN result type depends on the expression and context. Prefer the `unknown` default and narrow at the call site, or pass `T` only when you are sure.
|
|
75
|
+
|
|
76
|
+
A failed evaluation throws `ExpressionError` carrying the offending `expression` and the original cause:
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
import { ExpressionError, evaluate } from "@coldsmirk/abacus-core";
|
|
80
|
+
|
|
81
|
+
try {
|
|
82
|
+
await evaluate("amount > "); // malformed
|
|
83
|
+
} catch (error) {
|
|
84
|
+
if (error instanceof ExpressionError) {
|
|
85
|
+
error.expression; // "amount > "
|
|
86
|
+
error.cause; // the underlying engine error
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Engine lifecycle
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
function loadEngine(): Promise<ExpressionEngine>; // load once; concurrent callers share the promise
|
|
95
|
+
function isEngineReady(): boolean; // has it finished loading?
|
|
96
|
+
function getEngineSync(): ExpressionEngine; // the instance, or throws ExpressionNotReadyError
|
|
97
|
+
function getEngineError(): ExpressionError | null; // the last load failure, if any
|
|
98
|
+
function configureEngine(options: LoadEngineOptions): void;
|
|
99
|
+
function resetEngine(): void;
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
`loadEngine()` is idempotent: the first call starts the load, and concurrent or later calls share the same in-flight promise (and then the resolved instance). A **failed** load is not cached — the rejected promise is dropped (the error is latched on `getEngineError()` for inspection) so a later `loadEngine()` retries from scratch. This is the clear-and-reload retry primitive after a transient failure.
|
|
103
|
+
|
|
104
|
+
`ExpressionEngine` is the low-level synchronous instance returned by `loadEngine()` / `getEngineSync()`. Most apps use the top-level helpers above instead of calling its methods directly, but it is exported for advanced use:
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
interface ExpressionEngine {
|
|
108
|
+
evaluate: <T = unknown>(expression: string, context?: ExpressionContext) => T;
|
|
109
|
+
evaluateUnary: (expression: string, context?: ExpressionContext) => boolean;
|
|
110
|
+
validate: (expression: string) => unknown; // ZEN's raw diagnostic payload (null when valid)
|
|
111
|
+
validateUnary: (expression: string) => unknown;
|
|
112
|
+
getCompletions: () => unknown; // ZEN's raw completion metadata
|
|
113
|
+
analyze: (variables: ExpressionType, source: string, unary: boolean) => ExpressionAnalysis;
|
|
114
|
+
satisfies: (actual: ExpressionType, expected: ExpressionType) => boolean;
|
|
115
|
+
isReady: () => boolean;
|
|
116
|
+
}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### Hosting the WebAssembly binary
|
|
120
|
+
|
|
121
|
+
In a normal browser app, the engine resolves its co-located `.wasm` through the GoRules package's own `import.meta.url`, which bundlers (Vite, webpack, Rspack) rewrite to a served asset URL — **no configuration needed**.
|
|
122
|
+
|
|
123
|
+
For environments where that automatic resolution does not work — a non-browser or non-DOM host (Node, SSR, a Web Worker) or CDN-hosted wasm — supply the binary explicitly via `configureEngine({ wasmInput })` **before** the first load. `wasmInput` accepts whatever the wasm initializer accepts (a URL, `Response`, `ArrayBuffer`, bytes, …):
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
import { configureEngine, loadEngine } from "@coldsmirk/abacus-core";
|
|
127
|
+
|
|
128
|
+
configureEngine({ wasmInput: await fetch("https://cdn.example.com/zen.wasm").then(r => r.arrayBuffer()) });
|
|
129
|
+
await loadEngine();
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
`configureEngine()` throws if called after the engine has started loading. `resetEngine()` drops the loaded engine, the cached type context, the latched error, and the configured input — mainly for tests, but also the way to re-`configureEngine()` after a load.
|
|
133
|
+
|
|
134
|
+
## Type analysis & intelligence
|
|
135
|
+
|
|
136
|
+
These functions power editors: completion, hover types, and diagnostics. They all accept a **variable-context type tree** of type `ExpressionType` describing the shape of the data the expression runs against.
|
|
137
|
+
|
|
138
|
+
### The `ExpressionType` shape
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
type ExpressionType =
|
|
142
|
+
| "Any" | "Null" | "Bool" | "String" | "Number" | "Date" // primitive kinds
|
|
143
|
+
| { Const: string } // a literal constant
|
|
144
|
+
| { Enum: [string | undefined, string[]] } // a named enum + its members
|
|
145
|
+
| { Array: ExpressionType } // a homogeneous array
|
|
146
|
+
| { Object: Record<string, ExpressionType> }; // a nested object
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
Example — a form context with a number, a string, and a nested object:
|
|
150
|
+
|
|
151
|
+
```ts
|
|
152
|
+
const variables: ExpressionType = {
|
|
153
|
+
Object: {
|
|
154
|
+
amount: "Number",
|
|
155
|
+
status: "String",
|
|
156
|
+
customer: { Object: { name: "String", since: "Date" } },
|
|
157
|
+
tags: { Array: "String" },
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
### Functions
|
|
163
|
+
|
|
164
|
+
```ts
|
|
165
|
+
function analyzeTypes(variables: ExpressionType, source: string, mode: ExpressionMode): Promise<ExpressionAnalysis>;
|
|
166
|
+
function getDiagnostics(expression: string, mode: ExpressionMode): Promise<ExpressionDiagnostic | null>;
|
|
167
|
+
function getCompletionItems(): Promise<ExpressionCompletion[]>;
|
|
168
|
+
function satisfiesType(actual: ExpressionType, expected: ExpressionType): Promise<boolean>;
|
|
169
|
+
// ...each has a *Sync twin with the same signature (minus the Promise).
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
```ts
|
|
173
|
+
import { analyzeTypes, getDiagnostics, satisfiesType } from "@coldsmirk/abacus-core";
|
|
174
|
+
|
|
175
|
+
const analysis = await analyzeTypes(variables, "amount > 1000", "standard");
|
|
176
|
+
analysis.rootKind; // the context type (the variables object)
|
|
177
|
+
analysis.spans[0].kind; // "Bool" — spans[0] is the whole-expression result type
|
|
178
|
+
|
|
179
|
+
await getDiagnostics("amount >", "standard"); // → positioned diagnostic, or null when valid
|
|
180
|
+
await satisfiesType("Number", "Number"); // → true (is `actual` assignable to `expected`?)
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
The result shapes:
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
interface ExpressionAnalysis {
|
|
187
|
+
rootKind: ExpressionType; // the context type
|
|
188
|
+
spans: ExpressionTypeSpan[]; // per-span inferred types; spans[0] is the whole-expression result
|
|
189
|
+
}
|
|
190
|
+
interface ExpressionTypeSpan {
|
|
191
|
+
error: string | null; // a type error attached to this span, if any
|
|
192
|
+
kind: ExpressionType; // the inferred type of this span
|
|
193
|
+
nodeKind: string; // the syntax-node kind
|
|
194
|
+
span: [number, number]; // [from, to] character offsets
|
|
195
|
+
}
|
|
196
|
+
interface ExpressionDiagnostic {
|
|
197
|
+
from: number; // start offset
|
|
198
|
+
to: number; // end offset
|
|
199
|
+
message: string; // human-readable message
|
|
200
|
+
source: string; // origin label, e.g. "Parser error" (localized)
|
|
201
|
+
}
|
|
202
|
+
interface ExpressionCompletion {
|
|
203
|
+
type: "function" | "method" | "variable";
|
|
204
|
+
label: string; // the name to insert
|
|
205
|
+
detail: string; // signature, e.g. "(value: string) -> number"
|
|
206
|
+
info: string; // description (localized)
|
|
207
|
+
boost: number | null; // sort weight
|
|
208
|
+
methodFor: string | null; // for methods, the type-kind they attach to, e.g. "Date"
|
|
209
|
+
}
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
> Building an editor? You usually do not call these directly — `@coldsmirk/abacus-codemirror` and `@coldsmirk/abacus-react` wire them into CodeMirror for you.
|
|
213
|
+
|
|
214
|
+
## Compiling conditions
|
|
215
|
+
|
|
216
|
+
A common need is to let users author conditions in a UI (field / operator / value rows, AND/OR groups, prioritized branches) and turn that structure into a ZEN expression. This package models that structure and compiles it — without depending on any editor.
|
|
217
|
+
|
|
218
|
+
### The condition model
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
interface FieldConditionInput { // a field/operator/value triple
|
|
222
|
+
kind: "field";
|
|
223
|
+
subject: string; // an identifier path, e.g. "amount" or "customer.age"
|
|
224
|
+
operator: ConditionOperator;
|
|
225
|
+
value: unknown;
|
|
226
|
+
}
|
|
227
|
+
interface ExpressionConditionInput { // a raw ZEN expression, passed through
|
|
228
|
+
kind: "expression";
|
|
229
|
+
expression: string;
|
|
230
|
+
}
|
|
231
|
+
type ConditionInput = FieldConditionInput | ExpressionConditionInput;
|
|
232
|
+
|
|
233
|
+
interface ConditionGroupInput { // conditions combined with AND
|
|
234
|
+
conditions: readonly ConditionInput[];
|
|
235
|
+
}
|
|
236
|
+
interface ConditionBranchInput { // a branch guarded by groups combined with OR
|
|
237
|
+
id: string;
|
|
238
|
+
priority: number; // lower number = higher priority
|
|
239
|
+
isDefault?: boolean;
|
|
240
|
+
conditionGroups?: readonly ConditionGroupInput[];
|
|
241
|
+
}
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
### Operators
|
|
245
|
+
|
|
246
|
+
`ConditionOperator` is derived from the runtime constant `CONDITION_OPERATORS`, so validators and condition UIs can build their allow-list from one source of truth. Each maps to ZEN as follows:
|
|
247
|
+
|
|
248
|
+
| Operator | ZEN output |
|
|
249
|
+
| --------------------------- | ---------------------------------------------------------------------------------------------- |
|
|
250
|
+
| `eq` / `ne` | `subject == value` / `subject != value` |
|
|
251
|
+
| `gt` / `gte` / `lt` / `lte` | `subject > value` (and `>=`, `<`, `<=`) |
|
|
252
|
+
| `contains` / `not_contains` | `contains(subject, value)` / `not contains(subject, value)` |
|
|
253
|
+
| `starts_with` / `ends_with` | `startsWith(subject, value)` / `endsWith(subject, value)` |
|
|
254
|
+
| `in` / `not_in` | `subject in [..]` / `not (subject in [..])` (a scalar value is wrapped to a one-element array) |
|
|
255
|
+
| `is_empty` / `is_not_empty` | a typed emptiness test (null / blank string / empty array) and its negation |
|
|
256
|
+
|
|
257
|
+
### Compiling and selecting
|
|
258
|
+
|
|
259
|
+
```ts
|
|
260
|
+
function compileCondition(condition: ConditionInput): string | null;
|
|
261
|
+
function compileGroup(group: ConditionGroupInput): string | null; // conditions joined with AND
|
|
262
|
+
function compileBranch(branch: ConditionBranchInput): string | null; // groups joined with OR
|
|
263
|
+
function selectBranch(branches: readonly ConditionBranchInput[], context: ExpressionContext): Promise<BranchSelection>;
|
|
264
|
+
function selectBranchWith(
|
|
265
|
+
branches: readonly ConditionBranchInput[],
|
|
266
|
+
context: ExpressionContext,
|
|
267
|
+
engine: Pick<ExpressionEngine, "evaluate" | "validate">,
|
|
268
|
+
): BranchSelection; // synchronous; bring your own loaded engine
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
```ts
|
|
272
|
+
import { compileCondition, selectBranch } from "@coldsmirk/abacus-core";
|
|
273
|
+
|
|
274
|
+
compileCondition({ kind: "field", subject: "amount", operator: "gt", value: 1000 });
|
|
275
|
+
// → "amount > 1000"
|
|
276
|
+
|
|
277
|
+
const branches = [
|
|
278
|
+
{ id: "default", priority: 99, isDefault: true },
|
|
279
|
+
{ id: "vip", priority: 1, conditionGroups: [{ conditions: [
|
|
280
|
+
{ kind: "field", subject: "amount", operator: "gt", value: 1000 },
|
|
281
|
+
] }] },
|
|
282
|
+
];
|
|
283
|
+
await selectBranch(branches, { amount: 1500 }); // { branchId: "vip", matched: true }
|
|
284
|
+
await selectBranch(branches, { amount: 10 }); // { branchId: "default", matched: false }
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
`selectBranch` tests non-default branches in ascending `priority` order and returns the first whose compiled expression evaluates to `true`; otherwise it falls back to the default branch (or a `null` id if there is none). A branch whose expression throws at runtime (e.g. comparing a missing field) is treated as _not matching_ rather than propagating — so a missing value degrades to the default branch instead of crashing. In development (`NODE_ENV !== "production"`) a non-default branch that compiles to nothing — a mistyped subject, an unrepresentable value — logs a `console.warn`, since it can never match and would otherwise only show up as "always falls through to default".
|
|
288
|
+
|
|
289
|
+
```ts
|
|
290
|
+
type BranchSelection =
|
|
291
|
+
| { matched: true; branchId: string } // a non-default branch matched
|
|
292
|
+
| { matched: false; branchId: string | null }; // default fallback, or null if none
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
### Safety: subjects, values, and escaping
|
|
296
|
+
|
|
297
|
+
The compiler is designed not to become an expression-injection sink:
|
|
298
|
+
|
|
299
|
+
- A **subject** is emitted verbatim, so it must be a plain identifier path (`amount`, `user.age`, `items[0]`) whose segments are not ZEN reserved words (`and`, `or`, `not`, `in`, `true`, `false`, `null`). Anything else (`len(secret)`, `a or b`, a bare `true`, …) makes the condition compile to `null` and be dropped.
|
|
300
|
+
- A **value** is serialized to a ZEN literal via `toZenLiteral`, never interpolated as code. Strings are quoted _raw_ (ZEN honours no backslash escapes) by picking a delimiter the value does not contain; a value that cannot be represented (an object, a string containing both quote styles, a non-finite number) makes the condition degrade to `null`.
|
|
301
|
+
|
|
302
|
+
```ts
|
|
303
|
+
function toZenLiteral(value: unknown): string; // throws if the value has no faithful ZEN representation
|
|
304
|
+
|
|
305
|
+
toZenLiteral("active"); // "'active'"
|
|
306
|
+
toZenLiteral("it's"); // "\"it's\"" (switches delimiter)
|
|
307
|
+
toZenLiteral(1500); // "1500"
|
|
308
|
+
toZenLiteral(["BJ", "SH"]); // "['BJ', 'SH']"
|
|
309
|
+
toZenLiteral(null); // "null"
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
`compileCondition` / `compileGroup` / `compileBranch` return `null` (rather than throwing) whenever a part cannot be represented, so an incomplete or invalid condition simply drops out instead of producing broken ZEN.
|
|
313
|
+
|
|
314
|
+
## Localization
|
|
315
|
+
|
|
316
|
+
Every piece of editor-produced text — built-in descriptions, diagnostic origin labels, and type-check prose — flows through a single typed catalog, so you can switch language or override individual strings in one place. (The engine's own raw error bodies, identifiers, and type signatures are never translated.)
|
|
317
|
+
|
|
318
|
+
```ts
|
|
319
|
+
interface ExpressionMessages {
|
|
320
|
+
sourceLabel: (type?: string) => string; // diagnostic origin, e.g. "parserError" → "Parser error"
|
|
321
|
+
completionInfo: (englishInfo: string) => string; // translate a built-in's English description
|
|
322
|
+
typeCheckSource: string; // the source label on type-check diagnostics
|
|
323
|
+
expectedBoolean: (actualType: string) => string; // warning for a non-boolean unary result
|
|
324
|
+
expectedType: (expectedType: string, actualType: string) => string; // expected-type-mismatch warning
|
|
325
|
+
}
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
```ts
|
|
329
|
+
import { configureExpressionMessages } from "@coldsmirk/abacus-core";
|
|
330
|
+
|
|
331
|
+
configureExpressionMessages({ locale: "zh-CN" }); // switch to a built-in locale
|
|
332
|
+
configureExpressionMessages({ messages: { typeCheckSource: "Validation" } }); // override individual strings
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
The catalog is **process-global and last-write-wins** — there is one active catalog per runtime, so configure it once at startup. Built-in catalogs `enMessages` (the default) and `zhCNMessages` are exported. `getExpressionMessages()` returns the active one.
|
|
336
|
+
|
|
337
|
+
To add a language the library does not ship, register a full catalog under a key, then select it like any built-in — built-in and custom locales share one registry, so there is no privileged path:
|
|
338
|
+
|
|
339
|
+
```ts
|
|
340
|
+
import { configureExpressionMessages, enMessages, registerExpressionLocale } from "@coldsmirk/abacus-core";
|
|
341
|
+
|
|
342
|
+
registerExpressionLocale("ja-JP", {
|
|
343
|
+
...enMessages,
|
|
344
|
+
typeCheckSource: "型チェック",
|
|
345
|
+
// ...override the rest
|
|
346
|
+
});
|
|
347
|
+
configureExpressionMessages({ locale: "ja-JP" });
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
> `@coldsmirk/abacus-react` re-exports `configureExpressionMessages` / `registerExpressionLocale` and also exposes `locale` / `messages` on `ExpressionConfigProvider` for convenience.
|
|
351
|
+
|
|
352
|
+
## Errors
|
|
353
|
+
|
|
354
|
+
```ts
|
|
355
|
+
class ExpressionError extends Error { // engine load / evaluation failure
|
|
356
|
+
readonly expression?: string; // the offending expression, if any
|
|
357
|
+
// `cause` carries the original failure
|
|
358
|
+
}
|
|
359
|
+
class ExpressionNotReadyError extends ExpressionError { // a *Sync helper called before the engine loaded
|
|
360
|
+
}
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
## API reference
|
|
364
|
+
|
|
365
|
+
- **Evaluate** — `evaluate`, `evaluateSync`, `evaluateUnary`, `evaluateUnarySync`
|
|
366
|
+
- **Engine lifecycle** — `loadEngine`, `isEngineReady`, `getEngineSync`, `getEngineError`, `configureEngine`, `resetEngine`
|
|
367
|
+
- **Type analysis** — `analyzeTypes` / `analyzeTypesSync`, `getDiagnostics` / `getDiagnosticsSync`, `getCompletionItems` / `getCompletionItemsSync`, `satisfiesType` / `satisfiesTypeSync`
|
|
368
|
+
- **Conditions** — `compileCondition`, `compileGroup`, `compileBranch`, `selectBranch`, `selectBranchWith`, `toZenLiteral`, `CONDITION_OPERATORS`
|
|
369
|
+
- **Localization** — `configureExpressionMessages`, `registerExpressionLocale`, `getExpressionMessages`, `enMessages`, `zhCNMessages`
|
|
370
|
+
- **Errors** — `ExpressionError`, `ExpressionNotReadyError`
|
|
371
|
+
- **Types** — `ExpressionType`, `ExpressionMode`, `ExpressionContext`, `ExpressionEngine`, `LoadEngineOptions`, `ExpressionAnalysis`, `ExpressionTypeSpan`, `ExpressionCompletion`, `ExpressionDiagnostic`, `ExpressionMessages`, `ExpressionLocale`, `BuiltInExpressionLocale`, `ConfigureMessagesOptions`, `ConditionInput`, `FieldConditionInput`, `ExpressionConditionInput`, `ConditionGroupInput`, `ConditionBranchInput`, `ConditionOperator`, `BranchSelection`
|
|
372
|
+
|
|
373
|
+
## License
|
|
374
|
+
|
|
375
|
+
Apache-2.0
|