@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.
Files changed (139) hide show
  1. package/README.md +41 -0
  2. package/lib/JavaScriptEvaluator.d.ts +71 -0
  3. package/lib/JavaScriptEvaluator.js +245 -0
  4. package/lib/JavaScriptEvaluator.js.map +1 -0
  5. package/lib/TemplateArchiveProcessor.d.ts +151 -0
  6. package/lib/TemplateArchiveProcessor.js +447 -0
  7. package/lib/TemplateArchiveProcessor.js.map +1 -0
  8. package/lib/TemplateMarkInterpreter.d.ts +34 -0
  9. package/lib/TemplateMarkInterpreter.js +689 -0
  10. package/lib/TemplateMarkInterpreter.js.map +1 -0
  11. package/lib/TemplateMarkNodes.d.ts +19 -0
  12. package/lib/TemplateMarkNodes.js +45 -0
  13. package/lib/TemplateMarkNodes.js.map +1 -0
  14. package/lib/TemplateMarkToJavaScriptCompiler.d.ts +20 -0
  15. package/lib/TemplateMarkToJavaScriptCompiler.js +99 -0
  16. package/lib/TemplateMarkToJavaScriptCompiler.js.map +1 -0
  17. package/lib/TypeScriptCompilationContext.d.ts +42 -0
  18. package/lib/TypeScriptCompilationContext.js +170 -0
  19. package/lib/TypeScriptCompilationContext.js.map +1 -0
  20. package/lib/TypeScriptRuntime.d.ts +17 -0
  21. package/lib/TypeScriptRuntime.js +84 -0
  22. package/lib/TypeScriptRuntime.js.map +1 -0
  23. package/lib/TypeScriptToJavaScriptCompiler.d.ts +11 -0
  24. package/lib/TypeScriptToJavaScriptCompiler.js +169 -0
  25. package/lib/TypeScriptToJavaScriptCompiler.js.map +1 -0
  26. package/lib/drafting/Boolean/index.d.ts +6 -0
  27. package/lib/drafting/Boolean/index.js +30 -0
  28. package/lib/drafting/Boolean/index.js.map +1 -0
  29. package/lib/drafting/DateTime/index.d.ts +8 -0
  30. package/lib/drafting/DateTime/index.js +33 -0
  31. package/lib/drafting/DateTime/index.js.map +1 -0
  32. package/lib/drafting/Double/format.d.ts +14 -0
  33. package/lib/drafting/Double/format.js +62 -0
  34. package/lib/drafting/Double/format.js.map +1 -0
  35. package/lib/drafting/Double/index.d.ts +8 -0
  36. package/lib/drafting/Double/index.js +33 -0
  37. package/lib/drafting/Double/index.js.map +1 -0
  38. package/lib/drafting/DraftFormat.d.ts +5 -0
  39. package/lib/drafting/DraftFormat.js +18 -0
  40. package/lib/drafting/DraftFormat.js.map +1 -0
  41. package/lib/drafting/Duration/index.d.ts +6 -0
  42. package/lib/drafting/Duration/index.js +39 -0
  43. package/lib/drafting/Duration/index.js.map +1 -0
  44. package/lib/drafting/Integer/format.d.ts +14 -0
  45. package/lib/drafting/Integer/format.js +52 -0
  46. package/lib/drafting/Integer/format.js.map +1 -0
  47. package/lib/drafting/Integer/index.d.ts +8 -0
  48. package/lib/drafting/Integer/index.js +33 -0
  49. package/lib/drafting/Integer/index.js.map +1 -0
  50. package/lib/drafting/Long/index.d.ts +8 -0
  51. package/lib/drafting/Long/index.js +33 -0
  52. package/lib/drafting/Long/index.js.map +1 -0
  53. package/lib/drafting/MonetaryAmount/currencycode.d.ts +35 -0
  54. package/lib/drafting/MonetaryAmount/currencycode.js +53 -0
  55. package/lib/drafting/MonetaryAmount/currencycode.js.map +1 -0
  56. package/lib/drafting/MonetaryAmount/formatTokens.d.ts +13 -0
  57. package/lib/drafting/MonetaryAmount/formatTokens.js +44 -0
  58. package/lib/drafting/MonetaryAmount/formatTokens.js.map +1 -0
  59. package/lib/drafting/MonetaryAmount/index.d.ts +13 -0
  60. package/lib/drafting/MonetaryAmount/index.js +51 -0
  61. package/lib/drafting/MonetaryAmount/index.js.map +1 -0
  62. package/lib/drafting/PreciseAmount/index.d.ts +17 -0
  63. package/lib/drafting/PreciseAmount/index.js +113 -0
  64. package/lib/drafting/PreciseAmount/index.js.map +1 -0
  65. package/lib/drafting/String/index.d.ts +6 -0
  66. package/lib/drafting/String/index.js +25 -0
  67. package/lib/drafting/String/index.js.map +1 -0
  68. package/lib/drafting/index.d.ts +2 -0
  69. package/lib/drafting/index.js +63 -0
  70. package/lib/drafting/index.js.map +1 -0
  71. package/lib/index.d.ts +7 -0
  72. package/lib/index.js +42 -0
  73. package/lib/index.js.map +1 -0
  74. package/lib/llm/LLMConfig.d.ts +121 -0
  75. package/lib/llm/LLMConfig.js +30 -0
  76. package/lib/llm/LLMConfig.js.map +1 -0
  77. package/lib/llm/LLMExecutor.d.ts +77 -0
  78. package/lib/llm/LLMExecutor.js +603 -0
  79. package/lib/llm/LLMExecutor.js.map +1 -0
  80. package/lib/llm/ModelManagerSchema.d.ts +14 -0
  81. package/lib/llm/ModelManagerSchema.js +67 -0
  82. package/lib/llm/ModelManagerSchema.js.map +1 -0
  83. package/lib/llm/Reasoners.d.ts +190 -0
  84. package/lib/llm/Reasoners.js +643 -0
  85. package/lib/llm/Reasoners.js.map +1 -0
  86. package/lib/model-gen/concerto.d.ts +13 -0
  87. package/lib/model-gen/concerto.js +4 -0
  88. package/lib/model-gen/concerto.js.map +1 -0
  89. package/lib/model-gen/concerto.metamodel@1.0.0.d.ts +196 -0
  90. package/lib/model-gen/concerto.metamodel@1.0.0.js +4 -0
  91. package/lib/model-gen/concerto.metamodel@1.0.0.js.map +1 -0
  92. package/lib/model-gen/concerto@1.0.0.d.ts +19 -0
  93. package/lib/model-gen/concerto@1.0.0.js +4 -0
  94. package/lib/model-gen/concerto@1.0.0.js.map +1 -0
  95. package/lib/model-gen/org.accordproject.ciceromark@0.6.0.d.ts +49 -0
  96. package/lib/model-gen/org.accordproject.ciceromark@0.6.0.js +4 -0
  97. package/lib/model-gen/org.accordproject.ciceromark@0.6.0.js.map +1 -0
  98. package/lib/model-gen/org.accordproject.commonmark@0.5.0.d.ts +89 -0
  99. package/lib/model-gen/org.accordproject.commonmark@0.5.0.js +4 -0
  100. package/lib/model-gen/org.accordproject.commonmark@0.5.0.js.map +1 -0
  101. package/lib/model-gen/org.accordproject.templatemark@0.5.0.d.ts +76 -0
  102. package/lib/model-gen/org.accordproject.templatemark@0.5.0.js +11 -0
  103. package/lib/model-gen/org.accordproject.templatemark@0.5.0.js.map +1 -0
  104. package/lib/runtime/declarations.d.ts +2 -0
  105. package/lib/runtime/declarations.js +21 -0
  106. package/lib/runtime/declarations.js.map +1 -0
  107. package/lib/slc/model-gen/concerto.d.ts +13 -0
  108. package/lib/slc/model-gen/concerto.decorator@1.0.0.d.ts +6 -0
  109. package/lib/slc/model-gen/concerto.decorator@1.0.0.js +5 -0
  110. package/lib/slc/model-gen/concerto.decorator@1.0.0.js.map +1 -0
  111. package/lib/slc/model-gen/concerto.js +5 -0
  112. package/lib/slc/model-gen/concerto.js.map +1 -0
  113. package/lib/slc/model-gen/concerto@1.0.0.d.ts +24 -0
  114. package/lib/slc/model-gen/concerto@1.0.0.js +6 -0
  115. package/lib/slc/model-gen/concerto@1.0.0.js.map +1 -0
  116. package/lib/slc/model-gen/org.accordproject.contract@0.2.0.d.ts +7 -0
  117. package/lib/slc/model-gen/org.accordproject.contract@0.2.0.js +5 -0
  118. package/lib/slc/model-gen/org.accordproject.contract@0.2.0.js.map +1 -0
  119. package/lib/slc/model-gen/org.accordproject.runtime@0.2.0.d.ts +15 -0
  120. package/lib/slc/model-gen/org.accordproject.runtime@0.2.0.js +4 -0
  121. package/lib/slc/model-gen/org.accordproject.runtime@0.2.0.js.map +1 -0
  122. package/lib/slc/model-gen/org.accordproject.time@0.3.0.d.ts +46 -0
  123. package/lib/slc/model-gen/org.accordproject.time@0.3.0.js +48 -0
  124. package/lib/slc/model-gen/org.accordproject.time@0.3.0.js.map +1 -0
  125. package/lib/utils.d.ts +35 -0
  126. package/lib/utils.js +122 -0
  127. package/lib/utils.js.map +1 -0
  128. package/lib/worker.d.ts +1 -0
  129. package/{dist → lib}/worker.js +12 -10
  130. package/lib/worker.js.map +1 -0
  131. package/package.json +46 -25
  132. package/umd/template-engine.js +13 -0
  133. package/umd/template-engine.js.LICENSE.txt +21 -0
  134. package/dist/index.d.ts +0 -186
  135. package/dist/index.js +0 -1275
  136. package/dist/index.js.map +0 -1
  137. package/dist/index.mjs +0 -1248
  138. package/dist/index.mjs.map +0 -1
  139. package/dist/worker.js.map +0 -1
