@accordproject/template-engine 3.1.0 → 4.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -0
- package/lib/JavaScriptEvaluator.d.ts +71 -0
- package/lib/JavaScriptEvaluator.js +245 -0
- package/lib/JavaScriptEvaluator.js.map +1 -0
- package/lib/TemplateArchiveProcessor.d.ts +151 -0
- package/lib/TemplateArchiveProcessor.js +447 -0
- package/lib/TemplateArchiveProcessor.js.map +1 -0
- package/lib/TemplateMarkInterpreter.d.ts +34 -0
- package/lib/TemplateMarkInterpreter.js +689 -0
- package/lib/TemplateMarkInterpreter.js.map +1 -0
- package/lib/TemplateMarkNodes.d.ts +19 -0
- package/lib/TemplateMarkNodes.js +45 -0
- package/lib/TemplateMarkNodes.js.map +1 -0
- package/lib/TemplateMarkToJavaScriptCompiler.d.ts +20 -0
- package/lib/TemplateMarkToJavaScriptCompiler.js +99 -0
- package/lib/TemplateMarkToJavaScriptCompiler.js.map +1 -0
- package/lib/TypeScriptCompilationContext.d.ts +42 -0
- package/lib/TypeScriptCompilationContext.js +170 -0
- package/lib/TypeScriptCompilationContext.js.map +1 -0
- package/lib/TypeScriptRuntime.d.ts +17 -0
- package/lib/TypeScriptRuntime.js +84 -0
- package/lib/TypeScriptRuntime.js.map +1 -0
- package/lib/TypeScriptToJavaScriptCompiler.d.ts +11 -0
- package/lib/TypeScriptToJavaScriptCompiler.js +169 -0
- package/lib/TypeScriptToJavaScriptCompiler.js.map +1 -0
- package/lib/drafting/Boolean/index.d.ts +6 -0
- package/lib/drafting/Boolean/index.js +30 -0
- package/lib/drafting/Boolean/index.js.map +1 -0
- package/lib/drafting/DateTime/index.d.ts +8 -0
- package/lib/drafting/DateTime/index.js +33 -0
- package/lib/drafting/DateTime/index.js.map +1 -0
- package/lib/drafting/Double/format.d.ts +14 -0
- package/lib/drafting/Double/format.js +62 -0
- package/lib/drafting/Double/format.js.map +1 -0
- package/lib/drafting/Double/index.d.ts +8 -0
- package/lib/drafting/Double/index.js +33 -0
- package/lib/drafting/Double/index.js.map +1 -0
- package/lib/drafting/DraftFormat.d.ts +5 -0
- package/lib/drafting/DraftFormat.js +18 -0
- package/lib/drafting/DraftFormat.js.map +1 -0
- package/lib/drafting/Duration/index.d.ts +6 -0
- package/lib/drafting/Duration/index.js +39 -0
- package/lib/drafting/Duration/index.js.map +1 -0
- package/lib/drafting/Integer/format.d.ts +14 -0
- package/lib/drafting/Integer/format.js +52 -0
- package/lib/drafting/Integer/format.js.map +1 -0
- package/lib/drafting/Integer/index.d.ts +8 -0
- package/lib/drafting/Integer/index.js +33 -0
- package/lib/drafting/Integer/index.js.map +1 -0
- package/lib/drafting/Long/index.d.ts +8 -0
- package/lib/drafting/Long/index.js +33 -0
- package/lib/drafting/Long/index.js.map +1 -0
- package/lib/drafting/MonetaryAmount/currencycode.d.ts +35 -0
- package/lib/drafting/MonetaryAmount/currencycode.js +53 -0
- package/lib/drafting/MonetaryAmount/currencycode.js.map +1 -0
- package/lib/drafting/MonetaryAmount/formatTokens.d.ts +13 -0
- package/lib/drafting/MonetaryAmount/formatTokens.js +44 -0
- package/lib/drafting/MonetaryAmount/formatTokens.js.map +1 -0
- package/lib/drafting/MonetaryAmount/index.d.ts +13 -0
- package/lib/drafting/MonetaryAmount/index.js +51 -0
- package/lib/drafting/MonetaryAmount/index.js.map +1 -0
- package/lib/drafting/PreciseAmount/index.d.ts +17 -0
- package/lib/drafting/PreciseAmount/index.js +113 -0
- package/lib/drafting/PreciseAmount/index.js.map +1 -0
- package/lib/drafting/String/index.d.ts +6 -0
- package/lib/drafting/String/index.js +25 -0
- package/lib/drafting/String/index.js.map +1 -0
- package/lib/drafting/index.d.ts +2 -0
- package/lib/drafting/index.js +63 -0
- package/lib/drafting/index.js.map +1 -0
- package/lib/index.d.ts +7 -0
- package/lib/index.js +42 -0
- package/lib/index.js.map +1 -0
- package/lib/llm/LLMConfig.d.ts +121 -0
- package/lib/llm/LLMConfig.js +30 -0
- package/lib/llm/LLMConfig.js.map +1 -0
- package/lib/llm/LLMExecutor.d.ts +77 -0
- package/lib/llm/LLMExecutor.js +603 -0
- package/lib/llm/LLMExecutor.js.map +1 -0
- package/lib/llm/ModelManagerSchema.d.ts +14 -0
- package/lib/llm/ModelManagerSchema.js +67 -0
- package/lib/llm/ModelManagerSchema.js.map +1 -0
- package/lib/llm/Reasoners.d.ts +190 -0
- package/lib/llm/Reasoners.js +643 -0
- package/lib/llm/Reasoners.js.map +1 -0
- package/lib/model-gen/concerto.d.ts +13 -0
- package/lib/model-gen/concerto.js +4 -0
- package/lib/model-gen/concerto.js.map +1 -0
- package/lib/model-gen/concerto.metamodel@1.0.0.d.ts +196 -0
- package/lib/model-gen/concerto.metamodel@1.0.0.js +4 -0
- package/lib/model-gen/concerto.metamodel@1.0.0.js.map +1 -0
- package/lib/model-gen/concerto@1.0.0.d.ts +19 -0
- package/lib/model-gen/concerto@1.0.0.js +4 -0
- package/lib/model-gen/concerto@1.0.0.js.map +1 -0
- package/lib/model-gen/org.accordproject.ciceromark@0.6.0.d.ts +49 -0
- package/lib/model-gen/org.accordproject.ciceromark@0.6.0.js +4 -0
- package/lib/model-gen/org.accordproject.ciceromark@0.6.0.js.map +1 -0
- package/lib/model-gen/org.accordproject.commonmark@0.5.0.d.ts +89 -0
- package/lib/model-gen/org.accordproject.commonmark@0.5.0.js +4 -0
- package/lib/model-gen/org.accordproject.commonmark@0.5.0.js.map +1 -0
- package/lib/model-gen/org.accordproject.templatemark@0.5.0.d.ts +76 -0
- package/lib/model-gen/org.accordproject.templatemark@0.5.0.js +11 -0
- package/lib/model-gen/org.accordproject.templatemark@0.5.0.js.map +1 -0
- package/lib/runtime/declarations.d.ts +2 -0
- package/lib/runtime/declarations.js +21 -0
- package/lib/runtime/declarations.js.map +1 -0
- package/lib/slc/model-gen/concerto.d.ts +13 -0
- package/lib/slc/model-gen/concerto.decorator@1.0.0.d.ts +6 -0
- package/lib/slc/model-gen/concerto.decorator@1.0.0.js +5 -0
- package/lib/slc/model-gen/concerto.decorator@1.0.0.js.map +1 -0
- package/lib/slc/model-gen/concerto.js +5 -0
- package/lib/slc/model-gen/concerto.js.map +1 -0
- package/lib/slc/model-gen/concerto@1.0.0.d.ts +24 -0
- package/lib/slc/model-gen/concerto@1.0.0.js +6 -0
- package/lib/slc/model-gen/concerto@1.0.0.js.map +1 -0
- package/lib/slc/model-gen/org.accordproject.contract@0.2.0.d.ts +7 -0
- package/lib/slc/model-gen/org.accordproject.contract@0.2.0.js +5 -0
- package/lib/slc/model-gen/org.accordproject.contract@0.2.0.js.map +1 -0
- package/lib/slc/model-gen/org.accordproject.runtime@0.2.0.d.ts +15 -0
- package/lib/slc/model-gen/org.accordproject.runtime@0.2.0.js +4 -0
- package/lib/slc/model-gen/org.accordproject.runtime@0.2.0.js.map +1 -0
- package/lib/slc/model-gen/org.accordproject.time@0.3.0.d.ts +46 -0
- package/lib/slc/model-gen/org.accordproject.time@0.3.0.js +48 -0
- package/lib/slc/model-gen/org.accordproject.time@0.3.0.js.map +1 -0
- package/lib/utils.d.ts +35 -0
- package/lib/utils.js +122 -0
- package/lib/utils.js.map +1 -0
- package/lib/worker.d.ts +1 -0
- package/{dist → lib}/worker.js +12 -10
- package/lib/worker.js.map +1 -0
- package/package.json +46 -25
- package/umd/template-engine.js +13 -0
- package/umd/template-engine.js.LICENSE.txt +21 -0
- package/dist/index.d.ts +0 -186
- package/dist/index.js +0 -1275
- package/dist/index.js.map +0 -1
- package/dist/index.mjs +0 -1248
- package/dist/index.mjs.map +0 -1
- package/dist/worker.js.map +0 -1
package/README.md
CHANGED
|
@@ -180,6 +180,47 @@ Note that this module is primarily intended for tool authors, or developers embe
|
|
|
180
180
|
npm install @accordproject/template-engine --save
|
|
181
181
|
```
|
|
182
182
|
|
|
183
|
+
Requires Node.js >= 22.
|
|
184
|
+
|
|
185
|
+
## Browser usage
|
|
186
|
+
|
|
187
|
+
The package is published with two entry points:
|
|
188
|
+
|
|
189
|
+
- `lib/index.js` — the Node.js build (`tsc` output, typed via `lib/index.d.ts`).
|
|
190
|
+
- `umd/template-engine.js` — a pre-built UMD browser bundle (referenced by the `browser`
|
|
191
|
+
field, so bundlers pick it up automatically for web builds).
|
|
192
|
+
|
|
193
|
+
The full author-and-run loop works **in the browser** — parse a template to TemplateMark,
|
|
194
|
+
type-check it, compile its embedded TypeScript logic to JavaScript, and evaluate it — which
|
|
195
|
+
is what powers the [Template Playground](https://playground.accordproject.org). For
|
|
196
|
+
convenience the bundle also re-exports `ModelManager` (concerto) and `TemplateMarkTransformer`
|
|
197
|
+
(markdown-template), so a single bundle can run the whole `model -> template -> agreement` flow
|
|
198
|
+
with one concerto instance:
|
|
199
|
+
|
|
200
|
+
```html
|
|
201
|
+
<script src="https://unpkg.com/@accordproject/template-engine/umd/template-engine.js"></script>
|
|
202
|
+
<script>
|
|
203
|
+
const { ModelManager, TemplateMarkTransformer, TemplateMarkInterpreter } = window['template-engine'];
|
|
204
|
+
const modelManager = new ModelManager();
|
|
205
|
+
modelManager.addCTOModel('namespace test@1.0.0\n@template\nconcept TemplateData { o String name }');
|
|
206
|
+
const templateMark = new TemplateMarkTransformer()
|
|
207
|
+
.fromMarkdownTemplate({ content: 'Hello {{name}}!' }, modelManager, 'contract');
|
|
208
|
+
const engine = new TemplateMarkInterpreter(modelManager, {});
|
|
209
|
+
const agreement = await engine.generate(templateMark, { $class: 'test@1.0.0.TemplateData', name: 'World' });
|
|
210
|
+
</script>
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
Notes on browser limitations:
|
|
214
|
+
|
|
215
|
+
- Logic that imports **arbitrary** 3rd-party packages must be shipped as a **compiled archive**
|
|
216
|
+
(JavaScript logic, dependencies already bundled — produced offline in Node.js). In the browser,
|
|
217
|
+
source archives (TypeScript logic) compile against a fixed set of supported runtime dependencies.
|
|
218
|
+
- `Template.fromDirectory()`/`fromUrl()` and child-process logic evaluation are Node-only; in the
|
|
219
|
+
browser load templates via `Template.fromArchive(buffer)` and use the default in-process evaluator.
|
|
220
|
+
|
|
221
|
+
The browser bundle is exercised by the Playwright tests in the `e2e/` workspace, which load
|
|
222
|
+
`umd/template-engine.js` into a headless Chromium and run a real `generate()`.
|
|
223
|
+
|
|
183
224
|
## License <a name="license"></a>
|
|
184
225
|
Accord Project source code files are made available under the Apache License, Version 2.0 (Apache-2.0), located in the LICENSE file. Accord Project documentation files are made available under the Creative Commons Attribution 4.0 International License (CC-BY-4.0), available at http://creativecommons.org/licenses/by/4.0/.
|
|
185
226
|
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
export type EvalOptions = {
|
|
3
|
+
timeout: number;
|
|
4
|
+
};
|
|
5
|
+
export type EvalRequest = {
|
|
6
|
+
verbose?: boolean;
|
|
7
|
+
templateLogic?: boolean;
|
|
8
|
+
code: string;
|
|
9
|
+
functionName?: string;
|
|
10
|
+
argumentNames: string[];
|
|
11
|
+
arguments: any[];
|
|
12
|
+
};
|
|
13
|
+
type WorkItem = {
|
|
14
|
+
pid?: number;
|
|
15
|
+
startTime: number;
|
|
16
|
+
expireTime: number;
|
|
17
|
+
request: EvalRequest;
|
|
18
|
+
resolve: (result: any) => void;
|
|
19
|
+
reject: (result: any) => void;
|
|
20
|
+
};
|
|
21
|
+
export type EvalResponse = {
|
|
22
|
+
result: any;
|
|
23
|
+
timeout?: boolean;
|
|
24
|
+
starvation?: boolean;
|
|
25
|
+
message?: string;
|
|
26
|
+
stack?: string;
|
|
27
|
+
elapsed?: number;
|
|
28
|
+
maxQueueDepthExceeded?: boolean;
|
|
29
|
+
};
|
|
30
|
+
export type JavaScriptEvaluatorOptions = {
|
|
31
|
+
waitInterval: number;
|
|
32
|
+
maxWorkers: number;
|
|
33
|
+
maxQueueDepth: number;
|
|
34
|
+
};
|
|
35
|
+
type ChildProcess = {
|
|
36
|
+
pid?: number;
|
|
37
|
+
} & EventEmitter;
|
|
38
|
+
export declare const dynamicImport: <T>(path: string, symbol?: string) => Promise<any>;
|
|
39
|
+
/**
|
|
40
|
+
* This class implements two JS function evaluation strategies:
|
|
41
|
+
* 1. evalDangerously which creates a dynamic function and run it in-process
|
|
42
|
+
* This should only be used with trusted code, or within a sandbox (e.g. the browser)
|
|
43
|
+
* 2. evalChildProcess which spins up a child Node process to eval the function
|
|
44
|
+
* The maximum number of child processes is capped via JavaScriptEvaluatorOptions
|
|
45
|
+
* as well as the maximum queue depth for the queue used to wait for a free worker
|
|
46
|
+
* child process. Not that to prevent cross-request contamination
|
|
47
|
+
* child processes are NOT pooled and are never reused.
|
|
48
|
+
*/
|
|
49
|
+
export declare class JavaScriptEvaluator {
|
|
50
|
+
options: JavaScriptEvaluatorOptions;
|
|
51
|
+
workers: Array<ChildProcess>;
|
|
52
|
+
queue: Array<WorkItem>;
|
|
53
|
+
constructor(options?: JavaScriptEvaluatorOptions);
|
|
54
|
+
/**
|
|
55
|
+
* Evaluates a JS function in process.
|
|
56
|
+
* @param {EvalRequest} request - the eval request
|
|
57
|
+
* @returns {Promise} a promise to the result
|
|
58
|
+
*/
|
|
59
|
+
evalDangerously(request: EvalRequest): Promise<EvalResponse>;
|
|
60
|
+
/**
|
|
61
|
+
* Evaluates a JS function using a node child process
|
|
62
|
+
* @param {EvalRequest} request the eval request
|
|
63
|
+
* @param {EvalOptions} options the options for the request
|
|
64
|
+
* @returns {Promise<EvalResponse>} the async result
|
|
65
|
+
*/
|
|
66
|
+
evalChildProcess(request: EvalRequest, options?: EvalOptions): Promise<EvalResponse>;
|
|
67
|
+
private processQueue;
|
|
68
|
+
private getWorkerPath;
|
|
69
|
+
private doWork;
|
|
70
|
+
}
|
|
71
|
+
export {};
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/*
|
|
3
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
* you may not use this file except in compliance with the License.
|
|
5
|
+
* You may obtain a copy of the License at
|
|
6
|
+
*
|
|
7
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
*
|
|
9
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
* See the License for the specific language governing permissions and
|
|
13
|
+
* limitations under the License.
|
|
14
|
+
*/
|
|
15
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
16
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
17
|
+
};
|
|
18
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
19
|
+
exports.JavaScriptEvaluator = exports.dynamicImport = void 0;
|
|
20
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
21
|
+
const child_process_1 = __importDefault(require("child_process"));
|
|
22
|
+
const jsonpath_1 = __importDefault(require("jsonpath"));
|
|
23
|
+
const dayjs_1 = __importDefault(require("dayjs"));
|
|
24
|
+
const path_1 = __importDefault(require("path"));
|
|
25
|
+
async function sleep(msec) {
|
|
26
|
+
return new Promise(resolve => setTimeout(resolve, msec));
|
|
27
|
+
}
|
|
28
|
+
// we use this to import modules because it's an ESM module and direct imports won't work...
|
|
29
|
+
// see: https://github.com/TypeStrong/ts-node/discussions/1290
|
|
30
|
+
const _import = async (path) => new Function('specifier', 'return import(specifier)')(path);
|
|
31
|
+
// we create a wrapper for the _import above and returns the `default` exported method/function/symbol
|
|
32
|
+
// inferred by the module name or a custom one base on user preferences...
|
|
33
|
+
const dynamicImport = async (path, symbol) => {
|
|
34
|
+
const mod = await _import(path);
|
|
35
|
+
return symbol ? mod.symbol : mod.default;
|
|
36
|
+
};
|
|
37
|
+
exports.dynamicImport = dynamicImport;
|
|
38
|
+
/**
|
|
39
|
+
* This class implements two JS function evaluation strategies:
|
|
40
|
+
* 1. evalDangerously which creates a dynamic function and run it in-process
|
|
41
|
+
* This should only be used with trusted code, or within a sandbox (e.g. the browser)
|
|
42
|
+
* 2. evalChildProcess which spins up a child Node process to eval the function
|
|
43
|
+
* The maximum number of child processes is capped via JavaScriptEvaluatorOptions
|
|
44
|
+
* as well as the maximum queue depth for the queue used to wait for a free worker
|
|
45
|
+
* child process. Not that to prevent cross-request contamination
|
|
46
|
+
* child processes are NOT pooled and are never reused.
|
|
47
|
+
*/
|
|
48
|
+
class JavaScriptEvaluator {
|
|
49
|
+
constructor(options = { waitInterval: 50, maxWorkers: 8, maxQueueDepth: 1000 }) {
|
|
50
|
+
this.options = options;
|
|
51
|
+
this.workers = [];
|
|
52
|
+
this.queue = [];
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Evaluates a JS function in process.
|
|
56
|
+
* @param {EvalRequest} request - the eval request
|
|
57
|
+
* @returns {Promise} a promise to the result
|
|
58
|
+
*/
|
|
59
|
+
async evalDangerously(request) {
|
|
60
|
+
return new Promise((resolve, reject) => {
|
|
61
|
+
try {
|
|
62
|
+
if (request.verbose) {
|
|
63
|
+
console.log(request.code);
|
|
64
|
+
}
|
|
65
|
+
const start = new Date().getTime();
|
|
66
|
+
let result = null;
|
|
67
|
+
// is this a simple JS function?
|
|
68
|
+
if (!request.templateLogic) {
|
|
69
|
+
const fun = new Function(...['dayjs', 'jp', ...request.argumentNames], request.code);
|
|
70
|
+
result = fun(...[dayjs_1.default, jsonpath_1.default, ...request.arguments]);
|
|
71
|
+
const end = new Date().getTime();
|
|
72
|
+
resolve({ result, elapsed: end - start });
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
// this is a template logic esm module, so we need to dynamic import it
|
|
76
|
+
const dataUri = 'data:text/javascript;base64,'
|
|
77
|
+
+ btoa(request.code);
|
|
78
|
+
(0, exports.dynamicImport)(dataUri)
|
|
79
|
+
.then(templateLogicConstructor => {
|
|
80
|
+
const instance = new templateLogicConstructor();
|
|
81
|
+
if (!request.functionName) {
|
|
82
|
+
throw new Error('No function name specified for template logic');
|
|
83
|
+
}
|
|
84
|
+
result = instance[request.functionName](...request.arguments);
|
|
85
|
+
const end = new Date().getTime();
|
|
86
|
+
resolve({ result, elapsed: end - start });
|
|
87
|
+
})
|
|
88
|
+
.catch(err => {
|
|
89
|
+
console.error(err);
|
|
90
|
+
if (err instanceof Error) {
|
|
91
|
+
reject({
|
|
92
|
+
message: err.message,
|
|
93
|
+
stack: err.stack,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
reject({
|
|
98
|
+
message: String(err),
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
console.error(err);
|
|
106
|
+
if (err instanceof Error) {
|
|
107
|
+
reject({
|
|
108
|
+
message: err.message,
|
|
109
|
+
stack: err.stack,
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
reject({
|
|
114
|
+
message: String(err),
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Evaluates a JS function using a node child process
|
|
122
|
+
* @param {EvalRequest} request the eval request
|
|
123
|
+
* @param {EvalOptions} options the options for the request
|
|
124
|
+
* @returns {Promise<EvalResponse>} the async result
|
|
125
|
+
*/
|
|
126
|
+
async evalChildProcess(request, options = { timeout: 10000 }) {
|
|
127
|
+
// console.log('Workers count: ' + this.workers.length);
|
|
128
|
+
return new Promise((resolve, reject) => {
|
|
129
|
+
const now = new Date().getTime();
|
|
130
|
+
const workItem = {
|
|
131
|
+
startTime: now,
|
|
132
|
+
expireTime: now + options.timeout,
|
|
133
|
+
request,
|
|
134
|
+
resolve,
|
|
135
|
+
reject
|
|
136
|
+
};
|
|
137
|
+
if (this.queue.length >= this.options.maxQueueDepth) {
|
|
138
|
+
reject({ maxQueueDepthExceeded: true, elapsed: 0 });
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
this.queue.push(workItem);
|
|
142
|
+
this.processQueue(options);
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
processQueue(options) {
|
|
146
|
+
const now = new Date().getTime();
|
|
147
|
+
const notExpired = this.queue.filter(w => (now < w.expireTime));
|
|
148
|
+
const expired = this.queue.filter(w => (now >= w.expireTime));
|
|
149
|
+
this.queue = notExpired;
|
|
150
|
+
expired.forEach(w => {
|
|
151
|
+
w.reject({ timeout: true, starvation: true, elapsed: now - w.startTime });
|
|
152
|
+
});
|
|
153
|
+
if (this.workers.length < this.options.maxWorkers) {
|
|
154
|
+
// we have a free worker
|
|
155
|
+
const next = this.queue.shift();
|
|
156
|
+
if (next) {
|
|
157
|
+
this.doWork(next, options)
|
|
158
|
+
.then(result => next.resolve(result))
|
|
159
|
+
.catch(error => next.reject(error));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
// no free worker, so sleep and then try again
|
|
164
|
+
sleep(this.options.waitInterval)
|
|
165
|
+
.then(() => {
|
|
166
|
+
this.processQueue(options);
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
getWorkerPath() {
|
|
171
|
+
try {
|
|
172
|
+
const thisPath = require.resolve('@accordproject/template-engine');
|
|
173
|
+
return path_1.default.join(thisPath, '..', 'worker.js');
|
|
174
|
+
}
|
|
175
|
+
catch (err) { // eslint-disable-line @typescript-eslint/no-unused-vars
|
|
176
|
+
// if we cannot load the module it likely means we are running
|
|
177
|
+
// a unit test inside the module...
|
|
178
|
+
return path_1.default.join(__dirname, '..', 'lib', 'worker.js');
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
doWork(work, options) {
|
|
182
|
+
return new Promise((resolve, reject) => {
|
|
183
|
+
const start = new Date().getTime();
|
|
184
|
+
// check for browser
|
|
185
|
+
if (!child_process_1.default.fork) {
|
|
186
|
+
reject({ message: 'Cannot use evalChildProcess because child_process.fork is not defined.' });
|
|
187
|
+
}
|
|
188
|
+
// on timeout will send SIGTERM
|
|
189
|
+
const workerPath = this.getWorkerPath();
|
|
190
|
+
// console.debug(`Worker path: ${workerPath}`);
|
|
191
|
+
const worker = child_process_1.default.fork(workerPath, { timeout: options.timeout, env: {} });
|
|
192
|
+
if (worker.pid === undefined || worker.pid === null) {
|
|
193
|
+
throw new Error('Failed to fork child process');
|
|
194
|
+
}
|
|
195
|
+
this.workers.push(worker);
|
|
196
|
+
work.pid = worker.pid;
|
|
197
|
+
let result;
|
|
198
|
+
worker.on('error', (err) => {
|
|
199
|
+
this.workers = this.workers.filter((w) => w.pid !== worker.pid);
|
|
200
|
+
const end = new Date().getTime();
|
|
201
|
+
if (err instanceof Error) {
|
|
202
|
+
reject({
|
|
203
|
+
message: err.message,
|
|
204
|
+
stack: err.stack,
|
|
205
|
+
elapsed: end - start
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
else {
|
|
209
|
+
reject({
|
|
210
|
+
message: String(err),
|
|
211
|
+
elapsed: end - start
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
worker.on('message', (msg) => {
|
|
216
|
+
result = msg;
|
|
217
|
+
});
|
|
218
|
+
worker.on('exit', (code) => {
|
|
219
|
+
if (code === null) {
|
|
220
|
+
// timeout
|
|
221
|
+
this.workers = this.workers.filter((w) => w.pid !== worker.pid);
|
|
222
|
+
const end = new Date().getTime();
|
|
223
|
+
reject({ timeout: true, elapsed: end - start });
|
|
224
|
+
}
|
|
225
|
+
else if (code === 0 && result) {
|
|
226
|
+
// success!
|
|
227
|
+
this.workers = this.workers.filter((w) => w.pid !== worker.pid);
|
|
228
|
+
const end = new Date().getTime();
|
|
229
|
+
resolve({ ...result, elapsed: end - start });
|
|
230
|
+
}
|
|
231
|
+
else {
|
|
232
|
+
// null result or non-zero code from worker means an error
|
|
233
|
+
// result will be undefined if the user code calls process.exit()
|
|
234
|
+
this.workers = this.workers.filter((w) => w.pid !== worker.pid);
|
|
235
|
+
const end = new Date().getTime();
|
|
236
|
+
reject({ code, result, elapsed: end - start });
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
// send the request to the child process
|
|
240
|
+
worker.send(work.request);
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
exports.JavaScriptEvaluator = JavaScriptEvaluator;
|
|
245
|
+
//# sourceMappingURL=JavaScriptEvaluator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"JavaScriptEvaluator.js","sourceRoot":"","sources":["../src/JavaScriptEvaluator.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;GAYG;;;;;;AAEH,uDAAuD;AAEvD,kEAA0C;AAC1C,wDAA0B;AAC1B,kDAA0B;AAE1B,gDAAwB;AA4CxB,KAAK,UAAU,KAAK,CAAC,IAAY;IAC7B,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC;AAC7D,CAAC;AAED,4FAA4F;AAC5F,8DAA8D;AAC9D,MAAM,OAAO,GAAG,KAAK,EAAE,IAAY,EAAE,EAAE,CAAC,IAAI,QAAQ,CAAC,WAAW,EAAE,0BAA0B,CAAC,CAAC,IAAI,CAAC,CAAC;AAEpG,sGAAsG;AACtG,0EAA0E;AACnE,MAAM,aAAa,GAAG,KAAK,EAAK,IAAY,EAAE,MAAe,EAAE,EAAE;IACpE,MAAM,GAAG,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAChC,OAAO,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,OAAY,CAAC;AAClD,CAAC,CAAA;AAHY,QAAA,aAAa,iBAGzB;AAID;;;;;;;;;GASG;AACH,MAAa,mBAAmB;IAK5B,YAAY,UAAsC,EAAC,YAAY,EAAE,EAAE,EAAE,UAAU,EAAE,CAAC,EAAE,aAAa,EAAE,IAAI,EAAC;QACpG,IAAI,CAAC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AAC,CAAC,CAAC,GAAG,KAAK,MAAM,CAAC,GAAG,CAAC,CAAC;oBAC9E,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAC;oBACjC,MAAM,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,GAAG,KAAK,EAAE,CAAC,CAAC;gBACnD,CAAC;YACL,CAAC,CAAC,CAAC;YACH,wCAAwC;YACxC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC9B,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AAtMD,kDAsMC"}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { Template } from '@accordproject/cicero-core';
|
|
2
|
+
import { TwoSlashReturn } from '@typescript/twoslash';
|
|
3
|
+
import { LLMExecutorConfig } from './llm/LLMConfig';
|
|
4
|
+
/** The contract state. */
|
|
5
|
+
export type State = object;
|
|
6
|
+
/** A response/result returned by the contract logic. */
|
|
7
|
+
export type Response = object;
|
|
8
|
+
/** An event emitted by the contract logic. */
|
|
9
|
+
export type Event = object;
|
|
10
|
+
/** The result of triggering a template: the response, updated state, and events. */
|
|
11
|
+
export type TriggerResponse = {
|
|
12
|
+
result: Response;
|
|
13
|
+
state: State;
|
|
14
|
+
events: Event[];
|
|
15
|
+
};
|
|
16
|
+
/** The result of initializing a template: the initial state. */
|
|
17
|
+
export type InitResponse = {
|
|
18
|
+
state: State;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* A template archive processor: can draft content using the
|
|
22
|
+
* templatemark for the archive and trigger the logic of the archive
|
|
23
|
+
*/
|
|
24
|
+
export declare class TemplateArchiveProcessor {
|
|
25
|
+
/** The template used by the processor. */
|
|
26
|
+
template: Template;
|
|
27
|
+
/** Cache of compiled logic, keyed by script identifier. */
|
|
28
|
+
private compiledLogicCache?;
|
|
29
|
+
/** Optional LLM fallback configuration. */
|
|
30
|
+
llmConfig?: LLMExecutorConfig;
|
|
31
|
+
/** Lazily-created LLM executor reused across debug/init/trigger calls. */
|
|
32
|
+
private llmExecutor?;
|
|
33
|
+
/**
|
|
34
|
+
* Creates a template archive processor
|
|
35
|
+
* @param {Template} template - the template to be used by the processor
|
|
36
|
+
* @param {LLMExecutorConfig} [llmConfig] - optional LLM fallback configuration
|
|
37
|
+
*/
|
|
38
|
+
constructor(template: Template, llmConfig?: LLMExecutorConfig);
|
|
39
|
+
/**
|
|
40
|
+
* Drafts a template by merging it with data
|
|
41
|
+
* @param {any} data the data to merge with the template
|
|
42
|
+
* @param {string} format the output format
|
|
43
|
+
* @param {any} options merge options
|
|
44
|
+
* @param {[string]} currentTime the current value for 'now'
|
|
45
|
+
* @returns {Promise} the drafted content
|
|
46
|
+
*/
|
|
47
|
+
draft(data: any, format: string, options: any, currentTime?: string): Promise<any>;
|
|
48
|
+
/**
|
|
49
|
+
* Compile the logic of a template
|
|
50
|
+
* @param {boolean} [enableCompiledLogicCache] - whether to cache the compiled logic for future use
|
|
51
|
+
* @returns {Promise<Record<string, TwoSlashReturn>>} the compiled code for each typescript file
|
|
52
|
+
*/
|
|
53
|
+
compileLogic(enableCompiledLogicCache?: boolean): Promise<Record<string, TwoSlashReturn>>;
|
|
54
|
+
/**
|
|
55
|
+
* Asserts that a runtime payload's declared type is, or extends, the given runtime
|
|
56
|
+
* base type. This enforces the runtime class hierarchy nominally (by `$class`), which
|
|
57
|
+
* the type system cannot: request is a bivariant `trigger` parameter, and State's
|
|
58
|
+
* generated interface is structurally satisfied by any identified concept. Using the
|
|
59
|
+
* model's own assignability, the bare base type and any subclass are accepted while a
|
|
60
|
+
* plain concept that does not extend the base is rejected.
|
|
61
|
+
* @param {any} payload - a serialized Concerto object (has a `$class`), or undefined
|
|
62
|
+
* @param {string} baseFqn - the fully-qualified name of the runtime base type
|
|
63
|
+
* @param {string} role - the payload's role, used in the error message
|
|
64
|
+
* @throws {Error} if the payload's type is not the base type or a subclass of it
|
|
65
|
+
*/
|
|
66
|
+
private assertRuntimeHierarchy;
|
|
67
|
+
/**
|
|
68
|
+
* Populates the `contract` back-reference that `org.accordproject.runtime.Obligation`
|
|
69
|
+
* (and therefore any event that extends it, e.g. a template's `PaymentObligationEvent`)
|
|
70
|
+
* requires, so that template logic never has to set it explicitly.
|
|
71
|
+
*
|
|
72
|
+
* Only events whose `contract` field is not already set are touched, so template logic
|
|
73
|
+
* that deliberately points an obligation at a different contract is left alone. Filling
|
|
74
|
+
* the field in is only meaningful when the template's own data model is itself a
|
|
75
|
+
* `Contract` (or a subtype of it) - that's the only instance in scope at `trigger()` time
|
|
76
|
+
* that the relationship is allowed to point to. The `Serializer` this class uses is
|
|
77
|
+
* constructed with `acceptResourcesForRelationships: true`, so handing it the full `data`
|
|
78
|
+
* resource is enough for it to resolve the relationship from that resource's own
|
|
79
|
+
* `$class`/identifier.
|
|
80
|
+
* @param {Event[]} events - the events returned by the template logic, mutated in place
|
|
81
|
+
* @param {any} data - the contract/clause data instance passed into trigger()
|
|
82
|
+
* @throws {Error} if an Obligation-derived event is missing `contract` and the template's
|
|
83
|
+
* data model does not extend Contract, so there is nothing valid to auto-populate with
|
|
84
|
+
*/
|
|
85
|
+
private populateObligationBackReferences;
|
|
86
|
+
private assertTemplateLogicSubclass;
|
|
87
|
+
/**
|
|
88
|
+
* Determines whether LLM fallback is enabled.
|
|
89
|
+
* @returns {boolean} true if an LLM config is present and not disabled
|
|
90
|
+
*/
|
|
91
|
+
private shouldUseLLM;
|
|
92
|
+
/**
|
|
93
|
+
* Constructs an LLM executor for this template.
|
|
94
|
+
* @returns {LLMExecutor} the LLM executor
|
|
95
|
+
* @throws {Error} if no LLM config is present
|
|
96
|
+
*/
|
|
97
|
+
private makeLLMExecutor;
|
|
98
|
+
/**
|
|
99
|
+
* Executes the template's compiled TypeScript trigger logic.
|
|
100
|
+
* @param {any} data - the data for the template
|
|
101
|
+
* @param {any} request - the request to send to the template logic
|
|
102
|
+
* @param {any} [priorState] - the state produced by init() (or a previous
|
|
103
|
+
* trigger()); required for stateful templates, ignored for stateless ones
|
|
104
|
+
* @param {string} [currentTime] - the current time, defaults to now
|
|
105
|
+
* @param {number} [utcOffset] - the UTC offset, defaults to zero
|
|
106
|
+
* @returns {Promise<TriggerResponse>} the response and any events
|
|
107
|
+
*/
|
|
108
|
+
private executeTypeScriptTrigger;
|
|
109
|
+
/**
|
|
110
|
+
* Executes the template's compiled TypeScript init logic. Returns an empty
|
|
111
|
+
* state when the compiled logic defines no `init` method (stateless template).
|
|
112
|
+
* @param {any} data - the data for the template
|
|
113
|
+
* @param {string} [currentTime] - the current time, defaults to now
|
|
114
|
+
* @param {number} [utcOffset] - the UTC offset, defaults to zero
|
|
115
|
+
* @returns {Promise<InitResponse>} the new state
|
|
116
|
+
*/
|
|
117
|
+
private executeTypeScriptInit;
|
|
118
|
+
/**
|
|
119
|
+
* Trigger the logic of a template.
|
|
120
|
+
*
|
|
121
|
+
* Stateful templates (`this.template.isStateful()`) carry state across
|
|
122
|
+
* executions, so they must always be seeded with `priorState` — the state
|
|
123
|
+
* returned by a prior call to {@link init} (or by a prior call to
|
|
124
|
+
* `trigger`) — before a request can be evaluated. There is no implicit
|
|
125
|
+
* "empty" state for a template that declares custom State fields; calling
|
|
126
|
+
* `trigger` without `priorState` for such a template throws. Stateless
|
|
127
|
+
* templates ignore `priorState` entirely.
|
|
128
|
+
* @param {object} data - the data for the template
|
|
129
|
+
* @param {object} request - the request to send to the template logic
|
|
130
|
+
* @param {object} priorState - the state to evaluate the request against.
|
|
131
|
+
* For stateful templates this is required and must be the state produced
|
|
132
|
+
* by init() or a previous trigger(); for stateless templates it is ignored.
|
|
133
|
+
* @param {[string]} currentTime - the current time, defaults to now
|
|
134
|
+
* @param {[number]} utcOffset - the UTC offset, defaults to zero
|
|
135
|
+
* @param {boolean} [enableCompiledLogicCache] - whether to use the compiled logic cache
|
|
136
|
+
* @returns {Promise<TriggerResponse>} the response and any events
|
|
137
|
+
* @throws {Error} if the template is stateful and no priorState is supplied, or if an
|
|
138
|
+
* emitted event extends `org.accordproject.runtime.Obligation` and its `contract`
|
|
139
|
+
* back-reference can't be auto-populated (see {@link populateObligationBackReferences})
|
|
140
|
+
*/
|
|
141
|
+
trigger(data: any, request: any, priorState?: any, currentTime?: string, utcOffset?: number, enableCompiledLogicCache?: boolean): Promise<TriggerResponse>;
|
|
142
|
+
/**
|
|
143
|
+
* Init the logic of a template.
|
|
144
|
+
* @param {object} data - the data for the template
|
|
145
|
+
* @param {[string]} currentTime - the current time, defaults to now
|
|
146
|
+
* @param {[number]} utcOffset - the UTC offset, defaults to zero
|
|
147
|
+
* @param {boolean} [enableCompiledLogicCache] - whether to use the compiled logic cache
|
|
148
|
+
* @returns {Promise<InitResponse>} the new state
|
|
149
|
+
*/
|
|
150
|
+
init(data: any, currentTime?: string, utcOffset?: number, enableCompiledLogicCache?: boolean): Promise<InitResponse>;
|
|
151
|
+
}
|