@accordproject/template-engine 3.0.1 → 4.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/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 +61 -0
- package/lib/TemplateArchiveProcessor.js +152 -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 +15 -0
- package/lib/TypeScriptCompilationContext.js +57 -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/index.d.ts +13 -0
- package/lib/drafting/MonetaryAmount/index.js +67 -0
- package/lib/drafting/MonetaryAmount/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 +43 -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/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 +3 -0
- package/lib/runtime/declarations.js +22 -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 +6 -0
- package/lib/utils.js +71 -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 +37 -25
- package/umd/template-engine.js +13 -0
- package/umd/template-engine.js.LICENSE.txt +21 -0
- package/dist/index.d.ts +0 -174
- package/dist/index.js +0 -1244
- package/dist/index.js.map +0 -1
- package/dist/index.mjs +0 -1217
- 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,CA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BACjC,MAAM,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,GAAG,KAAK,EAAE,CAAC,CAAC;gBACpD,CAAC;qBACI,IAAI,IAAI,KAAK,CAAC,IAAI,MAAM,EAAE,CAAC;oBAC5B,WAAW;oBACX,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAe,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,KAAK,MAAM,CAAC,GAAG,CAAC,CAAC;oBAC9E,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAC;oBACjC,OAAO,CAAC,EAAE,GAAG,MAAM,EAAE,OAAO,EAAE,GAAG,GAAG,KAAK,EAAE,CAAC,CAAC;gBACjD,CAAC;qBAAM,CAAC;oBACJ,0DAA0D;oBAC1D,iEAAiE;oBACjE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAe,EAAE,EAAE,CAAC,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,61 @@
|
|
|
1
|
+
import { Template } from '@accordproject/cicero-core';
|
|
2
|
+
import { TwoSlashReturn } from '@typescript/twoslash';
|
|
3
|
+
export type State = object;
|
|
4
|
+
export type Response = object;
|
|
5
|
+
export type Event = object;
|
|
6
|
+
export type TriggerResponse = {
|
|
7
|
+
result: Response;
|
|
8
|
+
state: State;
|
|
9
|
+
events: Event[];
|
|
10
|
+
};
|
|
11
|
+
export type InitResponse = {
|
|
12
|
+
state: State;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* A template archive processor: can draft content using the
|
|
16
|
+
* templatemark for the archive and trigger the logic of the archive
|
|
17
|
+
*/
|
|
18
|
+
export declare class TemplateArchiveProcessor {
|
|
19
|
+
template: Template;
|
|
20
|
+
private compiledLogicCache?;
|
|
21
|
+
/**
|
|
22
|
+
* Creates a template archive processor
|
|
23
|
+
* @param {Template} template - the template to be used by the processor
|
|
24
|
+
*/
|
|
25
|
+
constructor(template: Template);
|
|
26
|
+
/**
|
|
27
|
+
* Drafts a template by merging it with data
|
|
28
|
+
* @param {any} data the data to merge with the template
|
|
29
|
+
* @param {string} format the output format
|
|
30
|
+
* @param {any} options merge options
|
|
31
|
+
* @param {[string]} currentTime the current value for 'now'
|
|
32
|
+
* @returns {Promise} the drafted content
|
|
33
|
+
*/
|
|
34
|
+
draft(data: any, format: string, options: any, currentTime?: string): Promise<any>;
|
|
35
|
+
/**
|
|
36
|
+
* Compile the logic of a template
|
|
37
|
+
* @param {boolean} [enableCompiledLogicCache] - whether to cache the compiled logic for future use
|
|
38
|
+
* @returns {Promise<Record<string, TwoSlashReturn>>} the compiled code for each typescript file
|
|
39
|
+
*/
|
|
40
|
+
compileLogic(enableCompiledLogicCache?: boolean): Promise<Record<string, TwoSlashReturn>>;
|
|
41
|
+
/**
|
|
42
|
+
* Trigger the logic of a template.
|
|
43
|
+
* @param {object} data - the data for the template
|
|
44
|
+
* @param {object} request - the request to send to the template logic
|
|
45
|
+
* @param {object} state - the current state of the template
|
|
46
|
+
* @param {[string]} currentTime - the current time, defaults to now
|
|
47
|
+
* @param {[number]} utcOffset - the UTC offset, defaults to zero
|
|
48
|
+
* @param {boolean} [enableCompiledLogicCache] - whether to use the compiled logic cache
|
|
49
|
+
* @returns {Promise<TriggerResponse>} the response and any events
|
|
50
|
+
*/
|
|
51
|
+
trigger(data: any, request: any, state?: any, currentTime?: string, utcOffset?: number, enableCompiledLogicCache?: boolean): Promise<TriggerResponse>;
|
|
52
|
+
/**
|
|
53
|
+
* Init the logic of a template.
|
|
54
|
+
* @param {object} data - the data for the template
|
|
55
|
+
* @param {[string]} currentTime - the current time, defaults to now
|
|
56
|
+
* @param {[number]} utcOffset - the UTC offset, defaults to zero
|
|
57
|
+
* @param {boolean} [enableCompiledLogicCache] - whether to use the compiled logic cache
|
|
58
|
+
* @returns {Promise<InitResponse>} the new state
|
|
59
|
+
*/
|
|
60
|
+
init(data: any, currentTime?: string, utcOffset?: number, enableCompiledLogicCache?: boolean): Promise<InitResponse>;
|
|
61
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
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
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
|
+
exports.TemplateArchiveProcessor = void 0;
|
|
17
|
+
const TemplateMarkInterpreter_1 = require("./TemplateMarkInterpreter");
|
|
18
|
+
const markdown_template_1 = require("@accordproject/markdown-template");
|
|
19
|
+
const markdown_transform_1 = require("@accordproject/markdown-transform");
|
|
20
|
+
const TypeScriptToJavaScriptCompiler_1 = require("./TypeScriptToJavaScriptCompiler");
|
|
21
|
+
const JavaScriptEvaluator_1 = require("./JavaScriptEvaluator");
|
|
22
|
+
const declarations_1 = require("./runtime/declarations");
|
|
23
|
+
/**
|
|
24
|
+
* A template archive processor: can draft content using the
|
|
25
|
+
* templatemark for the archive and trigger the logic of the archive
|
|
26
|
+
*/
|
|
27
|
+
class TemplateArchiveProcessor {
|
|
28
|
+
/**
|
|
29
|
+
* Creates a template archive processor
|
|
30
|
+
* @param {Template} template - the template to be used by the processor
|
|
31
|
+
*/
|
|
32
|
+
constructor(template) {
|
|
33
|
+
this.template = template;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Drafts a template by merging it with data
|
|
37
|
+
* @param {any} data the data to merge with the template
|
|
38
|
+
* @param {string} format the output format
|
|
39
|
+
* @param {any} options merge options
|
|
40
|
+
* @param {[string]} currentTime the current value for 'now'
|
|
41
|
+
* @returns {Promise} the drafted content
|
|
42
|
+
*/
|
|
43
|
+
async draft(data, format, options, currentTime) {
|
|
44
|
+
// Setup
|
|
45
|
+
const metadata = this.template.getMetadata();
|
|
46
|
+
const templateKind = metadata.getTemplateType() !== 0 ? 'clause' : 'contract';
|
|
47
|
+
// Get the data
|
|
48
|
+
const modelManager = this.template.getModelManager();
|
|
49
|
+
const engine = new TemplateMarkInterpreter_1.TemplateMarkInterpreter(modelManager, {});
|
|
50
|
+
const templateMarkTransformer = new markdown_template_1.TemplateMarkTransformer();
|
|
51
|
+
const templateMarkDom = templateMarkTransformer.fromMarkdownTemplate({ content: this.template.getTemplate() }, modelManager, templateKind);
|
|
52
|
+
const now = currentTime ? currentTime : new Date().toISOString();
|
|
53
|
+
// console.log(JSON.stringify(templateMarkDom, null, 2));
|
|
54
|
+
const ciceroMark = await engine.generate(templateMarkDom, data, { now });
|
|
55
|
+
// console.log(JSON.stringify(ciceroMark));
|
|
56
|
+
const result = (0, markdown_transform_1.transform)(ciceroMark.toJSON(), 'ciceromark', ['ciceromark_unquoted', format], null, options);
|
|
57
|
+
// console.log(result);
|
|
58
|
+
return result;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Compile the logic of a template
|
|
62
|
+
* @param {boolean} [enableCompiledLogicCache] - whether to cache the compiled logic for future use
|
|
63
|
+
* @returns {Promise<Record<string, TwoSlashReturn>>} the compiled code for each typescript file
|
|
64
|
+
*/
|
|
65
|
+
async compileLogic(enableCompiledLogicCache = false) {
|
|
66
|
+
if (enableCompiledLogicCache && this.compiledLogicCache) {
|
|
67
|
+
return this.compiledLogicCache;
|
|
68
|
+
}
|
|
69
|
+
const logicManager = this.template.getLogicManager();
|
|
70
|
+
if (logicManager.getLanguage() === 'typescript') {
|
|
71
|
+
const compiledCode = {};
|
|
72
|
+
const tsFiles = logicManager.getScriptManager().getScriptsForTarget('typescript');
|
|
73
|
+
for (let n = 0; n < tsFiles.length; n++) {
|
|
74
|
+
const tsFile = tsFiles[n];
|
|
75
|
+
const compiler = new TypeScriptToJavaScriptCompiler_1.TypeScriptToJavaScriptCompiler(this.template.getModelManager(), this.template.getTemplateModel().getFullyQualifiedName());
|
|
76
|
+
await compiler.initialize();
|
|
77
|
+
// add the runtime type definitions to all ts files??
|
|
78
|
+
const code = `${Buffer.from(declarations_1.SMART_LEGAL_CONTRACT_BASE64, 'base64').toString()}
|
|
79
|
+
${tsFile.getContents()}`;
|
|
80
|
+
const result = compiler.compile(code);
|
|
81
|
+
compiledCode[tsFile.getIdentifier()] = result;
|
|
82
|
+
}
|
|
83
|
+
if (enableCompiledLogicCache) {
|
|
84
|
+
this.compiledLogicCache = compiledCode;
|
|
85
|
+
}
|
|
86
|
+
return compiledCode;
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
throw new Error('Only TypeScript is supported at this time');
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Trigger the logic of a template.
|
|
94
|
+
* @param {object} data - the data for the template
|
|
95
|
+
* @param {object} request - the request to send to the template logic
|
|
96
|
+
* @param {object} state - the current state of the template
|
|
97
|
+
* @param {[string]} currentTime - the current time, defaults to now
|
|
98
|
+
* @param {[number]} utcOffset - the UTC offset, defaults to zero
|
|
99
|
+
* @param {boolean} [enableCompiledLogicCache] - whether to use the compiled logic cache
|
|
100
|
+
* @returns {Promise<TriggerResponse>} the response and any events
|
|
101
|
+
*/
|
|
102
|
+
async trigger(data, request, state, currentTime, utcOffset, enableCompiledLogicCache) {
|
|
103
|
+
const compiledCode = await this.compileLogic(enableCompiledLogicCache);
|
|
104
|
+
const resolvedTime = currentTime ?? new Date().toISOString();
|
|
105
|
+
const resolvedOffset = utcOffset ?? 0;
|
|
106
|
+
const evaluator = new JavaScriptEvaluator_1.JavaScriptEvaluator();
|
|
107
|
+
const evalResponse = await evaluator.evalDangerously({
|
|
108
|
+
templateLogic: true,
|
|
109
|
+
verbose: false,
|
|
110
|
+
functionName: 'trigger',
|
|
111
|
+
code: compiledCode['logic/logic.ts'].code, // TODO DCS - how to find the code to run?
|
|
112
|
+
argumentNames: ['data', 'request', 'state'],
|
|
113
|
+
arguments: [data, request, state, resolvedTime, resolvedOffset]
|
|
114
|
+
});
|
|
115
|
+
if (evalResponse.result) {
|
|
116
|
+
return evalResponse.result;
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
throw new Error('Trigger failed with message: ' + evalResponse.message);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Init the logic of a template.
|
|
124
|
+
* @param {object} data - the data for the template
|
|
125
|
+
* @param {[string]} currentTime - the current time, defaults to now
|
|
126
|
+
* @param {[number]} utcOffset - the UTC offset, defaults to zero
|
|
127
|
+
* @param {boolean} [enableCompiledLogicCache] - whether to use the compiled logic cache
|
|
128
|
+
* @returns {Promise<InitResponse>} the new state
|
|
129
|
+
*/
|
|
130
|
+
async init(data, currentTime, utcOffset, enableCompiledLogicCache) {
|
|
131
|
+
const compiledCode = await this.compileLogic(enableCompiledLogicCache);
|
|
132
|
+
const resolvedTime = currentTime ?? new Date().toISOString();
|
|
133
|
+
const resolvedOffset = utcOffset ?? 0;
|
|
134
|
+
const evaluator = new JavaScriptEvaluator_1.JavaScriptEvaluator();
|
|
135
|
+
const evalResponse = await evaluator.evalDangerously({
|
|
136
|
+
templateLogic: true,
|
|
137
|
+
verbose: false,
|
|
138
|
+
functionName: 'init',
|
|
139
|
+
code: compiledCode['logic/logic.ts'].code, // TODO DCS - how to find the code to run?
|
|
140
|
+
argumentNames: ['data'],
|
|
141
|
+
arguments: [data, resolvedTime, resolvedOffset]
|
|
142
|
+
});
|
|
143
|
+
if (evalResponse.result) {
|
|
144
|
+
return evalResponse.result;
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
throw new Error('Init failed with message: ' + evalResponse.message);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
exports.TemplateArchiveProcessor = TemplateArchiveProcessor;
|
|
152
|
+
//# sourceMappingURL=TemplateArchiveProcessor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"TemplateArchiveProcessor.js","sourceRoot":"","sources":["../src/TemplateArchiveProcessor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;GAYG;;;AAKH,uEAAoE;AACpE,wEAA2E;AAC3E,0EAA8D;AAC9D,qFAAkF;AAGlF,+DAA4D;AAC5D,yDAAqE;AAgBrE;;;GAGG;AACH,MAAa,wBAAwB;IAIjC;;;OAGG;IACH,YAAY,QAAkB;QAC1B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC7B,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,KAAK,CAAC,IAAS,EAAE,MAAc,EAAE,OAAY,EAAE,WAAoB;QACrE,QAAQ;QACR,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC;QAC7C,MAAM,YAAY,GAAG,QAAQ,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC;QAE9E,eAAe;QACf,MAAM,YAAY,GAA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H,IAAG,YAAY,CAAC,MAAM,EAAE,CAAC;YACrB,OAAO,YAAY,CAAC,MAAsB,CAAC;QAC/C,CAAC;aACI,CAAC;YACF,MAAM,IAAI,KAAK,CAAC,4BAA4B,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC;QACzE,CAAC;IACL,CAAC;CACJ;AA7ID,4DA6IC"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { ClassDeclaration, ModelManager } from '@accordproject/concerto-core';
|
|
2
|
+
import { TemplateData } from './TemplateMarkNodes';
|
|
3
|
+
import { GenerationOptions } from './TypeScriptRuntime';
|
|
4
|
+
/**
|
|
5
|
+
* A template engine: merges the markup and logic of a template with
|
|
6
|
+
* JSON data to produce JSON data.
|
|
7
|
+
*/
|
|
8
|
+
export declare class TemplateMarkInterpreter {
|
|
9
|
+
modelManager: ModelManager;
|
|
10
|
+
templateClass: ClassDeclaration;
|
|
11
|
+
clauseLibrary: object;
|
|
12
|
+
constructor(modelManager: ModelManager, clauseLibrary: object, templateConceptFqn?: string);
|
|
13
|
+
/**
|
|
14
|
+
* Checks that a TemplateMark JSON document is valid with respect to the
|
|
15
|
+
* TemplateMark model, as well as the template model.
|
|
16
|
+
*
|
|
17
|
+
* Checks:
|
|
18
|
+
* 1. Variable names are valid properties in the template model
|
|
19
|
+
* 2. Optional properties have guards
|
|
20
|
+
* @param {*} templateMark the TemplateMark JSON object
|
|
21
|
+
* @returns {*} TemplateMark JSON that has been typed checked and has type metadata added
|
|
22
|
+
* @throws {Error} if the templateMark document is invalid
|
|
23
|
+
*/
|
|
24
|
+
checkTypes(templateMark: object): object;
|
|
25
|
+
/**
|
|
26
|
+
* Compiles the code nodes containing TS to code nodes containing JS.
|
|
27
|
+
* @param {*} templateMark the TemplateMark JSON object
|
|
28
|
+
* @returns {*} TemplateMark JSON with JS nodes
|
|
29
|
+
* @throws {Error} if the templateMark document is invalid
|
|
30
|
+
*/
|
|
31
|
+
compileTypeScriptToJavaScript(templateMark: object): Promise<object>;
|
|
32
|
+
validateCiceroMark(ciceroMark: object): object;
|
|
33
|
+
generate(templateMark: object, data: TemplateData, options?: GenerationOptions): Promise<any>;
|
|
34
|
+
}
|