-
Notifications
You must be signed in to change notification settings - Fork 4
/
TemplateProcessor.ts
1976 lines (1778 loc) · 87.8 KB
/
TemplateProcessor.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2023 Cisco Systems, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {default as jp} from './JsonPointer.js';
import isEqual from "lodash-es/isEqual.js";
import merge from 'lodash-es/merge.js';
import yaml from 'js-yaml';
import MetaInfoProducer, {JsonPointerString, JsonPointerStructureArray, MetaInfo} from './MetaInfoProducer.js';
import DependencyFinder from './DependencyFinder.js';
import path from 'path';
import fs from 'fs';
import ConsoleLogger, {Levels, LOG_LEVELS, StatedLogger} from "./ConsoleLogger.js";
import FancyLogger from "./FancyLogger.js";
import {TimerManager} from "./TimerManager.js";
import {stringifyTemplateJSON} from './utils/stringify.js';
import {debounce} from "./utils/debounce.js"
import {rateLimit} from "./utils/rateLimit.js"
import {ExecutionStatus} from "./ExecutionStatus.js";
import {Sleep} from "./utils/Sleep.js";
import {saferFetch} from "./utils/FetchWrapper.js";
declare const BUILD_TARGET: string | undefined;
type MetaInfoMap = Record<JsonPointerString, MetaInfo[]>;
export type Snapshot = {template:object, options:{}, output: any, prepared?:boolean}
export type StatedError = {
error: {
message: string;
name?: string;
stack?: string | null;
};
};
export type Op = "set"|"delete"|"forceSetInternal";
export type Fork = {forkId:string, output:object};
export type Plan = {
sortedJsonPtrs:JsonPointerString[],
didUpdate: boolean[] //peers with sortedJsonPointers, tells us which of those locations in output actually updated
data?:any, op?:Op, //if present and op="set", the data is applied to first json pointer
output:object,
forkId:string,
forkStack:Fork[] //allows us to have nested execution contexts that cen restored by popping this stack onto output
lastCompletedStep?:PlanStep,
};
type SnapshotPlan = {//a plan that simply dumps a snapshot
op:"snapshot",
generatedSnapshot: string
};
export type PlanStep = {
jsonPtr:JsonPointerString,
data?:any,
op?:Op,
output:object,
forkStack:Fork[],
forkId:string,
didUpdate:boolean
}
/**
* a FunctionGenerator is used to generate functions that need the context of which expression they were called from
* which is made available to them in the MetaInf
*/
export type FunctionGenerator = (metaInfo: MetaInfo, templateProcessor: TemplateProcessor) => (Promise<(arg: any) => Promise<any>>);
/**
* defines the function signature for data change callbacks, called when data at the ptr changes
*/
export type DataChangeCallback = (data:any, ptr:JsonPointerString, removed?:boolean)=>void
/**
* This is the main TemplateProcessor class.
*
* @remarks
* The TemplateProcessor class is responsible for processing templates and interfacing with your program that may
* provide changing inputs over time and react to changes with callbacks. Many examples can be found in
* `src/test/TemplateProcessor.test.js`
*
* @example Initialize a simple template stored in local object 'o'
* ```
* //initialize a simple template stored in local object 'o'
* test("test 6", async () => {
* const o = {
* "a": 10,
* "b": [
* "../${a}",
* ]
* };
* const tp = new TemplateProcessor(o);
* await tp.initialize();
* expect(o).toEqual({
* "a": 10,
* "b": [10]
* });
* });
* ```
* @example Pass the TemplateProcessor a context containing a function named `nozzle` and a variable named `ZOINK`
* ```
* //Pass the TemplateProcessor a context containing a function named `nozzle` and a variable named `ZOINK`
* test("context", async () => {
* const nozzle = (something) => "nozzle got some " + something;
* const context = {"nozzle": nozzle, "ZOINK": "ZOINK"}
* const tp = new TemplateProcessor({
* "a": "${$nozzle($ZOINK)}"
* }, context);
* await tp.initialize();
* expect(tp.output).toEqual(
* {
* "a": "nozzle got some ZOINK",
* }
* );
* });
* ```
* @example Parse template from JSON or YAML
* ```
* it('should correctly identify and parse JSON string', async () => {
* const jsonString = '{"key": "value"}';
* const instance = TemplateProcessor.fromString(jsonString);
* await instance.initialize();
* expect(instance).toBeInstanceOf(TemplateProcessor);
* expect(instance.output).toEqual({ key: "value" }); // Assuming parsedObject is publicly accessible
* });
*
* it('should correctly identify and parse YAML string using ---', async () => {
* const yamlString = `---
* key: value`;
* const instance = TemplateProcessor.fromString(yamlString);
* await instance.initialize();
* expect(instance).toBeInstanceOf(TemplateProcessor);
* expect(instance.output).toEqual({ key: "value" });
* });
* ```
* @example React to changes using data change callbacks on various locations in the template
* ```
* test("test 1", async () => {
* const tp = new TemplateProcessor({
* "a": "aaa",
* "b": "${a}"
* });
* await tp.initialize();
* const received = [];
* tp.setDataChangeCallback("/a", (data, jsonPtr) => {
* received.push({data, jsonPtr})
* });
* tp.setDataChangeCallback("/b", (data, jsonPtr) => {
* received.push({data, jsonPtr})
* });
* tp.setDataChangeCallback("/", (data, jsonPtr) => {
* received.push({data, jsonPtr})
* });
* await tp.setData("/a", 42);
* expect(received).toEqual([
* {
* "data": 42,
* "jsonPtr": "/a"
* },
* {
* "data": 42,
* "jsonPtr": "/b"
* },
* {
* "data": {
* "a": 42,
* "b": 42
* },
* "jsonPtr": [
* "/a",
* "/b"
* ]
* }
* ]);
* });
* ```
*/
export default class TemplateProcessor {
/**
* Loads a template and initializes a new template processor instance.
*
* @static
* @param {Object} template - The template data to be processed.
* @param {Object} [context={}] - Optional context data for the template.
* @returns {Promise<TemplateProcessor>} Returns an initialized instance of `TemplateProcessor`.
*/
static async load(template:object, context = {}):Promise<TemplateProcessor> {
const t = new TemplateProcessor(template, context);
await t.initialize();
return t;
}
/**
* Default set of functions provided for the template processor.
*
* @remarks
* These functions are commonly used utilities available for
* usage within the template processor's context. You can replace set this to
* determine which functions are available from templates
*
* @static
* @type {{
* fetch: typeof fetch,
* setInterval: typeof setInterval,
* clearInterval: typeof clearInterval,
* setTimeout: typeof setTimeout,
* console: Console
* }}
*/
static DEFAULT_FUNCTIONS = {
fetch:saferFetch,
setInterval,
clearInterval,
setTimeout,
console,
debounce,
Date,
rateLimit
}
private static _isNodeJS = typeof process !== 'undefined' && process.release && process.release.name === 'node';
/** Represents the logger used within the template processor. */
logger: StatedLogger;
/** Contextual data for the template processing. */
context: any;
/** Contains the processed output after template processing. */
output: {}={};
/** Represents the raw input for the template processor. */
input: any;
/** This object mirrors the template output in structure but where the output contains actual data,
* this object contains MetaInfo nodes that track metadata on the actual nodes */
templateMeta: any;
/** List of warnings generated during template processing. */
warnings: any[] = [];
/** Maps JSON pointers of import paths to their associated meta information. */
metaInfoByJsonPointer: MetaInfoMap={};
/** A set of tags associated with the template. */
tagSet: Set<string>;
/** Configuration options for the template processor. */
options: any = {};
/** Debugger utility for the template processor. */
debugger: any;
/** Contains any errors encountered during template processing. */
errorReport: {[key: JsonPointerString]:any}={};
/** Execution plans 'from' a given JSON Pointer. So key is JSON Pointer and value is array of JSON
* pointers (a plan) */
private executionPlans: { [key: JsonPointerString]: JsonPointerString[] }={};
/** A queue of execution plans awaiting processing. */
private readonly executionQueue:(Plan|SnapshotPlan)[] = [];
/** function generators can be provided by a caller when functions need to be
* created in such a way that they are somehow 'responsive' or dependent on their
* location inside the template. Both the generator function, and the function
* it generates are asynchronous functions (ie they return a promise).
* $import is an example of this kind of behavior.
* When $import('http://mytemplate.com/foo.json') is called, the import function
* is actually genrated on the fly, using knowledge of the json path that it was
* called at, to replace the content of the template at that path with the downloaded
* content.*/
functionGenerators: Map<string, FunctionGenerator>;
/** for every json pointer, we have multiple callbacks that are stored in a Set
* @private
*/
private changeCallbacks:Map<JsonPointerString, Set<DataChangeCallback>>;
/** Flag indicating if the template processor is currently initializing. */
private isInitializing: boolean;
/** A unique identifier for the template processor instance. */
private readonly uniqueId;
private tempVars:JsonPointerString[]=[];
private timerManager:TimerManager;
/** Allows caller to set a callback to propagate initialization into their framework */
public readonly onInitialize: Map<string,() => Promise<void>|void>;
/**
* Allows a caller to receive a callback after the template is evaluated, but before any temporary variables are
* removed. This function is slated to be replaced with a map of functions like onInitialize
* @deprecated
*/
public postInitialize: ()=> Promise<void> = async () =>{};
public executionStatus: ExecutionStatus;
public static fromString(template:string, context = {}, options={} ):TemplateProcessor{
let inferredType: "JSON" | "YAML" | "UNKNOWN" = "UNKNOWN";
// Check for JSON
if (template.trim().startsWith('{') || template.trim().startsWith('[')) {
inferredType = "JSON";
}
// Check for YAML
else if (template.includes('---') || /[^":]\s*:\s*[^"]/g.test(template)) {
inferredType = "YAML";
}
let parsedObject;
// Based on the inferred type, parse the string
if (inferredType === "JSON") {
parsedObject = JSON.parse(template);
} else if (inferredType === "YAML") {
parsedObject = yaml.load(template);
} else {
throw new Error("Unknown format");
}
// Return an instance of TemplateProcessor with the parsed object
return new TemplateProcessor(parsedObject, context, options);
}
constructor(template={}, context = {}, options={}) {
this.timerManager = new TimerManager(); //prevent leaks from $setTimeout and $setInterval
this.uniqueId = Math.random()*1e6;
this.setData = this.setData.bind(this); // Bind template-accessible functions like setData and import
this.import = this.import.bind(this); // allows clients to directly call import on this TemplateProcessor
this.logger = new ConsoleLogger("info");
this.setupContext(context);
this.resetTemplate(template);
this.options = options;
this.isInitializing = false;
this.changeCallbacks = new Map();
this.functionGenerators = new Map();
this.tagSet = new Set();
this.onInitialize = new Map();
this.executionStatus = new ExecutionStatus();
}
// resetting template means that we are resetting all data holders and set up new template
private resetTemplate(template:object) {
this.input = JSON.parse(JSON.stringify(template));
this.output = template; //initial output is input template
this.templateMeta = JSON.parse(JSON.stringify(template));// Copy the given template to `initialize the templateMeta
this.warnings = [];
this.metaInfoByJsonPointer = {}; //there will be one key "/" for the root and one additional key for each import statement in the template
this.errorReport = {}
this.tempVars = [];
}
setupContext(context: {}) {
this.context = merge(
{},
TemplateProcessor.DEFAULT_FUNCTIONS,
{"save": (output:object)=>{ //default implementation of save just logs the execution status
if (this.isEnabled("debug")){
console.debug(this.executionStatus.toJsonString());
}
return output;
}}, //note that save is before context, by design, so context can override save as needed
context,
{"set": this.setData},
{"sleep": new Sleep(this.timerManager).sleep}
);
const safe = this.withErrorHandling.bind(this);
for (const key in this.context) {
if (typeof this.context[key] === 'function') {
if (key === "setTimeout" || key === "setInterval") {
//replace with wrappers that allow us to ensure we kill all prior timers when template re-inits
this.context[key] = this.timerManager[key].bind(this.timerManager);
} else {
this.context[key] = safe(this.context[key]);
}
}
}
}
/**
* Template processor initialize can be called from 2 major use cases
* 1. initialize a new importedSubtemplate processor importedSubtemplate
* 2. $import a new importedSubtemplate for an existing importedSubtemplate processor
* in the second case we need to reset the importedSubtemplate processor data holders
* @param importedSubtemplate - the object representing the importedSubtemplate
* @param jsonPtr - defaults to "/" which is to say, this importedSubtemplate is the root importedSubtemplate. When we $import a importedSubtemplate inside an existing importedSubtemplate, then we must provide a path other than root to import into. Typically, we would use the json pointer of the expression where the $import function is used.
* @param snapshottedOutput - if provided, output is set to this initial value
*
*/
public async initialize(importedSubtemplate: {}|undefined = undefined, jsonPtr: string = "/", snapshottedOutput: {}|undefined = undefined):Promise<void> {
if(jsonPtr === "/"){
this.timerManager.clearAll();
this.executionStatus.clear();
}
// if initialize is called with a importedSubtemplate and root json pointer (which is "/" b default)
// we need to reset the importedSubtemplate. Otherwise, we rely on the one provided in the constructor
if (importedSubtemplate !== undefined && jsonPtr === "/") {
this.resetTemplate(importedSubtemplate)
}
if(snapshottedOutput){
this.output = snapshottedOutput; //use by restore to set the restored output state
}
if (jsonPtr === "/" && this.isInitializing) {
console.error("-----Initialization '/' is already in progress. Ignoring concurrent call to initialize!!!! Strongly consider checking your JS code for errors.-----");
return;
}
// Set the lock
this.isInitializing = true;
//run all initialization plugins
for (const [name, task] of this.onInitialize) {
this.logger.debug(`Running onInitialize plugin '${name}'...`);
await task();
}
try {
if (jsonPtr === "/") {
this.errorReport = {}; //clear the error report when we initialize a root importedSubtemplate
}
if (typeof BUILD_TARGET !== 'undefined' && BUILD_TARGET !== 'web') {
const _level = this.logger.level; //carry the ConsoleLogger level over to the fancy logger
this.logger = await FancyLogger.getLogger() as StatedLogger;
this.logger.level = _level;
}
this.logger.verbose(`initializing (uid=${this.uniqueId})...`);
this.logger.debug(`tags: ${JSON.stringify(Array.from(this.tagSet))}`);
this.executionPlans = {}; //clear execution plans
let parsedJsonPtr:JsonPointerStructureArray = jp.parse(jsonPtr);
parsedJsonPtr = parsedJsonPtr.filter(e=>e!=="");//isEqual(parsedJsonPtr, [""]) ? [] : parsedJsonPtr; //correct [""] to []
let compilationTarget;
if(jsonPtr === "/"){ //this is the root, not an imported sub-importedSubtemplate
compilationTarget = this.input; //standard case
}else{
compilationTarget = importedSubtemplate; //the case where we already initialized once, and now we are initializing an imported sub-template
}
const metaInfos = await this.createMetaInfos(compilationTarget , parsedJsonPtr);
this.metaInfoByJsonPointer[jsonPtr] = metaInfos; //dictionary for importedSubtemplate meta info, by import path (jsonPtr)
this.sortMetaInfos(metaInfos);
this.populateTemplateMeta(metaInfos);
this.setupDependees(metaInfos); //dependency <-> dependee is now bidirectional
this.propagateTags(metaInfos);
this.tempVars = [...this.tempVars, ...this.cacheTmpVarLocations(metaInfos)];
await this.evaluateInitialPlan(jsonPtr);
await this.postInitialize();
this.removeTemporaryVariables(this.tempVars, jsonPtr);
this.logger.verbose("initialization complete...");
this.logOutput(this.output);
}finally {
this.isInitializing = false;
}
}
close():void{
this.timerManager.clearAll();
this.changeCallbacks.clear();
this.executionStatus.clear();
}
private async evaluateInitialPlan(jsonPtr:JsonPointerString) {
const startTime = Date.now(); // Capture start time
this.logger.verbose(`evaluating template (uid=${this.uniqueId})...`);
await this.evaluateInitialPlanDependencies(this.metaInfoByJsonPointer[jsonPtr]);
const endTime = Date.now(); // Capture end time
this.logger.verbose(`evaluation complete in ${endTime - startTime} ms...`);
//the commented out approach below us necessary if we want to push in imports. It has the unsolved problem
//that if the existing template has dependencies on the to-be-imported template, and we are not forcing it
//in externally but rather the import is written as part of the template that the things that depend on the
//import will be executed twice.
/*
const rootMetaInfos = this.metaInfoByJsonPointer["/"];
if (jsonPtr === "/") { //<-- root/parent template
await this.evaluateInitialPlanDependencies(rootMetaInfos);
} else { //<-- child/imported template
//this is the case of an import. Imports target something other than root
const importedMetaInfos = this.metaInfoByJsonPointer[jsonPtr];
await this.evaluateInitialPlanDependencies([
...TemplateProcessor.dependsOnImportedTemplate(rootMetaInfos, jsonPtr),
...importedMetaInfos
]);
}
*/
}
//this is used to wrap all functions that we expose to jsonata expressions so that
//they do not throw exceptions, but instead return {"error":{...the error...}}
private withErrorHandling<T extends any[]>(fn:(...args:T)=>any) {
return (...args:T) => {
try {
const result = fn(...args);
if (result instanceof Promise) {
return result.catch(error => {
this.logger.error(error.toString());
return {
"error": {
message: error.message,
name: error.name,
stack: error.stack,
}
};
});
}
return result;
} catch (error:any) {
this.logger.error(error.toString());
return {
"error": {
message: error.message,
name: error.name,
stack: error.stack,
}
};
}
};
};
/**
* allows direct injection of ${expression} into template at given jsonPointer.
* @param expression
* @param jsonPointer
*/
async setExpression(expression:string, jsonPointer:JsonPointerString){
if(!MetaInfoProducer.EMBEDDED_EXPR_REGEX.test(expression)){
throw new Error("Not a valid stated exprssion (MetaInfoProducer.EMBEDDED_EXPR_REGEX test did not pass): " + expression);
}
await this.import(expression, jsonPointer);
}
async import(template:object|string, jsonPtrImportPath:JsonPointerString) {
jp.set(this.output, jsonPtrImportPath, template);
await this.initialize(template, jsonPtrImportPath);
}
private static NOOP = Symbol('NOOP');
private getImport(metaInfo: MetaInfo):(templateToImport:string)=>Promise<symbol> { //we provide the JSON Pointer that targets where the imported content will go
//import the template to the location pointed to by jsonPtr
return async (importMe) => {
let resp;
const parsedUrl = this.parseURL(importMe);
if (parsedUrl) { //remote download
this.logger.debug(`Attempting to fetch imported URL '${importMe}'`);
resp = await this.fetchFromURL(parsedUrl);
resp = this.extractFragmentIfNeeded(resp, parsedUrl);
} else if(MetaInfoProducer.EMBEDDED_EXPR_REGEX.test(importMe)){ //this is the case of importing an expression string
resp = importMe; //literally a direction expression like '/${foo}'
}else {
this.logger.debug(`Attempting local file import of '${importMe}'`);
try {
if (TemplateProcessor._isNodeJS || (typeof BUILD_TARGET !== 'undefined' && BUILD_TARGET !== 'web')) {
resp = await this.localImport(importMe);
}
}catch (error){
this.logger.debug("argument to import doesn't seem to be a file path");
}
if(resp === undefined){
this.logger.debug(`Attempting literal import of object '${importMe}'`);
resp = this.validateAsJSON(importMe);
}
}
if(resp === undefined){
throw new Error(`Import failed for '${importMe}' at '${metaInfo.jsonPointer__}'`);
}
await this.setContentInTemplate(resp, metaInfo);
return TemplateProcessor.NOOP;
}
}
private parseURL(input:string):URL|false {
try {
return new URL(input);
} catch (e) {
return false;
}
}
private async fetchFromURL(url:URL) {
try {
this.logger.debug(`fetching ${url}`);
const resp = await fetch(url);
if (!resp.ok) return resp;
// Determine content type from headers or URL
const contentType = resp.headers.get("content-type");
let format;
if (contentType) {
if (contentType.includes("application/json")) {
format = 'json';
} else if (contentType.includes("text/yaml")) {
format = 'yaml';
}
} //we can still encounter incorrect conetnt-type like text/plain for json or yaml on various hosting sites like github raw
if(!format){
// If content-type is not available, check the URL file extension
const fileExtension = url.pathname.split('.').pop();
if (fileExtension === 'json') {
format = 'json';
} else if (fileExtension === 'yaml' || fileExtension === 'yml') {
format = 'yaml';
}
}
switch (format) {
case 'json':
return await resp.json();
case 'yaml':
const text = await resp.text();
return yaml.load(text);
default:
throw new Error(`Cannot determine response format for URL: ${url}`);
}
} catch (e) {
const msg = `error fetching ${url}`;
this.logger.error(e);
throw new Error(msg);
}
}
private extractFragmentIfNeeded(response:any, url:URL) {
const jsonPointer = url.hash && url.hash.substring(1);
if (jsonPointer && jp.has(response, jsonPointer)) {
this.logger.debug(`Extracting fragment at ${jsonPointer}`);
return jp.get(response, jsonPointer);
} else if (jsonPointer) {
throw new Error(`fragment ${jsonPointer} does not exist in JSON received from ${url}`);
}
return response;
}
private validateAsJSON(obj:string) {
try {
const jsonString = JSON.stringify(obj);
const parsedObject = JSON.parse(jsonString);
const isEqual = JSON.stringify(obj) === JSON.stringify(parsedObject);
if(!isEqual || typeof obj !== "object"){
return undefined
}
return obj;
} catch (e) {
return undefined;
}
}
private async setContentInTemplate(literalTemplateToImport:any, metaInfo: MetaInfo):Promise<void> {
const jsonPtrIntoTemplate:string = metaInfo.jsonPointer__ as string;
jp.set(this.output, jsonPtrIntoTemplate, literalTemplateToImport);
await this.initialize(literalTemplateToImport, jsonPtrIntoTemplate); //, jp.parse(metaInfo.exprTargetJsonPointer__)
}
private async createMetaInfos(template:object, rootJsonPtr:JsonPointerStructureArray = []) {
let initialMetaInfos = await MetaInfoProducer.getMetaInfos(template);
return initialMetaInfos.reduce((acc: MetaInfo[], metaInfo) => {
metaInfo.jsonPointer__ = [...rootJsonPtr, ...metaInfo.jsonPointer__];
metaInfo.exprTargetJsonPointer__ = metaInfo.jsonPointer__.slice(0, -1);
const cdUpPath = metaInfo.exprRootPath__;
if (cdUpPath) {
const cdUpParts = cdUpPath.match(/\.\.\//g);
if (cdUpParts) { // ../../{...}
metaInfo.exprTargetJsonPointer__ = metaInfo.exprTargetJsonPointer__.slice(0, -cdUpParts.length);
} else if (cdUpPath.match(/^\/$/g)) { // /${...}
metaInfo.exprTargetJsonPointer__ = this.adjustRootForSimpleExpressionImports(template, rootJsonPtr);
} else if (cdUpPath.match(/^\/\/$/g)) { // //${...}
metaInfo.exprTargetJsonPointer__ = []; //absolute root
} else {
const jsonPtr = jp.compile(metaInfo.jsonPointer__);
const msg = `unexpected 'path' expression '${cdUpPath} (see https://github.com/cisco-open/stated#rerooting-expressions)`;
const errorObject = {name: 'invalidExpRoot', message: msg}
this.errorReport[jsonPtr as string] = {error: errorObject};
this.logger.error(msg);
}
}
if (metaInfo.expr__ !== undefined) {
try {
const depFinder = new DependencyFinder(metaInfo.expr__);
metaInfo.compiledExpr__ = depFinder.compiledExpression;
//we have to filter out "" from the dependencies as these are akin to 'no-op' path steps
metaInfo.dependencies__ = depFinder.findDependencies().map(depArray => depArray.filter(pathPart => pathPart !== ""));
acc.push(metaInfo);
} catch (e) {
this.logger.error(JSON.stringify(e));
const jsonPtr = jp.compile(metaInfo.jsonPointer__);
const msg = `problem analysing expression : ${metaInfo.expr__}`;
const errorObject = {name: "badJSONata", message: msg}
this.errorReport[jsonPtr] = {error: errorObject};
this.logger.error(msg);
}
} else {
acc.push(metaInfo);
}
return acc;
}, []);
}
private sortMetaInfos(metaInfos:MetaInfo[]) {
metaInfos.sort((a, b) => a.jsonPointer__ < b.jsonPointer__ ? -1 : (a.jsonPointer__ > b.jsonPointer__ ? 1 : 0));
}
private populateTemplateMeta(metaInfos:MetaInfo[]) {
metaInfos.forEach(meta => {
const initialDependenciesPathParts:JsonPointerStructureArray[] = this.removeLeadingDollarsFromDependencies(meta);
meta.absoluteDependencies__ = this.makeDepsAbsolute(meta.exprTargetJsonPointer__ as JsonPointerStructureArray, initialDependenciesPathParts);
meta.dependencies__ = initialDependenciesPathParts;
//so if we will never allow replacement of the entire root document. But modulo that if-statement we can setup the templateMeta
if (meta.jsonPointer__.length > 0) {
//if we are here then the templateMetaData can be set to the meta we just populated
jp.set(this.templateMeta, meta.jsonPointer__, meta);
}
TemplateProcessor.compileToJsonPointer(meta);
});
}
//mutates all the pieces of metaInf that are path parts and turns them into JSON Pointer syntax
private static compileToJsonPointer(meta:MetaInfo) {
meta.absoluteDependencies__ = [...new Set((meta.absoluteDependencies__ as JsonPointerStructureArray[]).map(jp.compile))];
meta.dependencies__ = (meta.dependencies__ as JsonPointerStructureArray[]).map(jp.compile);
meta.exprTargetJsonPointer__ = jp.compile(meta.exprTargetJsonPointer__ as JsonPointerStructureArray);
meta.jsonPointer__ = jp.compile(meta.jsonPointer__ as JsonPointerStructureArray);
meta.parent__ = jp.compile(meta.parent__ as JsonPointerStructureArray);
}
private setupDependees(metaInfos:MetaInfo[]) {
metaInfos.forEach(i => {
(i.absoluteDependencies__ as JsonPointerString[])?.forEach((ptr:JsonPointerString) => {
if (!jp.has(this.templateMeta, ptr)) {
const parent = jp.parent(ptr);
const nonMaterialized = {
"materialized__": false,
"jsonPointer__": ptr,
"dependees__": [], //a non-materialized node has a dependency on the parent node
"dependencies__": [], //we are passed the phase where dependencies have been converted to absolute so we can skip populating this
"absoluteDependencies__": [], //parent.length===0?[]:[parent], //empty parent is root document; tracking dep's on root is silly
"tags__": new Set<string>(),
"treeHasExpressions__": false,
parent__: parent
};
jp.set(this.templateMeta, ptr, nonMaterialized);
metaInfos.push(nonMaterialized); //create metaInfos node for non-materialized node
}
const meta = jp.get(this.templateMeta, ptr) as MetaInfo;
//so there is still the possibility that the node in the templateMeta existed, but it was just created
//as an empty object or array node when a "deeper" json pointer was set. Like /view/0/0/0/name would
//result in 2 empty intermediate array objects. And then someone can have a dependency on /view/0 or
///view/0/0 neither of which would have had their metadata properly defaulted
if(meta.jsonPointer__ === undefined){
const parent = jp.parent(ptr);
const nonMaterialized = {
"materialized__": false,
"jsonPointer__": ptr,
"dependees__": [],
"dependencies__": [],
"absoluteDependencies__": [], //parent.length===0?[]:[parent],
"tags__": new Set<string>(),
"treeHasExpressions__": false,
parent__: parent
};
merge(meta, nonMaterialized);
}
(meta.dependees__ as JsonPointerString[]).push(i.jsonPointer__ as JsonPointerString);
});
});
}
private async evaluateInitialPlanDependencies(metaInfos:MetaInfo[]) {
const evaluationPlan = this.topologicalSort(metaInfos, true);//we want the execution plan to only be a list of nodes containing expressions (expr=true)
return await this.executePlan({
sortedJsonPtrs:evaluationPlan,
data: TemplateProcessor.NOOP,
output:this.output,
forkStack:[],
forkId:"ROOT",
didUpdate:[]
});
}
private makeDepsAbsolute(parentJsonPtr:JsonPointerStructureArray, localJsonPtrs:JsonPointerStructureArray[]) {
return localJsonPtrs.map(localJsonPtr => { //both parentJsonPtr and localJsonPtr are like ["a", "b", "c"] (array of parts)
return [...parentJsonPtr, ...localJsonPtr]
})
}
private removeLeadingDollarsFromDependencies(metaInfo:MetaInfo):JsonPointerStructureArray[] {
// Extract dependencies__ and jsonPointer__ from metaInfo
const {dependencies__} = metaInfo;
// Iterate through each depsArray in dependencies__ using reduce function
dependencies__.forEach(depsArray => {
const root = depsArray[0];
if (root === "" || root === "$") {
(depsArray as JsonPointerStructureArray).shift();
}
});
return dependencies__ as JsonPointerStructureArray[];
}
private propagateTags(metaInfos:MetaInfo[]) {
// Set of visited nodes to avoid infinite loops
const visited = new Set();
// Recursive function for DFS
const dfs = (node:MetaInfo)=> {
if (node.jsonPointer__==undefined || visited.has(node.jsonPointer__)) return;
visited.add(node.jsonPointer__);
// Iterate through the node's dependencies
node.absoluteDependencies__?.forEach(jsonPtr => {
const dependency: MetaInfo = jp.get(this.templateMeta, jsonPtr) as MetaInfo;
// Recurse on the dependency to ensure we collect all its tags
dfs(dependency);
// Propagate tags from the dependency to the node
dependency.tags__?.forEach(tag => node.tags__.add(tag));
});
}
// Start DFS from all nodes in metaInfos
metaInfos.forEach(node => dfs(node));
}
/**
* temp vars are in scope if all tags are present OR the expression's fieldname ends in !, which makes
* it an absolutely temporary variable since.
* @param metaInfo
* @private
*/
private isTempVarInScope(metaInfo: MetaInfo){
return metaInfo.temp__ === true
&& (
(metaInfo.jsonPointer__ as JsonPointerString).endsWith("!")
||
this.allTagsPresent(metaInfo.tags__)
)
}
private cacheTmpVarLocations(metaInfos:MetaInfo[]):JsonPointerString[]{
const tmpVars:JsonPointerString[] = [];
metaInfos.forEach(metaInfo => { //var must also be in scope of tags
if (this.isTempVarInScope(metaInfo)) {
tmpVars.push(metaInfo.jsonPointer__ as JsonPointerString);
}
})
return tmpVars
}
private removeTemporaryVariables(tmpVars:JsonPointerString[], jsonPtrOfTemplate:JsonPointerString): void{
//only remove temp variables after all imports are finished and we are finishing render of the root template
if(jsonPtrOfTemplate === "/") {
tmpVars.forEach(jsonPtr => {
if (jp.has(this.output, jsonPtr)) {
const current = jp.get(this.output, jsonPtr);
jp.remove(this.output, jsonPtr);
this.callDataChangeCallbacks(current, jsonPtr, true)
}
});
}
}
private topologicalSort(metaInfos:MetaInfo[], exprsOnly = true, fanout=true):JsonPointerString[] {
const visited = new Set();
const recursionStack:Set<JsonPointerString> = new Set(); //for circular dependency detection
const orderedJsonPointers:Set<string> = new Set();
const templateMeta = this.templateMeta;
//--------------- utility sub-functions follow ----------------//
const listDependencies = (metaInfo:MetaInfo) => {
markAsVisited(metaInfo); //visited tells us 'globally' is a node has ever been visited
//...however, we also need to track the traversal of dependencies that is 'local' to a single
//originating node/expression. Circularity of references is limited to this "local" Scope. If we
//detected circularity with the global 'visited' list, it would mean that circularity was somehow
//a property of the entire template, which it is not. Circularity is a property of individual expression
//fanouts, '.from' a given expression/node
addToScope(metaInfo);
followDependencies(metaInfo);
emit(metaInfo);
followChildren(metaInfo);
removeFromScope(metaInfo); //...and clear that 'local' scope now that we finished processing the node
}
const hasJsonPointer = (metaInfo:MetaInfo) => {
return metaInfo.jsonPointer__ !== undefined;
}
const markAsVisited = (metaInfo:MetaInfo) => {
visited.add(metaInfo.jsonPointer__);
}
const addToScope = (metaInfo:MetaInfo) => {
recursionStack.add(metaInfo.jsonPointer__ as JsonPointerString);
}
const removeFromScope = (metaInfo:MetaInfo) => {
recursionStack.delete(metaInfo.jsonPointer__ as JsonPointerString);
}
/**
* Used to detect a condition where like "data:${data.foo}" which essentially declares a dependency on the
* expression itself. This is inherently circular. You cannot say "use that thing in this expression, where
* that thing is a product of evaluating this expression". You also cannot say "use that thing in this
* expression where that thing is a direct ancestor of this expression" as that is also circular, implying that
* the expression tries to reference an ancestor node, whose descendent includes this very node.
* @param exprNode
* @param dependency
*/
const isCommonPrefix = (exprNode:JsonPointerString, dependency:JsonPointerString):boolean=>{
return exprNode.startsWith(dependency) || dependency.startsWith(exprNode);
}
//metaInfo gets arranged into a tree. The fields that end with "__" are part of the meta info about the
//template. Fields that don't end in "__" are children of the given object in the template
const followChildren = (metaInfoNode:any) => {
for (const childKey in metaInfoNode) {
if (!childKey.endsWith("__")) { //ignore metadata fields
const child = metaInfoNode[childKey];
if (!visited.has(child.jsonPointer__)) {
listDependencies(child);
}
}
}
}
const searchUpForExpression = (childNode:MetaInfo):MetaInfo|undefined=> {
let pathParts = jp.parse(childNode.jsonPointer__ as JsonPointerString);
/*
const directParent = jp.compile(pathParts.slice(0, -1));
//if a dependency of an expression is rooted in the expression itself, such as "data:${data.foo}" then this is a circular dependency
if (visited.has(directParent) && (jp.get(this.templateMeta, directParent) as MetaInfo).expr__) {
logCircularDependency(childNode.jsonPointer__ as JsonPointerString);
return undefined;
}
*/
while (pathParts.length > 1) {
pathParts = pathParts.slice(0, -1); //get the parent expression
const jsonPtr = jp.compile(pathParts);
const ancestorNode = jp.get(this.templateMeta, jsonPtr) as MetaInfo;
if (ancestorNode.materialized__ === true) {
return ancestorNode;
}
}
return undefined;
}
const followDependencies = (metaInfo:MetaInfo) => {
if (!metaInfo.absoluteDependencies__) return;
for (const dependency of metaInfo.absoluteDependencies__) {
if (recursionStack.has(dependency as JsonPointerString)
|| isCommonPrefix(metaInfo.jsonPointer__ as JsonPointerString, dependency as JsonPointerString)) {
logCircularDependency(dependency as JsonPointerString);
continue; //do not follow circular dependencies
}
if (visited.has(dependency)) continue;
const dependencyNode = jp.get(templateMeta, dependency) as MetaInfo;
processUnmaterializedDependency(dependencyNode);
listDependencies(dependencyNode);
}
}
const logCircularDependency = (dependency:JsonPointerString) => {
const e = '🔃 Circular dependency ' + Array.from(recursionStack).join(' → ') + " → " + dependency;
this.warnings.push(e);
this.logger.log('warn', e);
}
const processUnmaterializedDependency = (dependencyNode:MetaInfo) => {
if (!dependencyNode.materialized__) {
const ancestor = searchUpForExpression(dependencyNode);