@sasjs/adapter 5.1.2 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/ContextManager.js +2 -2
  2. package/README.md +14 -0
  3. package/SAS9ApiClient.d.ts +2 -3
  4. package/SAS9ApiClient.js +2 -2
  5. package/SASViyaApiClient.d.ts +0 -1
  6. package/SASViyaApiClient.js +11 -11
  7. package/SASjs.d.ts +6 -2
  8. package/SASjs.js +36 -28
  9. package/SASjsApiClient.d.ts +40 -6
  10. package/SASjsApiClient.js +103 -3
  11. package/SessionManager.js +1 -1
  12. package/api/viya/executeOnComputeApi.js +9 -10
  13. package/api/viya/pollJobState.d.ts +26 -3
  14. package/api/viya/pollJobState.js +29 -13
  15. package/api/viya/saveLog.js +1 -2
  16. package/api/viya/uploadTables.js +1 -2
  17. package/auth/AuthManager.js +2 -2
  18. package/auth/getAccessTokenForSasjs.js +1 -2
  19. package/auth/getAccessTokenForViya.js +1 -2
  20. package/auth/getTokens.js +3 -4
  21. package/auth/openWebPage.js +3 -4
  22. package/auth/refreshTokensForSasjs.js +1 -2
  23. package/auth/refreshTokensForViya.js +1 -2
  24. package/auth/verifySas9Login.js +1 -2
  25. package/auth/verifySasViyaLogin.js +3 -3
  26. package/dist/minified_sas9.js +103 -43
  27. package/dist/sasjs-adapter.js +7449 -7783
  28. package/job-execution/JesJobExecutor.js +2 -2
  29. package/job-execution/Sas9JobExecutor.d.ts +5 -1
  30. package/job-execution/Sas9JobExecutor.js +5 -0
  31. package/job-execution/SasjsJobExecutor.js +2 -2
  32. package/job-execution/WebJobExecutor.js +3 -3
  33. package/minified/sas9/SASjs.js +6 -6
  34. package/minified/sas9/WebJobExecutor.js +2 -2
  35. package/package.json +18 -17
  36. package/request/RequestClient.d.ts +1 -2
  37. package/request/RequestClient.js +10 -10
  38. package/request/Sas9RequestClient.d.ts +22 -5
  39. package/request/Sas9RequestClient.js +90 -22
  40. package/types/SASjsConfig.d.ts +0 -1
  41. package/types/SASjsConfig.js +1 -1
  42. package/types/Session.js +1 -1
  43. package/types/WriteStream.d.ts +0 -2
  44. package/types/errors/UnsafeRedirectError.d.ts +15 -0
  45. package/types/errors/UnsafeRedirectError.js +24 -0
  46. package/types/errors/index.d.ts +1 -0
  47. package/types/errors/index.js +1 -0
  48. package/utils/appendExtraResponseAttributes.js +1 -2
  49. package/utils/asyncForEach.js +1 -2
  50. package/utils/isIeOrEdge.js +1 -2
  51. package/utils/validateInput.d.ts +1 -1
package/ContextManager.js CHANGED
@@ -137,8 +137,8 @@ class ContextManager {
137
137
  return context;
138
138
  });
139
139
  }
