-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathJavaScriptResource.mustache
More file actions
833 lines (759 loc) · 34.1 KB
/
Copy pathJavaScriptResource.mustache
File metadata and controls
833 lines (759 loc) · 34.1 KB
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
fiftyoneDegreesManager = function() {
'use strict';
var json = {{&_jsonObject}};
var parameters = {{&_parameters}};
var sessionId = "{{&_sessionId}}";
// The session id is deliberately not part of the key: it changes on
// every request, and session storage is already scoped to one tab.
var sessionKey = "{{_objName}}";
this.sessionId = sessionId;
var sequence = {{&_sequence}};
// Log any errors returned in the JSON object.
if(json.error !== undefined){
console.log(json.error);
}
// Log any warnings returned in the JSON object.
if (json.warnings !== undefined) {
console.log(json.warnings);
}
// Set to true when the JSON object is complete.
var completed = false;
// Set to true when the `catchError` is called.
let failed = false;
// changeFuncs is an array of functions. When onChange is called and passed
// a function, the function is registered and is called when processing is
// complete.
var changeFuncs = [];
// Counter is used to count how many pieces of callbacks are expected. Every
// time the completedCallback method is called, the counter is decremented
// by 1.
var callbackCounter = 0;
// Array of JavaScript properties that have started evaluation.
var jsPropertiesStarted = [];
// Properties whose snippets have run but whose evidence has not yet reached
// the server. They are flagged in session storage only once the response
// they feed is cached, so a flag can never be present without the payload
// it belongs to.
var jsPropertiesPending = [];
// startsWith polyfill.
var startsWith = function(source, searchValue) {
return source.lastIndexOf(searchValue, 0) === 0;
}
// endsWith polyfill.
var endsWith = function(source, searchValue) {
return source.substring(source.length - searchValue.length, source.length) === searchValue;
}
var clearCache = function() {
if (sessionStorage) {
// Iterate backwards: removeItem shifts every later key down one
// index, so a forward loop skips whichever key moves into the slot
// just vacated.
for (var i = sessionStorage.length - 1; i >= 0; i--) {
var key = sessionStorage.key(i);
// Match the exact key or the key plus a separator. Without the
// session id the prefix is short enough that a bare startsWith
// would also match an unrelated key on the same origin.
if (key === sessionKey || startsWith(key, sessionKey + "_")) {
sessionStorage.removeItem(key);
}
}
}
}
// Read the cached payload, or null when there is none or it cannot be used.
// An entry that does not parse into an object is cleared here rather than
// ignored: this runs before the '_property_' flags are read, so a bad entry
// makes this page view execute the snippets again instead of completing
// with neither the cached values nor a request.
var getCachedJson = function() {
if (!sessionStorage) {
return null;
}
var cachedResponse = sessionStorage.getItem(sessionKey);
if (!cachedResponse) {
return null;
}
var cachedJson = null;
try {
cachedJson = JSON.parse(cachedResponse);
} catch (err) {
// Handled by the check below, which also covers a payload that
// parses to null or to a value that is not an object.
}
if (typeof cachedJson !== 'object' || cachedJson === null) {
clearCache();
return null;
}
return cachedJson;
}
// Suffix the server appends to a property name to carry the reason that
// property has no value.
var nullReasonSuffix = 'nullreason';
// Cached values take precedence over the payload rendered for this page
// view. The cached payload is the response to a request that carried the
// JavaScript evidence, whereas the payload rendered into this page view was
// answered from headers alone, so the cached value is the better-informed
// one. Leaving the rendered value in place would discard exactly what the
// cache exists to preserve: a property the server can answer from headers
// is not null, so its ambiguous answer would survive - on an iPhone
// 'hardwarename' is the whole candidate list rather than the resolved model.
var mergeCached = function(cachedJson) {
Object.getOwnPropertyNames(cachedJson).forEach(function(group) {
var cachedGroup = cachedJson[group];
// Only aspect objects carry cached values. The arrays at this level
// (javascriptProperties, errors, warnings) describe the request that
// produced them, so taking them from an earlier page view would
// resurrect a stale error or a snippet list the server no longer
// sends.
if (typeof cachedGroup !== 'object' ||
cachedGroup === null ||
Array.isArray(cachedGroup)) {
return;
}
var freshGroup = json[group];
if (freshGroup === undefined || freshGroup === null) {
json[group] = cachedGroup;
return;
}
// Anything the server has just supplied as a non-object wins, and
// is not something values can be merged into.
if (typeof freshGroup !== 'object' || Array.isArray(freshGroup)) {
return;
}
for (var name in cachedGroup) {
// Reasons are carried with the value they describe, below, so
// that a cached reason is never left next to a value it did not
// arrive with.
if (endsWith(name, nullReasonSuffix)) {
continue;
}
// A cached null says only that the earlier response could not
// answer either, so it is not worth losing the fresh value for.
if (cachedGroup[name] === null || cachedGroup[name] === undefined) {
continue;
}
freshGroup[name] = cachedGroup[name];
var reasonName = name + nullReasonSuffix;
if (cachedGroup[reasonName] === undefined) {
delete freshGroup[reasonName];
} else {
freshGroup[reasonName] = cachedGroup[reasonName];
}
}
});
return json;
}
// Get stored values with the '51D_' prefix that have been added to the request
// and return the data as key value pairs. This method is needed to extract
// stored values for inclusion in the GET or POST request for situations
// where CORS will prevent them from being sent to third parties.
var getFodSavedValues = function() {
let fodValues = {};
{{#_enableCookies}}
{
let keyValuePairs = document.cookie.split(/; */);
for(let nextPair of keyValuePairs) {
let firstEqualsLocation = nextPair.indexOf("=");
let name = nextPair.substring(0, firstEqualsLocation);
if(startsWith(name, "51D_")){
let value = nextPair.substring(firstEqualsLocation+1);
fodValues[name] = value;
}
}
};
{{/_enableCookies}}
{{^_enableCookies}}
{
// Collect values from session storage
let session51DataPrefix = sessionKey + "_data_";
for(let i = 0, n = window.sessionStorage.length; i < n; ++i) {
let nextKey = window.sessionStorage.key(i);
if(startsWith(nextKey, session51DataPrefix)){
let value = window.sessionStorage[nextKey];
fodValues[nextKey.substring(session51DataPrefix.length)] = value;
}
}
};
{{/_enableCookies}}
return fodValues;
};
// Extract key value pairs from the '51D_' prefixed values and concatenates
// them to form a query string for the subsequent json refresh.
var getParametersFromStorage = function() {
var fodValues = getFodSavedValues();
var keyValuePairs = [];
for (var key in fodValues) {
if (fodValues.hasOwnProperty(key)) {
// Url encode the value.
// This is done to ensure that invalid characters (e.g. = chars at the end of
// base 64 encoded strings) reach the server intact.
// The server will automatically decode the value before passing it into the
// Pipeline API.
keyValuePairs.push(key + "=" + encodeURIComponent(fodValues[key]));
}
}
return keyValuePairs;
};
// Fetch a value safely from the json object. If a key somewhere down the
// '.' separated hierarchy of keys is not present then 'undefined' is
// returned rather than letting an exception occur.
var getFromJson = function(key, allowObjects, allowBooleans) {
var result = undefined;
if (typeof allowObjects === "undefined") { allowObjects = false; }
if (typeof allowBooleans === "undefined") { allowBooleans = false; }
if (typeof(key) === "string") {
var functions = json;
var segments = key.split('.');
var i = 0;
while (functions !== undefined && i < segments.length) {
functions = functions[segments[i++]];
}
if (typeof functions === "string") {
result = functions;
} else if (allowBooleans && typeof functions === "boolean") {
result = functions;
} else if (allowObjects && typeof functions === "object" && functions !== null) {
result = functions;
}
}
return result;
}
// Executed at the end of the processJSproperties method or for each piece
// of JavaScript which has 51D code injected. When there are 0 pieces of
// JavaScript left to process then reload the JSON object.
var completedCallback = function(resolve, reject){
callbackCounter--;
if (callbackCounter === 0) {
{{#_updateEnabled}}
processRequest(resolve, reject);
{{/_updateEnabled}}
} else if (callbackCounter < 0){
reject('Too many callbacks.');
}
}
// Executes any JavaScript contained in the JSON data. Session storage is
// used to check the process state of the JavaScript property, if the name
// of the property exists as a key then it has been processed. If all the
// processed JavaScript properties have been flagged as processed already
// then session storage is checked again for a JSON payload. If it exists
// then this is loaded into the managers internal data store. If not or if
// JavaScript properties have been processed then the call-back is
// processed with any new evidence produced by the JavaScript properties.
// If JavaScript properties are processed then a key containing the name of
// the JavaScript property is added to session storage. The complete flag is
// set to true when there is no further JavaScript to be processed.
var processJsProperties = function(resolve, reject, jsProperties, ignoreDelayFlag) {
var started = 0;
var cachedJson = getCachedJson();
// Held for the duration of the loop so that a snippet which invokes its
// callback synchronously cannot take the counter to zero, and dispatch a
// request, while snippets later in the list have not been run yet.
callbackCounter++;
// If there is no cached response and there are JavaScript code snippets
// then process them and perform any call-backs required.
if (jsProperties !== undefined && jsProperties.length > 0) {
{{^_enableCookies}}
let valueSetPrefix = new RegExp('document\\.cookie\\s*=\\s*(("([A-Za-z0-9_"\\s\\+]+)\\s*=\\s*"\\s*\\+\\s*([^\\s};]+))|(`([A-Za-z0-9_]+)\\s*=\\s*\\$\\{([^}]+)\\}`))', 'g');
let session51DataPrefix = sessionKey + "_data_";
let sessionSetPatch = 'window.sessionStorage["' + session51DataPrefix + '$3$6"]=$4$7';
{{/_enableCookies}}
// Execute each of the JavaScript property code snippets using the
// index of the value to access the value to avoid problems with
// JavaScript returning erroneous values.
for (var index = 0; index < jsProperties.length; index++) {
var name = jsProperties[index];
if (jsPropertiesStarted.indexOf(name) !== -1) {
continue;
}
var body = getFromJson(name);
var isCached = cachedJson &&
sessionStorage.getItem(sessionKey + "_property_" + name);
// If the property has already been processed then skip it.
if (isCached) {
// Record it as started so that hasJSFunctions agrees this
// snippet will not run in this page view. If it disagreed,
// loadParsedJSON would hand back to a call to process that
// does nothing and returns to loadParsedJSON again.
jsPropertiesStarted.push(name);
continue;
}
// Create new function bound to this instance and execute it.
// This is needed to ensure the scope of the function is
// associated with this instance if any members are altered or
// added. Avoids global scoped variables.
var delay = getFromJson(name + 'delayexecution', false, true);
if (
(ignoreDelayFlag || delay === undefined || delay === false) &&
typeof body === "string" &&
body.length
) {
var func = undefined;
var searchString = '// 51D replace this comment with callback function.';
completed = false;
jsPropertiesStarted.push(name);
started++;
{{^_enableCookies}}
body = body.replaceAll(valueSetPrefix, sessionSetPatch);
{{/_enableCookies}}
if (body.indexOf(searchString) !== -1){
callbackCounter++;
body = body.replace(/\/\/ 51D replace this comment with callback function./g, 'callbackFunc(resolveFunc, rejectFunc);');
func = new Function('callbackFunc', 'resolveFunc', 'rejectFunc',
"try {\n" +
body + "\n" +
"} catch (err) {\n" +
"console.log(err);" +
"}"
);
func(completedCallback, resolve, reject);
} else {
func = new Function(
"try {\n" +
body + "\n" +
"} catch (err) {\n" +
"console.log(err);" +
"}"
);
func();
}
// Held until the response this snippet feeds is cached.
// Flagging it here instead would leave the flag behind when
// the page is left before the request completes, and an
// older cached payload would then validate it. Within this
// page view jsPropertiesStarted already stops it re-running.
jsPropertiesPending.push(name);
// If the property is `javascripthardwareprofile` then check if the
// profile has been set. If not then remove current property from
// the list of properties that have started to prevent the
// 2nd request from being made.
if (name === "device.javascripthardwareprofile") {
var hrw = getFodSavedValues();
if (hrw && !hrw["51D_ProfileIds"]) {
// The snippet produced no profile, so it must not be
// flagged when the response is cached. With the key
// stable a flag would otherwise mark the property as
// done for the rest of the tab session and it would
// never be attempted again. The name stays in
// jsPropertiesStarted so that only the next page
// view retries it, not this one.
var pendingIndex = jsPropertiesPending.indexOf(name);
if (pendingIndex > -1) {
jsPropertiesPending.splice(pendingIndex, 1);
}
started--;
}
}
}
}
}
if (started === 0) {
// Nothing started, so nothing in the loop incremented the counter.
// Release the hold without dispatching a request. This must stay
// ahead of loadParsedJSON, which can re-enter this function through
// process(): if the outer hold were still counted the nested round
// could never reach zero and would never dispatch.
callbackCounter--;
// A snippet that has run has evidence the cached payload cannot
// account for, which is why completing from the cache is confined
// to this branch: doing it after a snippet started would suppress
// the request that carries that evidence.
if (cachedJson) {
loadParsedJSON(resolve, reject, mergeCached(cachedJson));
}
failed = false;
completed = true;
} else {
// Release the hold. If every snippet that started has already called
// back this dispatches now; otherwise the last callback to arrive does.
completedCallback(resolve, reject);
}
};
{{#_updateEnabled}}
{{^_supportsFetch}}
// Standard method to create a CORS HTTP request ready to send data.
var createCORSRequest = function(method, url) {
var xhr;
try {
xhr = new XMLHttpRequest();
} catch(err){
xhr = null;
}
if (xhr !== null && "withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials"
// property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS
// requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
};
{{/_supportsFetch}}
{{/_updateEnabled}}
// Check if the JSON object still has any JavaScript snippets to run. The
// conditions here must match the ones processJsProperties runs a snippet
// under: if this says yes and processJsProperties then does nothing,
// loadParsedJSON calls process and is called back into forever.
var hasJSFunctions = function() {
var jsProperties = json.javascriptProperties;
if (jsProperties === undefined || jsProperties === null) {
return false;
}
for (var i = 0; i < jsProperties.length; i++) {
var name = jsProperties[i];
if (jsPropertiesStarted.indexOf(name) !== -1) {
continue;
}
if (getFromJson(name + 'delayexecution', false, true) === true) {
continue;
}
var body = getFromJson(name);
if (typeof body === "string" && body.length > 0) {
return true;
}
}
return false;
}
// Process the JavaScript properties.
var process = function(resolve, reject){
processJsProperties(resolve, reject, json.javascriptProperties, false);
}
var fireChangeFuncs = function(json) {
for (var i = 0; i < changeFuncs.length; i++) {
if (typeof changeFuncs[i] === 'function' &&
changeFuncs[i].length === 1) {
changeFuncs[i](json);
}
}
}
// Continues with an already parsed payload. Defined outside the update
// section because the cached branch of processJsProperties calls it, and
// with the key no longer carrying the session id a payload cached by an
// update-enabled render can still be present when this one is rendered.
var loadParsedJSON = function(resolve, reject, newJson) {
json = newJson;
if (hasJSFunctions()) {
// json updated so fire 'on change' functions
// before executing any new JS properties that
// have come back.
fireChangeFuncs(json);
process(resolve, reject);
} else {
failed = false;
completed = true;
// json updated so fire 'on change' functions
// This must happen after completed = true in order
// for 'complete' functions to fire.
fireChangeFuncs(json);
resolve(json);
}
}
{{#_updateEnabled}}
// Process the response as json and call the resolve method.
var loadJSON = function(resolve, reject, responseText) {
var newJson;
try {
newJson = JSON.parse(responseText);
} catch(err) {
clearCache();
reject(new Error("Invalid JSON - the endpoint is likely setup incorrectly", { cause: err }));
return;
}
loadParsedJSON(resolve, reject, newJson);
}
// Sends a POST request to the call-back URL to retrieve and updated
// JSON payload from the cloud service. A POST request is used so that
// parameters can be passed in the request body, this is to get around
// the limitations on the length of query strings. As POST requests are not
// cached by browsers, the result of the POST request is stored in session
// storage on a successful response. This can then be checked before making
// repeat requests to the call-back URL.
// Any saved value parameters that have been set by the executed JavaScript
// properties are added to the list of parameters, this list is then
// serialized as Form Data and sent in the POST body to the call-back URL,
// refreshing the JSON data. The new JSON is then loaded if the request is
// returned with a success status code. If there was a problem then the
// session storage items are invalidated and reject is called.
var processRequest = function(resolve, reject){
// parameters is rendered from this page view's own query evidence, so
// it is already what the refresh should report and nothing from an
// earlier page view belongs in it. The values the snippets produce are
// the one thing that does carry over, and they come from their own
// storage below rather than from a stored copy of this object.
// Get additional parameters in case they are not sent
// by the browser.
var savedValueParams = getParametersFromStorage();
for(var savedValueIndex in savedValueParams) {
var parts = savedValueParams[savedValueIndex].split('=');
parameters[parts[0]] = parts[1];
}
var params = [];
for (var param in parameters) {
if (parameters.hasOwnProperty(param)) {
params.push(param+"="+parameters[param])
}
}
// Additional evidence provided by the page. Sent in the request
// body only and never stored.
var pageEvidence = window["{{_objName}}Evidence"];
if (pageEvidence && typeof pageEvidence === "object") {
for (var evidenceKey in pageEvidence) {
if (Object.prototype.hasOwnProperty.call(pageEvidence, evidenceKey)) {
params.push(encodeURIComponent(evidenceKey) + "=" + encodeURIComponent(pageEvidence[evidenceKey]));
}
}
}
// Add the session and sequence to the request
if (sessionId) {
params.push("session-id=" + sessionId);
}
if (sequence) {
params.push("sequence=" + sequence);
}
var postBody = "";
if (params.length > 0) {
postBody = params.join('&').replace(/%20/g, '+');
}
{{#_supportsFetch}}
fetch('{{{_url}}}', {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: postBody
})
.then(response => {
if (!response.ok) {
throw new Error('Request failed with status ' + response.status);
}
return response.text();
})
.then(responseText => {
{{/_supportsFetch}}
{{^_supportsFetch}}
// Request callback URL with additional parameters.
var xhr = createCORSRequest('POST', '{{{_url}}}');
// If there is no support for HTTP requests then call reject and throw
// a no CORS support error.
if (!xhr) {
reject(new Error('CORS not supported'));
return;
}
// Add the HTTP header for POST form data.
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Accept', 'application/json');
xhr.onload = function () {
// An error status still reaches onload, and error details come back
// as a JSON body, so they must not be treated as data or cached.
if (xhr.status < 200 || xhr.status > 299) {
clearCache();
reject(new Error('Request failed with status ' + xhr.status));
return;
}
// Get the response body from the request.
var responseText = xhr.responseText;
{{/_supportsFetch}}
// Cache the response text, and flag the snippets it accounts for at
// the same moment, so that the two cannot disagree. Cleared before
// loadJSON, which can re-enter processJsProperties and queue names
// for the next request.
if (sessionStorage) {
sessionStorage.setItem(sessionKey, responseText);
for (var pending = 0; pending < jsPropertiesPending.length; pending++) {
sessionStorage.setItem(
sessionKey + "_property_" + jsPropertiesPending[pending], true);
}
}
jsPropertiesPending = [];
// Load the JSON object from the response text
loadJSON(resolve, reject, responseText);
// Increment the sequence on a successful request
sequence++;
{{#_supportsFetch}}
})
.catch(error => {
// Invalidate the cache on error.
clearCache();
reject(error);
});
{{/_supportsFetch}}
{{^_supportsFetch}}
};
xhr.onerror = function () {
// An error occurred with the request. Invalidate the cache and
// return the details in the call to reject method.
clearCache();
reject(Error(xhr.statusText));
};
// Send the GET request.
xhr.send(postBody);
{{/_supportsFetch}}
}
{{/_updateEnabled}}
// Function logs errors, used to 'reject' a promise or for error callbacks.
var catchError = function(value) {
failed = true;
function errorToDesc(subError) {
let msg = subError.message;
if (!msg) {
msg = String(subError);
}
let cause = subError.cause;
if (cause) {
msg += '\n--- caused by ---\n';
msg += errorToDesc(cause);
}
return msg;
}
let errorDesc = errorToDesc(value);
console.log(errorDesc);
if (json.errors === null || json.errors === undefined) {
json.errors = [errorDesc];
} else if (Array.isArray(json.errors)) {
json.errors.push(errorDesc);
}
fireChangeFuncs(json);
}
// Populate this instance of the FOD object with getters to access the
// properties. If the value is null then get the noValueMessage from the
// JSON object corresponding to the property.
var update = function(data){
var self = this;
Object.getOwnPropertyNames(data).forEach(function(key) {
self[key] = {};
for(var i in data[key]){
var obj = self[key];
(function(i) {
Object.defineProperty(obj, i, {
get: function (){
if(data[key][i] === null && (i !== "javascriptProperties")){
return data[key][i + "nullreason"];
} else {
return data[key][i];
}
}
})
})(i);
}
});
}
{{#_hasDelayedProperties}}
// Get the JS property(s) that, when evaluated, will populate
// evidence that can be used to determine the value of the
// supplied property.
// The supplied name can either be a complete property name or a top level
// aspect name.
// Where the aspect name is given, ALL evidence properties under that
// key will be returned.
// Example property names are 'location.country' or 'devices.profiles.hardwarename'
// Example aspect names are 'location' or 'devices'
var getEvidenceProperties = function (name) {
var evidenceProperties = getFromJson(name + 'evidenceproperties');
if(typeof evidenceProperties === "undefined") {
var item = getFromJson(name, true);
evidenceProperties = getEvidencePropertiesFromObject(item);
}
return evidenceProperties;
}
// Get all values in any 'evidenceproperty' fields on this object
// or sub-objects.
var getEvidencePropertiesFromObject = function (dataObject) {
var evidenceProperties = [];
for (var prop in dataObject) {
if (dataObject.hasOwnProperty(prop)) {
var value = dataObject[prop];
// Property name ends with 'evidenceproperties' so is
// what we're looking for.
// Add the values to the array if we don't already have it.
if (value !== null && Array.isArray(value) && endsWith(prop, 'evidenceproperties')) {
value.forEach(function(item, index) {
if(evidenceProperties.indexOf(item) === -1) {
evidenceProperties.push(item);
}
});
}
// Item is an object so recursively call this method
// and add any resulting evidence properties to the list.
else if(typeof value === 'object' && value !== null) {
getEvidencePropertiesFromObject(value).forEach(function(item, index) {
if(evidenceProperties.indexOf(item) === -1) {
evidenceProperties.push(item);
}
});
}
}
}
return evidenceProperties;
}
{{/_hasDelayedProperties}}
{{#_supportsPromises}}
this.promise = new Promise(function(resolve, reject) {
process(resolve,reject);
});
{{/_supportsPromises}}
this.onChange = function(resolve) {
changeFuncs.push(resolve);
// A page view served from the session storage cache finishes inside
// the constructor, before page code can get here, so a handler
// registered afterwards would never hear about a change that has
// already happened. Catching it up is what 'complete' already does.
if ((completed || failed) &&
typeof resolve === 'function' &&
resolve.length === 1) {
resolve(json);
}
}
this.complete = function(resolve, properties) {
{{#_hasDelayedProperties}}
// If properties is set then check if we need to kick off
// processing of anything.
if(typeof properties !== "undefined") {
// If properties is a string then split on comma to produce
// an array of one or more key names.
if(typeof properties === "string") {
properties = properties.split(',');
}
if(Array.isArray(properties)) {
properties.forEach(function(key, i) {
// We pass an empty function rather than 'resolve' because we
// don't want to call resolve when a single evidence function
// evaluates but after all of them have completed.
// This is handled by the 'if(complete)' code below.
processJsProperties(function(json) {}, catchError, getEvidenceProperties(key), true);
});
}
}
{{/_hasDelayedProperties}}
if(completed || failed){
resolve(json);
}else{
this.onChange(function(data) {
if(completed || failed){
resolve(data);
}
})
}
};
// Update this instance with the initial JSON payload.
update.call(this, json);
{{#_supportsPromises}}
var parent = this;
this.promise.then(function(value) {
// JSON has been updated so replace the current instance.
update.call(parent, value);
failed = false;
completed = true;
}).catch(catchError);
{{/_supportsPromises}}
{{^_supportsPromises}}
process(function(json) {}, catchError);
{{/_supportsPromises}}
}
var {{_objName}} = new fiftyoneDegreesManager();