@memberjunction/templates 1.5.2 → 1.5.3

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 ADDED
@@ -0,0 +1,3 @@
1
+ # @memberjunction/templates
2
+
3
+ The `@memberjunction/templates` library provides types and functionality for managing and executing templates.
@@ -0,0 +1,67 @@
1
+ import { BaseEngine, UserInfo } from "@memberjunction/core";
2
+ import { TemplateCategoryEntity, TemplateContentEntity, TemplateContentTypeEntity, TemplateParamEntity } from "@memberjunction/core-entities";
3
+ import * as nunjucks from 'nunjucks';
4
+ import { TemplateEntityExtended, TemplateRenderResult } from '@memberjunction/templates-base-types';
5
+ /**
6
+ * This class extends the nunjucks loader to allow adding templates directly to the loader
7
+ */
8
+ export declare class TemplateEntityLoader extends nunjucks.Loader {
9
+ async: true;
10
+ private templates;
11
+ /**
12
+ * Add a new template to the loader
13
+ * @param templateId
14
+ * @param template
15
+ */
16
+ AddTemplate(templateId: number, template: TemplateEntityExtended): void;
17
+ /**
18
+ * This method is required to be implemented by a subclass of Loader. It is used to get the source of a template by name.
19
+ * @param name - this is actually the templateId but nunjucks calls it name and makes it a string, we handle it as a number internally
20
+ * @returns
21
+ */
22
+ getSource(name: string, callBack: any): void;
23
+ }
24
+ /**
25
+ * TemplateEngine is used for accessing template metadata/caching it, and rendering templates
26
+ */
27
+ export declare class TemplateEngine extends BaseEngine<TemplateEngine> {
28
+ /**
29
+ * Returns the global instance of the class. This is a singleton class, so there is only one instance of it in the application. Do not directly create new instances of it, always use this method to get the instance.
30
+ */
31
+ static get Instance(): TemplateEngine;
32
+ Config(forceRefresh?: boolean, contextUser?: UserInfo): Promise<void>;
33
+ protected AdditionalLoading(contextUser?: UserInfo): Promise<void>;
34
+ private _nunjucksEnv;
35
+ private _templateLoader;
36
+ private _Templates;
37
+ get Templates(): TemplateEntityExtended[];
38
+ private _TemplateContentTypes;
39
+ get TemplateContentTypes(): TemplateContentTypeEntity[];
40
+ private _TemplateCategories;
41
+ get TemplateCategories(): TemplateCategoryEntity[];
42
+ private _TemplateContents;
43
+ get TemplateContents(): TemplateContentEntity[];
44
+ private _TemplateParams;
45
+ get TemplateParams(): TemplateParamEntity[];
46
+ AddTemplate(templateEntity: TemplateEntityExtended): void;
47
+ /**
48
+ * Convenience method to find a template by name, case-insensitive
49
+ * @param templateName
50
+ * @returns
51
+ */
52
+ FindTemplate(templateName: string): TemplateEntityExtended;
53
+ /**
54
+ * Renders a template with the given data.
55
+ * @param templateEntity the template object to render
56
+ * @param templateContent the template content item (within the template)
57
+ * @param data
58
+ */
59
+ RenderTemplate(templateEntity: TemplateEntityExtended, templateContent: TemplateContentEntity, data: any): Promise<TemplateRenderResult>;
60
+ /**
61
+ * Promisifies the Nunjucks template rendering process.
62
+ * @param template the Nunjucks template object
63
+ * @param data the data to render the template with
64
+ */
65
+ protected renderTemplateAsync(template: nunjucks.Template, data: any): Promise<string>;
66
+ }
67
+ //# sourceMappingURL=TemplateEngine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TemplateEngine.d.ts","sourceRoot":"","sources":["../src/TemplateEngine.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAA4B,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AACtF,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAC9I,OAAO,KAAK,QAAQ,MAAM,UAAU,CAAC;AAGrC,OAAO,EAAE,sBAAsB,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAA;AAEnG;;GAEG;AACH,qBAAa,oBAAqB,SAAQ,QAAQ,CAAC,MAAM;IAC9C,KAAK,EAAE,IAAI,CAAC;IAEnB,OAAO,CAAC,SAAS,CAAwD;IAEzE;;;;OAIG;IACI,WAAW,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,sBAAsB;IAIvE;;;;OAIG;IACI,SAAS,CAAC,IA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k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.TemplateEngine = exports.TemplateEntityLoader = void 0;
27
+ const core_1 = require("@memberjunction/core");
28
+ const nunjucks = __importStar(require("nunjucks"));
29
+ const global_1 = require("@memberjunction/global");
30
+ const TemplateExtensionBase_1 = require("./extensions/TemplateExtensionBase");
31
+ /**
32
+ * This class extends the nunjucks loader to allow adding templates directly to the loader
33
+ */
34
+ class TemplateEntityLoader extends nunjucks.Loader {
35
+ constructor() {
36
+ super(...arguments);
37
+ this.templates = {};
38
+ }
39
+ /**
40
+ * Add a new template to the loader
41
+ * @param templateId
42
+ * @param template
43
+ */
44
+ AddTemplate(templateId, template) {
45
+ this.templates[templateId] = template;
46
+ }
47
+ /**
48
+ * This method is required to be implemented by a subclass of Loader. It is used to get the source of a template by name.
49
+ * @param name - this is actually the templateId but nunjucks calls it name and makes it a string, we handle it as a number internally
50
+ * @returns
51
+ */
52
+ getSource(name, callBack) {
53
+ const templateId = Number(name);
54
+ const template = this.templates[templateId];
55
+ if (template) {
56
+ callBack({
57
+ src: template.Get,
58
+ path: templateId,
59
+ noCache: true
60
+ });
61
+ }
62
+ }
63
+ }
64
+ exports.TemplateEntityLoader = TemplateEntityLoader;
65
+ /**
66
+ * TemplateEngine is used for accessing template metadata/caching it, and rendering templates
67
+ */
68
+ class TemplateEngine extends core_1.BaseEngine {
69
+ /**
70
+ * Returns the global instance of the class. This is a singleton class, so there is only one instance of it in the application. Do not directly create new instances of it, always use this method to get the instance.
71
+ */
72
+ static get Instance() {
73
+ return super.getInstance();
74
+ }
75
+ async Config(forceRefresh, contextUser) {
76
+ const c = [
77
+ {
78
+ EntityName: 'Template Content Types',
79
+ PropertyName: '_TemplateContentTypes',
80
+ },
81
+ {
82
+ EntityName: 'Template Categories',
83
+ PropertyName: '_TemplateCategories'
84
+ },
85
+ {
86
+ EntityName: 'Templates',
87
+ PropertyName: '_Templates',
88
+ },
89
+ {
90
+ EntityName: 'Template Contents',
91
+ PropertyName: '_TemplateContents',
92
+ },
93
+ {
94
+ EntityName: 'Template Params',
95
+ PropertyName: '_TemplateParams',
96
+ },
97
+ ];
98
+ await this.Load(c, forceRefresh, contextUser);
99
+ }
100
+ async AdditionalLoading(contextUser) {
101
+ // post-process the template content and params to associate them with a template
102
+ this.Templates.forEach((t) => {
103
+ t.Content = this.TemplateContents.filter((tc) => tc.TemplateID === t.ID);
104
+ t.Params = this.TemplateParams.filter((tp) => tp.TemplateID === t.ID);
105
+ });
106
+ // do this after the templates are loaded and doing it inside AdditionalLoading() ensures it is done after the templates are loaded and
107
+ // only done once
108
+ this._templateLoader = new TemplateEntityLoader();
109
+ this._nunjucksEnv = new nunjucks.Environment(this._templateLoader, { autoescape: true, dev: true });
110
+ // get all of the extensions that are registered and register them with nunjucks
111
+ const extensions = global_1.MJGlobal.Instance.ClassFactory.GetAllRegistrations(TemplateExtensionBase_1.TemplateExtensionBase);
112
+ if (extensions && extensions.length > 0) {
113
+ for (const ext of extensions) {
114
+ const instance = new ext.SubClass(contextUser);
115
+ this._nunjucksEnv.addExtension(ext.Key, instance);
116
+ }
117
+ // const aiPromptExtension = new AIPromptExtension();
118
+ // aiPromptExtension._contextUser = contextUser;
119
+ // this._nunjucksEnv.addExtension('AIPrompt', aiPromptExtension);
120
+ }
121
+ }
122
+ get Templates() {
123
+ return this._Templates;
124
+ }
125
+ get TemplateContentTypes() {
126
+ return this._TemplateContentTypes;
127
+ }
128
+ get TemplateCategories() {
129
+ return this._TemplateCategories;
130
+ }
131
+ get TemplateContents() {
132
+ return this._TemplateContents;
133
+ }
134
+ get TemplateParams() {
135
+ return this._TemplateParams;
136
+ }
137
+ AddTemplate(templateEntity) {
138
+ this._templateLoader.AddTemplate(templateEntity.ID, templateEntity);
139
+ }
140
+ /**
141
+ * Convenience method to find a template by name, case-insensitive
142
+ * @param templateName
143
+ * @returns
144
+ */
145
+ FindTemplate(templateName) {
146
+ return this.Templates.find((t) => t.Name.trim().toLowerCase() === templateName.trim().toLowerCase());
147
+ }
148
+ /**
149
+ * Renders a template with the given data.
150
+ * @param templateEntity the template object to render
151
+ * @param templateContent the template content item (within the template)
152
+ * @param data
153
+ */
154
+ async RenderTemplate(templateEntity, templateContent, data) {
155
+ try {
156
+ if (!templateContent) {
157
+ return {
158
+ Success: false,
159
+ Output: null,
160
+ Message: 'templateContent variable is required'
161
+ };
162
+ }
163
+ const valResult = templateEntity.ValidateTemplateInput(data);
164
+ if (!valResult.Success) {
165
+ return {
166
+ Success: false,
167
+ Output: null,
168
+ Message: valResult.Errors.join(', ')
169
+ };
170
+ }
171
+ const template = new nunjucks.Template(templateContent.TemplateText, this._nunjucksEnv);
172
+ const result = await this.renderTemplateAsync(template, data);
173
+ return {
174
+ Success: true,
175
+ Output: result,
176
+ Message: undefined
177
+ };
178
+ }
179
+ catch (e) {
180
+ return {
181
+ Success: false,
182
+ Output: null,
183
+ Message: e.message
184
+ };
185
+ }
186
+ }
187
+ /**
188
+ * Promisifies the Nunjucks template rendering process.
189
+ * @param template the Nunjucks template object
190
+ * @param data the data to render the template with
191
+ */
192
+ async renderTemplateAsync(template, data) {
193
+ return new Promise((resolve, reject) => {
194
+ template.render(data, (err, result) => {
195
+ if (err) {
196
+ reject(err);
197
+ }
198
+ else {
199
+ resolve(result);
200
+ }
201
+ });
202
+ });
203
+ }
204
+ }
205
+ exports.TemplateEngine = TemplateEngine;
206
+ //# sourceMappingURL=TemplateEngine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TemplateEngine.js","sourceRoot":"","sources":["../src/TemplateEngine.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+CAAsF;AAEtF,mDAAqC;AACrC,mDAAkD;AAClD,8EAA2E;AAG3E;;GAEG;AACH,MAAa,oBAAqB,SAAQ,QAAQ,CAAC,MAAM;IAAzD;;QAGY,cAAS,GAAqD,EAAE,CAAC;IA2B7E,CAAC;IAzBG;;;;OAIG;IACI,WAAW,CAAC,UAAkB,EAAE,QAAgC;QACnE,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,GAAG,QAAQ,CAAC;IAC1C,CAAC;IAED;;;;OAIG;IACI,SAAS,CAAC,IAAY,EAAE,QAAa;QACxC,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;QAChC,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QAC5C,IAAI,QAAQ,EAAE,CAAC;YACX,QAAQ,CAAC;gBACL,GAAG,EAAE,QAAQ,CAAC,GAAG;gBACjB,IAAI,EAAE,UAAU;gBAChB,OAAO,EAAE,IAAI;aAChB,CAAC,CAAC;QACP,CAAC;IACL,CAAC;CACJ;AA9BD,oDA8BC;AAED;;GAEG;AACH,MAAa,cAAe,SAAQ,iBAA0B;IAC1D;;OAEG;IACI,MAAM,KAAK,QAAQ;QACvB,OAAO,KAAK,CAAC,WAAW,EAAkB,CAAC;IAC9C,CAAC;IAEM,KAAK,CAAC,MAAM,CAAC,YAAsB,EAAE,WAAsB;QAC9D,M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CAAC;CACJ;AAjKD,wCAiKC"}
@@ -0,0 +1,23 @@
1
+ import { UserInfo } from "@memberjunction/core";
2
+ import { NunjucksCallback, TemplateExtensionBase } from "./TemplateExtensionBase";
3
+ import { AIModelEntityExtended } from "@memberjunction/core-entities";
4
+ import { Parser, Nodes, Lexer, Context } from 'nunjucks';
5
+ /**
6
+ * This class is an extension for the Nunjucks template engine that allows for the use of an AI prompt in a template.
7
+ */
8
+ export declare class AIPromptExtension extends TemplateExtensionBase {
9
+ constructor(contextUser: UserInfo);
10
+ parse(parser: Parser, nodes: Nodes, lexer: Lexer): any;
11
+ run(context: Context, body: any, errorBody: any, params: any, callBack: NunjucksCallback, a: any, b: any, c: any): void;
12
+ /**
13
+ * Default implementation simply returns 'OpenAI' - override this in your subclass if you are using a different AI vendor.
14
+ * @returns
15
+ */
16
+ protected get DefaultAIVendorName(): string;
17
+ /**
18
+ * Default implementation simply grabs the first AI model that matches GetAIModelName().
19
+ * @returns
20
+ */
21
+ protected GetAIModel(vendorName: string, contextUser: UserInfo): Promise<AIModelEntityExtended>;
22
+ }
23
+ //# sourceMappingURL=AIPrompt.extension.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AIPrompt.extension.d.ts","sourceRoot":"","sources":["../../src/extensions/AIPrompt.extension.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAE1D,OAAO,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAGlF,OAAO,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AACtE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AAEzD;;GAEG;AACH,qBACa,iBAAkB,SAAQ,qBAAqB;gBAC5C,WAAW,EAAE,QAAQ;IAK1B,KAAK,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK;IAkChD,GAAG,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,KAAA,EAAE,QAAQ,EAAE,gBAAgB,EAAE,CAAC,KAAA,EAAE,CAAC,KAAA,EAAE,CAAC,KAAA;IAsCnG;;;OAGG;IACH,SAAS,KAAK,mBAAmB,IAAI,MAAM,CAE1C;IAED;;;OAGG;cACa,UAAU,CAAC,UAAU,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,GAAG,OAAO,CAAC,qBAAqB,CAAC;CAQxG"}
@@ -0,0 +1,195 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.AIPromptExtension = void 0;
13
+ const core_1 = require("@memberjunction/core");
14
+ const global_1 = require("@memberjunction/global");
15
+ const TemplateExtensionBase_1 = require("./TemplateExtensionBase");
16
+ const aiengine_1 = require("@memberjunction/aiengine");
17
+ const ai_1 = require("@memberjunction/ai");
18
+ /**
19
+ * This class is an extension for the Nunjucks template engine that allows for the use of an AI prompt in a template.
20
+ */
21
+ let AIPromptExtension = class AIPromptExtension extends TemplateExtensionBase_1.TemplateExtensionBase {
22
+ constructor(contextUser) {
23
+ super(contextUser);
24
+ this.tags = ['AIPrompt'];
25
+ }
26
+ parse(parser, nodes, lexer) {
27
+ // get the tag token
28
+ var tok = parser.nextToken();
29
+ // parse the args and move after the block end. passing true
30
+ // as the second arg is required if there are no parentheses
31
+ var params = parser.parseSignature(null, true);
32
+ parser.advanceAfterBlockEnd(tok.value);
33
+ // parse the body and possibly the error block, which is optional
34
+ var body = parser.parseUntilBlocks('error', 'endAIPrompt');
35
+ var errorBody = null;
36
+ if (parser.skipSymbol('error')) {
37
+ parser.skip(lexer.TOKEN_BLOCK_END);
38
+ errorBody = parser.parseUntilBlocks('endAIPrompt');
39
+ }
40
+ parser.advanceAfterBlockEnd();
41
+ // Parse the args and move after the block end.
42
+ // const args = parser.parseSignature(null, true);
43
+ // parser.advanceAfterBlockEnd(tok.value);
44
+ // // Parse the body
45
+ // const body = parser.parseUntilBlocks('endAIPrompt');
46
+ // parser.advanceAfterBlockEnd();
47
+ // const errorBody = '';
48
+ // See above for notes about CallExtension
49
+ return new nodes.CallExtensionAsync(this, 'run', params, [body, errorBody, params]);
50
+ }
51
+ run(context, body, errorBody, params, callBack, a, b, c) {
52
+ const prompt = body();
53
+ // we now have the LLM prompt in the prompt variable
54
+ // we can't use async/await here because this is a synchronous function
55
+ // so instead we will use the callback pattern
56
+ // we will get the highest power model from the AI Engine
57
+ // then we will create an instance of the LLM class
58
+ aiengine_1.AIEngine.Instance.Config(false, this.ContextUser).then(async () => {
59
+ try {
60
+ const model = await aiengine_1.AIEngine.Instance.GetHighestPowerModel('Groq', 'llm', this.ContextUser);
61
+ const llm = global_1.MJGlobal.Instance.ClassFactory.CreateInstance(ai_1.BaseLLM, model.DriverClass, (0, ai_1.GetAIAPIKey)(model.DriverClass));
62
+ const llmResult = await llm.ChatCompletion({
63
+ messages: [
64
+ {
65
+ role: 'system',
66
+ content: `Background: The output from this will be DIRECTLY inserted into a messaging template going to a recipient. For this reason whenever
67
+ you are prompted to provide a result, do not preface it with any text, just provide the result itself. Do not use
68
+ markdown, HTML, or any other special formatting. Assume that the text you are generating will go directly into a message.
69
+ <IMPORTANT>ONLY PROVIDE THE RESPONSE REQUESTED FOR THE MESSAGE - **** DO NOT ADD ANYTHING ELSE ****</IMPORTANT>`,
70
+ },
71
+ {
72
+ role: 'user',
73
+ content: `${prompt}`,
74
+ }
75
+ ],
76
+ model: model.APINameOrName
77
+ });
78
+ if (llmResult && llmResult.success) {
79
+ callBack(null, llmResult.data.choices[0].message.content);
80
+ }
81
+ }
82
+ catch (e) {
83
+ (0, core_1.LogError)(e);
84
+ }
85
+ });
86
+ }
87
+ /**
88
+ * Default implementation simply returns 'OpenAI' - override this in your subclass if you are using a different AI vendor.
89
+ * @returns
90
+ */
91
+ get DefaultAIVendorName() {
92
+ return 'OpenAI';
93
+ }
94
+ /**
95
+ * Default implementation simply grabs the first AI model that matches GetAIModelName().
96
+ * @returns
97
+ */
98
+ async GetAIModel(vendorName, contextUser) {
99
+ await aiengine_1.AIEngine.Instance.Config(false, contextUser); // most of the time this is already loaded, but just in case it isn't we will load it here
100
+ const models = aiengine_1.AIEngine.Models.filter(m => m.AIModelType.trim().toLowerCase() === 'llm' &&
101
+ m.Vendor.trim().toLowerCase() === vendorName.trim().toLowerCase());
102
+ // next, sort the models by the PowerRank field so that the highest power rank model is the first array element
103
+ models.sort((a, b) => b.PowerRank - a.PowerRank); // highest power rank first
104
+ return models[0];
105
+ }
106
+ };
107
+ exports.AIPromptExtension = AIPromptExtension;
108
+ exports.AIPromptExtension = AIPromptExtension = __decorate([
109
+ (0, global_1.RegisterClass)(TemplateExtensionBase_1.TemplateExtensionBase, 'AIPrompt'),
110
+ __metadata("design:paramtypes", [core_1.UserInfo])
111
+ ], AIPromptExtension);
112
+ // function AIPromptExtension() {
113
+ // this.tags = ['AIPrompt'];
114
+ // this.parse = function(parser, nodes, lexer) {
115
+ // // get the tag token
116
+ // var tok = parser.nextToken();
117
+ // // parse the args and move after the block end. passing true
118
+ // // as the second arg is required if there are no parentheses
119
+ // var args = parser.parseSignature(null, true);
120
+ // parser.advanceAfterBlockEnd(tok.value);
121
+ // // parse the body and possibly the error block, which is optional
122
+ // var body = parser.parseUntilBlocks('error', 'endAIPrompt');
123
+ // var errorBody = null;
124
+ // if(parser.skipSymbol('error')) {
125
+ // parser.skip(lexer.TOKEN_BLOCK_END);
126
+ // errorBody = parser.parseUntilBlocks('endAIPrompt');
127
+ // }
128
+ // parser.advanceAfterBlockEnd();
129
+ // // Parse the args and move after the block end.
130
+ // // const args = parser.parseSignature(null, true);
131
+ // // parser.advanceAfterBlockEnd(tok.value);
132
+ // // // Parse the body
133
+ // // const body = parser.parseUntilBlocks('endAIPrompt');
134
+ // // parser.advanceAfterBlockEnd();
135
+ // // const errorBody = '';
136
+ // // See above for notes about CallExtension
137
+ // return new nodes.CallExtensionAsync(this, 'run', args, [body, errorBody]);
138
+ // };
139
+ // this.run = function(context, body, errorBody, callBack) {
140
+ // const prompt = body();
141
+ // // we now have the LLM prompt in the prompt variable
142
+ // // we can't use async/await here because this is a synchronous function
143
+ // // so instead we will use the callback pattern
144
+ // // we will get the highest power model from the AI Engine
145
+ // // then we will create an instance of the LLM class
146
+ // AIEngine.Instance.LoadAIMetadata(this._contextUser).then(async () => {
147
+ // try {
148
+ // const model = await AIEngine.Instance.GetHighestPowerModel('Groq','llm', this._contextUser)
149
+ // const llm = MJGlobal.Instance.ClassFactory.CreateInstance<BaseLLM>(BaseLLM, model.DriverClass, GetAIAPIKey(model.DriverClass))
150
+ // const llmResult = await llm.ChatCompletion({
151
+ // messages: [
152
+ // {
153
+ // role: 'system',
154
+ // content: `Background: The output from this will be DIRECTLY inserted into a messaging template going to a recipient. For this reason whenever
155
+ // you are prompted to provide a result, do not preface it with any text, just provide the result itself. Do not use
156
+ // markdown, HTML, or any other special formatting. Assume that the text you are generating will go directly into a message.
157
+ // <IMPORTANT>ONLY PROVIDE THE RESPONSE REQUESTED FOR THE MESSAGE - **** DO NOT ADD ANYTHING ELSE ****</IMPORTANT>`,
158
+ // },
159
+ // {
160
+ // role: 'user',
161
+ // content: `${prompt}`,
162
+ // }
163
+ // ],
164
+ // model: model.APINameOrName
165
+ // })
166
+ // if (llmResult && llmResult.success) {
167
+ // callBack(null, llmResult.data.choices[0].message.content);
168
+ // }
169
+ // }
170
+ // catch (e) {
171
+ // LogError(e);
172
+ // }
173
+ // });
174
+ // };
175
+ // }
176
+ // /**
177
+ // * Default implementation simply returns 'OpenAI' - override this in your subclass if you are using a different AI vendor.
178
+ // * @returns
179
+ // */
180
+ // function AIVendorName(): string {
181
+ // return 'OpenAI';
182
+ // }
183
+ // /**
184
+ // * Default implementation simply grabs the first AI model that matches GetAIModelName().
185
+ // * @returns
186
+ // */
187
+ // async function GetAIModel(vendorName: string, contextUser: UserInfo): Promise<AIModelEntityExtended> {
188
+ // await AIEngine.LoadAIMetadata(contextUser); // most of the time this is already loaded, but just in case it isn't we will load it here
189
+ // const models = AIEngine.Models.filter(m => m.AIModelType.trim().toLowerCase() === 'llm' &&
190
+ // m.Vendor.trim().toLowerCase() === vendorName.trim().toLowerCase())
191
+ // // next, sort the models by the PowerRank field so that the highest power rank model is the first array element
192
+ // models.sort((a, b) => b.PowerRank - a.PowerRank); // highest power rank first
193
+ // return models[0];
194
+ // }
195
+ //# sourceMappingURL=AIPrompt.extension.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AIPrompt.extension.js","sourceRoot":"","sources":["../../src/extensions/AIPrompt.extension.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,+CAA0D;AAC1D,mDAAiE;AACjE,mEAAkF;AAClF,uDAAoD;AACpD,2CAA0D;AAI1D;;GAEG;AAEI,IAAM,iBAAiB,GAAvB,MAAM,iBAAkB,SAAQ,6CAAqB;IACxD,YAAY,WAAqB;QAC7B,KAAK,CAAC,WAAW,CAAC,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,CAAC,UAAU,CAAC,CAAC;IAC7B,CAAC;IAEM,KAAK,CAAC,MAAc,EAAE,KAAY,EAAE,KAAY;QACnD,oBAAoB;QACpB,IAAI,GAAG,GAAG,MA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;AACpD,4BAA4B;AAC5B,yBAAyB;AACzB,iDAAiD;AACjD,qBAAqB;AACrB,wDAAwD;AACxD,iFAAiF;AACjF,oBAAoB;AACpB,gBAAgB;AAChB,0BAA0B;AAC1B,+BAA+B;AAC/B,gBAAgB;AAChB,cAAc;AACd,SAAS;AACT,IAAI;AAIJ,MAAM;AACN,6HAA6H;AAC7H,eAAe;AACf,MAAM;AACN,oCAAoC;AACpC,uBAAuB;AACvB,IAAI;AAEJ,MAAM;AACN,2FAA2F;AAC3F,eAAe;AACf,MAAM;AACN,yGAAyG;AACzG,6IAA6I;AAC7I,kGAAkG;AAClG,uHAAuH;AACvH,sHAAsH;AACtH,oFAAoF;AACpF,wBAAwB;AACxB,IAAI"}
@@ -0,0 +1,27 @@
1
+ import { UserInfo } from "@memberjunction/core";
2
+ import { Parser, Nodes, Lexer, Context } from 'nunjucks';
3
+ export type NunjucksCallback = (err: Error | null, result?: any) => void;
4
+ /**
5
+ * Used for extending the functionality of the template engine (Nunjucks). Sub-class this class to create a new template extension.
6
+ */
7
+ export declare abstract class TemplateExtensionBase {
8
+ /**
9
+ * One or more tags that represent case-sensitive tag names that will invoke this extension.
10
+ */
11
+ tags: string[];
12
+ get ContextUser(): UserInfo;
13
+ private _contextUser;
14
+ constructor(contextUser: UserInfo);
15
+ /**
16
+ * Required, must implement this method to parse the template and return the results of a call to nodes.CallExtensionAsync()
17
+ * @param parser
18
+ * @param nodes
19
+ * @param lexer
20
+ */
21
+ abstract parse(parser: Parser, nodes: Nodes, lexer: Lexer): any;
22
+ /**
23
+ * Required, must implement this method to run the extension.
24
+ */
25
+ abstract run(context: Context, body: any, errorBody: any, params: any, callBack: NunjucksCallback, a: any, b: any, c: any): any;
26
+ }
27
+ //# sourceMappingURL=TemplateExtensionBase.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TemplateExtensionBase.d.ts","sourceRoot":"","sources":["../../src/extensions/TemplateExtensionBase.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AAGzD,MAAM,MAAM,gBAAgB,GAAG,CAAC,GAAG,EAAE,KAAK,GAAG,IAAI,EAAE,MAAM,CAAC,EAAE,GAAG,KAAK,IAAI,CAAC;AAEzE;;GAEG;AACH,8BAAsB,qBAAqB;IACvC;;OAEG;IACI,IAAI,EAAE,MAAM,EAAE,CAAM;IAE3B,IAAW,WAAW,IAAI,QAAQ,CAEjC;IACD,OAAO,CAAC,YAAY,CAAW;gBAEnB,WAAW,EAAE,QAAQ;IAIjC;;;;;OAKG;aACa,KAAK,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,GAAG,GAAG;IACtE;;OAEG;aACa,GAAG,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,KAAA,EAAE,QAAQ,EAAE,gBAAgB,EAAE,CAAC,KAAA,EAAE,CAAC,KAAA,EAAE,CAAC,KAAA;CAC/G"}
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TemplateExtensionBase = void 0;
4
+ /**
5
+ * Used for extending the functionality of the template engine (Nunjucks). Sub-class this class to create a new template extension.
6
+ */
7
+ class TemplateExtensionBase {
8
+ get ContextUser() {
9
+ return this._contextUser;
10
+ }
11
+ constructor(contextUser) {
12
+ /**
13
+ * One or more tags that represent case-sensitive tag names that will invoke this extension.
14
+ */
15
+ this.tags = [];
16
+ this._contextUser = contextUser;
17
+ }
18
+ }
19
+ exports.TemplateExtensionBase = TemplateExtensionBase;
20
+ //# sourceMappingURL=TemplateExtensionBase.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TemplateExtensionBase.js","sourceRoot":"","sources":["../../src/extensions/TemplateExtensionBase.ts"],"names":[],"mappings":";;;AAMA;;GAEG;AACH,MAAsB,qBAAqB;IAMvC,IAAW,WAAW;QAClB,OAAO,IAAI,CAAC,YAAY,CAAC;IAC7B,CAAC;IAGD,YAAY,WAAqB;QAVjC;;WAEG;QACI,SAAI,GAAa,EAAE,CAAC;QAQvB,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC;IACpC,CAAC;CAaJ;AA1BD,sDA0BC"}
package/dist/index.d.ts CHANGED
@@ -1,2 +1,4 @@
1
- export { TemplateEngineService } from './template-engine';
1
+ export * from './TemplateEngine';
2
+ export * from './extensions/AIPrompt.extension';
3
+ export * from './extensions/TemplateExtensionBase';
2
4
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,kBAAkB,CAAC;AACjC,cAAc,iCAAiC,CAAC;AAChD,cAAc,oCAAoC,CAAC"}
package/dist/index.js CHANGED
@@ -1,2 +1,22 @@
1
- export { TemplateEngineService } from './template-engine';
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ const ai_groq_1 = require("@memberjunction/ai-groq");
18
+ (0, ai_groq_1.LoadGroqLLM)(); // make sure it doesnt get tree shaken out, we need Groq
19
+ __exportStar(require("./TemplateEngine"), exports);
20
+ __exportStar(require("./extensions/AIPrompt.extension"), exports);
21
+ __exportStar(require("./extensions/TemplateExtensionBase"), exports);
2
22
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,qDAAsD;AACtD,IAAA,qBAAW,GAAE,CAAC,CAAC,wDAAwD;AAGvE,mDAAiC;AACjC,kEAAgD;AAChD,qEAAmD"}
package/package.json CHANGED
@@ -1,10 +1,9 @@
1
1
  {
2
2
  "name": "@memberjunction/templates",
3
- "version": "1.5.2",
3
+ "version": "1.5.3",
4
4
  "description": "MemberJunction Templating Engine and Utilities - Used for any application that requires templating utility functionality. NOTE: this package does use Angular Universal for compilation but is not marked with the usual ng prefix because it is a server-side library and not used within Angular apps.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
- "type": "module",
8
7
  "files": [
9
8
  "/dist"
10
9
  ],
@@ -13,23 +12,19 @@
13
12
  "build": "tsc",
14
13
  "test": "echo \"Error: no test specified\" && exit 1"
15
14
  },
