-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathexceptionless.node.js
1620 lines (1619 loc) · 60.8 KB
/
exceptionless.node.js
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
var child = require("child_process");
var http = require("http");
var SettingsManager = (function () {
function SettingsManager() {
}
SettingsManager.onChanged = function (handler) {
!!handler && this._handlers.push(handler);
};
SettingsManager.applySavedServerSettings = function (config) {
config.log.info('Applying saved settings.');
config.settings = Utils.merge(config.settings, this.getSavedServerSettings(config));
this.changed(config);
};
SettingsManager.checkVersion = function (version, config) {
if (version) {
var savedConfigVersion = parseInt(config.storage.get(this._configPath + "-version"), 10);
if (isNaN(savedConfigVersion) || version > savedConfigVersion) {
config.log.info("Updating settings from v" + (!isNaN(savedConfigVersion) ? savedConfigVersion : 0) + " to v" + version);
this.updateSettings(config);
}
}
};
SettingsManager.updateSettings = function (config) {
var _this = this;
if (!config.isValid) {
config.log.error('Unable to update settings: ApiKey is not set.');
return;
}
config.submissionClient.getSettings(config, function (response) {
if (!response || !response.success || !response.settings) {
return;
}
config.settings = Utils.merge(config.settings, response.settings);
var savedServerSettings = SettingsManager.getSavedServerSettings(config);
for (var key in savedServerSettings) {
if (response.settings[key]) {
continue;
}
delete config.settings[key];
}
var path = SettingsManager._configPath;
config.storage.save(path + "-version", response.settingsVersion);
config.storage.save(path, response.settings);
config.log.info('Updated settings');
_this.changed(config);
});
};
SettingsManager.changed = function (config) {
var handlers = this._handlers;
for (var index = 0; index < handlers.length; index++) {
handlers[index](config);
}
};
SettingsManager.getSavedServerSettings = function (config) {
return config.storage.get(this._configPath) || {};
};
SettingsManager._configPath = 'ex-server-settings.json';
SettingsManager._handlers = [];
return SettingsManager;
})();
exports.SettingsManager = SettingsManager;
var DefaultLastReferenceIdManager = (function () {
function DefaultLastReferenceIdManager() {
this._lastReferenceId = null;
}
DefaultLastReferenceIdManager.prototype.getLast = function () {
return this._lastReferenceId;
};
DefaultLastReferenceIdManager.prototype.clearLast = function () {
this._lastReferenceId = null;
};
DefaultLastReferenceIdManager.prototype.setLast = function (eventId) {
this._lastReferenceId = eventId;
};
return DefaultLastReferenceIdManager;
})();
exports.DefaultLastReferenceIdManager = DefaultLastReferenceIdManager;
var ConsoleLog = (function () {
function ConsoleLog() {
}
ConsoleLog.prototype.info = function (message) {
this.log('info', message);
};
ConsoleLog.prototype.warn = function (message) {
this.log('warn', message);
};
ConsoleLog.prototype.error = function (message) {
this.log('error', message);
};
ConsoleLog.prototype.log = function (level, message) {
if (console && console[level]) {
console[level]("[" + level + "] Exceptionless: " + message);
}
};
return ConsoleLog;
})();
exports.ConsoleLog = ConsoleLog;
var NullLog = (function () {
function NullLog() {
}
NullLog.prototype.info = function (message) { };
NullLog.prototype.warn = function (message) { };
NullLog.prototype.error = function (message) { };
return NullLog;
})();
exports.NullLog = NullLog;
var EventPluginContext = (function () {
function EventPluginContext(client, event, contextData) {
this.client = client;
this.event = event;
this.contextData = contextData ? contextData : new ContextData();
}
Object.defineProperty(EventPluginContext.prototype, "log", {
get: function () {
return this.client.config.log;
},
enumerable: true,
configurable: true
});
return EventPluginContext;
})();
exports.EventPluginContext = EventPluginContext;
var EventPluginManager = (function () {
function EventPluginManager() {
}
EventPluginManager.run = function (context, callback) {
var wrap = function (plugin, next) {
return function () {
try {
if (!context.cancelled) {
plugin.run(context, next);
}
}
catch (ex) {
context.cancelled = true;
context.log.error("Error running plugin '" + plugin.name + "': " + ex.message + ". Discarding Event.");
}
if (context.cancelled && !!callback) {
callback(context);
}
};
};
var plugins = context.client.config.plugins;
var wrappedPlugins = [];
if (!!callback) {
wrappedPlugins[plugins.length] = wrap({ name: 'cb', priority: 9007199254740992, run: callback }, null);
}
for (var index = plugins.length - 1; index > -1; index--) {
wrappedPlugins[index] = wrap(plugins[index], !!callback || (index < plugins.length - 1) ? wrappedPlugins[index + 1] : null);
}
wrappedPlugins[0]();
};
EventPluginManager.addDefaultPlugins = function (config) {
config.addPlugin(new ConfigurationDefaultsPlugin());
config.addPlugin(new ErrorPlugin());
config.addPlugin(new DuplicateCheckerPlugin());
config.addPlugin(new ModuleInfoPlugin());
config.addPlugin(new RequestInfoPlugin());
config.addPlugin(new EnvironmentInfoPlugin());
config.addPlugin(new SubmissionMethodPlugin());
};
return EventPluginManager;
})();
exports.EventPluginManager = EventPluginManager;
var ReferenceIdPlugin = (function () {
function ReferenceIdPlugin() {
this.priority = 20;
this.name = 'ReferenceIdPlugin';
}
ReferenceIdPlugin.prototype.run = function (context, next) {
if ((!context.event.reference_id || context.event.reference_id.length === 0) && context.event.type === 'error') {
context.event.reference_id = Utils.guid().replace('-', '').substring(0, 10);
}
next && next();
};
return ReferenceIdPlugin;
})();
exports.ReferenceIdPlugin = ReferenceIdPlugin;
var DefaultEventQueue = (function () {
function DefaultEventQueue(config) {
this._processingQueue = false;
this._config = config;
}
DefaultEventQueue.prototype.enqueue = function (event) {
var config = this._config;
this.ensureQueueTimer();
if (this.areQueuedItemsDiscarded()) {
config.log.info('Queue items are currently being discarded. The event will not be queued.');
return;
}
var key = "ex-q-" + new Date().toJSON() + "-" + Utils.randomNumber();
config.log.info("Enqueuing event: " + key + " type=" + event.type + " " + (!!event.reference_id ? 'refid=' + event.reference_id : ''));
config.storage.save(key, event);
};
DefaultEventQueue.prototype.process = function (isAppExiting) {
var _this = this;
function getEvents(events) {
var items = [];
for (var index = 0; index < events.length; index++) {
items.push(events[index].value);
}
return items;
}
var queueNotProcessed = 'The queue will not be processed.';
var config = this._config;
var log = config.log;
this.ensureQueueTimer();
if (this._processingQueue) {
return;
}
log.info('Processing queue...');
if (!config.enabled) {
log.info("Configuration is disabled. " + queueNotProcessed);
return;
}
if (!config.isValid) {
log.info("Invalid Api Key. " + queueNotProcessed);
return;
}
this._processingQueue = true;
try {
var events_1 = config.storage.getList('ex-q', config.submissionBatchSize);
if (!events_1 || events_1.length === 0) {
this._processingQueue = false;
return;
}
log.info("Sending " + events_1.length + " events to " + config.serverUrl + ".");
config.submissionClient.postEvents(getEvents(events_1), config, function (response) {
_this.processSubmissionResponse(response, events_1);
log.info('Finished processing queue.');
_this._processingQueue = false;
}, isAppExiting);
}
catch (ex) {
log.error("Error processing queue: " + ex);
this.suspendProcessing();
this._processingQueue = false;
}
};
DefaultEventQueue.prototype.suspendProcessing = function (durationInMinutes, discardFutureQueuedItems, clearQueue) {
var config = this._config;
if (!durationInMinutes || durationInMinutes <= 0) {
durationInMinutes = 5;
}
config.log.info("Suspending processing for " + durationInMinutes + " minutes.");
this._suspendProcessingUntil = new Date(new Date().getTime() + (durationInMinutes * 60000));
if (discardFutureQueuedItems) {
this._discardQueuedItemsUntil = new Date(new Date().getTime() + (durationInMinutes * 60000));
}
if (clearQueue) {
this.removeEvents(config.storage.getList('ex-q'));
}
};
DefaultEventQueue.prototype.areQueuedItemsDiscarded = function () {
return this._discardQueuedItemsUntil && this._discardQueuedItemsUntil > new Date();
};
DefaultEventQueue.prototype.ensureQueueTimer = function () {
var _this = this;
if (!this._queueTimer) {
this._queueTimer = setInterval(function () { return _this.onProcessQueue(); }, 10000);
}
};
DefaultEventQueue.prototype.isQueueProcessingSuspended = function () {
return this._suspendProcessingUntil && this._suspendProcessingUntil > new Date();
};
DefaultEventQueue.prototype.onProcessQueue = function () {
if (!this.isQueueProcessingSuspended() && !this._processingQueue) {
this.process();
}
};
DefaultEventQueue.prototype.processSubmissionResponse = function (response, events) {
var noSubmission = 'The event will not be submitted.';
var config = this._config;
var log = config.log;
if (response.success) {
log.info("Sent " + events.length + " events.");
this.removeEvents(events);
return;
}
if (response.serviceUnavailable) {
log.error('Server returned service unavailable.');
this.suspendProcessing();
return;
}
if (response.paymentRequired) {
log.info('Too many events have been submitted, please upgrade your plan.');
this.suspendProcessing(null, true, true);
return;
}
if (response.unableToAuthenticate) {
log.info("Unable to authenticate, please check your configuration. " + noSubmission);
this.suspendProcessing(15);
this.removeEvents(events);
return;
}
if (response.notFound || response.badRequest) {
log.error("Error while trying to submit data: " + response.message);
this.suspendProcessing(60 * 4);
this.removeEvents(events);
return;
}
if (response.requestEntityTooLarge) {
var message = 'Event submission discarded for being too large.';
if (config.submissionBatchSize > 1) {
log.error(message + " Retrying with smaller batch size.");
config.submissionBatchSize = Math.max(1, Math.round(config.submissionBatchSize / 1.5));
}
else {
log.error(message + " " + noSubmission);
this.removeEvents(events);
}
return;
}
if (!response.success) {
log.error("Error submitting events: " + (response.message || 'Please check the network tab for more info.'));
this.suspendProcessing();
}
};
DefaultEventQueue.prototype.removeEvents = function (events) {
for (var index = 0; index < (events || []).length; index++) {
this._config.storage.remove(events[index].path);
}
};
return DefaultEventQueue;
})();
exports.DefaultEventQueue = DefaultEventQueue;
var InMemoryStorage = (function () {
function InMemoryStorage(maxItems) {
this._items = [];
this._maxItems = maxItems > 0 ? maxItems : 250;
}
InMemoryStorage.prototype.save = function (path, value) {
if (!path || !value) {
return false;
}
this.remove(path);
if (this._items.push({ created: new Date().getTime(), path: path, value: value }) > this._maxItems) {
this._items.shift();
}
return true;
};
InMemoryStorage.prototype.get = function (path) {
var item = path ? this.getList("^" + path + "$", 1)[0] : null;
return item ? item.value : null;
};
InMemoryStorage.prototype.getList = function (searchPattern, limit) {
var items = this._items;
if (!searchPattern) {
return items.slice(0, limit);
}
var regex = new RegExp(searchPattern);
var results = [];
for (var index = 0; index < items.length; index++) {
if (regex.test(items[index].path)) {
results.push(items[index]);
if (results.length >= limit) {
break;
}
}
}
return results;
};
InMemoryStorage.prototype.remove = function (path) {
if (path) {
var item = this.getList("^" + path + "$", 1)[0];
if (item) {
this._items.splice(this._items.indexOf(item), 1);
}
}
};
return InMemoryStorage;
})();
exports.InMemoryStorage = InMemoryStorage;
var DefaultSubmissionClient = (function () {
function DefaultSubmissionClient() {
this.configurationVersionHeader = 'x-exceptionless-configversion';
}
DefaultSubmissionClient.prototype.postEvents = function (events, config, callback, isAppExiting) {
var data = Utils.stringify(events, config.dataExclusions);
var request = this.createRequest(config, 'POST', '/api/v2/events', data);
var cb = this.createSubmissionCallback(config, callback);
return config.submissionAdapter.sendRequest(request, cb, isAppExiting);
};
DefaultSubmissionClient.prototype.postUserDescription = function (referenceId, description, config, callback) {
var path = "/api/v2/events/by-ref/" + encodeURIComponent(referenceId) + "/user-description";
var data = Utils.stringify(description, config.dataExclusions);
var request = this.createRequest(config, 'POST', path, data);
var cb = this.createSubmissionCallback(config, callback);
return config.submissionAdapter.sendRequest(request, cb);
};
DefaultSubmissionClient.prototype.getSettings = function (config, callback) {
var request = this.createRequest(config, 'GET', '/api/v2/projects/config');
var cb = function (status, message, data, headers) {
if (status !== 200) {
return callback(new SettingsResponse(false, null, -1, null, message));
}
var settings;
try {
settings = JSON.parse(data);
}
catch (e) {
config.log.error("Unable to parse settings: '" + data + "'");
}
if (!settings || isNaN(settings.version)) {
return callback(new SettingsResponse(false, null, -1, null, 'Invalid configuration settings.'));
}
callback(new SettingsResponse(true, settings.settings || {}, settings.version));
};
return config.submissionAdapter.sendRequest(request, cb);
};
DefaultSubmissionClient.prototype.createRequest = function (config, method, path, data) {
if (data === void 0) { data = null; }
return {
method: method,
path: path,
data: data,
serverUrl: config.serverUrl,
apiKey: config.apiKey,
userAgent: config.userAgent
};
};
DefaultSubmissionClient.prototype.createSubmissionCallback = function (config, callback) {
var _this = this;
return function (status, message, data, headers) {
var settingsVersion = headers && parseInt(headers[_this.configurationVersionHeader], 10);
SettingsManager.checkVersion(settingsVersion, config);
callback(new SubmissionResponse(status, message));
};
};
return DefaultSubmissionClient;
})();
exports.DefaultSubmissionClient = DefaultSubmissionClient;
var Utils = (function () {
function Utils() {
}
Utils.addRange = function (target) {
var values = [];
for (var _i = 1; _i < arguments.length; _i++) {
values[_i - 1] = arguments[_i];
}
if (!target) {
target = [];
}
if (!values || values.length === 0) {
return target;
}
for (var index = 0; index < values.length; index++) {
if (values[index] && target.indexOf(values[index]) < 0) {
target.push(values[index]);
}
}
return target;
};
Utils.getHashCode = function (source) {
if (!source || source.length === 0) {
return null;
}
var hash = 0;
for (var index = 0; index < source.length; index++) {
var character = source.charCodeAt(index);
hash = ((hash << 5) - hash) + character;
hash |= 0;
}
return hash.toString();
};
Utils.getCookies = function (cookies) {
var result = {};
var parts = (cookies || '').split('; ');
for (var index = 0; index < parts.length; index++) {
var cookie = parts[index].split('=');
result[cookie[0]] = cookie[1];
}
return result;
};
Utils.guid = function () {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
};
Utils.merge = function (defaultValues, values) {
var result = {};
for (var key in defaultValues || {}) {
if (!!defaultValues[key]) {
result[key] = defaultValues[key];
}
}
for (var key in values || {}) {
if (!!values[key]) {
result[key] = values[key];
}
}
return result;
};
Utils.parseVersion = function (source) {
if (!source) {
return null;
}
var versionRegex = /(v?((\d+)\.(\d+)(\.(\d+))?)(?:-([\dA-Za-z\-]+(?:\.[\dA-Za-z\-]+)*))?(?:\+([\dA-Za-z\-]+(?:\.[\dA-Za-z\-]+)*))?)/;
var matches = versionRegex.exec(source);
if (matches && matches.length > 0) {
return matches[0];
}
return null;
};
Utils.parseQueryString = function (query) {
if (!query || query.length === 0) {
return null;
}
var pairs = query.split('&');
if (pairs.length === 0) {
return null;
}
var result = {};
for (var index = 0; index < pairs.length; index++) {
var pair = pairs[index].split('=');
result[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return result;
};
Utils.randomNumber = function () {
return Math.floor(Math.random() * 9007199254740992);
};
Utils.stringify = function (data, exclusions) {
function checkForMatch(pattern, value) {
if (!pattern || !value || typeof value !== 'string') {
return false;
}
var trim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
pattern = pattern.toLowerCase().replace(trim, '');
value = value.toLowerCase().replace(trim, '');
if (pattern.length <= 0) {
return false;
}
var startsWithWildcard = pattern[0] === '*';
if (startsWithWildcard) {
pattern = pattern.slice(1);
}
var endsWithWildcard = pattern[pattern.length - 1] === '*';
if (endsWithWildcard) {
pattern = pattern.substring(0, pattern.length - 1);
}
if (startsWithWildcard && endsWithWildcard) {
return value.indexOf(pattern) !== -1;
}
if (startsWithWildcard) {
return value.lastIndexOf(pattern) === (value.length - pattern.length);
}
if (endsWithWildcard) {
return value.indexOf(pattern) === 0;
}
return value === pattern;
}
function stringifyImpl(obj, excludedKeys) {
var cache = [];
return JSON.stringify(obj, function (key, value) {
for (var index = 0; index < (excludedKeys || []).length; index++) {
if (checkForMatch(excludedKeys[index], key)) {
return;
}
}
if (typeof value === 'object' && !!value) {
if (cache.indexOf(value) !== -1) {
return;
}
cache.push(value);
}
return value;
});
}
if (({}).toString.call(data) === '[object Array]') {
var result = [];
for (var index = 0; index < data.length; index++) {
result[index] = JSON.parse(stringifyImpl(data[index], exclusions || []));
}
return JSON.stringify(result);
}
return stringifyImpl(data, exclusions || []);
};
return Utils;
})();
exports.Utils = Utils;
var Configuration = (function () {
function Configuration(configSettings) {
this.defaultTags = [];
this.defaultData = {};
this.enabled = true;
this.lastReferenceIdManager = new DefaultLastReferenceIdManager();
this.settings = {};
this._plugins = [];
this._serverUrl = 'https://collector.exceptionless.io';
this._dataExclusions = [];
function inject(fn) {
return typeof fn === 'function' ? fn(this) : fn;
}
configSettings = Utils.merge(Configuration.defaults, configSettings);
this.log = inject(configSettings.log) || new NullLog();
this.apiKey = configSettings.apiKey;
this.serverUrl = configSettings.serverUrl;
this.environmentInfoCollector = inject(configSettings.environmentInfoCollector);
this.errorParser = inject(configSettings.errorParser);
this.lastReferenceIdManager = inject(configSettings.lastReferenceIdManager) || new DefaultLastReferenceIdManager();
this.moduleCollector = inject(configSettings.moduleCollector);
this.requestInfoCollector = inject(configSettings.requestInfoCollector);
this.submissionBatchSize = inject(configSettings.submissionBatchSize) || 50;
this.submissionAdapter = inject(configSettings.submissionAdapter);
this.submissionClient = inject(configSettings.submissionClient) || new DefaultSubmissionClient();
this.storage = inject(configSettings.storage) || new InMemoryStorage();
this.queue = inject(configSettings.queue) || new DefaultEventQueue(this);
SettingsManager.applySavedServerSettings(this);
EventPluginManager.addDefaultPlugins(this);
}
Object.defineProperty(Configuration.prototype, "apiKey", {
get: function () {
return this._apiKey;
},
set: function (value) {
this._apiKey = value || null;
this.log.info("apiKey: " + this._apiKey);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Configuration.prototype, "isValid", {
get: function () {
return !!this.apiKey && this.apiKey.length >= 10;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Configuration.prototype, "serverUrl", {
get: function () {
return this._serverUrl;
},
set: function (value) {
if (!!value) {
this._serverUrl = value;
this.log.info("serverUrl: " + this._serverUrl);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Configuration.prototype, "dataExclusions", {
get: function () {
var exclusions = this.settings['@@DataExclusions'];
return this._dataExclusions.concat(exclusions && exclusions.split(',') || []);
},
enumerable: true,
configurable: true
});
Configuration.prototype.addDataExclusions = function () {
var exclusions = [];
for (var _i = 0; _i < arguments.length; _i++) {
exclusions[_i - 0] = arguments[_i];
}
this._dataExclusions = Utils.addRange.apply(Utils, [this._dataExclusions].concat(exclusions));
};
Object.defineProperty(Configuration.prototype, "plugins", {
get: function () {
return this._plugins.sort(function (p1, p2) {
return (p1.priority < p2.priority) ? -1 : (p1.priority > p2.priority) ? 1 : 0;
});
},
enumerable: true,
configurable: true
});
Configuration.prototype.addPlugin = function (pluginOrName, priority, pluginAction) {
var plugin = !!pluginAction ? { name: pluginOrName, priority: priority, run: pluginAction } : pluginOrName;
if (!plugin || !plugin.run) {
this.log.error('Add plugin failed: Run method not defined');
return;
}
if (!plugin.name) {
plugin.name = Utils.guid();
}
if (!plugin.priority) {
plugin.priority = 0;
}
var pluginExists = false;
var plugins = this._plugins;
for (var index = 0; index < plugins.length; index++) {
if (plugins[index].name === plugin.name) {
pluginExists = true;
break;
}
}
if (!pluginExists) {
plugins.push(plugin);
}
};
Configuration.prototype.removePlugin = function (pluginOrName) {
var name = typeof pluginOrName === 'string' ? pluginOrName : pluginOrName.name;
if (!name) {
this.log.error('Remove plugin failed: Plugin name not defined');
return;
}
var plugins = this._plugins;
for (var index = 0; index < plugins.length; index++) {
if (plugins[index].name === name) {
plugins.splice(index, 1);
break;
}
}
};
Configuration.prototype.setVersion = function (version) {
if (!!version) {
this.defaultData['@version'] = version;
}
};
Configuration.prototype.setUserIdentity = function (userInfoOrIdentity, name) {
var USER_KEY = '@user';
var userInfo = typeof userInfoOrIdentity !== 'string' ? userInfoOrIdentity : { identity: userInfoOrIdentity, name: name };
var shouldRemove = !userInfo || (!userInfo.identity && !userInfo.name);
if (shouldRemove) {
delete this.defaultData[USER_KEY];
}
else {
this.defaultData[USER_KEY] = userInfo;
}
this.log.info("user identity: " + (shouldRemove ? 'null' : userInfo.identity));
};
Object.defineProperty(Configuration.prototype, "userAgent", {
get: function () {
return 'exceptionless-js/1.1.1';
},
enumerable: true,
configurable: true
});
Configuration.prototype.useReferenceIds = function () {
this.addPlugin(new ReferenceIdPlugin());
};
Configuration.prototype.useDebugLogger = function () {
this.log = new ConsoleLog();
};
Object.defineProperty(Configuration, "defaults", {
get: function () {
if (Configuration._defaultSettings === null) {
Configuration._defaultSettings = {};
}
return Configuration._defaultSettings;
},
enumerable: true,
configurable: true
});
Configuration._defaultSettings = null;
return Configuration;
})();
exports.Configuration = Configuration;
var EventBuilder = (function () {
function EventBuilder(event, client, pluginContextData) {
this._validIdentifierErrorMessage = 'must contain between 8 and 100 alphanumeric or \'-\' characters.';
this.target = event;
this.client = client;
this.pluginContextData = pluginContextData || new ContextData();
}
EventBuilder.prototype.setType = function (type) {
if (!!type) {
this.target.type = type;
}
return this;
};
EventBuilder.prototype.setSource = function (source) {
if (!!source) {
this.target.source = source;
}
return this;
};
EventBuilder.prototype.setSessionId = function (sessionId) {
if (!this.isValidIdentifier(sessionId)) {
throw new Error("SessionId " + this._validIdentifierErrorMessage);
}
this.target.session_id = sessionId;
return this;
};
EventBuilder.prototype.setReferenceId = function (referenceId) {
if (!this.isValidIdentifier(referenceId)) {
throw new Error("ReferenceId " + this._validIdentifierErrorMessage);
}
this.target.reference_id = referenceId;
return this;
};
EventBuilder.prototype.setMessage = function (message) {
if (!!message) {
this.target.message = message;
}
return this;
};
EventBuilder.prototype.setGeo = function (latitude, longitude) {
if (latitude < -90.0 || latitude > 90.0) {
throw new Error('Must be a valid latitude value between -90.0 and 90.0.');
}
if (longitude < -180.0 || longitude > 180.0) {
throw new Error('Must be a valid longitude value between -180.0 and 180.0.');
}
this.target.geo = latitude + "," + longitude;
return this;
};
EventBuilder.prototype.setUserIdentity = function (userInfoOrIdentity, name) {
var userInfo = typeof userInfoOrIdentity !== 'string' ? userInfoOrIdentity : { identity: userInfoOrIdentity, name: name };
if (!userInfo || (!userInfo.identity && !userInfo.name)) {
return this;
}
this.setProperty('@user', userInfo);
return this;
};
EventBuilder.prototype.setValue = function (value) {
if (!!value) {
this.target.value = value;
}
return this;
};
EventBuilder.prototype.addTags = function () {
var tags = [];
for (var _i = 0; _i < arguments.length; _i++) {
tags[_i - 0] = arguments[_i];
}
this.target.tags = Utils.addRange.apply(Utils, [this.target.tags].concat(tags));
return this;
};
EventBuilder.prototype.setProperty = function (name, value) {
if (!name || (value === undefined || value == null)) {
return this;
}
if (!this.target.data) {
this.target.data = {};
}
this.target.data[name] = value;
return this;
};
EventBuilder.prototype.markAsCritical = function (critical) {
if (critical) {
this.addTags('Critical');
}
return this;
};
EventBuilder.prototype.addRequestInfo = function (request) {
if (!!request) {
this.pluginContextData['@request'] = request;
}
return this;
};
EventBuilder.prototype.submit = function (callback) {
this.client.submitEvent(this.target, this.pluginContextData, callback);
};
EventBuilder.prototype.isValidIdentifier = function (value) {
if (!value) {
return true;
}
if (value.length < 8 || value.length > 100) {
return false;
}
for (var index = 0; index < value.length; index++) {
var code = value.charCodeAt(index);
var isDigit = (code >= 48) && (code <= 57);
var isLetter = ((code >= 65) && (code <= 90)) || ((code >= 97) && (code <= 122));
var isMinus = code === 45;
if (!(isDigit || isLetter) && !isMinus) {
return false;
}
}
return true;
};
return EventBuilder;
})();
exports.EventBuilder = EventBuilder;
var ContextData = (function () {
function ContextData() {
}
ContextData.prototype.setException = function (exception) {
if (exception) {
this['@@_Exception'] = exception;
}
};
Object.defineProperty(ContextData.prototype, "hasException", {
get: function () {
return !!this['@@_Exception'];
},
enumerable: true,
configurable: true
});
ContextData.prototype.getException = function () {
return this['@@_Exception'] || null;
};
ContextData.prototype.markAsUnhandledError = function () {
this['@@_IsUnhandledError'] = true;
};
Object.defineProperty(ContextData.prototype, "isUnhandledError", {
get: function () {
return !!this['@@_IsUnhandledError'];
},
enumerable: true,
configurable: true
});
ContextData.prototype.setSubmissionMethod = function (method) {
if (method) {
this['@@_SubmissionMethod'] = method;
}
};
ContextData.prototype.getSubmissionMethod = function () {
return this['@@_SubmissionMethod'] || null;
};
return ContextData;
})();
exports.ContextData = ContextData;
var SubmissionResponse = (function () {
function SubmissionResponse(statusCode, message) {
this.success = false;
this.badRequest = false;
this.serviceUnavailable = false;
this.paymentRequired = false;
this.unableToAuthenticate = false;
this.notFound = false;
this.requestEntityTooLarge = false;
this.statusCode = statusCode;
this.message = message;
this.success = statusCode >= 200 && statusCode <= 299;
this.badRequest = statusCode === 400;
this.serviceUnavailable = statusCode === 503;
this.paymentRequired = statusCode === 402;
this.unableToAuthenticate = statusCode === 401 || statusCode === 403;
this.notFound = statusCode === 404;
this.requestEntityTooLarge = statusCode === 413;
}
return SubmissionResponse;
})();
exports.SubmissionResponse = SubmissionResponse;
var ExceptionlessClient = (function () {
function ExceptionlessClient(settingsOrApiKey, serverUrl) {
if (typeof settingsOrApiKey !== 'object') {
this.config = new Configuration(settingsOrApiKey);
}
else {
this.config = new Configuration({ apiKey: settingsOrApiKey, serverUrl: serverUrl });
}
}
ExceptionlessClient.prototype.createException = function (exception) {
var pluginContextData = new ContextData();
pluginContextData.setException(exception);
return this.createEvent(pluginContextData).setType('error');
};
ExceptionlessClient.prototype.submitException = function (exception, callback) {
this.createException(exception).submit(callback);
};
ExceptionlessClient.prototype.createUnhandledException = function (exception, submissionMethod) {
var builder = this.createException(exception);
builder.pluginContextData.markAsUnhandledError();
builder.pluginContextData.setSubmissionMethod(submissionMethod);
return builder;
};
ExceptionlessClient.prototype.submitUnhandledException = function (exception, submissionMethod, callback) {
this.createUnhandledException(exception, submissionMethod).submit(callback);
};
ExceptionlessClient.prototype.createFeatureUsage = function (feature) {
return this.createEvent().setType('usage').setSource(feature);
};
ExceptionlessClient.prototype.submitFeatureUsage = function (feature, callback) {
this.createFeatureUsage(feature).submit(callback);
};
ExceptionlessClient.prototype.createLog = function (sourceOrMessage, message, level) {
var builder = this.createEvent().setType('log');
if (message && level) {
builder = builder.setSource(sourceOrMessage).setMessage(message).setProperty('@level', level);
}
else if (message) {
builder = builder.setSource(sourceOrMessage).setMessage(message);
}
else {
var caller = arguments.callee.caller;
builder = builder.setSource(caller && caller.name).setMessage(sourceOrMessage);
}
return builder;
};
ExceptionlessClient.prototype.submitLog = function (sourceOrMessage, message, level, callback) {
this.createLog(sourceOrMessage, message, level).submit(callback);
};
ExceptionlessClient.prototype.createNotFound = function (resource) {
return this.createEvent().setType('404').setSource(resource);
};
ExceptionlessClient.prototype.submitNotFound = function (resource, callback) {
this.createNotFound(resource).submit(callback);
};
ExceptionlessClient.prototype.createSessionStart = function (sessionId) {
return this.createEvent().setType('start').setSessionId(sessionId);
};
ExceptionlessClient.prototype.submitSessionStart = function (sessionId, callback) {
this.createSessionStart(sessionId).submit(callback);
};
ExceptionlessClient.prototype.createSessionEnd = function (sessionId) {
return this.createEvent().setType('end').setSessionId(sessionId);
};
ExceptionlessClient.prototype.submitSessionEnd = function (sessionId, callback) {
this.createSessionEnd(sessionId).submit(callback);
};
ExceptionlessClient.prototype.createEvent = function (pluginContextData) {
return new EventBuilder({ date: new Date() }, this, pluginContextData);
};
ExceptionlessClient.prototype.submitEvent = function (event, pluginContextData, callback) {
function cancelled(context) {
if (!!context) {