@molecule/api-ai-workflow-engine 1.0.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 +115 -0
- package/dist/browser-guard.d.ts +2 -0
- package/dist/browser-guard.d.ts.map +1 -0
- package/dist/browser-guard.js +18 -0
- package/dist/index.d.ts +165 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +238 -0
- package/dist/safe-evaluator.d.ts +58 -0
- package/dist/safe-evaluator.d.ts.map +1 -0
- package/dist/safe-evaluator.js +303 -0
- package/package.json +44 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
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
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is based on (or derived from) the Work and for which the
|
|
41
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
42
|
+
represent, as a whole, an original work of authorship.
|
|
43
|
+
|
|
44
|
+
"Contribution" shall mean any work of authorship, including the
|
|
45
|
+
original version of the Work and any modifications or additions
|
|
46
|
+
to that Work, that is intentionally submitted to the Licensor for
|
|
47
|
+
inclusion in the Work by the copyright owner or by an individual or
|
|
48
|
+
Legal Entity authorized to submit on behalf of the copyright owner.
|
|
49
|
+
|
|
50
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
51
|
+
on behalf of whom a Contribution has been received by the Licensor and
|
|
52
|
+
subsequently incorporated within the Work.
|
|
53
|
+
|
|
54
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
55
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
56
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
57
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
58
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
59
|
+
Work and such Derivative Works in Source or Object form.
|
|
60
|
+
|
|
61
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
62
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
63
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
64
|
+
patent license to make, have made, use, offer to sell, sell, import,
|
|
65
|
+
and otherwise transfer the Work.
|
|
66
|
+
|
|
67
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
68
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
69
|
+
modifications, and in Source or Object form, provided that You
|
|
70
|
+
meet the following conditions:
|
|
71
|
+
|
|
72
|
+
(a) You must give any other recipients of the Work or
|
|
73
|
+
Derivative Works a copy of this License; and
|
|
74
|
+
|
|
75
|
+
(b) You must cause any modified files to carry prominent notices
|
|
76
|
+
stating that You changed the files; and
|
|
77
|
+
|
|
78
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
79
|
+
that You distribute, all copyright, patent, trademark, and
|
|
80
|
+
attribution notices from the Source form of the Work,
|
|
81
|
+
excluding those notices that do not pertain to any part of
|
|
82
|
+
the Derivative Works; and
|
|
83
|
+
|
|
84
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
85
|
+
distribution, then any Derivative Works that You distribute must
|
|
86
|
+
include a readable copy of the attribution notices contained
|
|
87
|
+
within such NOTICE file.
|
|
88
|
+
|
|
89
|
+
5. Submission of Contributions.
|
|
90
|
+
|
|
91
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
92
|
+
names, trademarks, service marks, or product names of the Licensor.
|
|
93
|
+
|
|
94
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
95
|
+
agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
|
|
96
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
|
|
97
|
+
|
|
98
|
+
8. Limitation of Liability. In no event and under no legal theory shall
|
|
99
|
+
any Contributor be liable to You for damages.
|
|
100
|
+
|
|
101
|
+
9. Accepting Warranty or Additional Liability.
|
|
102
|
+
|
|
103
|
+
Copyright 2026 Molecule Dev, Inc.
|
|
104
|
+
|
|
105
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
106
|
+
you may not use this file except in compliance with the License.
|
|
107
|
+
You may obtain a copy of the License at
|
|
108
|
+
|
|
109
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
110
|
+
|
|
111
|
+
Unless required by applicable law or agreed to in writing, software
|
|
112
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
113
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
114
|
+
See the License for the specific language governing permissions and
|
|
115
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser guard — `@molecule/api-ai-workflow-engine` is SERVER-ONLY.
|
|
3
|
+
*
|
|
4
|
+
* Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
|
|
5
|
+
* Evaluating a server package in a browser bundle is always an import-graph mistake
|
|
6
|
+
* (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
|
|
7
|
+
* ("Buffer is not defined") far from the culprit. Throwing here names the package and
|
|
8
|
+
* the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
|
|
9
|
+
* unaffected: the throw requires browser globals AND the absence of a node runtime.
|
|
10
|
+
*/
|
|
11
|
+
const g = globalThis;
|
|
12
|
+
if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
|
|
13
|
+
throw new Error('@molecule/api-ai-workflow-engine is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
|
|
14
|
+
'from server code (a server route/function or your API), or dynamic-import it inside ' +
|
|
15
|
+
'the server handler — never from components or shared client modules, and never ' +
|
|
16
|
+
'polyfill Buffer/process to silence this.');
|
|
17
|
+
}
|
|
18
|
+
export {};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@molecule/api-ai-workflow-engine` — trigger / condition / action
|
|
3
|
+
* workflow runner with pluggable handler registry + an optional AI
|
|
4
|
+
* `ai_prompt` step (send a templated prompt to the bonded AI provider
|
|
5
|
+
* mid-run).
|
|
6
|
+
*
|
|
7
|
+
* Extracted from ai-workflow-automator flagship. Use it like an
|
|
8
|
+
* embeddable Zapier engine inside your app.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* import { createWorkflowEngine } from '@molecule/api-ai-workflow-engine'
|
|
13
|
+
*
|
|
14
|
+
* const engine = createWorkflowEngine({
|
|
15
|
+
* triggers: {
|
|
16
|
+
* 'webhook.received': async (ctx) => ctx.payload,
|
|
17
|
+
* },
|
|
18
|
+
* actions: {
|
|
19
|
+
* 'slack.message': async ({ channel, text }) => slackClient.chat.postMessage({ channel, text }),
|
|
20
|
+
* },
|
|
21
|
+
* })
|
|
22
|
+
*
|
|
23
|
+
* const run = await engine.execute({
|
|
24
|
+
* trigger: 'webhook.received',
|
|
25
|
+
* triggerInput: { payload: req.body },
|
|
26
|
+
* steps: [
|
|
27
|
+
* { type: 'condition', expression: '$.event === "purchase"' },
|
|
28
|
+
* // Native HTTP step — routed through the swappable `@molecule/api-http` core:
|
|
29
|
+
* { type: 'http', method: 'POST', url: 'https://hooks.example.com/${$.id}', body: { amount: '${$.amount}' }, output: 'webhook' },
|
|
30
|
+
* { type: 'action', action: 'slack.message', params: { channel: '#sales', text: 'New sale: ${$.amount}' } },
|
|
31
|
+
* ],
|
|
32
|
+
* })
|
|
33
|
+
* ```
|
|
34
|
+
*
|
|
35
|
+
* @remarks
|
|
36
|
+
* SECURITY — `condition` step evaluation is SAFE BY DEFAULT. Expressions are run
|
|
37
|
+
* through a small built-in interpreter ({@link safeEvaluateCondition}) that
|
|
38
|
+
* supports member access, comparisons, boolean logic and literals but does NOT
|
|
39
|
+
* use `new Function`/`eval`, cannot call functions or assign, and blocks
|
|
40
|
+
* `__proto__`/`constructor`/`prototype` — so a malicious expression cannot
|
|
41
|
+
* execute arbitrary code. Full unsandboxed JavaScript (`new Function`) is
|
|
42
|
+
* OPT-IN only via `EngineOptions.allowUnsafeConditionEval: true` — enable it
|
|
43
|
+
* ONLY for workflow definitions authored by TRUSTED developers/admins, never
|
|
44
|
+
* from end-user input. You may also supply your own `EngineOptions.conditionEvaluator`
|
|
45
|
+
* (e.g. a hardened sandbox), which replaces both built-ins. An expression that
|
|
46
|
+
* throws or fails to parse counts as `false` — the run short-circuits with
|
|
47
|
+
* `ok: true` (a skipped run, not a failure).
|
|
48
|
+
*
|
|
49
|
+
* `'http'` steps ARE executed: the request is sent through the swappable
|
|
50
|
+
* `@molecule/api-http` core (bond `@molecule/api-http-axios` etc. to change the
|
|
51
|
+
* client — the engine hardcodes no HTTP library). `${$.path}` templates in
|
|
52
|
+
* `url`/`headers`/`params`/`body` are resolved against context, the
|
|
53
|
+
* `{ status, statusText, headers, data }` response is written to `output`, and a
|
|
54
|
+
* trace entry is recorded. A non-2xx response (the http core throws an
|
|
55
|
+
* `HttpError`) yields an `errored` trace entry and halts the run — never a
|
|
56
|
+
* silent skip. Registering an `http.*` action still works too, if you want a
|
|
57
|
+
* fully custom HTTP path. SSRF caution: validate any user-influenced `url`.
|
|
58
|
+
*
|
|
59
|
+
* Only `ai_prompt` steps need a bonded `ai` provider (`@molecule/api-ai`);
|
|
60
|
+
* with none bonded that step errors and the run returns `ok: false` with the
|
|
61
|
+
* error on its trace entry. All other step types run without any AI provider.
|
|
62
|
+
*
|
|
63
|
+
* @module
|
|
64
|
+
*/
|
|
65
|
+
import { type ConditionEvaluator } from './safe-evaluator.js';
|
|
66
|
+
export * from './browser-guard.js';
|
|
67
|
+
export * from './safe-evaluator.js';
|
|
68
|
+
/** Union of all supported step type discriminants. */
|
|
69
|
+
export type WorkflowStepType = 'condition' | 'action' | 'delay' | 'http' | 'ai_prompt';
|
|
70
|
+
/** A step that evaluates a JS expression and short-circuits the run on false. */
|
|
71
|
+
export interface ConditionStep {
|
|
72
|
+
type: 'condition';
|
|
73
|
+
/** JS expression evaluated against `$` (the workflow context). */
|
|
74
|
+
expression: string;
|
|
75
|
+
}
|
|
76
|
+
/** A step that invokes a registered action handler with resolved params. */
|
|
77
|
+
export interface ActionStep {
|
|
78
|
+
type: 'action';
|
|
79
|
+
/** Action key registered with the engine. */
|
|
80
|
+
action: string;
|
|
81
|
+
/** Param template — `${$.x.y}` placeholders are resolved against context. */
|
|
82
|
+
params?: Record<string, unknown>;
|
|
83
|
+
/** Where to write the action's return value into the context. */
|
|
84
|
+
output?: string;
|
|
85
|
+
}
|
|
86
|
+
/** A step that pauses workflow execution for a fixed number of milliseconds. */
|
|
87
|
+
export interface DelayStep {
|
|
88
|
+
type: 'delay';
|
|
89
|
+
/** Milliseconds to sleep. */
|
|
90
|
+
ms: number;
|
|
91
|
+
}
|
|
92
|
+
/** A step that sends a prompt to the bonded AI provider and writes the response into context. */
|
|
93
|
+
export interface AIPromptStep {
|
|
94
|
+
type: 'ai_prompt';
|
|
95
|
+
prompt: string;
|
|
96
|
+
/** Field on context to write the model's text response. */
|
|
97
|
+
output: string;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* A step that performs an outbound HTTP request via the swappable
|
|
101
|
+
* `@molecule/api-http` core (never a hardcoded fetch/axios). `${$.path}`
|
|
102
|
+
* templates in `url`, `headers`, `params`, and `body` are resolved against
|
|
103
|
+
* context before the request is sent.
|
|
104
|
+
*/
|
|
105
|
+
export interface HttpStep {
|
|
106
|
+
type: 'http';
|
|
107
|
+
/** Request URL (supports `${$.path}` templates). */
|
|
108
|
+
url: string;
|
|
109
|
+
/** HTTP method; defaults to `GET`. */
|
|
110
|
+
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
|
|
111
|
+
/** Request headers (values support `${$.path}` templates). */
|
|
112
|
+
headers?: Record<string, string>;
|
|
113
|
+
/** Query parameters (values support `${$.path}` templates). */
|
|
114
|
+
params?: Record<string, string | number | boolean | undefined>;
|
|
115
|
+
/** Request body — objects are JSON-encoded by the http core (supports templates). */
|
|
116
|
+
body?: unknown;
|
|
117
|
+
/** Where to write `{ status, statusText, headers, data }` into the context. */
|
|
118
|
+
output?: string;
|
|
119
|
+
}
|
|
120
|
+
/** Discriminated union of all step types that a workflow definition may contain. */
|
|
121
|
+
export type WorkflowStep = ConditionStep | ActionStep | DelayStep | AIPromptStep | HttpStep;
|
|
122
|
+
/** Describes a complete workflow: which trigger fires it and what steps to run. */
|
|
123
|
+
export interface WorkflowDefinition {
|
|
124
|
+
trigger: string;
|
|
125
|
+
triggerInput?: Record<string, unknown>;
|
|
126
|
+
steps: WorkflowStep[];
|
|
127
|
+
}
|
|
128
|
+
/** Result returned by `WorkflowEngine.execute` — overall outcome plus per-step trace. */
|
|
129
|
+
export interface WorkflowRun {
|
|
130
|
+
ok: boolean;
|
|
131
|
+
context: Record<string, unknown>;
|
|
132
|
+
/** What happened at each step: 'executed' | 'skipped' | 'errored'. */
|
|
133
|
+
trace: Array<{
|
|
134
|
+
index: number;
|
|
135
|
+
type: WorkflowStepType;
|
|
136
|
+
outcome: 'executed' | 'skipped' | 'errored';
|
|
137
|
+
error?: string;
|
|
138
|
+
}>;
|
|
139
|
+
}
|
|
140
|
+
/** Public interface for the workflow engine returned by `createWorkflowEngine`. */
|
|
141
|
+
export interface WorkflowEngine {
|
|
142
|
+
execute(definition: WorkflowDefinition): Promise<WorkflowRun>;
|
|
143
|
+
}
|
|
144
|
+
/** Configuration passed to `createWorkflowEngine` — trigger and action handler maps. */
|
|
145
|
+
export interface EngineOptions {
|
|
146
|
+
triggers: Record<string, (ctx: Record<string, unknown>) => Promise<unknown> | unknown>;
|
|
147
|
+
actions: Record<string, (params: Record<string, unknown>) => Promise<unknown> | unknown>;
|
|
148
|
+
/**
|
|
149
|
+
* Custom condition evaluator. When provided it fully replaces the built-in
|
|
150
|
+
* evaluators — neither the safe interpreter nor `new Function` is used. Plug
|
|
151
|
+
* in your own hardened/sandboxed expression engine here.
|
|
152
|
+
*/
|
|
153
|
+
conditionEvaluator?: ConditionEvaluator;
|
|
154
|
+
/**
|
|
155
|
+
* Opt in to evaluating `condition` expressions as full, UNSANDBOXED JavaScript
|
|
156
|
+
* via `new Function`. SECURITY: only enable for workflow definitions authored by
|
|
157
|
+
* TRUSTED developers/admins — never end-user input. Ignored when
|
|
158
|
+
* `conditionEvaluator` is supplied. Defaults to `false`, i.e. the safe,
|
|
159
|
+
* non-`new Function` interpreter ({@link safeEvaluateCondition}) is used.
|
|
160
|
+
*/
|
|
161
|
+
allowUnsafeConditionEval?: boolean;
|
|
162
|
+
}
|
|
163
|
+
/** Creates a `WorkflowEngine` instance wired with the provided trigger and action handlers. */
|
|
164
|
+
export declare function createWorkflowEngine(opts: EngineOptions): WorkflowEngine;
|
|
165
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"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"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@molecule/api-ai-workflow-engine` — trigger / condition / action
|
|
3
|
+
* workflow runner with pluggable handler registry + an optional AI
|
|
4
|
+
* `ai_prompt` step (send a templated prompt to the bonded AI provider
|
|
5
|
+
* mid-run).
|
|
6
|
+
*
|
|
7
|
+
* Extracted from ai-workflow-automator flagship. Use it like an
|
|
8
|
+
* embeddable Zapier engine inside your app.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* import { createWorkflowEngine } from '@molecule/api-ai-workflow-engine'
|
|
13
|
+
*
|
|
14
|
+
* const engine = createWorkflowEngine({
|
|
15
|
+
* triggers: {
|
|
16
|
+
* 'webhook.received': async (ctx) => ctx.payload,
|
|
17
|
+
* },
|
|
18
|
+
* actions: {
|
|
19
|
+
* 'slack.message': async ({ channel, text }) => slackClient.chat.postMessage({ channel, text }),
|
|
20
|
+
* },
|
|
21
|
+
* })
|
|
22
|
+
*
|
|
23
|
+
* const run = await engine.execute({
|
|
24
|
+
* trigger: 'webhook.received',
|
|
25
|
+
* triggerInput: { payload: req.body },
|
|
26
|
+
* steps: [
|
|
27
|
+
* { type: 'condition', expression: '$.event === "purchase"' },
|
|
28
|
+
* // Native HTTP step — routed through the swappable `@molecule/api-http` core:
|
|
29
|
+
* { type: 'http', method: 'POST', url: 'https://hooks.example.com/${$.id}', body: { amount: '${$.amount}' }, output: 'webhook' },
|
|
30
|
+
* { type: 'action', action: 'slack.message', params: { channel: '#sales', text: 'New sale: ${$.amount}' } },
|
|
31
|
+
* ],
|
|
32
|
+
* })
|
|
33
|
+
* ```
|
|
34
|
+
*
|
|
35
|
+
* @remarks
|
|
36
|
+
* SECURITY — `condition` step evaluation is SAFE BY DEFAULT. Expressions are run
|
|
37
|
+
* through a small built-in interpreter ({@link safeEvaluateCondition}) that
|
|
38
|
+
* supports member access, comparisons, boolean logic and literals but does NOT
|
|
39
|
+
* use `new Function`/`eval`, cannot call functions or assign, and blocks
|
|
40
|
+
* `__proto__`/`constructor`/`prototype` — so a malicious expression cannot
|
|
41
|
+
* execute arbitrary code. Full unsandboxed JavaScript (`new Function`) is
|
|
42
|
+
* OPT-IN only via `EngineOptions.allowUnsafeConditionEval: true` — enable it
|
|
43
|
+
* ONLY for workflow definitions authored by TRUSTED developers/admins, never
|
|
44
|
+
* from end-user input. You may also supply your own `EngineOptions.conditionEvaluator`
|
|
45
|
+
* (e.g. a hardened sandbox), which replaces both built-ins. An expression that
|
|
46
|
+
* throws or fails to parse counts as `false` — the run short-circuits with
|
|
47
|
+
* `ok: true` (a skipped run, not a failure).
|
|
48
|
+
*
|
|
49
|
+
* `'http'` steps ARE executed: the request is sent through the swappable
|
|
50
|
+
* `@molecule/api-http` core (bond `@molecule/api-http-axios` etc. to change the
|
|
51
|
+
* client — the engine hardcodes no HTTP library). `${$.path}` templates in
|
|
52
|
+
* `url`/`headers`/`params`/`body` are resolved against context, the
|
|
53
|
+
* `{ status, statusText, headers, data }` response is written to `output`, and a
|
|
54
|
+
* trace entry is recorded. A non-2xx response (the http core throws an
|
|
55
|
+
* `HttpError`) yields an `errored` trace entry and halts the run — never a
|
|
56
|
+
* silent skip. Registering an `http.*` action still works too, if you want a
|
|
57
|
+
* fully custom HTTP path. SSRF caution: validate any user-influenced `url`.
|
|
58
|
+
*
|
|
59
|
+
* Only `ai_prompt` steps need a bonded `ai` provider (`@molecule/api-ai`);
|
|
60
|
+
* with none bonded that step errors and the run returns `ok: false` with the
|
|
61
|
+
* error on its trace entry. All other step types run without any AI provider.
|
|
62
|
+
*
|
|
63
|
+
* @module
|
|
64
|
+
*/
|
|
65
|
+
import { hasProvider as hasAI, requireProvider as requireAI } from '@molecule/api-ai';
|
|
66
|
+
import { request as httpRequest } from '@molecule/api-http';
|
|
67
|
+
import { safeEvaluateCondition, unsafeEvaluateCondition, } from './safe-evaluator.js';
|
|
68
|
+
export * from './browser-guard.js';
|
|
69
|
+
export * from './safe-evaluator.js';
|
|
70
|
+
/** Recursively replaces `${$.path}` placeholders in strings (and nested structures) with values from context. */
|
|
71
|
+
function resolveTemplates(value, ctx) {
|
|
72
|
+
if (typeof value === 'string') {
|
|
73
|
+
return value.replace(/\$\{\$\.([^}]+)\}/g, (_, path) => {
|
|
74
|
+
const parts = path.split('.');
|
|
75
|
+
let cur = ctx;
|
|
76
|
+
for (const p of parts) {
|
|
77
|
+
if (cur && typeof cur === 'object' && p in cur) {
|
|
78
|
+
cur = cur[p];
|
|
79
|
+
}
|
|
80
|
+
else
|
|
81
|
+
return '';
|
|
82
|
+
}
|
|
83
|
+
return String(cur ?? '');
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
if (Array.isArray(value))
|
|
87
|
+
return value.map((v) => resolveTemplates(v, ctx));
|
|
88
|
+
if (value && typeof value === 'object') {
|
|
89
|
+
const out = {};
|
|
90
|
+
for (const [k, v] of Object.entries(value))
|
|
91
|
+
out[k] = resolveTemplates(v, ctx);
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
return value;
|
|
95
|
+
}
|
|
96
|
+
/** Writes a value into the workflow context at a dot-separated path, creating intermediate objects as needed. */
|
|
97
|
+
function setContextPath(ctx, path, value) {
|
|
98
|
+
const parts = path.split('.');
|
|
99
|
+
let cur = ctx;
|
|
100
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
101
|
+
const k = parts[i];
|
|
102
|
+
if (!(k in cur) || typeof cur[k] !== 'object' || cur[k] === null)
|
|
103
|
+
cur[k] = {};
|
|
104
|
+
cur = cur[k];
|
|
105
|
+
}
|
|
106
|
+
cur[parts[parts.length - 1]] = value;
|
|
107
|
+
}
|
|
108
|
+
/** Creates a `WorkflowEngine` instance wired with the provided trigger and action handlers. */
|
|
109
|
+
export function createWorkflowEngine(opts) {
|
|
110
|
+
// Resolve the condition evaluator ONCE: an explicit custom evaluator wins;
|
|
111
|
+
// otherwise `new Function` only when explicitly opted into; safe by default.
|
|
112
|
+
const evaluateCondition = opts.conditionEvaluator ??
|
|
113
|
+
(opts.allowUnsafeConditionEval ? unsafeEvaluateCondition : safeEvaluateCondition);
|
|
114
|
+
return {
|
|
115
|
+
async execute(def) {
|
|
116
|
+
const triggerFn = opts.triggers[def.trigger];
|
|
117
|
+
if (!triggerFn) {
|
|
118
|
+
return {
|
|
119
|
+
ok: false,
|
|
120
|
+
context: {},
|
|
121
|
+
trace: [
|
|
122
|
+
{
|
|
123
|
+
index: -1,
|
|
124
|
+
type: 'condition',
|
|
125
|
+
outcome: 'errored',
|
|
126
|
+
error: `Unknown trigger: ${def.trigger}`,
|
|
127
|
+
},
|
|
128
|
+
],
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
const ctx = { ...(def.triggerInput ?? {}) };
|
|
132
|
+
try {
|
|
133
|
+
const triggerOutput = await triggerFn(ctx);
|
|
134
|
+
Object.assign(ctx, triggerOutput ?? {});
|
|
135
|
+
}
|
|
136
|
+
catch (err) {
|
|
137
|
+
return {
|
|
138
|
+
ok: false,
|
|
139
|
+
context: ctx,
|
|
140
|
+
trace: [
|
|
141
|
+
{
|
|
142
|
+
index: -1,
|
|
143
|
+
type: 'condition',
|
|
144
|
+
outcome: 'errored',
|
|
145
|
+
error: err instanceof Error ? err.message : String(err),
|
|
146
|
+
},
|
|
147
|
+
],
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
const trace = [];
|
|
151
|
+
for (let i = 0; i < def.steps.length; i++) {
|
|
152
|
+
const step = def.steps[i];
|
|
153
|
+
try {
|
|
154
|
+
if (step.type === 'condition') {
|
|
155
|
+
const ok = evaluateCondition(step.expression, ctx);
|
|
156
|
+
trace.push({ index: i, type: step.type, outcome: ok ? 'executed' : 'skipped' });
|
|
157
|
+
if (!ok)
|
|
158
|
+
return { ok: true, context: ctx, trace };
|
|
159
|
+
}
|
|
160
|
+
else if (step.type === 'delay') {
|
|
161
|
+
await new Promise((r) => setTimeout(r, step.ms));
|
|
162
|
+
trace.push({ index: i, type: step.type, outcome: 'executed' });
|
|
163
|
+
}
|
|
164
|
+
else if (step.type === 'action') {
|
|
165
|
+
const action = opts.actions[step.action];
|
|
166
|
+
if (!action)
|
|
167
|
+
throw new Error(`Unknown action: ${step.action}`);
|
|
168
|
+
const params = resolveTemplates(step.params ?? {}, ctx);
|
|
169
|
+
const result = await action(params);
|
|
170
|
+
if (step.output)
|
|
171
|
+
setContextPath(ctx, step.output, result);
|
|
172
|
+
trace.push({ index: i, type: step.type, outcome: 'executed' });
|
|
173
|
+
}
|
|
174
|
+
else if (step.type === 'http') {
|
|
175
|
+
const url = resolveTemplates(step.url, ctx);
|
|
176
|
+
const options = { method: step.method ?? 'GET' };
|
|
177
|
+
if (step.headers) {
|
|
178
|
+
options.headers = resolveTemplates(step.headers, ctx);
|
|
179
|
+
}
|
|
180
|
+
if (step.params) {
|
|
181
|
+
options.params = resolveTemplates(step.params, ctx);
|
|
182
|
+
}
|
|
183
|
+
if (step.body !== undefined) {
|
|
184
|
+
options.body = resolveTemplates(step.body, ctx);
|
|
185
|
+
}
|
|
186
|
+
// Non-2xx responses throw an HttpError here → caught below → `errored`
|
|
187
|
+
// trace entry (never a silent skip).
|
|
188
|
+
const res = await httpRequest(url, options);
|
|
189
|
+
if (step.output) {
|
|
190
|
+
setContextPath(ctx, step.output, {
|
|
191
|
+
status: res.status,
|
|
192
|
+
statusText: res.statusText,
|
|
193
|
+
headers: res.headers,
|
|
194
|
+
data: res.data,
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
trace.push({ index: i, type: step.type, outcome: 'executed' });
|
|
198
|
+
}
|
|
199
|
+
else if (step.type === 'ai_prompt') {
|
|
200
|
+
if (!hasAI())
|
|
201
|
+
throw new Error('No AI provider bonded — ai_prompt step requires one');
|
|
202
|
+
const ai = requireAI();
|
|
203
|
+
const prompt = resolveTemplates(step.prompt, ctx);
|
|
204
|
+
let answer = '';
|
|
205
|
+
for await (const event of ai.chat({
|
|
206
|
+
messages: [{ role: 'user', content: prompt }],
|
|
207
|
+
})) {
|
|
208
|
+
// A ChatEvent's text payload is `content` (NOT `text`, which is
|
|
209
|
+
// the ContentBlock shape) — reading `event.text` did nothing.
|
|
210
|
+
if (event.type === 'text')
|
|
211
|
+
answer += event.content;
|
|
212
|
+
}
|
|
213
|
+
setContextPath(ctx, step.output, answer);
|
|
214
|
+
trace.push({ index: i, type: step.type, outcome: 'executed' });
|
|
215
|
+
}
|
|
216
|
+
else {
|
|
217
|
+
// Exhaustiveness guard: every WorkflowStepType MUST have an executor.
|
|
218
|
+
// `never` makes an unhandled type a compile error; the runtime throw
|
|
219
|
+
// means an out-of-union step (e.g. via a cast) errors explicitly and
|
|
220
|
+
// is recorded in the trace — never silently dropped.
|
|
221
|
+
const unhandled = step;
|
|
222
|
+
throw new Error(`Unsupported step type: ${unhandled.type}`);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
catch (err) {
|
|
226
|
+
trace.push({
|
|
227
|
+
index: i,
|
|
228
|
+
type: step.type,
|
|
229
|
+
outcome: 'errored',
|
|
230
|
+
error: err instanceof Error ? err.message : String(err),
|
|
231
|
+
});
|
|
232
|
+
return { ok: false, context: ctx, trace };
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return { ok: true, context: ctx, trace };
|
|
236
|
+
},
|
|
237
|
+
};
|
|
238
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Condition-expression evaluators for the workflow engine.
|
|
3
|
+
*
|
|
4
|
+
* A workflow `condition` step carries an author-provided `expression` string.
|
|
5
|
+
* Two strategies are offered, so the UNSAFE one is never the silent default:
|
|
6
|
+
*
|
|
7
|
+
* - {@link safeEvaluateCondition} — the DEFAULT. A tiny, purpose-built
|
|
8
|
+
* expression interpreter that supports member access (`$.a.b`), comparisons
|
|
9
|
+
* (`===`, `!==`, `==`, `!=`, `>`, `>=`, `<`, `<=`), boolean logic
|
|
10
|
+
* (`&&`, `||`, `!`), unary minus, grouping, and literals. It does **not** use
|
|
11
|
+
* `new Function`/`eval`, cannot call functions, cannot assign, and blocks
|
|
12
|
+
* `__proto__`/`constructor`/`prototype` access — so a malicious expression
|
|
13
|
+
* has no way to execute arbitrary code.
|
|
14
|
+
* - {@link unsafeEvaluateCondition} — OPT-IN only. Evaluates the expression as
|
|
15
|
+
* full, unsandboxed JavaScript via `new Function`. Only ever run expressions
|
|
16
|
+
* authored by TRUSTED developers/admins with this — never end-user input.
|
|
17
|
+
*
|
|
18
|
+
* Both return `false` (never throw) for an unparseable or throwing expression,
|
|
19
|
+
* so a bad condition short-circuits the run rather than crashing it.
|
|
20
|
+
*
|
|
21
|
+
* @module
|
|
22
|
+
*/
|
|
23
|
+
/**
|
|
24
|
+
* Signature for a pluggable condition evaluator. Return `true` to let the run
|
|
25
|
+
* continue past the `condition` step, `false` to short-circuit it.
|
|
26
|
+
*
|
|
27
|
+
* @param expression - The author-provided condition expression.
|
|
28
|
+
* @param context - The workflow context the expression is evaluated against (`$`).
|
|
29
|
+
* @returns Whether the condition passed.
|
|
30
|
+
*/
|
|
31
|
+
export type ConditionEvaluator = (expression: string, context: Record<string, unknown>) => boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Safely evaluates a workflow condition expression WITHOUT `new Function`/`eval`.
|
|
34
|
+
*
|
|
35
|
+
* Supports member access against the context (`$.a.b`, `$.list[0]`), comparisons,
|
|
36
|
+
* boolean logic, unary `!`/`-`, grouping, and literals. Function calls,
|
|
37
|
+
* assignments, and arbitrary JavaScript are unsupported — such an expression is
|
|
38
|
+
* unparseable and evaluates to `false` rather than executing. An unparseable or
|
|
39
|
+
* throwing expression counts as a non-matching condition.
|
|
40
|
+
*
|
|
41
|
+
* @param expression - The condition expression to evaluate.
|
|
42
|
+
* @param context - The workflow context (bound to `$`).
|
|
43
|
+
* @returns `true` if the expression is truthy, otherwise `false`.
|
|
44
|
+
*/
|
|
45
|
+
export declare const safeEvaluateCondition: ConditionEvaluator;
|
|
46
|
+
/**
|
|
47
|
+
* UNSAFE: evaluates a workflow condition expression as full, unsandboxed
|
|
48
|
+
* JavaScript via `new Function`. This is arbitrary code execution in the API
|
|
49
|
+
* process — only run expressions authored by TRUSTED developers/admins, NEVER
|
|
50
|
+
* end-user input. Opt in explicitly via `EngineOptions.allowUnsafeConditionEval`;
|
|
51
|
+
* it is never the default. A throwing or unparseable expression counts as `false`.
|
|
52
|
+
*
|
|
53
|
+
* @param expression - The condition expression to evaluate as JavaScript.
|
|
54
|
+
* @param context - The workflow context (bound to `$`).
|
|
55
|
+
* @returns `true` if the expression is truthy, otherwise `false`.
|
|
56
|
+
*/
|
|
57
|
+
export declare const unsafeEvaluateCondition: ConditionEvaluator;
|
|
58
|
+
//# sourceMappingURL=safe-evaluator.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"safe-evaluator.d.ts","sourceRoot":"","sources":["../src/safe-evaluator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH;;;;;;;GAOG;AACH,MAAM,MAAM,kBAAkB,GAAG,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAA;AA6PlG;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,qBAAqB,EAAE,kBAQnC,CAAA;AAED;;;;;;;;;;GAUG;AACH,eAAO,MAAM,uBAAuB,EAAE,kBAQrC,CAAA"}
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Condition-expression evaluators for the workflow engine.
|
|
3
|
+
*
|
|
4
|
+
* A workflow `condition` step carries an author-provided `expression` string.
|
|
5
|
+
* Two strategies are offered, so the UNSAFE one is never the silent default:
|
|
6
|
+
*
|
|
7
|
+
* - {@link safeEvaluateCondition} — the DEFAULT. A tiny, purpose-built
|
|
8
|
+
* expression interpreter that supports member access (`$.a.b`), comparisons
|
|
9
|
+
* (`===`, `!==`, `==`, `!=`, `>`, `>=`, `<`, `<=`), boolean logic
|
|
10
|
+
* (`&&`, `||`, `!`), unary minus, grouping, and literals. It does **not** use
|
|
11
|
+
* `new Function`/`eval`, cannot call functions, cannot assign, and blocks
|
|
12
|
+
* `__proto__`/`constructor`/`prototype` access — so a malicious expression
|
|
13
|
+
* has no way to execute arbitrary code.
|
|
14
|
+
* - {@link unsafeEvaluateCondition} — OPT-IN only. Evaluates the expression as
|
|
15
|
+
* full, unsandboxed JavaScript via `new Function`. Only ever run expressions
|
|
16
|
+
* authored by TRUSTED developers/admins with this — never end-user input.
|
|
17
|
+
*
|
|
18
|
+
* Both return `false` (never throw) for an unparseable or throwing expression,
|
|
19
|
+
* so a bad condition short-circuits the run rather than crashing it.
|
|
20
|
+
*
|
|
21
|
+
* @module
|
|
22
|
+
*/
|
|
23
|
+
/** Member keys that are never resolved, to keep the safe evaluator inert against prototype access. */
|
|
24
|
+
const BLOCKED_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
25
|
+
/** Splits a condition expression into tokens; throws on an unexpected character. */
|
|
26
|
+
function tokenize(src) {
|
|
27
|
+
const tokens = [];
|
|
28
|
+
let i = 0;
|
|
29
|
+
const n = src.length;
|
|
30
|
+
const isDigit = (c) => c >= '0' && c <= '9';
|
|
31
|
+
const isIdStart = (c) => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c === '_';
|
|
32
|
+
const isIdPart = (c) => isIdStart(c) || isDigit(c);
|
|
33
|
+
while (i < n) {
|
|
34
|
+
const c = src[i];
|
|
35
|
+
if (c === ' ' || c === '\t' || c === '\n' || c === '\r') {
|
|
36
|
+
i++;
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
// String literal (single or double quoted, with basic escapes).
|
|
40
|
+
if (c === '"' || c === "'") {
|
|
41
|
+
const quote = c;
|
|
42
|
+
i++;
|
|
43
|
+
let s = '';
|
|
44
|
+
while (i < n && src[i] !== quote) {
|
|
45
|
+
if (src[i] === '\\' && i + 1 < n) {
|
|
46
|
+
const esc = src[i + 1];
|
|
47
|
+
s += esc === 'n' ? '\n' : esc === 't' ? '\t' : esc === 'r' ? '\r' : esc;
|
|
48
|
+
i += 2;
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
s += src[i];
|
|
52
|
+
i++;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (i >= n)
|
|
56
|
+
throw new Error('Unterminated string literal');
|
|
57
|
+
i++; // consume closing quote
|
|
58
|
+
tokens.push({ t: 'str', v: s });
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
// Number literal (integer or decimal).
|
|
62
|
+
if (isDigit(c)) {
|
|
63
|
+
let num = '';
|
|
64
|
+
while (i < n && (isDigit(src[i]) || src[i] === '.')) {
|
|
65
|
+
num += src[i];
|
|
66
|
+
i++;
|
|
67
|
+
}
|
|
68
|
+
tokens.push({ t: 'num', v: Number(num) });
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
// Identifier / keyword.
|
|
72
|
+
if (isIdStart(c)) {
|
|
73
|
+
let id = '';
|
|
74
|
+
while (i < n && isIdPart(src[i])) {
|
|
75
|
+
id += src[i];
|
|
76
|
+
i++;
|
|
77
|
+
}
|
|
78
|
+
tokens.push({ t: 'id', v: id });
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
// Multi-character operators.
|
|
82
|
+
const three = src.slice(i, i + 3);
|
|
83
|
+
if (three === '===' || three === '!==') {
|
|
84
|
+
tokens.push({ t: 'op', v: three });
|
|
85
|
+
i += 3;
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
const two = src.slice(i, i + 2);
|
|
89
|
+
if (two === '==' ||
|
|
90
|
+
two === '!=' ||
|
|
91
|
+
two === '>=' ||
|
|
92
|
+
two === '<=' ||
|
|
93
|
+
two === '&&' ||
|
|
94
|
+
two === '||') {
|
|
95
|
+
tokens.push({ t: 'op', v: two });
|
|
96
|
+
i += 2;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
// Single-character operators / punctuation.
|
|
100
|
+
if ('<>!().[]$-'.includes(c)) {
|
|
101
|
+
tokens.push({ t: 'op', v: c });
|
|
102
|
+
i++;
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
throw new Error(`Unexpected character in expression: ${c}`);
|
|
106
|
+
}
|
|
107
|
+
return tokens;
|
|
108
|
+
}
|
|
109
|
+
/** Reads `key` off `obj` without boxing primitives or touching prototype keys. */
|
|
110
|
+
function safeMember(obj, key) {
|
|
111
|
+
if (obj == null)
|
|
112
|
+
return undefined;
|
|
113
|
+
if (BLOCKED_KEYS.has(key))
|
|
114
|
+
return undefined;
|
|
115
|
+
if (typeof obj === 'object' || typeof obj === 'string') {
|
|
116
|
+
return obj[key];
|
|
117
|
+
}
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Recursive-descent interpreter over the token stream. Evaluates directly
|
|
122
|
+
* against `context` — it never builds callable code.
|
|
123
|
+
*/
|
|
124
|
+
function interpret(tokens, context) {
|
|
125
|
+
let p = 0;
|
|
126
|
+
const peek = () => tokens[p];
|
|
127
|
+
const isOp = (v) => {
|
|
128
|
+
const tok = tokens[p];
|
|
129
|
+
return tok?.t === 'op' && tok.v === v;
|
|
130
|
+
};
|
|
131
|
+
const expectOp = (v) => {
|
|
132
|
+
if (!isOp(v))
|
|
133
|
+
throw new Error(`Expected '${v}'`);
|
|
134
|
+
p++;
|
|
135
|
+
};
|
|
136
|
+
const parseOr = () => {
|
|
137
|
+
let left = parseAnd();
|
|
138
|
+
while (isOp('||')) {
|
|
139
|
+
p++;
|
|
140
|
+
const right = parseAnd();
|
|
141
|
+
left = left || right;
|
|
142
|
+
}
|
|
143
|
+
return left;
|
|
144
|
+
};
|
|
145
|
+
const parseAnd = () => {
|
|
146
|
+
let left = parseEquality();
|
|
147
|
+
while (isOp('&&')) {
|
|
148
|
+
p++;
|
|
149
|
+
const right = parseEquality();
|
|
150
|
+
left = left && right;
|
|
151
|
+
}
|
|
152
|
+
return left;
|
|
153
|
+
};
|
|
154
|
+
const parseEquality = () => {
|
|
155
|
+
let left = parseRelational();
|
|
156
|
+
while (isOp('===') || isOp('!==') || isOp('==') || isOp('!=')) {
|
|
157
|
+
const op = tokens[p].v;
|
|
158
|
+
p++;
|
|
159
|
+
const right = parseRelational();
|
|
160
|
+
if (op === '===')
|
|
161
|
+
left = left === right;
|
|
162
|
+
else if (op === '!==')
|
|
163
|
+
left = left !== right;
|
|
164
|
+
else if (op === '==')
|
|
165
|
+
left = left == right;
|
|
166
|
+
else
|
|
167
|
+
left = left != right;
|
|
168
|
+
}
|
|
169
|
+
return left;
|
|
170
|
+
};
|
|
171
|
+
const parseRelational = () => {
|
|
172
|
+
let left = parseUnary();
|
|
173
|
+
while (isOp('>=') || isOp('<=') || isOp('>') || isOp('<')) {
|
|
174
|
+
const op = tokens[p].v;
|
|
175
|
+
p++;
|
|
176
|
+
const right = parseUnary();
|
|
177
|
+
const a = left;
|
|
178
|
+
const b = right;
|
|
179
|
+
if (op === '>=')
|
|
180
|
+
left = a >= b;
|
|
181
|
+
else if (op === '<=')
|
|
182
|
+
left = a <= b;
|
|
183
|
+
else if (op === '>')
|
|
184
|
+
left = a > b;
|
|
185
|
+
else
|
|
186
|
+
left = a < b;
|
|
187
|
+
}
|
|
188
|
+
return left;
|
|
189
|
+
};
|
|
190
|
+
const parseUnary = () => {
|
|
191
|
+
if (isOp('!')) {
|
|
192
|
+
p++;
|
|
193
|
+
return !parseUnary();
|
|
194
|
+
}
|
|
195
|
+
if (isOp('-')) {
|
|
196
|
+
p++;
|
|
197
|
+
return -parseUnary();
|
|
198
|
+
}
|
|
199
|
+
return parsePrimary();
|
|
200
|
+
};
|
|
201
|
+
const parsePrimary = () => {
|
|
202
|
+
const tok = peek();
|
|
203
|
+
if (!tok)
|
|
204
|
+
throw new Error('Unexpected end of expression');
|
|
205
|
+
if (isOp('(')) {
|
|
206
|
+
p++;
|
|
207
|
+
const inner = parseOr();
|
|
208
|
+
expectOp(')');
|
|
209
|
+
return inner;
|
|
210
|
+
}
|
|
211
|
+
if (isOp('$'))
|
|
212
|
+
return parsePath();
|
|
213
|
+
if (tok.t === 'num' || tok.t === 'str') {
|
|
214
|
+
p++;
|
|
215
|
+
return tok.v;
|
|
216
|
+
}
|
|
217
|
+
if (tok.t === 'id') {
|
|
218
|
+
p++;
|
|
219
|
+
if (tok.v === 'true')
|
|
220
|
+
return true;
|
|
221
|
+
if (tok.v === 'false')
|
|
222
|
+
return false;
|
|
223
|
+
if (tok.v === 'null')
|
|
224
|
+
return null;
|
|
225
|
+
if (tok.v === 'undefined')
|
|
226
|
+
return undefined;
|
|
227
|
+
throw new Error(`Unknown identifier: ${tok.v}`);
|
|
228
|
+
}
|
|
229
|
+
throw new Error(`Unexpected token: ${tok.v}`);
|
|
230
|
+
};
|
|
231
|
+
const parsePath = () => {
|
|
232
|
+
expectOp('$');
|
|
233
|
+
let cur = context;
|
|
234
|
+
for (;;) {
|
|
235
|
+
if (isOp('.')) {
|
|
236
|
+
p++;
|
|
237
|
+
const prop = peek();
|
|
238
|
+
if (!prop || prop.t !== 'id')
|
|
239
|
+
throw new Error('Expected property name after "."');
|
|
240
|
+
p++;
|
|
241
|
+
cur = safeMember(cur, prop.v);
|
|
242
|
+
}
|
|
243
|
+
else if (isOp('[')) {
|
|
244
|
+
p++;
|
|
245
|
+
const key = parseOr();
|
|
246
|
+
expectOp(']');
|
|
247
|
+
cur = safeMember(cur, String(key));
|
|
248
|
+
}
|
|
249
|
+
else {
|
|
250
|
+
break;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return cur;
|
|
254
|
+
};
|
|
255
|
+
const result = parseOr();
|
|
256
|
+
if (p !== tokens.length)
|
|
257
|
+
throw new Error('Unexpected trailing tokens in expression');
|
|
258
|
+
return result;
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Safely evaluates a workflow condition expression WITHOUT `new Function`/`eval`.
|
|
262
|
+
*
|
|
263
|
+
* Supports member access against the context (`$.a.b`, `$.list[0]`), comparisons,
|
|
264
|
+
* boolean logic, unary `!`/`-`, grouping, and literals. Function calls,
|
|
265
|
+
* assignments, and arbitrary JavaScript are unsupported — such an expression is
|
|
266
|
+
* unparseable and evaluates to `false` rather than executing. An unparseable or
|
|
267
|
+
* throwing expression counts as a non-matching condition.
|
|
268
|
+
*
|
|
269
|
+
* @param expression - The condition expression to evaluate.
|
|
270
|
+
* @param context - The workflow context (bound to `$`).
|
|
271
|
+
* @returns `true` if the expression is truthy, otherwise `false`.
|
|
272
|
+
*/
|
|
273
|
+
export const safeEvaluateCondition = (expression, context) => {
|
|
274
|
+
try {
|
|
275
|
+
return Boolean(interpret(tokenize(expression), context));
|
|
276
|
+
}
|
|
277
|
+
catch (_error) {
|
|
278
|
+
// Unparseable/unsupported syntax is treated as a non-matching condition — the
|
|
279
|
+
// documented semantics: a bad condition short-circuits the run, never crashes it.
|
|
280
|
+
return false;
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
/**
|
|
284
|
+
* UNSAFE: evaluates a workflow condition expression as full, unsandboxed
|
|
285
|
+
* JavaScript via `new Function`. This is arbitrary code execution in the API
|
|
286
|
+
* process — only run expressions authored by TRUSTED developers/admins, NEVER
|
|
287
|
+
* end-user input. Opt in explicitly via `EngineOptions.allowUnsafeConditionEval`;
|
|
288
|
+
* it is never the default. A throwing or unparseable expression counts as `false`.
|
|
289
|
+
*
|
|
290
|
+
* @param expression - The condition expression to evaluate as JavaScript.
|
|
291
|
+
* @param context - The workflow context (bound to `$`).
|
|
292
|
+
* @returns `true` if the expression is truthy, otherwise `false`.
|
|
293
|
+
*/
|
|
294
|
+
export const unsafeEvaluateCondition = (expression, context) => {
|
|
295
|
+
try {
|
|
296
|
+
const fn = new Function('$', `return (${expression})`);
|
|
297
|
+
return Boolean(fn(context));
|
|
298
|
+
}
|
|
299
|
+
catch (_error) {
|
|
300
|
+
// An unparseable or throwing expression counts as a non-matching condition — safe to suppress.
|
|
301
|
+
return false;
|
|
302
|
+
}
|
|
303
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@molecule/api-ai-workflow-engine",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Trigger / condition / action workflow runner with AI-assisted step suggestions",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"scripts": {
|
|
9
|
+
"build": "tsc",
|
|
10
|
+
"test": "vitest run",
|
|
11
|
+
"test:watch": "vitest"
|
|
12
|
+
},
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"import": "./dist/index.js"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist"
|
|
21
|
+
],
|
|
22
|
+
"keywords": [
|
|
23
|
+
"molecule",
|
|
24
|
+
"ai",
|
|
25
|
+
"workflow",
|
|
26
|
+
"automation",
|
|
27
|
+
"zapier"
|
|
28
|
+
],
|
|
29
|
+
"license": "Apache-2.0",
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@molecule/api-http": "1.0.0",
|
|
32
|
+
"@types/node": "26.1.2",
|
|
33
|
+
"typescript": "6.0.3",
|
|
34
|
+
"vitest": "4.1.10"
|
|
35
|
+
},
|
|
36
|
+
"peerDependencies": {
|
|
37
|
+
"@molecule/api-bonds-default-express": "^1.0.0",
|
|
38
|
+
"@molecule/api-database": "^1.0.0",
|
|
39
|
+
"@molecule/api-i18n": "^1.0.0",
|
|
40
|
+
"@molecule/api-middleware-validation": "^1.0.0",
|
|
41
|
+
"@molecule/api-ai": "^1.0.0",
|
|
42
|
+
"@molecule/api-http": "^1.0.0"
|
|
43
|
+
}
|
|
44
|
+
}
|