16
- "keywords": [],
17
- "author": "",
15
+ "author": "MemberJunction.com",
18
16
  "license": "ISC",
19
17
  "devDependencies": {
20
- "ts-node-dev": "^2.0.0",
21
- "typescript": "^5.3.3",
22
- "@types/node": "^20.1.7"
18
+ "typescript": "^5.4.5"
23
19
  },
24
20
  "dependencies": {
25
- "@memberjunction/core": "~1.5.2",
26
- "@memberjunction/core-entities": "~1.5.2",
27
- "@memberjunction/global": "~1.5.2",
28
- "@memberjunction/data-context": "~1.5.2",
29
- "@angular/core": "~17.2.2",
30
- "@angular/common": "~17.2.2",
31
- "@angular/compiler": "~17.2.2",
32
- "@angular/platform-server": "~17.2.2",
33
- "@angular/platform-browser-dynamic": "~17.2.2"
21
+ "@memberjunction/core": "1.5.3",
22
+ "@memberjunction/templates-base-types": "1.5.3",
23
+ "@memberjunction/ai": "1.5.3",
24
+ "@memberjunction/aiengine": "1.5.3",
25
+ "@memberjunction/ai-groq": "1.5.3",
26
+ "@memberjunction/core-entities": "1.5.3",
27
+ "@memberjunction/global": "1.5.3",
28
+ "nunjucks": "3.2.4"
34
29
  }