@@ -0,0 +1,447 @@
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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
16
+ if (k2 === undefined) k2 = k;
17
+ var desc = Object.getOwnPropertyDescriptor(m, k);
18
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
19
+ desc = { enumerable: true, get: function() { return m[k]; } };
20
+ }
21
+ Object.defineProperty(o, k2, desc);
22
+ }) : (function(o, m, k, k2) {
23
+ if (k2 === undefined) k2 = k;
24
+ o[k2] = m[k];
25
+ }));
26
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
27
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
28
+ }) : function(o, v) {
29
+ o["default"] = v;
30
+ });
31
+ var __importStar = (this && this.__importStar) || (function () {
32
+ var ownKeys = function(o) {
33
+ ownKeys = Object.getOwnPropertyNames || function (o) {
34
+ var ar = [];
35
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
36
+ return ar;
37
+ };
38
+ return ownKeys(o);
39
+ };
40
+ return function (mod) {
41
+ if (mod && mod.__esModule) return mod;
42
+ var result = {};
43
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
44
+ __setModuleDefault(result, mod);
45
+ return result;
46
+ };
47
+ })();
48
+ Object.defineProperty(exports, "__esModule", { value: true });
49
+ exports.TemplateArchiveProcessor = void 0;
50
+ const concerto_core_1 = require("@accordproject/concerto-core");
51
+ const TemplateMarkInterpreter_1 = require("./TemplateMarkInterpreter");
52
+ const markdown_template_1 = require("@accordproject/markdown-template");
53
+ const markdown_transform_1 = require("@accordproject/markdown-transform");
54
+ const TypeScriptToJavaScriptCompiler_1 = require("./TypeScriptToJavaScriptCompiler");
55
+ const JavaScriptEvaluator_1 = require("./JavaScriptEvaluator");
56
+ const LLMExecutor_1 = require("./llm/LLMExecutor");
57
+ const utils_1 = require("./utils");
58
+ /**
59
+ * A template archive processor: can draft content using the
60
+ * templatemark for the archive and trigger the logic of the archive
61
+ */
62
+ class TemplateArchiveProcessor {
63
+ /**
64
+ * Creates a template archive processor
65
+ * @param {Template} template - the template to be used by the processor
66
+ * @param {LLMExecutorConfig} [llmConfig] - optional LLM fallback configuration
67
+ */
68
+ constructor(template, llmConfig) {
69
+ this.template = template;
70
+ this.llmConfig = llmConfig;
71
+ }
72
+ /**
73
+ * Drafts a template by merging it with data
74
+ * @param {any} data the data to merge with the template
75
+ * @param {string} format the output format
76
+ * @param {any} options merge options
77
+ * @param {[string]} currentTime the current value for 'now'
78
+ * @returns {Promise} the drafted content
79
+ */
80
+ async draft(data, format, options, currentTime) {
81
+ // Setup
82
+ const metadata = this.template.getMetadata();
83
+ const templateKind = metadata.getTemplateType() !== 0 ? 'clause' : 'contract';
84
+ // Get the data
85
+ const modelManager = this.template.getModelManager();
86
+ const engine = new TemplateMarkInterpreter_1.TemplateMarkInterpreter(modelManager, {});
87
+ const templateMarkTransformer = new markdown_template_1.TemplateMarkTransformer();
88
+ const templateMarkDom = templateMarkTransformer.fromMarkdownTemplate({ content: this.template.getTemplate() }, modelManager, templateKind);
89
+ const now = currentTime ? currentTime : new Date().toISOString();
90
+ const ciceroMark = await engine.generate(templateMarkDom, data, { now });
91
+ const result = (0, markdown_transform_1.transform)(ciceroMark.toJSON(), 'ciceromark', ['ciceromark_unquoted', format], null, options);
92
+ return result;
93
+ }
94
+ /**
95
+ * Compile the logic of a template
96
+ * @param {boolean} [enableCompiledLogicCache] - whether to cache the compiled logic for future use
97
+ * @returns {Promise<Record<string, TwoSlashReturn>>} the compiled code for each typescript file
98
+ */
99
+ async compileLogic(enableCompiledLogicCache = false) {
100
+ if (enableCompiledLogicCache && this.compiledLogicCache) {
101
+ return this.compiledLogicCache;
102
+ }
103
+ const logicManager = this.template.getLogicManager();
104
+ if (logicManager.getLanguage() === 'typescript') {
105
+ const compiledCode = {};
106
+ const tsFiles = logicManager.getScriptManager().getScriptsForTarget('typescript');
107
+ const logicScript = tsFiles.find((tsFile) => tsFile.getIdentifier() === 'logic/logic.ts');
108
+ await this.assertTemplateLogicSubclass(logicScript);
109
+ for (let n = 0; n < tsFiles.length; n++) {
110
+ const tsFile = tsFiles[n];
111
+ const compiler = new TypeScriptToJavaScriptCompiler_1.TypeScriptToJavaScriptCompiler(this.template.getModelManager(), this.template.getTemplateModel().getFullyQualifiedName());
112
+ await compiler.initialize();
113
+ // The runtime type declarations (IConcept, TemplateLogic, etc.) are
114
+ // provided by the compilation context, with the State / Request / Response /
115
+ // Event type positions bound to the model-derived Runtime* unions (the
116
+ // concrete base plus its subclasses).
117
+ const result = compiler.compile(tsFile.getContents());
118
+ // Surface the runtime-hierarchy constraint violation (TS2344) as a hard
119
+ // error. The state type argument must satisfy the RuntimeState union; a type
120
+ // that is structurally incompatible with the base (e.g. a concept with no
121
+ // $identifier used as state, or an emit that is not assignable to the base
122
+ // Event) fails the constraint. Structural matches to the bare base are
123
+ // allowed here and are instead checked nominally at runtime
124
+ // (assertRuntimeHierarchy). Scoped to the logic entry point and to TS2344 so
125
+ // that unrelated diagnostics (and non-logic scripts such as README.md) do
126
+ // not turn into hard failures.
127
+ const isLogicEntry = tsFile.getIdentifier().endsWith('logic.ts');
128
+ if (isLogicEntry) {
129
+ const hierarchyErrors = (result.errors || [])
130
+ .filter(e => e.category === 1 && e.code === 2344);
131
+ if (hierarchyErrors.length > 0) {
132
+ const message = hierarchyErrors.map(e => e.renderedMessage).join('\n');
133
+ throw new Error('Invalid template: State, Request, Response and Event declarations must ' +
134
+ 'be, or extend, their runtime base types (org.accordproject.runtime ' +
135
+ `State / Request / Response and the Concerto Event).\n${message}`);
136
+ }
137
+ }
138
+ compiledCode[tsFile.getIdentifier()] = result;
139
+ }
140
+ if (enableCompiledLogicCache) {
141
+ this.compiledLogicCache = compiledCode;
142
+ }
143
+ return compiledCode;
144
+ }
145
+ else {
146
+ throw new Error('Only TypeScript is supported at this time');
147
+ }
148
+ }
149
+ /**
150
+ * Asserts that a runtime payload's declared type is, or extends, the given runtime
151
+ * base type. This enforces the runtime class hierarchy nominally (by `$class`), which
152
+ * the type system cannot: request is a bivariant `trigger` parameter, and State's
153
+ * generated interface is structurally satisfied by any identified concept. Using the
154
+ * model's own assignability, the bare base type and any subclass are accepted while a
155
+ * plain concept that does not extend the base is rejected.
156
+ * @param {any} payload - a serialized Concerto object (has a `$class`), or undefined
157
+ * @param {string} baseFqn - the fully-qualified name of the runtime base type
158
+ * @param {string} role - the payload's role, used in the error message
159
+ * @throws {Error} if the payload's type is not the base type or a subclass of it
160
+ */
161
+ assertRuntimeHierarchy(payload, baseFqn, role) {
162
+ if (!payload || !payload.$class) {
163
+ return;
164
+ }
165
+ if (!(0, utils_1.isAssignableTo)(this.template.getModelManager(), payload.$class, baseFqn)) {
166
+ throw new Error(`Invalid ${role}: '${payload.$class}' must be, or extend, the runtime ` +
167
+ `${role} type (${baseFqn}).`);
168
+ }
169
+ }
170
+ /**
171
+ * Populates the `contract` back-reference that `org.accordproject.runtime.Obligation`
172
+ * (and therefore any event that extends it, e.g. a template's `PaymentObligationEvent`)
173
+ * requires, so that template logic never has to set it explicitly.
174
+ *
175
+ * Only events whose `contract` field is not already set are touched, so template logic
176
+ * that deliberately points an obligation at a different contract is left alone. Filling
177
+ * the field in is only meaningful when the template's own data model is itself a
178
+ * `Contract` (or a subtype of it) - that's the only instance in scope at `trigger()` time
179
+ * that the relationship is allowed to point to. The `Serializer` this class uses is
180
+ * constructed with `acceptResourcesForRelationships: true`, so handing it the full `data`
181
+ * resource is enough for it to resolve the relationship from that resource's own
182
+ * `$class`/identifier.
183
+ * @param {Event[]} events - the events returned by the template logic, mutated in place
184
+ * @param {any} data - the contract/clause data instance passed into trigger()
185
+ * @throws {Error} if an Obligation-derived event is missing `contract` and the template's
186
+ * data model does not extend Contract, so there is nothing valid to auto-populate with
187
+ */
188
+ populateObligationBackReferences(events, data) {
189
+ const modelManager = this.template.getModelManager();
190
+ events.forEach((event) => {
191
+ if (!event || !event.$class || event.contract) {
192
+ return;
193
+ }
194
+ if (!(0, utils_1.isAssignableTo)(modelManager, event.$class, utils_1.RUNTIME_OBLIGATION_FQN)) {
195
+ return;
196
+ }
197
+ if (data && data.$class && (0, utils_1.isAssignableTo)(modelManager, data.$class, utils_1.RUNTIME_CONTRACT_FQN)) {
198
+ // Relationship fields must be a "<fq-class>#<id>" string, not the full resource.
199
+ // Assigning `data` directly (as before) satisfies acceptResourcesForRelationships
200
+ // during population, but validate() then rejects it: that flag only relaxes what
201
+ // the populator will accept as *input*, it doesn't change what a relationship field
202
+ // is allowed to *hold* afterward - it still must be a Relationship, not a Resource.
203
+ const classDecl = modelManager.getType(data.$class);
204
+ const idField = classDecl.getIdentifierFieldName();
205
+ const idValue = idField ? data[idField] : undefined;
206
+ if (!idField || idValue === undefined) {
207
+ throw new Error(`Cannot populate the required 'contract' back-reference on event '${event.$class}': ` +
208
+ `the data model '${data.$class}' has no resolvable identifier value for field '${idField}'.`);
209
+ }
210
+ event.contract = `${idValue}`;
211
+ return;
212
+ }
213
+ throw new Error(`Cannot populate the required 'contract' back-reference on event '${event.$class}': ` +
214
+ `it extends ${utils_1.RUNTIME_OBLIGATION_FQN}, but this template's data model ` +
215
+ `('${data?.$class ?? 'undefined'}') does not extend ${utils_1.RUNTIME_CONTRACT_FQN}. Either ` +
216
+ "change the template model to extend Contract, or have the template logic set " +
217
+ "'contract' explicitly on the event before returning it.");
218
+ });
219
+ }
220
+ async assertTemplateLogicSubclass(tsFile) {
221
+ if (!tsFile) {
222
+ throw new Error('Template logic compilation requires a logic/logic.ts file.');
223
+ }
224
+ const tsImport = await Promise.resolve().then(() => __importStar(require('typescript')));
225
+ const tsModule = ('default' in tsImport && tsImport.default ? tsImport.default : tsImport);
226
+ const sourceFile = tsModule.createSourceFile(tsFile.getIdentifier(), tsFile.getContents(), tsModule.ScriptTarget.Latest, true, tsModule.ScriptKind.TS);
227
+ const hasTemplateLogicSubclass = sourceFile.statements.some((statement) => {
228
+ if (!tsModule.isClassDeclaration(statement) || !statement.heritageClauses) {
229
+ return false;
230
+ }
231
+ return statement.heritageClauses.some((clause) => clause.token === tsModule.SyntaxKind.ExtendsKeyword &&
232
+ clause.types.some((heritageType) => {
233
+ const expression = heritageType.expression;
234
+ return (tsModule.isIdentifier(expression) && expression.text === 'TemplateLogic') ||
235
+ (tsModule.isPropertyAccessExpression(expression) && expression.name.text === 'TemplateLogic');
236
+ }));
237
+ });
238
+ if (!hasTemplateLogicSubclass) {
239
+ throw new Error(`Template logic compilation requires ${tsFile.getIdentifier()} to define a class extending TemplateLogic.`);
240
+ }
241
+ }
242
+ /**
243
+ * Determines whether LLM fallback is enabled.
244
+ * @returns {boolean} true if an LLM config is present and not disabled
245
+ */
246
+ shouldUseLLM() {
247
+ return !!this.llmConfig && this.llmConfig.mode !== 'disabled';
248
+ }
249
+ /**
250
+ * Constructs an LLM executor for this template.
251
+ * @returns {LLMExecutor} the LLM executor
252
+ * @throws {Error} if no LLM config is present
253
+ */
254
+ makeLLMExecutor() {
255
+ if (!this.llmConfig) {
256
+ throw new Error('LLM fallback requested but llmConfig is missing');
257
+ }
258
+ if (!this.llmExecutor) {
259
+ this.llmExecutor = new LLMExecutor_1.LLMExecutor(this.template, this.llmConfig);
260
+ }
261
+ return this.llmExecutor;
262
+ }
263
+ /**
264
+ * Executes the template's compiled TypeScript trigger logic.
265
+ * @param {any} data - the data for the template
266
+ * @param {any} request - the request to send to the template logic
267
+ * @param {any} [priorState] - the state produced by init() (or a previous
268
+ * trigger()); required for stateful templates, ignored for stateless ones
269
+ * @param {string} [currentTime] - the current time, defaults to now
270
+ * @param {number} [utcOffset] - the UTC offset, defaults to zero
271
+ * @returns {Promise<TriggerResponse>} the response and any events
272
+ */
273
+ async executeTypeScriptTrigger(data, request, priorState, currentTime, utcOffset) {
274
+ const compiledCode = await this.compileLogic();
275
+ const resolvedTime = currentTime ?? new Date().toISOString();
276
+ const resolvedOffset = utcOffset ?? 0;
277
+ const evaluator = new JavaScriptEvaluator_1.JavaScriptEvaluator();
278
+ const evalResponse = await evaluator.evalDangerously({
279
+ templateLogic: true,
280
+ verbose: false,
281
+ functionName: 'trigger',
282
+ code: compiledCode['logic/logic.ts'].code, // TODO DCS - how to find the code to run?
283
+ argumentNames: ['data', 'request', 'state'],
284
+ arguments: [data, request, priorState, resolvedTime, resolvedOffset]
285
+ });
286
+ if (evalResponse.result) {
287
+ return evalResponse.result;
288
+ }
289
+ else {
290
+ throw new Error('Trigger failed with message: ' + evalResponse.message);
291
+ }
292
+ }
293
+ /**
294
+ * Executes the template's compiled TypeScript init logic. Returns an empty
295
+ * state when the compiled logic defines no `init` method (stateless template).
296
+ * @param {any} data - the data for the template
297
+ * @param {string} [currentTime] - the current time, defaults to now
298
+ * @param {number} [utcOffset] - the UTC offset, defaults to zero
299
+ * @returns {Promise<InitResponse>} the new state
300
+ */
301
+ async executeTypeScriptInit(data, currentTime, utcOffset) {
302
+ const compiledCode = await this.compileLogic();
303
+ const logicCode = compiledCode['logic/logic.ts']?.code;
304
+ // Check if the compiled code even contains an `init` method before calling it
305
+ if (!logicCode || (!logicCode.includes('init(') && !logicCode.includes('init ('))) {
306
+ // Stateless template — no init method defined, return empty state
307
+ return { state: {} };
308
+ }
309
+ const resolvedTime = currentTime ?? new Date().toISOString();
310
+ const resolvedOffset = utcOffset ?? 0;
311
+ const evaluator = new JavaScriptEvaluator_1.JavaScriptEvaluator();
312
+ const evalResponse = await evaluator.evalDangerously({
313
+ templateLogic: true,
314
+ verbose: false,
315
+ functionName: 'init',
316
+ code: logicCode, // TODO DCS - how to find the code to run?
317
+ argumentNames: ['data'],
318
+ arguments: [data, resolvedTime, resolvedOffset]
319
+ });
320
+ if (evalResponse.result) {
321
+ return evalResponse.result;
322
+ }
323
+ else {
324
+ throw new Error('Init failed with message: ' + evalResponse.message);
325
+ }
326
+ }
327
+ /**
328
+ * Trigger the logic of a template.
329
+ *
330
+ * Stateful templates (`this.template.isStateful()`) carry state across
331
+ * executions, so they must always be seeded with `priorState` — the state
332
+ * returned by a prior call to {@link init} (or by a prior call to
333
+ * `trigger`) — before a request can be evaluated. There is no implicit
334
+ * "empty" state for a template that declares custom State fields; calling
335
+ * `trigger` without `priorState` for such a template throws. Stateless
336
+ * templates ignore `priorState` entirely.
337
+ * @param {object} data - the data for the template
338
+ * @param {object} request - the request to send to the template logic
339
+ * @param {object} priorState - the state to evaluate the request against.
340
+ * For stateful templates this is required and must be the state produced
341
+ * by init() or a previous trigger(); for stateless templates it is ignored.
342
+ * @param {[string]} currentTime - the current time, defaults to now
343
+ * @param {[number]} utcOffset - the UTC offset, defaults to zero
344
+ * @param {boolean} [enableCompiledLogicCache] - whether to use the compiled logic cache
345
+ * @returns {Promise<TriggerResponse>} the response and any events
346
+ * @throws {Error} if the template is stateful and no priorState is supplied, or if an
347
+ * emitted event extends `org.accordproject.runtime.Obligation` and its `contract`
348
+ * back-reference can't be auto-populated (see {@link populateObligationBackReferences})
349
+ */
350
+ async trigger(data, request, priorState, currentTime, utcOffset, enableCompiledLogicCache) {
351
+ const factory = new concerto_core_1.Factory(this.template.getModelManager());
352
+ const serializer = new concerto_core_1.Serializer(factory, this.template.getModelManager(), { validate: true });
353
+ // Stateful templates must always be triggered against the state produced by
354
+ // init() (or a previous trigger()) — there is no implicit "empty" state for
355
+ // a template that declares custom State fields. Stateless templates have no
356
+ // persistent state, so priorState is not required for them.
357
+ if (this.template.isStateful() && (!priorState || Object.keys(priorState).length === 0)) {
358
+ throw new Error('Stateful templates require priorState: call init() first and pass its ' +
359
+ 'returned state (or the state returned by a previous trigger()) as priorState.');
360
+ }
361
+ // validate inputs before execution. A stateless template's init returns an empty
362
+ // placeholder state ({}); skip only that. Any other state - including a non-empty
363
+ // object with no $class - is validated normally (and fails if malformed).
364
+ if (data)
365
+ serializer.fromJSON(data);
366
+ if (request)
367
+ serializer.fromJSON(request);
368
+ if (priorState && Object.keys(priorState).length > 0)
369
+ serializer.fromJSON(priorState);
370
+ // enforce the runtime class hierarchy on the inputs
371
+ this.assertRuntimeHierarchy(request, utils_1.RUNTIME_REQUEST_FQN, 'request');
372
+ this.assertRuntimeHierarchy(priorState, utils_1.RUNTIME_STATE_FQN, 'state');
373
+ let triggerResponse;
374
+ const forceLLM = this.llmConfig?.mode === 'force';
375
+ // Run the template's TypeScript logic unless the caller forces the LLM path.
376
+ if (!forceLLM && this.template.hasLogic()) {
377
+ if (enableCompiledLogicCache) {
378
+ await this.compileLogic(true);
379
+ }
380
+ triggerResponse = await this.executeTypeScriptTrigger(data, request, priorState, currentTime, utcOffset);
381
+ }
382
+ else if (forceLLM || this.shouldUseLLM()) {
383
+ // Otherwise use the LLM executor
384
+ triggerResponse = await this.makeLLMExecutor().trigger(data, request, priorState, currentTime, utcOffset);
385
+ }
386
+ else {
387
+ throw new Error('No executable logic found and LLM fallback is disabled');
388
+ }
389
+ // validate outputs after execution (skip only the empty {} placeholder state)
390
+ if (triggerResponse.state && Object.keys(triggerResponse.state).length > 0)
391
+ serializer.fromJSON(triggerResponse.state);
392
+ if (triggerResponse.result)
393
+ serializer.fromJSON(triggerResponse.result);
394
+ if (triggerResponse.events && Array.isArray(triggerResponse.events)) {
395
+ this.populateObligationBackReferences(triggerResponse.events, data);
396
+ triggerResponse.events.forEach(e => serializer.fromJSON(e));
397
+ }
398
+ // enforce the runtime class hierarchy on the outputs
399
+ this.assertRuntimeHierarchy(triggerResponse.state, utils_1.RUNTIME_STATE_FQN, 'state');
400
+ this.assertRuntimeHierarchy(triggerResponse.result, utils_1.RUNTIME_RESPONSE_FQN, 'response');
401
+ if (triggerResponse.events && Array.isArray(triggerResponse.events)) {
402
+ triggerResponse.events.forEach(e => this.assertRuntimeHierarchy(e, utils_1.BASE_EVENT_FQN, 'event'));
403
+ }
404
+ return triggerResponse;
405
+ }
406
+ /**
407
+ * Init the logic of a template.
408
+ * @param {object} data - the data for the template
409
+ * @param {[string]} currentTime - the current time, defaults to now
410
+ * @param {[number]} utcOffset - the UTC offset, defaults to zero
411
+ * @param {boolean} [enableCompiledLogicCache] - whether to use the compiled logic cache
412
+ * @returns {Promise<InitResponse>} the new state
413
+ */
414
+ async init(data, currentTime, utcOffset, enableCompiledLogicCache) {
415
+ const factory = new concerto_core_1.Factory(this.template.getModelManager());
416
+ const serializer = new concerto_core_1.Serializer(factory, this.template.getModelManager(), { validate: true });
417
+ // validate inputs before execution
418
+ if (data)
419
+ serializer.fromJSON(data);
420
+ let initResponse;
421
+ const forceLLM = this.llmConfig?.mode === 'force';
422
+ // Run the template's TypeScript logic unless the caller forces the LLM path.
423
+ if (!forceLLM && this.template.hasLogic()) {
424
+ if (enableCompiledLogicCache) {
425
+ await this.compileLogic(true);
426
+ }
427
+ initResponse = await this.executeTypeScriptInit(data, currentTime, utcOffset);
428
+ }
429
+ else if (forceLLM || this.shouldUseLLM()) {
430
+ // Otherwise use the LLM executor
431
+ initResponse = await this.makeLLMExecutor().init(data, currentTime, utcOffset);
432
+ }
433
+ else {
434
+ throw new Error('No executable logic found and LLM fallback is disabled');
435
+ }
436
+ // validate outputs after execution. A stateless template returns an empty
437
+ // placeholder state ({}); skip only that - any other state is validated normally.
438
+ if (initResponse.state && Object.keys(initResponse.state).length > 0)
439
+ serializer.fromJSON(initResponse.state);
440
+ // enforce the runtime class hierarchy on the output state (skipped for the empty
441
+ // state of a stateless template, which has no $class)
442
+ this.assertRuntimeHierarchy(initResponse.state, utils_1.RUNTIME_STATE_FQN, 'state');
443
+ return initResponse;
444
+ }
445
+ }
446
+ exports.TemplateArchiveProcessor = TemplateArchiveProcessor;
447
+ //# sourceMappingURL=TemplateArchiveProcessor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TemplateArchiveProcessor.js","sourceRoot":"","sources":["../src/TemplateArchiveProcessor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;GAYG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKH,gEAAmE;AACnE,uEAAoE;AACpE,wEAA2E;AAC3E,0EAA8D;AAC9D,qFAAkF;AAIlF,+DAA4D;AAC5D,mDAAgD;AAEhD,mCAQiB;AAqBjB;;;GAGG;AACH,MAAa,wBAAwB;IAajC;;;;OAIG;IACH,YAAY,QAAkB,EAAE,SAA6B;QACzD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC/B,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,GAAG,IAAI,CAAC,QAAQ,CAAC,eAAe,EAAE,CAAC;QACrD,MAAM,MAAM,GAAG,IAAI,iDAAuB,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC;QAC7D,MAAM,uBAAuB,GAAG,IAAI,2CAAuB,EAAE,CAAC;QAC9D,MAAM,eAAe,GAAG,uBAAuB,CAAC,oBAAoB,CAChE,EAAE,OAAO,EA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AE,CAAC,IAAI,CAAC,IAAI,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC;QACnF,CAAC;aAAM,CAAC;YACJ,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;QAC9E,CAAC;QAED,0EAA0E;QAC1E,kFAAkF;QAClF,IAAI,YAAY,CAAC,KAAK,IAAI,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC;YAAE,UAAU,CAAC,QAAQ,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;QAE9G,iFAAiF;QACjF,sDAAsD;QACtD,IAAI,CAAC,sBAAsB,CAAC,YAAY,CAAC,KAAK,EAAE,yBAAiB,EAAE,OAAO,CAAC,CAAC;QAE5E,OAAO,YAAY,CAAC;IACxB,CAAC;CACJ;AAtbD,4DAsbC"}
@@ -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
+ }