140
- createLauncherContext(contextName, description, launchType = 'direct', accessToken) {
141
- return __awaiter(this, void 0, void 0, function* () {
140
+ createLauncherContext(contextName_1, description_1) {
141
+ return __awaiter(this, arguments, void 0, function* (contextName, description, launchType = 'direct', accessToken) {
142
142
  if (!contextName) {
143
143
  throw new Error('Context name is required.');
144
144
  }
package/README.md CHANGED
@@ -116,6 +116,20 @@ sasJs.logIn('USERNAME','PASSWORD'
116
116
 
117
117
  More examples of using authentication, and more, can be found in the [SASjs Seed Apps](https://github.com/search?q=topic%3Asasjs-app+org%3Asasjs+fork%3Atrue) on github.
118
118
 
119
+ ### SAS 9 credentials (deprecated)
120
+
121
+ Earlier versions logged into SAS 9 by passing a username and password, which were appended to the `_program` URL as `_username` and `_password`. This is deprecated.
122
+
123
+ It puts the credentials in a query string - where they are recorded by server logs, proxies, and anything else that logs request URLs - and SAS 9 only accepts them when the platform is configured to allow URL credentials, so it never worked without a server-side change. There is no drop-in replacement for the mechanism itself, and it will be removed in a future major version.
124
+
125
+ It surfaces in three places:
126
+
127
+ - `authConfigSas9` on `executeScript()`
128
+ - the `userName` and `password` arguments of `SAS9ApiClient.executeScript()`
129
+ - `username` and `password` in the job-execution config for `serverType: 'SAS9'`
130
+
131
+ Using it logs a single deprecation warning per process.
132
+
119
133
  ### Request / Response
120
134
 
121
135
  A simple request can be sent to SAS in the following fashion:
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import type * as https from 'https';
3
2
  /**
4
3
  * A client for interfacing with the SAS9 REST API.
@@ -23,8 +22,8 @@ export declare class SAS9ApiClient {
23
22
  /**
24
23
  * Executes code on a SAS9 server.
25
24
  * @param linesOfCode - an array of code lines to execute.
26
- * @param userName - the user name to log into the current SAS server.
27
- * @param password - the password to log into the current SAS server.
25
+ * @param userName - the user name to log into the current SAS server. Deprecated with the SAS 9 username / password login - see the "SAS 9 credentials" note in the README.
26
+ * @param password - the password to log into the current SAS server. Deprecated with the SAS 9 username / password login - see the "SAS 9 credentials" note in the README.
28
27
  */
29
28
  executeScript(linesOfCode: string[], userName: string, password: string): Promise<string>;
30
29
  }
package/SAS9ApiClient.js CHANGED
@@ -48,8 +48,8 @@ class SAS9ApiClient {
48
48
  /**
49
49
  * Executes code on a SAS9 server.
50
50
  * @param linesOfCode - an array of code lines to execute.
51
- * @param userName - the user name to log into the current SAS server.
52
- * @param password - the password to log into the current SAS server.
51
+ * @param userName - the user name to log into the current SAS server. Deprecated with the SAS 9 username / password login - see the "SAS 9 credentials" note in the README.
52
+ * @param password - the password to log into the current SAS server. Deprecated with the SAS 9 username / password login - see the "SAS 9 credentials" note in the README.
53
53
  */
54
54
  executeScript(linesOfCode, userName, password) {
55
55
  return __awaiter(this, void 0, void 0, function* () {
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { Job, Session, Context, ContextAllAttributes, Folder, File, EditContextInput, PollOptions } from './types';
3
2
  import { SasAuthResponse, MacroVar, AuthConfig } from '@sasjs/utils/types';
4
3
  import { RequestClient } from './request/RequestClient';
@@ -180,8 +180,8 @@ class SASViyaApiClient {
180
180
  * @param launchType - launch type of the context to be created.
181
181
  * @param accessToken - an access token for an authorized user.
182
182
  */
183
- createLauncherContext(contextName, description, launchType = 'direct', accessToken) {
184
- return __awaiter(this, void 0, void 0, function* () {
183
+ createLauncherContext(contextName_1, description_1) {
184
+ return __awaiter(this, arguments, void 0, function* (contextName, description, launchType = 'direct', accessToken) {
185
185
  return yield this.contextManager.createLauncherContext(contextName, description, launchType, accessToken);
186
186
  });
187
187
  }
@@ -221,8 +221,8 @@ class SASViyaApiClient {
221
221
  * @param variables - an object that represents macro variables.
222
222
  * @param onTokensRefreshed - optional callback invoked with the rotated token pair after a successful internal refresh, so consumers that persist tokens can store the new pair.
223
223
  */
224
- executeScript(jobPath, linesOfCode, contextName, authConfig, data = null, debug = false, expectWebout = false, waitForResult = true, pollOptions, printPid = false, variables, onTokensRefreshed) {
225
- return __awaiter(this, void 0, void 0, function* () {
224
+ executeScript(jobPath_1, linesOfCode_1, contextName_1, authConfig_1) {
225
+ return __awaiter(this, arguments, void 0, function* (jobPath, linesOfCode, contextName, authConfig, data = null, debug = false, expectWebout = false, waitForResult = true, pollOptions, printPid = false, variables, onTokensRefreshed) {
226
226
  return (0, executeOnComputeApi_1.executeOnComputeApi)(this.requestClient, this.sessionManager, this.rootFolderName, jobPath, linesOfCode, contextName, authConfig, data, debug, expectWebout, waitForResult, pollOptions, printPid, variables, onTokensRefreshed);
227
227
  });
228
228
  }
@@ -291,8 +291,8 @@ class SASViyaApiClient {
291
291
  * @param accessToken - an access token for authorizing the request.
292
292
  */
293
293
  createFile(fileName, contentBuffer, parentFolderPath, parentFolderUri, accessToken) {
294
- var _a;
295
294
  return __awaiter(this, void 0, void 0, function* () {
295
+ var _a;
296
296
  if (!parentFolderPath && !parentFolderUri) {
297
297
  throw new Error('Path or URI of the parent folder is required.');
298
298
  }
@@ -554,8 +554,8 @@ class SASViyaApiClient {
554
554
  * @param printPid - a boolean that indicates whether the function should print (PID) of the started job.
555
555
  * @param variables - an object that represents macro variables.
556
556
  */
557
- executeComputeJob(sasJob, contextName, debug, data, authConfig, waitForResult = true, expectWebout = false, pollOptions, printPid = false, variables, onTokensRefreshed) {
558
- return __awaiter(this, void 0, void 0, function* () {
557
+ executeComputeJob(sasJob_1, contextName_1, debug_1, data_1, authConfig_1) {
558
+ return __awaiter(this, arguments, void 0, function* (sasJob, contextName, debug, data, authConfig, waitForResult = true, expectWebout = false, pollOptions, printPid = false, variables, onTokensRefreshed) {
559
559
  let access_token = (authConfig || {}).access_token;
560
560
  if (authConfig) {
561
561
  ;
@@ -612,8 +612,8 @@ class SASViyaApiClient {
612
612
  * @param onTokensRefreshed - optional callback invoked with the rotated token pair after a successful internal refresh, so consumers that persist tokens can store the new pair.
613
613
  */
614
614
  executeJob(sasJob, contextName, debug, data, authConfig, onTokensRefreshed) {
615
- var _a, _b, _c;
616
615
  return __awaiter(this, void 0, void 0, function* () {
616
+ var _a, _b, _c;
617
617
  let access_token = (authConfig || {}).access_token;
618
618
  if (authConfig) {
619
619
  ;
@@ -766,8 +766,8 @@ class SASViyaApiClient {
766
766
  });
767
767
  }
768
768
  getFileUri(folderPath, fileName, accessToken) {
769
- var _a;
770
769
  return __awaiter(this, void 0, void 0, function* () {
770
+ var _a;
771
771
  const folderMembers = yield this.listFolder(folderPath, accessToken, 1000, {
772
772
  returnDetails: true
773
773
  }).catch((err) => {
@@ -824,8 +824,8 @@ class SASViyaApiClient {
824
824
  * @param {Object} [options] - Additional options.
825
825
  * @param {boolean} [options.returnDetails=false] - when set to true, the function will return an array of objects with member details, otherwise it will return an array of member names.
826
826
  */
827
- listFolder(sourceFolder, accessToken, limit = 20, options) {
828
- return __awaiter(this, void 0, void 0, function* () {
827
+ listFolder(sourceFolder_1, accessToken_1) {
828
+ return __awaiter(this, arguments, void 0, function* (sourceFolder, accessToken, limit = 20, options) {
829
829
  // checks if 'sourceFolder' is already a URI
830
830
  const sourceFolderUri = (0, utils_1.isUri)(sourceFolder)
831
831
  ? sourceFolder
package/SASjs.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { SASjsConfig, UploadFile, EditContextInput, PollOptions, VerboseMode, LoginOptions, LoginResult, ExecutionQuery, Tables } from './types';
3
2
  import { SASViyaApiClient } from './SASViyaApiClient';
4
3
  import { SASjsAuthResponse } from './SASjsApiClient';
@@ -11,6 +10,11 @@ interface ExecuteScriptParams {
11
10
  contextName?: string;
12
11
  runTime?: string;
13
12
  authConfig?: AuthConfig;
13
+ /**
14
+ * @deprecated The credentials are appended to the `_program` query string,
15
+ * which SAS 9 only accepts when the platform is configured to allow URL
16
+ * credentials. See the "SAS 9 credentials" note in the README.
17
+ */
14
18
  authConfigSas9?: AuthConfigSas9;
15
19
  debug?: boolean;
16
20
  onTokensRefreshed?: OnTokensRefreshed;
@@ -42,7 +46,7 @@ export default class SASjs {
42
46
  * @param contextName - (required for server type sas viya) context name on which code will be run on the server.
43
47
  * @param runTime - (required for server type sasjs) a string to represent runTime for code execution.
44
48
  * @param authConfig - (optional) a valid client, secret, refresh and access tokens that are authorised to execute scripts.
45
- * @param authConfigSas9 - (required for server type sas9) a valid username and password that are authorised to execute scripts.
49
+ * @param authConfigSas9 - (required for server type sas9) a valid username and password that are authorised to execute scripts. Deprecated: the credentials are appended to the `_program` query string, which SAS 9 only accepts when the platform is configured to allow URL credentials. See the "SAS 9 credentials" note in the README.
46
50
  * @param debug - (optional) if true, global debug config will be overriden
47
51
  * @param onTokensRefreshed - (optional, SAS Viya only) callback invoked with the rotated token pair after a successful internal refresh, so consumers that persist tokens can store the new pair.
48
52
  */
package/SASjs.js CHANGED
@@ -80,13 +80,13 @@ class SASjs {
80
80
  * @param contextName - (required for server type sas viya) context name on which code will be run on the server.
81
81
  * @param runTime - (required for server type sasjs) a string to represent runTime for code execution.
82
82
  * @param authConfig - (optional) a valid client, secret, refresh and access tokens that are authorised to execute scripts.
83
- * @param authConfigSas9 - (required for server type sas9) a valid username and password that are authorised to execute scripts.
83
+ * @param authConfigSas9 - (required for server type sas9) a valid username and password that are authorised to execute scripts. Deprecated: the credentials are appended to the `_program` query string, which SAS 9 only accepts when the platform is configured to allow URL credentials. See the "SAS 9 credentials" note in the README.
84
84
  * @param debug - (optional) if true, global debug config will be overriden
85
85
  * @param onTokensRefreshed - (optional, SAS Viya only) callback invoked with the rotated token pair after a successful internal refresh, so consumers that persist tokens can store the new pair.
86
86
  */
87
- executeScript({ linesOfCode, fileName, contextName, runTime, authConfig, authConfigSas9, debug, onTokensRefreshed }) {
88
- var _a, _b;
89
- return __awaiter(this, void 0, void 0, function* () {
87
+ executeScript(_a) {
88
+ return __awaiter(this, arguments, void 0, function* ({ linesOfCode, fileName, contextName, runTime, authConfig, authConfigSas9, debug, onTokensRefreshed }) {
89
+ var _b, _c;
90
90
  this.isMethodSupported('executeScript', [
91
91
  types_2.ServerType.Sas9,
92
92
  types_2.ServerType.Sasjs,
@@ -95,10 +95,10 @@ class SASjs {
95
95
  if (this.sasjsConfig.serverType === types_2.ServerType.Sas9) {
96
96
  if (!authConfigSas9)
97
97
  throw new Error('Auth config for sas9 is not provided');
98
- return yield ((_a = this.sas9ApiClient) === null || _a === void 0 ? void 0 : _a.executeScript(linesOfCode, authConfigSas9.userName, authConfigSas9.password));
98
+ return yield ((_b = this.sas9ApiClient) === null || _b === void 0 ? void 0 : _b.executeScript(linesOfCode, authConfigSas9.userName, authConfigSas9.password));
99
99
  }
100
100
  if (this.sasjsConfig.serverType === types_2.ServerType.Sasjs) {
101
- return yield ((_b = this.sasJSApiClient) === null || _b === void 0 ? void 0 : _b.executeScript(linesOfCode.join('\n'), runTime, authConfig));
101
+ return yield ((_c = this.sasJSApiClient) === null || _c === void 0 ? void 0 : _c.executeScript(linesOfCode.join('\n'), runTime, authConfig));
102
102
  }
103
103
  if (this.sasjsConfig.serverType === types_2.ServerType.SasViya) {
104
104
  contextName = contextName || this.sasjsConfig.contextName;
@@ -120,8 +120,8 @@ class SASjs {
120
120
  * @returns a promise that resolves into job execution result and log.
121
121
  */
122
122
  executeJob(query, appLoc, authConfig) {
123
- var _a;
124
123
  return __awaiter(this, void 0, void 0, function* () {
124
+ var _a;
125
125
  this.isMethodSupported('executeScript', [types_2.ServerType.Sasjs]);
126
126
  return yield ((_a = this.sasJSApiClient) === null || _a === void 0 ? void 0 : _a.executeJob(query, appLoc, authConfig));
127
127
  });
@@ -320,8 +320,8 @@ class SASjs {
320
320
  * @param accessToken - an access token for authorizing the request.
321
321
  */
322
322
  deleteFolder(folderPath, accessToken) {
323
- var _a;
324
323
  return __awaiter(this, void 0, void 0, function* () {
324
+ var _a;
325
325
  this.isMethodSupported('deleteFolder', [types_2.ServerType.SasViya]);
326
326
  return yield ((_a = this.sasViyaApiClient) === null || _a === void 0 ? void 0 : _a.deleteFolder(folderPath, accessToken));
327
327
  });
@@ -332,9 +332,9 @@ class SASjs {
332
332
  * @param accessToken - an access token for authorizing the request.
333
333
  * @param returnDetails - when set to true, the function will return an array of objects with member details, otherwise it will return an array of member names.
334
334
  */
335
- listFolder(sourceFolder, accessToken, limit, returnDetails = false) {
336
- var _a;
337
- return __awaiter(this, void 0, void 0, function* () {
335
+ listFolder(sourceFolder_1, accessToken_1, limit_1) {
336
+ return __awaiter(this, arguments, void 0, function* (sourceFolder, accessToken, limit, returnDetails = false) {
337
+ var _a;
338
338
  this.isMethodSupported('listFolder', [types_2.ServerType.SasViya]);
339
339
  return yield ((_a = this.sasViyaApiClient) === null || _a === void 0 ? void 0 : _a.listFolder(sourceFolder, accessToken, limit, {
340
340
  returnDetails
@@ -349,8 +349,8 @@ class SASjs {
349
349
  * @param accessToken - an access token for authorizing the request.
350
350
  */
351
351
  moveFolder(sourceFolder, targetParentFolder, targetFolderName, accessToken) {
352
- var _a;
353
352
  return __awaiter(this, void 0, void 0, function* () {
353
+ var _a;
354
354
  this.isMethodSupported('moveFolder', [types_2.ServerType.SasViya]);
355
355
  return yield ((_a = this.sasViyaApiClient) === null || _a === void 0 ? void 0 : _a.moveFolder(sourceFolder, targetParentFolder, targetFolderName, accessToken));
356
356
  });
@@ -458,8 +458,8 @@ class SASjs {
458
458
  * @param password - a string representing the password.
459
459
  * @param clientId - a string representing the client ID.
460
460
  */
461
- logIn(username, password, clientId, options = {}) {
462
- return __awaiter(this, void 0, void 0, function* () {
461
+ logIn(username_1, password_1, clientId_1) {
462
+ return __awaiter(this, arguments, void 0, function* (username, password, clientId, options = {}) {
463
463
  if (this.sasjsConfig.loginMechanism === types_1.LoginMechanism.Default) {
464
464
  if (!username || !password)
465
465
  throw new Error('A username and password are required when using the default login mechanism.');
@@ -491,8 +491,8 @@ class SASjs {
491
491
  * user is not logged in (eg to display a login form). The request will be
492
492
  * resubmitted after successful login.
493
493
  */
494
- uploadFile(sasJob, files, params, config = {}, loginRequiredCallback) {
495
- return __awaiter(this, void 0, void 0, function* () {
494
+ uploadFile(sasJob_1, files_1, params_1) {
495
+ return __awaiter(this, arguments, void 0, function* (sasJob, files, params, config = {}, loginRequiredCallback) {
496
496
  config = Object.assign(Object.assign({}, this.sasjsConfig), config);
497
497
  const data = { files, params };
498
498
  return yield this.fileUploader.execute(sasJob, data, config, loginRequiredCallback);
@@ -525,8 +525,8 @@ class SASjs {
525
525
  * to provide extra attributes (same names as those values) to be added in response
526
526
  * Supported values are declared in ExtraResponseAttributes type.
527
527
  */
528
- request(sasJob, data, config = {}, loginRequiredCallback, authConfig, extraResponseAttributes = []) {
529
- return __awaiter(this, void 0, void 0, function* () {
528
+ request(sasJob_1, data_1) {
529
+ return __awaiter(this, arguments, void 0, function* (sasJob, data, config = {}, loginRequiredCallback, authConfig, extraResponseAttributes = []) {
530
530
  config = Object.assign(Object.assign({}, this.sasjsConfig), config);
531
531
  const validationResult = (0, utils_1.validateInput)(data);
532
532
  // status is true if the data passes validation checks above
@@ -571,8 +571,8 @@ class SASjs {
571
571
  * using this function from the command line.
572
572
  * @param isForced - flag that indicates if target folder already exists, it and all subfolders have to be deleted.
573
573
  */
574
- deployServicePack(serviceJson, appLoc, serverUrl, accessToken, isForced = false) {
575
- return __awaiter(this, void 0, void 0, function* () {
574
+ deployServicePack(serviceJson_1, appLoc_1, serverUrl_1, accessToken_1) {
575
+ return __awaiter(this, arguments, void 0, function* (serviceJson, appLoc, serverUrl, accessToken, isForced = false) {
576
576
  this.isMethodSupported('deployServicePack', [types_2.ServerType.SasViya]);
577
577
  let sasApiClient = null;
578
578
  if (serverUrl || appLoc) {
@@ -627,21 +627,29 @@ class SASjs {
627
627
  * @param verboseMode - boolean or a string equal to 'bleached' to enable verbose mode (log every HTTP response).
628
628
  * @param onTokensRefreshed - (optional, SAS Viya only) callback invoked with the rotated token pair after a successful internal refresh, so consumers that persist tokens can store the new pair.
629
629
  */
630
- startComputeJob(sasJob, data, config = {}, authConfig, waitForResult, pollOptions, printPid = false, variables, verboseMode, onTokensRefreshed) {
631
- var _a, _b, _c, _d;
632
- return __awaiter(this, void 0, void 0, function* () {
630
+ startComputeJob(sasJob_1, data_1) {
631
+ return __awaiter(this, arguments, void 0, function* (sasJob, data, config = {}, authConfig, waitForResult, pollOptions, printPid = false, variables, verboseMode, onTokensRefreshed) {
632
+ var _a, _b, _c, _d, _e;
633
633
  config = Object.assign(Object.assign({}, this.sasjsConfig), config);
634
- this.isMethodSupported('startComputeJob', [types_2.ServerType.SasViya]);
635
- if (!config.contextName) {
636
- throw new Error('Context name is undefined. Please set a `contextName` in your SASjs or override config.');
637
- }
634
+ this.isMethodSupported('startComputeJob', [
635
+ types_2.ServerType.SasViya,
636
+ types_2.ServerType.Sasjs
637
+ ]);
638
638
  if (verboseMode) {
639
639
  (_a = this.requestClient) === null || _a === void 0 ? void 0 : _a.setVerboseMode(verboseMode);
640
640
  (_b = this.requestClient) === null || _b === void 0 ? void 0 : _b.enableVerboseMode();
641
641
  }
642
642
  else if (verboseMode === false)
643
643
  (_c = this.requestClient) === null || _c === void 0 ? void 0 : _c.disableVerboseMode();
644
- return (_d = this.sasViyaApiClient) === null || _d === void 0 ? void 0 : _d.executeComputeJob(sasJob, config.contextName, config.debug, data, authConfig, !!waitForResult, false, pollOptions, printPid, variables, onTokensRefreshed);
644
+ // A SASjs Server has no compute contexts and no job definitions: the program
645
+ // is a file in the drive, triggered by path. The result carries the same
646
+ // `links` a Viya compute job does, so polling and log retrieval are shared.
647
+ if (this.sasjsConfig.serverType === types_2.ServerType.Sasjs)
648
+ return (_d = this.sasJSApiClient) === null || _d === void 0 ? void 0 : _d.startComputeJob(sasJob, data, config, authConfig, !!waitForResult, pollOptions, printPid, variables, onTokensRefreshed);
649
+ if (!config.contextName) {
650
+ throw new Error('Context name is undefined. Please set a `contextName` in your SASjs or override config.');
651
+ }
652
+ return (_e = this.sasViyaApiClient) === null || _e === void 0 ? void 0 : _e.executeComputeJob(sasJob, config.contextName, config.debug, data, authConfig, !!waitForResult, false, pollOptions, printPid, variables, onTokensRefreshed);
645
653
  });
646
654
  }
647
655
  /**
@@ -1,5 +1,7 @@
1
- import { AuthConfig, ServicePackSASjs } from '@sasjs/utils/types';
2
- import { ExecutionQuery } from './types';
1
+ import { AuthConfig, MacroVar, ServicePackSASjs } from '@sasjs/utils/types';
2
+ import { ExecutionQuery, Job, PollOptions } from './types';
3
+ import { OnTokensRefreshed } from './auth/getTokens';
4
+ import { StateReader } from './api/viya/pollJobState';
3
5
  import { RequestClient } from './request/RequestClient';
4
6
  export interface SASjsAuthResponse {
5
7
  access_token: string;
@@ -10,6 +12,15 @@ export interface ScriptExecutionResult {
10
12
  webout?: string;
11
13
  printOutput?: string;
12
14
  }
15
+ /**
16
+ * How SASjs Server reports the state of a triggered program.
17
+ *
18
+ * Two differences from Viya, both its own to know: the body is JSON with a
19
+ * `state` member (`{ "state": "running" }`) rather than plain text, and
20
+ * `initialising` - a session that exists before the program has started - has
21
+ * no Viya equivalent and is not a terminal state.
22
+ */
23
+ export declare const readSasjsState: StateReader;
13
24
  export declare class SASjsApiClient {
14
25
  private requestClient;
15
26
  constructor(requestClient: RequestClient);
@@ -24,8 +35,8 @@ export declare class SASjsApiClient {
24
35
  deploy(dataJson: ServicePackSASjs, appLoc: string, authConfig?: AuthConfig): Promise<{
25
36
  status: string;
26
37
  message: string;
27
- streamServiceName?: string | undefined;
28
- example?: {} | undefined;
38
+ streamServiceName?: string;
39
+ example?: {};
29
40
  }>;
30
41
  /**
31
42
  * Creates/updates files within SASjs drive using uploaded json compressed file.
@@ -38,8 +49,8 @@ export declare class SASjsApiClient {
38
49
  deployZipFile(zipFilePath: string, authConfig?: AuthConfig): Promise<{
39
50
  status: string;
40
51
  message: string;
41
- streamServiceName?: string | undefined;
42
- example?: {} | undefined;
52
+ streamServiceName?: string;
53
+ example?: {};
43
54
  }>;
44
55
  executeJob(query: ExecutionQuery, appLoc: string, authConfig?: AuthConfig): Promise<{
45
56
  result: any;
@@ -58,6 +69,29 @@ export declare class SASjsApiClient {
58
69
  * @param authCode - the auth code received from the server.
59
70
  */
60
71
  getAccessToken(clientId: string, authCode: string): Promise<SASjsAuthResponse>;
72
+ /**
73
+ * Starts a stored program and returns the job it runs in.
74
+ *
75
+ * The result is the shape a Viya compute job has - an id and `links` with
76
+ * `state` and `log` relations - because that is what `pollJobState`,
77
+ * `fetchLogFileContent` and everything written against them already follow.
78
+ * A caller therefore does not need to know which of the two servers it is
79
+ * talking to.
80
+ *
81
+ * @param sasJob - the path of the program, relative to `appLoc` unless it starts with `/`.
82
+ * @param data - values passed to the program as macro variables.
83
+ * @param config - the SASjs config for this call; `debug` turns on `_debug`.
84
+ * @param authConfig - an access token, or the tokens to mint one from.
85
+ * @param waitForResult - poll until the program finishes before resolving.
86
+ * @param pollOptions - poll interval and maximum attempts, see `pollJobState`.
87
+ * @param printPid - include the OS process id in the job, while it is running.
88
+ * @param variables - macro variables, merged with `data`.
89
+ * @param onTokensRefreshed - called with the rotated token pair after a refresh.
90
+ */
91
+ startComputeJob(sasJob: string, data: any, config: any, authConfig?: AuthConfig, waitForResult?: boolean, pollOptions?: PollOptions, printPid?: boolean, variables?: MacroVar, onTokensRefreshed?: OnTokensRefreshed): Promise<{
92
+ job: Job;
93
+ log: string;
94
+ }>;
61
95
  /**
62
96
  * Exchanges the refresh token for an access token.
63
97
  * @param refreshToken - the refresh token received from the server.
package/SASjsApiClient.js CHANGED
@@ -12,14 +12,31 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
12
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.SASjsApiClient = void 0;
15
+ exports.SASjsApiClient = exports.readSasjsState = void 0;
16
16
  const form_data_1 = __importDefault(require("form-data"));
17
17
  const types_1 = require("@sasjs/utils/types");
18
18
  const error_1 = require("@sasjs/utils/error");
19
+ const pollJobState_1 = require("./api/viya/pollJobState");
20
+ const errors_1 = require("./types/errors");
19
21
  const getAccessTokenForSasjs_1 = require("./auth/getAccessTokenForSasjs");
20
22
  const refreshTokensForSasjs_1 = require("./auth/refreshTokensForSasjs");
21
23
  const getTokens_1 = require("./auth/getTokens");
22
24
  const isNode_1 = require("./utils/isNode");
25
+ /**
26
+ * How SASjs Server reports the state of a triggered program.
27
+ *
28
+ * Two differences from Viya, both its own to know: the body is JSON with a
29
+ * `state` member (`{ "state": "running" }`) rather than plain text, and
30
+ * `initialising` - a session that exists before the program has started - has
31
+ * no Viya equivalent and is not a terminal state.
32
+ */
33
+ const readSasjsState = (body) => {
34
+ const state = typeof body === 'string' ? body.trim() : body === null || body === void 0 ? void 0 : body.state;
35
+ if (state === 'initialising')
36
+ return pollJobState_1.JobState.Pending;
37
+ return (state !== null && state !== void 0 ? state : '');
38
+ };
39
+ exports.readSasjsState = readSasjsState;
23
40
  class SASjsApiClient {
24
41
  constructor(requestClient) {
25
42
  this.requestClient = requestClient;
@@ -89,8 +106,8 @@ class SASjsApiClient {
89
106
  * @param runTime - a string to representing runTime for code execution
90
107
  * @param authConfig - an object for authentication.
91
108
  */
92
- executeScript(code, runTime = 'sas', authConfig) {
93
- return __awaiter(this, void 0, void 0, function* () {
109
+ executeScript(code_1) {
110
+ return __awaiter(this, arguments, void 0, function* (code, runTime = 'sas', authConfig) {
94
111
  const access_token = yield this.getAccessTokenForRequest(authConfig);
95
112
  const executionResult = { log: '' };
96
113
  yield this.requestClient
@@ -119,6 +136,89 @@ class SASjsApiClient {
119
136
  return (0, getAccessTokenForSasjs_1.getAccessTokenForSasjs)(this.requestClient, clientId, authCode);
120
137
  });
121
138
  }
139
+ /**
140
+ * Starts a stored program and returns the job it runs in.
141
+ *
142
+ * The result is the shape a Viya compute job has - an id and `links` with
143
+ * `state` and `log` relations - because that is what `pollJobState`,
144
+ * `fetchLogFileContent` and everything written against them already follow.
145
+ * A caller therefore does not need to know which of the two servers it is
146
+ * talking to.
147
+ *
148
+ * @param sasJob - the path of the program, relative to `appLoc` unless it starts with `/`.
149
+ * @param data - values passed to the program as macro variables.
150
+ * @param config - the SASjs config for this call; `debug` turns on `_debug`.
151
+ * @param authConfig - an access token, or the tokens to mint one from.
152
+ * @param waitForResult - poll until the program finishes before resolving.
153
+ * @param pollOptions - poll interval and maximum attempts, see `pollJobState`.
154
+ * @param printPid - include the OS process id in the job, while it is running.
155
+ * @param variables - macro variables, merged with `data`.
156
+ * @param onTokensRefreshed - called with the rotated token pair after a refresh.
157
+ */
158
+ startComputeJob(sasJob_1, data_1, config_1, authConfig_1) {
159
+ return __awaiter(this, arguments, void 0, function* (sasJob, data, config, authConfig, waitForResult = true, pollOptions, printPid = false, variables, onTokensRefreshed) {
160
+ var _a, _b, _c;
161
+ const access_token = yield this.getAccessTokenForRequest(authConfig);
162
+ const _program = sasJob.startsWith('/')
163
+ ? sasJob
164
+ : `${(_a = config.appLoc) !== null && _a !== void 0 ? _a : ''}/${sasJob}`;
165
+ // Every query parameter becomes a macro variable, the same way the
166
+ // synchronous execute endpoint builds them. `_program` and `_debug` are
167
+ // reserved: they are set below from the arguments, so a payload or a macro
168
+ // variable set that happens to carry either key cannot redirect the call to
169
+ // a different program.
170
+ const query = new URLSearchParams();
171
+ const reserved = new Set(['_program', '_debug']);
172
+ for (const [key, value] of Object.entries(Object.assign(Object.assign({}, (data !== null && data !== void 0 ? data : {})), (variables !== null && variables !== void 0 ? variables : {}))))
173
+ if (!reserved.has(key) && value !== undefined && value !== null)
174
+ query.set(key, String(value));
175
+ query.set('_program', _program);
176
+ if (config.debug)
177
+ query.set('_debug', '131');
178
+ const { result } = yield this.requestClient
179
+ .post(`SASjsApi/stp/trigger?${query.toString()}`, {}, access_token)
180
+ .catch((err) => {
181
+ throw (0, error_1.prefixMessage)(err, 'Error while triggering the program. ');
182
+ });
183
+ // The trigger answers 200 with a failure body when the program cannot be
184
+ // found or the runtime refuses it, so a missing session id is the only
185
+ // signal that the call did not start anything. Without this the caller gets
186
+ // links built from `undefined` and the failure surfaces later as a 404 on a
187
+ // state URL.
188
+ if (!(result === null || result === void 0 ? void 0 : result.sessionId))
189
+ throw new Error(`Error while triggering the program. ${(_c = (_b = result === null || result === void 0 ? void 0 : result.error) !== null && _b !== void 0 ? _b : result === null || result === void 0 ? void 0 : result.message) !== null && _c !== void 0 ? _c : 'No session id was returned.'}`);
190
+ // absolute paths, as Viya job links are: a caller composes `${serverUrl}${href}`
191
+ // to fetch a log, so a relative href turns into `https://hostsasjsapi/...`
192
+ const links = [
193
+ {
194
+ rel: 'state',
195
+ href: `/SASjsApi/session/${result.sessionId}/state`,
196
+ method: 'GET'
197
+ },
198
+ {
199
+ rel: 'log',
200
+ href: `/SASjsApi/session/${result.sessionId}/log`,
201
+ method: 'GET'
202
+ },
203
+ {
204
+ rel: 'self',
205
+ href: `/SASjsApi/session/${result.sessionId}`,
206
+ method: 'GET'
207
+ }
208
+ ];
209
+ const job = Object.assign({ id: result.sessionId, links }, (printPid && result.pid !== undefined ? { pid: result.pid } : {}));
210
+ if (!waitForResult)
211
+ return { job, log: '' };
212
+ const state = yield (0, pollJobState_1.pollJobState)(this.requestClient, job, !!config.debug, authConfig, pollOptions, undefined, onTokensRefreshed, types_1.ServerType.Sasjs, exports.readSasjsState);
213
+ const { result: log } = yield this.requestClient
214
+ .get(`SASjsApi/session/${result.sessionId}/log`, access_token, 'text/plain')
215
+ .catch(() => ({ result: '' }));
216
+ const finished = Object.assign(Object.assign({}, job), { state });
217
+ if (state === pollJobState_1.JobState.Failed || state === pollJobState_1.JobState.Error)
218
+ throw new errors_1.ComputeJobExecutionError(finished, log !== null && log !== void 0 ? log : '');
219
+ return { job: finished, log: log !== null && log !== void 0 ? log : '' };
220
+ });
221
+ }
122
222
  /**
123
223
  * Exchanges the refresh token for an access token.
124
224
  * @param refreshToken - the refresh token received from the server.
package/SessionManager.js CHANGED
@@ -268,8 +268,8 @@ class SessionManager {
268
268
  * @returns - a promise which resolves with a session state.
269
269
  */
270
270
  waitForSession(session, etag, accessToken) {
271
- var _a;
272
271
  return __awaiter(this, void 0, void 0, function* () {
272
+ var _a;
273
273
  let { state: sessionState } = session;
274
274
  const { stateUrl } = session;
275
275
  const logger = (0, host_1.getLogger)();
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.executeOnComputeApi = void 0;
12
+ exports.executeOnComputeApi = executeOnComputeApi;
13
13
  const time_1 = require("@sasjs/utils/time");
14
14
  const types_1 = require("@sasjs/utils/types");
15
15
  const error_1 = require("@sasjs/utils/error");
@@ -35,9 +35,9 @@ const host_1 = require("../../utils/host");
35
35
  * @param variables - an object that represents macro variables.
36
36
  * @param onTokensRefreshed - optional callback invoked with the rotated token pair after a successful internal refresh, so consumers that persist tokens can store the new pair.
37
37
  */
38
- function executeOnComputeApi(requestClient, sessionManager, rootFolderName, jobPath, linesOfCode, contextName, authConfig, data = null, debug = false, expectWebout = false, waitForResult = true, pollOptions, printPid = false, variables, onTokensRefreshed) {
39
- var _a, _b;
40
- return __awaiter(this, void 0, void 0, function* () {
38
+ function executeOnComputeApi(requestClient_1, sessionManager_1, rootFolderName_1, jobPath_1, linesOfCode_1, contextName_1, authConfig_1) {
39
+ return __awaiter(this, arguments, void 0, function* (requestClient, sessionManager, rootFolderName, jobPath, linesOfCode, contextName, authConfig, data = null, debug = false, expectWebout = false, waitForResult = true, pollOptions, printPid = false, variables, onTokensRefreshed) {
40
+ var _a, _b;
41
41
  let access_token = (authConfig || {}).access_token;
42
42
  if (authConfig) {
43
43
  ;
@@ -124,11 +124,11 @@ function executeOnComputeApi(requestClient, sessionManager, rootFolderName, jobP
124
124
  session,
125
125
  sessionManager
126
126
  }, onTokensRefreshed).catch((err) => __awaiter(this, void 0, void 0, function* () {
127
- var _c, _d;
128
- const error = (_c = err === null || err === void 0 ? void 0 : err.response) === null || _c === void 0 ? void 0 : _c.data;
127
+ var _a, _b;
128
+ const error = (_a = err === null || err === void 0 ? void 0 : err.response) === null || _a === void 0 ? void 0 : _a.data;
129
129
  const result = /err=[0-9]*,/.exec(error);
130
130
  const errorCode = '5113';
131
- if (((_d = result === null || result === void 0 ? void 0 : result[0]) === null || _d === void 0 ? void 0 : _d.slice(4, -1)) === errorCode) {
131
+ if (((_b = result === null || result === void 0 ? void 0 : result[0]) === null || _b === void 0 ? void 0 : _b.slice(4, -1)) === errorCode) {
132
132
  const logCount = 1000000;
133
133
  const sessionLogUrl = postedJob.links.find((l) => l.rel === 'up').href + '/log';
134
134
  err.log = yield (0, utils_1.fetchLogByChunks)(requestClient, access_token, sessionLogUrl, logCount);
@@ -161,11 +161,11 @@ function executeOnComputeApi(requestClient, sessionManager, rootFolderName, jobP
161
161
  jobResult = yield requestClient
162
162
  .get(resultLink, access_token, 'text/plain')
163
163
  .catch((e) => __awaiter(this, void 0, void 0, function* () {
164
- var _e, _f;
164
+ var _a, _b;
165
165
  if (e instanceof __1.NotFoundError) {
166
166
  if (logLink) {
167
167
  const logUrl = `${logLink.href}/content`;
168
- const logCount = (_f = (_e = currentJob.logStatistics) === null || _e === void 0 ? void 0 : _e.lineCount) !== null && _f !== void 0 ? _f : 1000000;
168
+ const logCount = (_b = (_a = currentJob.logStatistics) === null || _a === void 0 ? void 0 : _a.lineCount) !== null && _b !== void 0 ? _b : 1000000;
169
169
  log = yield (0, utils_1.fetchLogByChunks)(requestClient, access_token, logUrl, logCount);
170
170
  return Promise.reject({
171
171
  status: 500,
@@ -195,4 +195,3 @@ function executeOnComputeApi(requestClient, sessionManager, rootFolderName, jobP
195
195
  }
196
196
  });
197
197
  }
198
- exports.executeOnComputeApi = executeOnComputeApi;