35
30
  }
@@ -1,6 +0,0 @@
1
- export declare class TemplateEngineService {
2
- private platformId;
3
- constructor();
4
- render(templateHtml: string, context?: any): Promise<string>;
5
- }
6
- //# sourceMappingURL=template-engine.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"template-engine.d.ts","sourceRoot":"","sources":["../src/template-engine.ts"],"names":[],"mappings":"AAoCA,qBACa,qBAAqB;IAC9B,OAAO,CAAC,UAAU,CAAS;;IAKvB,MAAM,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,GAAE,GAAQ,GAAG,OAAO,CAAC,MAAM,CAAC;CAevE"}
@@ -1,166 +0,0 @@
1
- var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
2
- function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
3
- var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
4
- var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
5
- var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
6
- var _, done = false;
7
- for (var i = decorators.length - 1; i >= 0; i--) {
8
- var context = {};
9
- for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
10
- for (var p in contextIn.access) context.access[p] = contextIn.access[p];
11
- context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
12
- var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
13
- if (kind === "accessor") {
14
- if (result === void 0) continue;
15
- if (result === null || typeof result !== "object") throw new TypeError("Object expected");
16
- if (_ = accept(result.get)) descriptor.get = _;
17
- if (_ = accept(result.set)) descriptor.set = _;
18
- if (_ = accept(result.init)) initializers.unshift(_);
19
- }
20
- else if (_ = accept(result)) {
21
- if (kind === "field") initializers.unshift(_);
22
- else descriptor[key] = _;
23
- }
24
- }
25
- if (target) Object.defineProperty(target, contextIn.name, descriptor);
26
- done = true;
27
- };
28
- var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
29
- var useValue = arguments.length > 2;
30
- for (var i = 0; i < initializers.length; i++) {
31
- value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
32
- }
33
- return useValue ? value : void 0;
34
- };
35
- var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) {
36
- if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
37
- return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
38
- };
39
- import { Injectable, NgModule, Component } from '@angular/core';
40
- import { isPlatformServer } from '@angular/common';
41
- import { renderModule } from '@angular/platform-server';
42
- import { ServerModule } from '@angular/platform-server';
43
- let TemplateRootComponent = (() => {
44
- let _classDecorators = [Component({
45
- selector: 'app-template-root',
46
- template: 'hola' // This will be dynamically populated
47
- })];
48
- let _classDescriptor;
49
- let _classExtraInitializers = [];
50
- let _classThis;
51
- var TemplateRootComponent = _classThis = class {
52
- constructor() {
53
- this.context = {}; // Data passed to the template
54
- }
55
- };
56
- __setFunctionName(_classThis, "TemplateRootComponent");
57
- (() => {
58
- const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
59
- __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
60
- TemplateRootComponent = _classThis = _classDescriptor.value;
61
- if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
62
- __runInitializers(_classThis, _classExtraInitializers);
63
- })();
64
- return TemplateRootComponent = _classThis;
65
- })();
66
- let TemplateRenderModule = (() => {
67
- let _classDecorators = [NgModule({
68
- imports: [ServerModule],
69
- declarations: [TemplateRootComponent],
70
- bootstrap: [TemplateRootComponent],
71
- })];
72
- let _classDescriptor;
73
- let _classExtraInitializers = [];
74
- let _classThis;
75
- var TemplateRenderModule = _classThis = class {
76
- };
77
- __setFunctionName(_classThis, "TemplateRenderModule");
78
- (() => {
79
- const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
80
- __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
81
- TemplateRenderModule = _classThis = _classDescriptor.value;
82
- if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
83
- __runInitializers(_classThis, _classExtraInitializers);
84
- })();
85
- return TemplateRenderModule = _classThis;
86
- })();
87
- // Dynamically create a component with the provided template
88
- let DynamicTemplateComponent = (() => {
89
- let _classDecorators = [Component({
90
- selector: 'app-dynamic-template',
91
- template: ''
92
- })];
93
- let _classDescriptor;
94
- let _classExtraInitializers = [];
95
- let _classThis;
96
- var DynamicTemplateComponent = _classThis = class {
97
- constructor() {
98
- this.context = {};
99
- }
100
- };
101
- __setFunctionName(_classThis, "DynamicTemplateComponent");
102
- (() => {
103
- const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
104
- __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
105
- DynamicTemplateComponent = _classThis = _classDescriptor.value;
106
- if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
107
- __runInitializers(_classThis, _classExtraInitializers);
108
- })();
109
- return DynamicTemplateComponent = _classThis;
110
- })();
111
- // Dynamically create a module to house the component
112
- let DynamicTemplateModule = (() => {
113
- let _classDecorators = [NgModule({
114
- imports: [TemplateRenderModule],
115
- declarations: [DynamicTemplateComponent]
116
- })];
117
- let _classDescriptor;
118
- let _classExtraInitializers = [];
119
- let _classThis;
120
- var DynamicTemplateModule = _classThis = class {
121
- };
122
- __setFunctionName(_classThis, "DynamicTemplateModule");
123
- (() => {
124
- const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
125
- __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
126
- DynamicTemplateModule = _classThis = _classDescriptor.value;
127
- if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
128
- __runInitializers(_classThis, _classExtraInitializers);
129
- })();
130
- return DynamicTemplateModule = _classThis;
131
- })();
132
- let TemplateEngineService = (() => {
133
- let _classDecorators = [Injectable({ providedIn: 'root' })];
134
- let _classDescriptor;
135
- let _classExtraInitializers = [];
136
- let _classThis;
137
- var TemplateEngineService = _classThis = class {
138
- constructor() {
139
- this.platformId = 'server'; // Directly set the platform ID
140
- }
141
- async render(templateHtml, context = {}) {
142
- if (!isPlatformServer(this.platformId)) {
143
- throw new Error('Template rendering must be done on the server.');
144
- }
145
- // Use Angular Universal's renderModule
146
- const html = await renderModule(DynamicTemplateModule, {
147
- document: `<app-template-root></app-template-root>`,
148
- extraProviders: [
149
- { provide: TemplateRootComponent, useValue: { context } }
150
- ]
151
- });
152
- return html;
153
- }
154
- };
155
- __setFunctionName(_classThis, "TemplateEngineService");
156
- (() => {
157
- const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
158
- __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
159
- TemplateEngineService = _classThis = _classDescriptor.value;
160
- if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
161
- __runInitializers(_classThis, _classExtraInitializers);
162
- })();
163
- return TemplateEngineService = _classThis;
164
- })();
165
- export { TemplateEngineService };
166
- //# sourceMappingURL=template-engine.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"template-engine.js","sourceRoot":"","sources":["../src/template-engine.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAChE,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;IAMlD,qBAAqB;4BAJ1B,SAAS,CAAC;YACT,QAAQ,EAAE,mBAAmB;YAC7B,QAAQ,EAAE,MAAM,CAAC,qCAAqC;SACvD,CAAC;;;;;;YAEA,YAAO,GAAQ,EAAE,CAAC,CAAC,8BAA8B;QACnD,CAAC;;;;;QAFD,6KAEC;;;QAFK,uDAAqB;;;;IASrB,oBAAoB;4BALzB,QAAQ,CAAC;YACR,OAAO,EAAE,CAAC,YAAY,CAAC;YACvB,YAAY,EAAE,CAAC,qBAAqB,CAAC;YACrC,SAAS,EAAE,CAAC,qBAAqB,CAAC;SACnC,CAAC;;;;;;;;;QACF,6KAA6B;;;QAAvB,uDAAoB;;;;AAE1B,4DAA4D;IAKtD,wBAAwB;4BAJ7B,SAAS,CAAC;YACP,QAAQ,EAAE,sBAAsB;YAChC,QAAQ,EAAE,EAAE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