-
Notifications
You must be signed in to change notification settings - Fork 21
/
h54s.js
1251 lines (1095 loc) · 98.2 KB
/
h54s.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
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.h54s = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/*
* h54s error constructor
* @constructor
*
*@param {string} type - Error type
*@param {string} message - Error message
*
*/
function h54sError(type, message) {
if(Error.captureStackTrace) {
Error.captureStackTrace(this);
}
this.message = message;
this.type = type;
}
h54sError.prototype = Object.create(Error.prototype, {
constructor: {
configurable: false,
enumerable: false,
writable: false,
value: h54sError
},
name: {
configurable: false,
enumerable: false,
writable: false,
value: 'h54sError'
}
});
module.exports = h54sError;
},{}],2:[function(require,module,exports){
var h54sError = require('./error.js');
/*
* Represents html5 for sas adapter
* @constructor
*
*@param {object} config - adapter config object, with keys like url, debug, etc.
*
*/
var h54s = module.exports = function(config) {
//default config values
this.maxXhrRetries = 5;
this.url = "/SASStoredProcess/do";
this.debug = false;
this.loginUrl = '/SASLogon/Logon.do';
this.retryAfterLogin = true;
this.sasApp = 'Stored Process Web App 9.3';
this.ajaxTimeout = 30000;
this.remoteConfigUpdateCallbacks = [];
this._pendingCalls = [];
this._ajax = require('./methods/ajax.js')();
_setConfig.call(this, config);
//override with remote if set
if(config && config.isRemoteConfig) {
var self = this;
this._disableCalls = true;
// '/base/test/h54sConfig.json' is for the testing with karma
//replaced with gulp in dev build
this._ajax.get('h54sConfig.json').success(function(res) {
var remoteConfig = JSON.parse(res.responseText);
for(var key in remoteConfig) {
if(remoteConfig.hasOwnProperty(key) && config[key] === undefined && key !== 'isRemoteConfig') {
config[key] = remoteConfig[key];
}
}
_setConfig.call(self, config);
//execute callbacks when we have remote config
//note that remote conifg is merged with instance config
for(var i = 0, n = self.remoteConfigUpdateCallbacks.length; i < n; i++) {
var fn = self.remoteConfigUpdateCallbacks[i];
fn();
}
//execute sas calls disabled while waiting for the config
self._disableCalls = false;
while(self._pendingCalls.length > 0) {
var pendingCall = self._pendingCalls.shift();
var sasProgram = pendingCall.sasProgram;
var callback = pendingCall.callback;
var params = pendingCall.params;
//update program with metadataRoot if it's not set
if(self.metadataRoot && pendingCall.params._program.indexOf(self.metadataRoot) === -1) {
pendingCall.params._program = self.metadataRoot.replace(/\/?$/, '/') + pendingCall.params._program.replace(/^\//, '');
}
//update debug because it may change in the meantime
params._debug = self.debug ? 131 : 0;
self.call(sasProgram, null, callback, params);
}
}).error(function (err) {
throw new h54sError('ajaxError', 'Remote config file cannot be loaded. Http status code: ' + err.status);
});
}
// private function to set h54s instance properties
function _setConfig(config) {
if(!config) {
this._ajax.setTimeout(this.ajaxTimeout);
return;
} else if(typeof config !== 'object') {
throw new h54sError('argumentError', 'First parameter should be config object');
}
//merge config object from parameter with this
for(var key in config) {
if(config.hasOwnProperty(key)) {
if((key === 'url' || key === 'loginUrl') && config[key].charAt(0) !== '/') {
config[key] = '/' + config[key];
}
this[key] = config[key];
}
}
//if server is remote use the full server url
//NOTE: this is not permited by the same-origin policy
if(config.hostUrl) {
if(config.hostUrl.charAt(config.hostUrl.length - 1) === '/') {
config.hostUrl = config.hostUrl.slice(0, -1);
}
this.hostUrl = config.hostUrl;
this.url = config.hostUrl + this.url;
this.loginUrl = config.hostUrl + this.loginUrl;
}
this._ajax.setTimeout(this.ajaxTimeout);
}
};
//replaced with gulp
h54s.version = '0.11.0';
h54s.prototype = require('./methods/methods.js');
h54s.Tables = require('./tables/tables.js');
//self invoked function module
require('./ie_polyfills.js');
},{"./error.js":1,"./ie_polyfills.js":3,"./methods/ajax.js":5,"./methods/methods.js":6,"./tables/tables.js":8}],3:[function(require,module,exports){
module.exports = function() {
if (!Object.create) {
Object.create = function(proto, props) {
if (typeof props !== "undefined") {
throw "The multiple-argument version of Object.create is not provided by this browser and cannot be shimmed.";
}
function ctor() { }
ctor.prototype = proto;
return new ctor();
};
}
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
if (!Object.keys) {
Object.keys = (function () {
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
return function (obj) {
if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
throw new TypeError('Object.keys called on non-object');
}
var result = [], prop, i;
for (prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
if (hasDontEnumBug) {
for (i = 0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) {
result.push(dontEnums[i]);
}
}
}
return result;
};
}());
}
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf
if (!Array.prototype.lastIndexOf) {
Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
'use strict';
if (this === void 0 || this === null) {
throw new TypeError();
}
var n, k,
t = Object(this),
len = t.length >>> 0;
if (len === 0) {
return -1;
}
n = len - 1;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) {
n = 0;
}
else if (n !== 0 && n != (1 / 0) && n != -(1 / 0)) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
for (k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n); k >= 0; k--) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
}();
},{}],4:[function(require,module,exports){
var logs = {
applicationLogs: [],
debugData: [],
sasErrors: [],
failedRequests: []
};
var limits = {
applicationLogs: 100,
debugData: 20,
failedRequests: 20,
sasErrors: 100
};
module.exports.get = {
getSasErrors: function() {
return logs.sasErrors;
},
getApplicationLogs: function() {
return logs.applicationLogs;
},
getDebugData: function() {
return logs.debugData;
},
getFailedRequests: function() {
return logs.failedRequests;
}
};
module.exports.clear = {
clearApplicationLogs: function() {
logs.applicationLogs.splice(0, logs.applicationLogs.length);
},
clearDebugData: function() {
logs.debugData.splice(0, logs.debugData.length);
},
clearSasErrors: function() {
logs.sasErrors.splice(0, logs.sasErrors.length);
},
clearFailedRequests: function() {
logs.failedRequests.splice(0, logs.failedRequests.length);
},
clearAllLogs: function() {
this.clearApplicationLogs();
this.clearDebugData();
this.clearSasErrors();
this.clearFailedRequests();
}
};
/*
* Adds application logs to an array of logs
*
* @param {string} res - server response
*
*/
module.exports.addApplicationLog = function(message, sasProgram) {
if(message === 'blank') {
return;
}
var log = {
message: message,
time: new Date(),
sasProgram: sasProgram
};
logs.applicationLogs.push(log);
if(logs.applicationLogs.length > limits.applicationLogs) {
logs.applicationLogs.shift();
}
};
/*
* Adds debug data to an array of logs
*
* @param {string} res - server response
*
*/
module.exports.addDebugData = function(htmlData, debugText, sasProgram, params) {
logs.debugData.push({
debugHtml: htmlData,
debugText: debugText,
sasProgram: sasProgram,
params: params,
time: new Date()
});
if(logs.debugData.length > limits.debugData) {
logs.debugData.shift();
}
};
/*
* Adds failed requests to an array of logs
*
* @param {string} res - server response
*
*/
module.exports.addFailedRequest = function(responseText, debugText, sasProgram) {
logs.failedRequests.push({
responseHtml: responseText,
responseText: debugText,
sasProgram: sasProgram,
time: new Date()
});
//max 20 failed requests
if(logs.failedRequests.length > limits.failedRequests) {
logs.failedRequests.shift();
}
};
/*
* Adds SAS errors to an array of logs
*
* @param {string} res - server response
*
*/
module.exports.addSasErrors = function(errors) {
logs.sasErrors = logs.sasErrors.concat(errors);
while(logs.sasErrors.length > limits.sasErrors) {
logs.sasErrors.shift();
}
};
},{}],5:[function(require,module,exports){
module.exports = function() {
var timeout = 30000;
var timeoutHandle;
var xhr = function(type, url, data, multipartFormData) {
var methods = {
success: function() {},
error: function() {}
};
var XHR = XMLHttpRequest || ActiveXObject;
var request = new XHR('MSXML2.XMLHTTP.3.0');
request.open(type, url, true);
//multipart/form-data is set automatically so no need for else block
if(!multipartFormData) {
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
request.onreadystatechange = function () {
if (request.readyState === 4) {
clearTimeout(timeoutHandle);
if (request.status >= 200 && request.status < 300) {
methods.success.call(methods, request);
} else {
methods.error.call(methods, request);
}
}
};
if(timeout > 0) {
timeoutHandle = setTimeout(function() {
request.abort();
}, timeout);
}
request.send(data);
return {
success: function (callback) {
methods.success = callback;
return this;
},
error: function (callback) {
methods.error = callback;
return this;
}
};
};
var serialize = function(obj) {
var str = [];
for(var p in obj) {
if (obj.hasOwnProperty(p)) {
if(obj[p] instanceof Array) {
for(var i = 0, n = obj[p].length; i < n; i++) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p][i]));
}
} else {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
}
}
return str.join("&");
};
var createMultipartFormDataPayload = function(obj) {
var data = new FormData();
for(var p in obj) {
if(obj.hasOwnProperty(p)) {
if(obj[p] instanceof Array) {
for(var i = 0, n = obj[p].length; i < n; i++) {
data.append(p, obj[p][i]);
}
} else {
data.append(p, obj[p]);
}
}
}
return data;
};
return {
get: function(url, data) {
var dataStr;
if(typeof data === 'object') {
dataStr = serialize(data);
}
var urlWithParams = dataStr ? (url + '?' + dataStr) : url;
return xhr('GET', urlWithParams);
},
post: function(url, data, multipartFormData) {
var payload;
if(typeof data === 'object') {
if(multipartFormData) {
payload = createMultipartFormDataPayload(data);
} else {
payload = serialize(data);
}
}
return xhr('POST', url, payload, multipartFormData);
},
setTimeout: function(t) {
timeout = t;
}
};
};
},{}],6:[function(require,module,exports){
var h54sError = require('../error.js');
var logs = require('../logs.js');
/*
* Call Sas program
*
* @param {string} sasProgram - Path of the sas program
* @param {function} callback - Callback function called when ajax call is finished
*
*/
module.exports.call = function(sasProgram, tablesObj, callback, params) {
var self = this;
var retryCount = 0;
var dbg = this.debug;
if (!callback || typeof callback !== 'function'){
throw new h54sError('argumentError', 'You must provide callback');
}
if(!sasProgram) {
throw new h54sError('argumentError', 'You must provide Sas program file path');
}
if(typeof sasProgram !== 'string') {
throw new h54sError('argumentError', 'First parameter should be string');
}
if(!params) {
params = {
_program: this.metadataRoot ? this.metadataRoot.replace(/\/?$/, '/') + sasProgram.replace(/^\//, '') : sasProgram,
_debug: this.debug ? 131 : 0,
_service: 'default',
};
}
if(tablesObj) {
if(tablesObj instanceof h54s.Tables) {
for(var key in tablesObj._tables) {
if(tablesObj._tables.hasOwnProperty(key)) {
params[key] = tablesObj._tables[key];
}
}
} else {
throw new h54sError('argumentError', 'Wrong type of tables object');
}
}
if(this._disableCalls) {
this._pendingCalls.push({
sasProgram: sasProgram,
callback: callback,
params: params
});
return;
}
this._ajax.post(this.url, params, true).success(function(res) {
if(self._utils.needToLogin.call(self, res)) {
//remember the call for latter use
self._pendingCalls.push({
sasProgram: sasProgram,
callback: callback,
params: params
});
//there's no need to continue if previous call returned login error
if(self._disableCalls) {
return;
} else {
self._disableCalls = true;
}
try {
var sasAppMatches = res.responseURL.match(/_sasapp=([^&]*)/);
self.sasApp = sasAppMatches[1].replace(/\+/g, ' ');
} catch(e) {
logs.addApplicationLog('Cannot extract _sasapp parameter from login URL');
}
callback(new h54sError('notLoggedinError', 'You are not logged in'));
} else {
var resObj, unescapedResObj;
if(!dbg) {
try {
resObj = self._utils.parseRes(res.responseText, sasProgram, params);
logs.addApplicationLog(resObj.logmessage, sasProgram);
resObj = self._utils.convertDates(resObj);
unescapedResObj = self._utils.unescapeValues(resObj);
callback(undefined, unescapedResObj);
} catch(e) {
if(e instanceof SyntaxError) {
if(retryCount < self.maxXhrRetries) {
self._ajax.post(self.url, params, true).success(this.success).error(this.error);
retryCount++;
logs.addApplicationLog("Retrying #" + retryCount, sasProgram);
} else {
self._utils.parseErrorResponse(res.responseText, sasProgram);
self._utils.addFailedResponse(res.responseText, sasProgram);
callback(new h54sError('parseError', 'Unable to parse response json'));
}
} else if(e instanceof h54sError) {
self._utils.parseErrorResponse(res.responseText, sasProgram);
self._utils.addFailedResponse(res.responseText, sasProgram);
callback(e);
} else {
self._utils.parseErrorResponse(res.responseText, sasProgram);
self._utils.addFailedResponse(res.responseText, sasProgram);
var err = new h54sError('unknownError', e.message);
err.stack = e.stack;
callback(err);
}
}
} else {
try {
resObj = self._utils.parseDebugRes(res.responseText, sasProgram, params);
logs.addApplicationLog(resObj.logmessage, sasProgram);
resObj = self._utils.convertDates(resObj);
unescapedResObj = self._utils.unescapeValues(resObj);
callback(undefined, unescapedResObj);
} catch(e) {
if(e instanceof SyntaxError) {
callback(new h54sError('parseError', e.message));
} else if(e instanceof h54sError) {
callback(e);
} else {
var error = new h54sError('unknownError', e.message);
error.stack = e.stack;
callback(error);
}
}
}
}
}).error(function(res) {
logs.addApplicationLog('Request failed with status: ' + res.status, sasProgram);
callback(new h54sError('httpError', res.statusText));
});
};
/*
* Login method
*
* @param {string} user - Login username
* @param {string} pass - Login password
* @param {function} callback - Callback function called when ajax call is finished
*
* OR
*
* @param {function} callback - Callback function called when ajax call is finished
*
*/
module.exports.login = function(user, pass, callback) {
var self = this;
if(!user || !pass) {
throw new h54sError('argumentError', 'Credentials not set');
}
if(typeof user !== 'string' || typeof pass !== 'string') {
throw new h54sError('argumentError', 'User and pass parameters must be strings');
}
//NOTE: callback optional?
if(!callback || typeof callback !== 'function') {
throw new h54sError('argumentError', 'You must provide callback');
}
var loginParams = {
_sasapp: self.sasApp,
_service: 'default',
ux: user,
px: pass,
//for SAS 9.4,
username: user,
password: pass
};
for (var key in this._aditionalLoginParams) {
loginParams[key] = this._aditionalLoginParams[key];
}
this._ajax.post(this.loginUrl, loginParams).success(function(res) {
if(self._utils.needToLogin.call(self, res)) {
//we are getting form again after redirect
//and need to login again using the new url
//_loginChanged is set in needToLogin function
//but if login url is not different, we are checking if there are aditional parameters
if(self._loginChanged || (self._isNewLoginPage && !self._aditionalLoginParams)) {
delete self._loginChanged;
var inputs = res.responseText.match(/<input.*"hidden"[^>]*>/g);
if(inputs) {
inputs.forEach(function(inputStr) {
var valueMatch = inputStr.match(/name="([^"]*)"\svalue="([^"]*)/);
loginParams[valueMatch[1]] = valueMatch[2];
});
}
var success = this.success, error = this.error;
self._ajax.post(self.loginUrl, loginParams).success(function() {
//we need this get request because of the sas 9.4 security checks
self._ajax.get(self.url).success(success).error(error);
}).error(this.error);
} else {
//getting form again, but it wasn't a redirect
logs.addApplicationLog('Wrong username or password');
callback(-1);
}
} else {
callback(res.status);
self._disableCalls = false;
while(self._pendingCalls.length > 0) {
var pendingCall = self._pendingCalls.shift();
var sasProgram = pendingCall.sasProgram;
var callbackPending = pendingCall.callback;
var params = pendingCall.params;
//update debug because it may change in the meantime
params._debug = self.debug ? 131 : 0;
if(self.retryAfterLogin) {
self.call(sasProgram, null, callbackPending, params);
}
}
}
}).error(function(res) {
//NOTE: error 502 if sasApp parameter is wrong
logs.addApplicationLog('Login failed with status code: ' + res.status);
callback(res.status);
});
};
/*
* Logout method
*
* @param {function} callback - Callback function called when ajax call is finished
*
*/
module.exports.logout = function(callback) {
this._ajax.get(this.url, {_action: 'logoff'}).success(function(res) {
callback();
}).error(function(res) {
logs.addApplicationLog('Logout failed with status code: ' + res.status);
callback(res.status);
});
};
/*
* Enter debug mode
*
*/
module.exports.setDebugMode = function() {
this.debug = true;
};
/*
* Exit debug mode
*
*/
module.exports.unsetDebugMode = function() {
this.debug = false;
};
for(var key in logs.get) {
if(logs.get.hasOwnProperty(key)) {
module.exports[key] = logs.get[key];
}
}
for(var key in logs.clear) {
if(logs.clear.hasOwnProperty(key)) {
module.exports[key] = logs.clear[key];
}
}
/*
* Add callback functions executed when properties are updated with remote config
*
*@callback - callback pushed to array
*
*/
module.exports.onRemoteConfigUpdate = function(callback) {
this.remoteConfigUpdateCallbacks.push(callback);
};
module.exports._utils = require('./utils.js');
},{"../error.js":1,"../logs.js":4,"./utils.js":7}],7:[function(require,module,exports){
var logs = require('../logs.js');
var h54sError = require('../error.js');
var programNotFoundPatt = /<title>(Stored Process Error|SASStoredProcess)<\/title>[\s\S]*<h2>Stored process not found:.*<\/h2>/;
/*
* Parse response from server
*
* @param {object} responseText - response html from the server
* @param {string} sasProgram - sas program path
* @param {object} params - params sent to sas program with addTable
*
*/
module.exports.parseRes = function(responseText, sasProgram, params) {
var matches = responseText.match(programNotFoundPatt);
if(matches) {
throw new h54sError('programNotFound', 'Sas program completed with errors');
}
//remove new lines in json response
return JSON.parse(responseText.replace(/(\r\n|\r|\n)/g, ''));
};
/*
* Parse response from server in debug mode
*
* @param {object} responseText - response html from the server
* @param {string} sasProgram - sas program path
* @param {object} params - params sent to sas program with addTable
*
*/
module.exports.parseDebugRes = function(responseText, sasProgram, params) {
var matches = responseText.match(programNotFoundPatt);
if(matches) {
throw new h54sError('programNotFound', 'Sas program completed with errors');
}
//find json
patt = /^(.?--h54s-data-start--)([\S\s]*?)(--h54s-data-end--)/m;
matches = responseText.match(patt);
var page = responseText.replace(patt, '');
var htmlBodyPatt = /<body.*>([\s\S]*)<\/body>/;
var bodyMatches = page.match(htmlBodyPatt);
//remove html tags
var debugText = bodyMatches[1].replace(/<[^>]*>/g, '');
debugText = this.decodeHTMLEntities(debugText);
logs.addDebugData(bodyMatches[1], debugText, sasProgram, params);
if(this.parseErrorResponse(responseText, sasProgram)) {
throw new h54sError('sasError', 'Sas program completed with errors');
}
if(!matches) {
throw new h54sError('parseError', 'Unable to parse response json');
}
//remove new lines in json response
var jsonObj = JSON.parse(matches[2].replace(/(\r\n|\r|\n)/g, ''));
return jsonObj;
};
/*
* Add failed response to logs - used only if debug=false
*
* @param {object} responseText - response html from the server
* @param {string} sasProgram - sas program path
*
*/
module.exports.addFailedResponse = function(responseText, sasProgram) {
var patt = /<script([\s\S]*)\/form>/;
var patt2 = /display\s?:\s?none;?\s?/;
//remove script with form for toggling the logs and "display:none" from style
responseText = responseText.replace(patt, '').replace(patt2, '');
var debugText = responseText.replace(/<[^>]*>/g, '');
debugText = this.decodeHTMLEntities(debugText);
logs.addFailedRequest(responseText, debugText, sasProgram);
};
/*
* Unescape all string values in returned object
*
* @param {object} obj
*
*/
module.exports.unescapeValues = function(obj) {
for (var key in obj) {
if (typeof obj[key] === 'string') {
obj[key] = decodeURIComponent(obj[key]);
} else if(typeof obj === 'object') {
this.unescapeValues(obj[key]);
}
}
return obj;
};
/*
* Parse error response from server and save errors in memory
*
* @param {string} res - server response
* #param {string} sasProgram - sas program which returned the response
*
*/
module.exports.parseErrorResponse = function(res, sasProgram) {
//capture 'ERROR: [text].' or 'ERROR xx [text].'
var patt = /ERROR(:\s|\s\d\d)(.*\.|.*\n.*\.)/gm;
var errors = res.match(patt);
if(!errors) {
return;
}
var errMessage;
for(var i = 0, n = errors.length; i < n; i++) {
errMessage = errors[i].replace(/<[^>]*>/g, '').replace(/(\n|\s{2,})/g, ' ');
errMessage = this.decodeHTMLEntities(errMessage);
errors[i] = {
sasProgram: sasProgram,
message: errMessage,
time: new Date()
};
}
logs.addSasErrors(errors);
return true;
};
/*
* Decode HTML entities
*
* @param {string} res - server response
*
*/
module.exports.decodeHTMLEntities = function (html) {
var tempElement = document.createElement('span');
var str = html.replace(/&(#(?:x[0-9a-f]+|\d+)|[a-z]+);/gi,
function (str) {
tempElement.innerHTML = str;
str = tempElement.textContent || tempElement.innerText;
return str;
}
);
return str;
};
/*
* Convert sas time to javascript date
*
* @param {number} sasDate - sas Tate object
*
*/
module.exports.fromSasDateTime = function (sasDate) {
var basedate = new Date("January 1, 1960 00:00:00");
var currdate = sasDate;
// offsets for UTC and timezones and BST
var baseOffset = basedate.getTimezoneOffset(); // in minutes
// convert sas datetime to a current valid javascript date
var basedateMs = basedate.getTime(); // in ms
var currdateMs = currdate * 1000; // to ms
var sasDatetime = currdateMs + basedateMs;
var jsDate = new Date();
jsDate.setTime(sasDatetime); // first time to get offset BST daylight savings etc
var currOffset = jsDate.getTimezoneOffset(); // adjust for offset in minutes
var offsetVar = (baseOffset - currOffset) * 60 * 1000; // difference in milliseconds
var offsetTime = sasDatetime - offsetVar; // finding BST and daylight savings
jsDate.setTime(offsetTime); // update with offset
return jsDate;
};
/*
* Convert sas timestamps to javascript Date object
*
* @param {object} obj
*
*/
module.exports.convertDates = function(obj) {
for (var key in obj) {
if (typeof obj[key] === 'number' && (key.indexOf('dt_') === 0 || key.indexOf('DT_') === 0)) {
obj[key] = this.fromSasDateTime(obj[key]);
} else if(typeof obj === 'object') {
this.convertDates(obj[key]);
}
}
return obj;
};
module.exports.needToLogin = function(responseObj) {
var patt = /<form.+action="(.*Logon[^"]*).*>/;
var matches = patt.exec(responseObj.responseText);
var newLoginUrl;
if(!matches) {
//there's no form, we are in. hooray!
return false;
} else {
var actionUrl = matches[1].replace(/\?.*/, '');
if(actionUrl.charAt(0) === '/') {
newLoginUrl = this.hostUrl ? this.hostUrl + actionUrl : actionUrl;
if(newLoginUrl !== this.loginUrl) {
this._loginChanged = true;
this.loginUrl = newLoginUrl;
}
} else {
//relative path
var lastIndOfSlash = responseObj.responseURL.lastIndexOf('/') + 1;
//remove everything after the last slash, and everything until the first
var relativeLoginUrl = responseObj.responseURL.substr(0, lastIndOfSlash).replace(/.*\/{2}[^\/]*/, '') + actionUrl;
newLoginUrl = this.hostUrl ? this.hostUrl + relativeLoginUrl : relativeLoginUrl;
if(newLoginUrl !== this.loginUrl) {
this._loginChanged = true;
this.loginUrl = newLoginUrl;
}
}
//save parameters from hidden form fields
var inputs = responseObj.responseText.match(/<input.*"hidden"[^>]*>/g);
var hiddenFormParams = {};
if(inputs) {
//it's new login page if we have these additional parameters