@sasjs/adapter 6.2.1 → 6.3.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.
@@ -1,6 +1,6 @@
1
+ import { AuthConfig } from './auth/AuthConfig';
1
2
  import { Context, EditContextInput, ContextAllAttributes } from './types';
2
3
  import { RequestClient } from './request/RequestClient';
3
- import { AuthConfig } from '@sasjs/utils/types';
4
4
  export declare class ContextManager {
5
5
  private serverUrl;
6
6
  private requestClient;
package/README.md CHANGED
@@ -109,6 +109,17 @@ sasJs.logIn('USERNAME','PASSWORD'
109
109
 
110
110
  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.
111
111
 
112
+ ### Viya client credentials
113
+
114
+ For noninteractive Viya execution, supply an application identity as `authConfig`:
115
+
116
+ ```typescript
117
+ const auth = { grantType: 'client_credentials' as const, client: 'client-id', secret: 'client-secret' }
118
+ await sasJs.executeScript({ linesOfCode: ['%put hello;'], authConfig: auth })
119
+ ```
120
+
121
+ The adapter requests an access token from SASLogon and reacquires it on expiry; this grant does not use a refresh token. The grant needs the client secret, so use it only where that secret stays private, such as a CLI or a server process, and not in an app delivered to a browser. The Viya client must have the permissions required by the requested operations. `SASViyaApiClient.withAccessTokenProvider(provider)` returns an independent client resolving a token per HTTP operation. `deployServicePack` also accepts such a provider in place of its access-token argument.
122
+
112
123
  ### SAS 9 credentials (deprecated)
113
124
 
114
125
  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.
@@ -1,5 +1,6 @@
1
1
  import { Job, Session, Context, ContextAllAttributes, Folder, File, EditContextInput, PollOptions } from './types';
2
- import { SasAuthResponse, MacroVar, AuthConfig } from '@sasjs/utils/types';
2
+ import { AuthConfig } from './auth/AuthConfig';
3
+ import { SasAuthResponse, MacroVar } from '@sasjs/utils/types';
3
4
  import { RequestClient } from './request/RequestClient';
4
5
  import { OnTokensRefreshed } from './auth/getTokens';
5
6
  import { FileResource } from './types/FileResource';
@@ -25,9 +26,13 @@ export declare class SASViyaApiClient {
25
26
  private contextManager;
26
27
  private folderMap;
27
28
  private folderMapGeneration;
29
+ private hasTokenProvider;
30
+ private providerBase?;
28
31
  invalidateFolderCache(): void;
29
32
  private fileExtensionMap;
30
33
  private boolExtensionMap;
34
+ /** Return a Viya client that resolves the bearer before every request. */
35
+ withAccessTokenProvider(provider: () => Promise<string> | string): SASViyaApiClient;
31
36
  /**
32
37
  * A helper method used to call appendRequest method of RequestClient
33
38
  * @param response - response from sasjs request
@@ -32,6 +32,11 @@ const refreshTokensForViya_1 = require("./auth/refreshTokensForViya");
32
32
  const host_1 = require("./utils/host");
33
33
  const NotFoundError_1 = require("./types/errors/NotFoundError");
34
34
  const validateForcedServicePack_1 = require("./utils/validateForcedServicePack");
35
+ class TokenProviderError extends Error {
36
+ constructor(error) {
37
+ super(error instanceof Error ? error.message : String(error));
38
+ }
39
+ }
35
40
  /**
36
41
  * A client for interfacing with the SAS Viya REST API.
37
42
  *
@@ -47,6 +52,7 @@ class SASViyaApiClient {
47
52
  this.contextManager = new ContextManager_1.ContextManager(this.serverUrl, this.requestClient);
48
53
  this.folderMap = new Map();
49
54
  this.folderMapGeneration = 0;
55
+ this.hasTokenProvider = false;
50
56
  this.fileExtensionMap = new Map();
51
57
  this.boolExtensionMap = false; // required in case the map has zero entries
52
58
  if (serverUrl)
@@ -57,6 +63,45 @@ class SASViyaApiClient {
57
63
  this.folderMap.clear();
58
64
  }
59
65
  // after an attempt to populate it.
66
+ /** Return a Viya client that resolves the bearer before every request. */
67
+ withAccessTokenProvider(provider) {
68
+ const positions = {
69
+ get: 1,
70
+ delete: 1,
71
+ post: 2,
72
+ put: 2,
73
+ patch: 2,
74
+ uploadFile: 2
75
+ };
76
+ const base = this.providerBase || this.requestClient;
77
+ const requestClient = new Proxy(base, {
78
+ get(target, property) {
79
+ const value = Reflect.get(target, property, target);
80
+ if (typeof value !== 'function')
81
+ return value;
82
+ if (typeof property === 'string' &&
83
+ Object.prototype.hasOwnProperty.call(positions, property)) {
84
+ return (...args) => __awaiter(this, void 0, void 0, function* () {
85
+ if (property === 'post' && args[0] === '/SASLogon/oauth/token')
86
+ return value.apply(target, args);
87
+ try {
88
+ args[positions[property]] = yield provider();
89
+ }
90
+ catch (error) {
91
+ throw new TokenProviderError(error);
92
+ }
93
+ return value.apply(target, args);
94
+ });
95
+ }
96
+ return value.bind(target);
97
+ }
98
+ });
99
+ const client = new SASViyaApiClient(this.serverUrl, this.rootFolderName, this.contextName, requestClient);
100
+ client.hasTokenProvider = true;
101
+ client.providerBase = base;
102
+ client.debug = this.debug;
103
+ return client;
104
+ }
60
105
  /**
61
106
  * A helper method used to call appendRequest method of RequestClient
62
107
  * @param response - response from sasjs request
@@ -230,6 +275,12 @@ class SASViyaApiClient {
230
275
  */
231
276
  executeScript(jobPath_1, linesOfCode_1, contextName_1, authConfig_1) {
232
277
  return __awaiter(this, arguments, void 0, function* (jobPath, linesOfCode, contextName, authConfig, data = null, debug = false, expectWebout = false, waitForResult = true, pollOptions, printPid = false, variables, onTokensRefreshed) {
278
+ if (authConfig &&
279
+ 'grantType' in authConfig &&
280
+ authConfig.grantType === 'client_credentials' &&
281
+ !this.hasTokenProvider) {
282
+ return this.withAccessTokenProvider(() => __awaiter(this, void 0, void 0, function* () { return (yield (0, getTokens_1.getTokens)(this.requestClient, authConfig)).access_token; })).executeScript(jobPath, linesOfCode, contextName, authConfig, data, debug, expectWebout, waitForResult, pollOptions, printPid, variables, onTokensRefreshed);
283
+ }
233
284
  return (0, executeOnComputeApi_1.executeOnComputeApi)(this.requestClient, this.sessionManager, this.rootFolderName, jobPath, linesOfCode, contextName, authConfig, data, debug, expectWebout, waitForResult, pollOptions, printPid, variables, onTokensRefreshed);
234
285
  });
235
286
  }
@@ -814,6 +865,12 @@ class SASViyaApiClient {
814
865
  */
815
866
  executeComputeJob(sasJob_1, contextName_1, debug_1, data_1, authConfig_1) {
816
867
  return __awaiter(this, arguments, void 0, function* (sasJob, contextName, debug, data, authConfig, waitForResult = true, expectWebout = false, pollOptions, printPid = false, variables, onTokensRefreshed) {
868
+ if (authConfig &&
869
+ 'grantType' in authConfig &&
870
+ authConfig.grantType === 'client_credentials' &&
871
+ !this.hasTokenProvider) {
872
+ return this.withAccessTokenProvider(() => __awaiter(this, void 0, void 0, function* () { return (yield (0, getTokens_1.getTokens)(this.requestClient, authConfig)).access_token; })).executeComputeJob(sasJob, contextName, debug, data, authConfig, waitForResult, expectWebout, pollOptions, printPid, variables, onTokensRefreshed);
873
+ }
817
874
  let access_token = (authConfig || {}).access_token;
818
875
  if (authConfig) {
819
876
  ;
@@ -872,6 +929,12 @@ class SASViyaApiClient {
872
929
  executeJob(sasJob, contextName, debug, data, authConfig, onTokensRefreshed) {
873
930
  return __awaiter(this, void 0, void 0, function* () {
874
931
  var _a, _b, _c;
932
+ if (authConfig &&
933
+ 'grantType' in authConfig &&
934
+ authConfig.grantType === 'client_credentials' &&
935
+ !this.hasTokenProvider) {
936
+ return this.withAccessTokenProvider(() => __awaiter(this, void 0, void 0, function* () { return (yield (0, getTokens_1.getTokens)(this.requestClient, authConfig)).access_token; })).executeJob(sasJob, contextName, debug, data, authConfig, onTokensRefreshed);
937
+ }
875
938
  let access_token = (authConfig || {}).access_token;
876
939
  if (authConfig) {
877
940
  ;
@@ -1023,7 +1086,8 @@ class SASViyaApiClient {
1023
1086
  const { result: folder } = yield this.requestClient
1024
1087
  .get(`${this.serverUrl}${url}`, accessToken)
1025
1088
  .catch((err) => {
1026
- if (err instanceof errors_1.CertificateError)
1089
+ if (err instanceof errors_1.CertificateError ||
1090
+ err instanceof TokenProviderError)
1027
1091
  throw err;
1028
1092
  return { result: null };
1029
1093
  });
@@ -1062,7 +1126,8 @@ class SASViyaApiClient {
1062
1126
  const { result: folder } = yield this.requestClient
1063
1127
  .get(`${this.serverUrl}${url}`, accessToken)
1064
1128
  .catch((err) => {
1065
- if (err instanceof errors_1.CertificateError)
1129
+ if (err instanceof errors_1.CertificateError ||
1130
+ err instanceof TokenProviderError)
1066
1131
  throw err;
1067
1132
  return { result: null };
1068
1133
  });
package/SASjs.d.ts CHANGED
@@ -2,7 +2,8 @@ import { SASjsConfig, UploadFile, EditContextInput, PollOptions, VerboseMode, Lo
2
2
  import { SASViyaApiClient } from './SASViyaApiClient';
3
3
  import { SASjsAuthResponse } from './SASjsApiClient';
4
4
  import { OnTokensRefreshed } from './auth/getTokens';
5
- import { MacroVar, AuthConfig, ExtraResponseAttributes, SasAuthResponse, AuthConfigSas9 } from '@sasjs/utils/types';
5
+ import { AuthConfig } from './auth/AuthConfig';
6
+ import { MacroVar, ExtraResponseAttributes, SasAuthResponse, AuthConfigSas9 } from '@sasjs/utils/types';
6
7
  import { AxiosResponse, AxiosError } from 'axios';
7
8
  interface ExecuteScriptParams {
8
9
  linesOfCode: string[];
@@ -364,7 +365,7 @@ export default class SASjs {
364
365
  * @param isForced - move the entire existing appLoc to the recycle bin before deploying (including content omitted from this pack); defaults to false. Requires exclusive control of appLoc, its parent and recycle bin. A failure may leave an incomplete app; see README for recovery.
365
366
  * @param onProgress - called immediately before each pack member is written, with its name, folder, type and 1-based position.
366
367
  */
367
- deployServicePack(serviceJson: any, appLoc?: string, serverUrl?: string, accessToken?: string, isForced?: boolean, onProgress?: (progress: DeployProgress) => void): Promise<void>;
368
+ deployServicePack(serviceJson: any, appLoc?: string, serverUrl?: string, accessToken?: string | (() => Promise<string> | string), isForced?: boolean, onProgress?: (progress: DeployProgress) => void): Promise<void>;
368
369
  /**
369
370
  * Kicks off execution of the given job via the compute API.
370
371
  * @returns an object representing the compute session created for the given job.
package/SASjs.js CHANGED
@@ -622,6 +622,8 @@ class SASjs {
622
622
  return __awaiter(this, arguments, void 0, function* (serviceJson, appLoc, serverUrl, accessToken, isForced = false, onProgress) {
623
623
  var _a, _b, _c;
624
624
  this.isMethodSupported('deployServicePack', [types_2.ServerType.SasViya]);
625
+ const tokenProvider = typeof accessToken === 'function' ? accessToken : undefined;
626
+ const staticToken = typeof accessToken === 'string' ? accessToken : undefined;
625
627
  let sasApiClient = null;
626
628
  if (serverUrl !== undefined || appLoc !== undefined) {
627
629
  if (serverUrl === undefined)
@@ -670,14 +672,16 @@ class SASjs {
670
672
  if (serverUrl === this.sasjsConfig.serverUrl)
671
673
  deploymentClient.copyCsrfFrom(this.requestClient);
672
674
  deploymentClient.restrictDeploymentTransport();
673
- const api = new SASViyaApiClient_1.SASViyaApiClient(serverUrl, appLoc, this.sasjsConfig.contextName, deploymentClient);
675
+ let api = new SASViyaApiClient_1.SASViyaApiClient(serverUrl, appLoc, this.sasjsConfig.contextName, deploymentClient);
676
+ if (tokenProvider)
677
+ api = api.withAccessTokenProvider(tokenProvider);
674
678
  (_a = this.sasViyaApiClient) === null || _a === void 0 ? void 0 : _a.invalidateFolderCache();
675
679
  try {
676
- const { parentId, recycled } = yield api.recycleDeploymentFolder(appLoc, accessToken);
680
+ const { parentId, recycled } = yield api.recycleDeploymentFolder(appLoc, staticToken);
677
681
  try {
678
682
  const parent = appLoc.slice(0, appLoc.lastIndexOf('/'));
679
683
  const name = appLoc.slice(appLoc.lastIndexOf('/') + 1);
680
- const root = yield api.createFolder(name, parent, `/folders/folders/${parentId}`, accessToken, false);
684
+ const root = yield api.createFolder(name, parent, `/folders/folders/${parentId}`, staticToken, false);
681
685
  if (!root ||
682
686
  root.name !== name ||
683
687
  root.parentFolderUri !== `/folders/folders/${parentId}` ||
@@ -685,7 +689,7 @@ class SASjs {
685
689
  typeof root.id !== 'string' ||
686
690
  !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(root.id))
687
691
  throw new Error('Invalid created app folder identity');
688
- yield this.createFoldersAndServices(appLoc, serviceJson.members, accessToken, api, false, {
692
+ yield this.createFoldersAndServices(appLoc, serviceJson.members, staticToken, api, false, {
689
693
  onProgress,
690
694
  index: 0,
691
695
  total: countMembers(serviceJson.members),
@@ -709,7 +713,9 @@ class SASjs {
709
713
  serviceJson.members[0].members.sort((member) => member.type === 'folder' ? -1 : 1);
710
714
  }
711
715
  const members = serviceJson.members;
712
- yield this.createFoldersAndServices(appLoc, members, accessToken, sasApiClient, isForced, { onProgress, index: 0, total: countMembers(members), strict: false });
716
+ if (tokenProvider)
717
+ sasApiClient = (sasApiClient || this.sasViyaApiClient).withAccessTokenProvider(tokenProvider);
718
+ yield this.createFoldersAndServices(appLoc, members, staticToken, sasApiClient, isForced, { onProgress, index: 0, total: countMembers(members), strict: false });
713
719
  });
714
720
  }
715
721
  /**
@@ -1,4 +1,5 @@
1
- import { AuthConfig, MacroVar, ServicePackSASjs } from '@sasjs/utils/types';
1
+ import { AuthConfig } from './auth/AuthConfig';
2
+ import { MacroVar, ServicePackSASjs } from '@sasjs/utils/types';
2
3
  import { ExecutionQuery, Job, PollOptions } from './types';
3
4
  import { OnTokensRefreshed } from './auth/getTokens';
4
5
  import { StateReader } from './api/viya/pollJobState';
@@ -1,4 +1,5 @@
1
- import { AuthConfig, MacroVar } from '@sasjs/utils/types';
1
+ import { AuthConfig } from '../../auth/AuthConfig';
2
+ import { MacroVar } from '@sasjs/utils/types';
2
3
  import { PollOptions } from '../..';
3
4
  import { OnTokensRefreshed } from '../../auth/getTokens';
4
5
  import { RequestClient } from '../../request/RequestClient';
@@ -1,4 +1,5 @@
1
- import { AuthConfig, ServerType } from '@sasjs/utils/types';
1
+ import { AuthConfig } from '../../auth/AuthConfig';
2
+ import { ServerType } from '@sasjs/utils/types';
2
3
  import { Job, PollOptions } from '../..';
3
4
  import { OnTokensRefreshed } from '../../auth/getTokens';
4
5
  import { RequestClient } from '../../request/RequestClient';
@@ -0,0 +1,11 @@
1
+ import { AuthConfig as UserAuthConfig } from '@sasjs/utils/types';
2
+ /** Viya client credentials are opt-in; existing user-token configurations remain supported. */
3
+ export type AuthConfig = UserAuthConfig | (UserAuthConfig & {
4
+ grantType: 'authorization_code';
5
+ }) | {
6
+ grantType: 'client_credentials';
7
+ client: string;
8
+ secret: string;
9
+ access_token?: string;
10
+ refresh_token?: string;
11
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,4 +1,5 @@
1
- import { AuthConfig, ServerType } from '@sasjs/utils/types';
1
+ import { AuthConfig } from './AuthConfig';
2
+ import { ServerType } from '@sasjs/utils/types';
2
3
  import { RequestClient } from '../request/RequestClient';
3
4
  /**
4
5
  * Callback invoked with the rotated token pair after a successful internal
package/auth/getTokens.js CHANGED
@@ -14,8 +14,90 @@ const auth_1 = require("@sasjs/utils/auth");
14
14
  const types_1 = require("@sasjs/utils/types");
15
15
  const refreshTokensForViya_1 = require("./refreshTokensForViya");
16
16
  const refreshTokensForSasjs_1 = require("./refreshTokensForSasjs");
17
+ const getTokenRequestErrorPrefix_1 = require("./getTokenRequestErrorPrefix");
18
+ const errors_1 = require("../types/errors");
17
19
  const host_1 = require("../utils/host");
18
20
  const apiBasePath_1 = require("../apiBasePath");
21
+ const clientTokens = new WeakMap();
22
+ /**
23
+ * Returns the auth configuration for a Viya client-credentials identity,
24
+ * requesting an access token when there is none or the held one has expired.
25
+ * This grant has no refresh token.
26
+ *
27
+ * The token is also written to `authConfig.access_token`, as the user-token
28
+ * path below does: code further down an execution chain (the job poll, for
29
+ * one) reads the token from the shared `authConfig`, not from this return
30
+ * value.
31
+ *
32
+ * A token's lifetime is counted from the moment the request was sent, so the
33
+ * held token is dropped no later than the server's own expiry. No further
34
+ * margin is subtracted. A response that states no `expires_in` is never held:
35
+ * the next call requests a new token.
36
+ * @param requestClient - the pre-configured HTTP request client
37
+ * @param authConfig - the client ID and secret, with `grantType` set to
38
+ * `client_credentials`
39
+ * @param serverType - must be SASVIYA.
40
+ */
41
+ function getClientCredentialsTokens(requestClient, authConfig, serverType) {
42
+ return __awaiter(this, void 0, void 0, function* () {
43
+ const { client, secret } = authConfig;
44
+ if (serverType !== types_1.ServerType.SasViya)
45
+ throw new Error('Client credentials require SAS Viya');
46
+ if (!client || !secret)
47
+ throw new Error('Client credentials require a client and secret');
48
+ const baseUrl = requestClient.getBaseUrl();
49
+ let state = clientTokens.get(authConfig);
50
+ if (!state ||
51
+ state.client !== client ||
52
+ state.secret !== secret ||
53
+ state.baseUrl !== baseUrl) {
54
+ state = { token: '', expiresAt: 0, client, secret, baseUrl };
55
+ clientTokens.set(authConfig, state);
56
+ }
57
+ let access_token;
58
+ if (!state.token || Date.now() >= state.expiresAt) {
59
+ if (!state.pending) {
60
+ const tokenState = state;
61
+ const requestedAt = Date.now();
62
+ const pair = `${client}:${secret}`;
63
+ const url = '/SASLogon/oauth/token';
64
+ const data = 'grant_type=client_credentials';
65
+ const headers = {
66
+ Authorization: 'Basic ' +
67
+ (typeof Buffer === 'undefined'
68
+ ? btoa(pair)
69
+ : Buffer.from(pair).toString('base64')),
70
+ 'Content-Type': 'application/x-www-form-urlencoded'
71
+ };
72
+ state.pending = requestClient
73
+ .post(url, data, undefined, 'application/x-www-form-urlencoded', headers)
74
+ .catch((err) => {
75
+ if (err instanceof errors_1.CertificateError)
76
+ throw err;
77
+ throw (0, getTokenRequestErrorPrefix_1.tokenRequestErrorMessage)(err, 'fetching access token', 'getTokens', types_1.ServerType.SasViya, url, data, headers, client, secret);
78
+ })
79
+ .then(({ result }) => {
80
+ if (!(result === null || result === void 0 ? void 0 : result.access_token))
81
+ throw new Error('Client credentials response did not contain an access token');
82
+ const expiresAt = requestedAt + (Number(result.expires_in) || 0) * 1000;
83
+ if (result.expires_in != null && Date.now() >= expiresAt)
84
+ throw new Error('Client credentials access token expired before receipt');
85
+ tokenState.token = result.access_token;
86
+ tokenState.expiresAt = expiresAt;
87
+ return tokenState.token;
88
+ })
89
+ .finally(() => {
90
+ tokenState.pending = undefined;
91
+ });
92
+ }
93
+ access_token = yield state.pending;
94
+ }
95
+ else
96
+ access_token = state.token;
97
+ authConfig.access_token = access_token;
98
+ return Object.assign(Object.assign({}, authConfig), { access_token });
99
+ });
100
+ }
19
101
  /**
20
102
  * Returns the auth configuration, refreshing the tokens if necessary.
21
103
  * This function can only be used by Node, if a server type is SASVIYA.
@@ -29,6 +111,9 @@ const apiBasePath_1 = require("../apiBasePath");
29
111
  */
30
112
  function getTokens(requestClient_1, authConfig_1) {
31
113
  return __awaiter(this, arguments, void 0, function* (requestClient, authConfig, serverType = types_1.ServerType.SasViya, onTokensRefreshed, apiBasePath = apiBasePath_1.DEFAULT_API_BASE_PATH) {
114
+ if ('grantType' in authConfig &&
115
+ authConfig.grantType === 'client_credentials')
116
+ return getClientCredentialsTokens(requestClient, authConfig, serverType);
32
117
  const logger = (0, host_1.getLogger)();
33
118
  // Note: client/secret are NOT mutated. The sas.cli public-client fallback
34
119
  // is applied only to the refresh call itself, so a caller that round-trips
@@ -5392,7 +5392,7 @@ const extractWeboutBlob_1 = __webpack_require__(5286);
5392
5392
  * @param serverUrl
5393
5393
  * @returns
5394
5394
  */
5395
- const parseSasViyaDebugResponse = (response, requestClient, serverUrl) => __awaiter(void 0, void 0, void 0, function* () {
5395
+ const parseSasViyaDebugResponse = (response, requestClient, serverUrl, accessToken) => __awaiter(void 0, void 0, void 0, function* () {
5396
5396
  // On viya 3.5, iframe is like <iframe style="width: 99%; height: 500px" src="..."></iframe>
5397
5397
  // On viya 4, iframe is like <iframe style="width: 99%; height: 500px; background-color:Canvas;" src=...></iframe>
5398
5398
  const iframeStart = response.split(/<iframe style="width: 99%; height: 500px" src="|<iframe style="width: 99%; height: 500px; background-color:Canvas;" src=/)[1];
@@ -5401,7 +5401,7 @@ const parseSasViyaDebugResponse = (response, requestClient, serverUrl) => __awai
5401
5401
  : null;
5402
5402
  if (jsonUrl) {
5403
5403
  return requestClient
5404
- .get(serverUrl + jsonUrl, undefined, 'text/plain')
5404
+ .get(serverUrl + jsonUrl, accessToken, 'text/plain')
5405
5405
  .then((res) => (0, utils_1.getValidJson)(res.result));
5406
5406
  }
5407
5407
  // Fallback: some Viya configurations inline the webout via a
@@ -3000,6 +3000,11 @@ const refreshTokensForViya_1 = __webpack_require__(5747);
3000
3000
  const host_1 = __webpack_require__(5334);
3001
3001
  const NotFoundError_1 = __webpack_require__(7403);
3002
3002
  const validateForcedServicePack_1 = __webpack_require__(8297);
3003
+ class TokenProviderError extends Error {
3004
+ constructor(error) {
3005
+ super(error instanceof Error ? error.message : String(error));
3006
+ }
3007
+ }
3003
3008
  /**
3004
3009
  * A client for interfacing with the SAS Viya REST API.
3005
3010
  *
@@ -3015,6 +3020,7 @@ class SASViyaApiClient {
3015
3020
  this.contextManager = new ContextManager_1.ContextManager(this.serverUrl, this.requestClient);
3016
3021
  this.folderMap = new Map();
3017
3022
  this.folderMapGeneration = 0;
3023
+ this.hasTokenProvider = false;
3018
3024
  this.fileExtensionMap = new Map();
3019
3025
  this.boolExtensionMap = false; // required in case the map has zero entries
3020
3026
  if (serverUrl)
@@ -3025,6 +3031,45 @@ class SASViyaApiClient {
3025
3031
  this.folderMap.clear();
3026
3032
  }
3027
3033
  // after an attempt to populate it.
3034
+ /** Return a Viya client that resolves the bearer before every request. */
3035
+ withAccessTokenProvider(provider) {
3036
+ const positions = {
3037
+ get: 1,
3038
+ delete: 1,
3039
+ post: 2,
3040
+ put: 2,
3041
+ patch: 2,
3042
+ uploadFile: 2
3043
+ };
3044
+ const base = this.providerBase || this.requestClient;
3045
+ const requestClient = new Proxy(base, {
3046
+ get(target, property) {
3047
+ const value = Reflect.get(target, property, target);
3048
+ if (typeof value !== 'function')
3049
+ return value;
3050
+ if (typeof property === 'string' &&
3051
+ Object.prototype.hasOwnProperty.call(positions, property)) {
3052
+ return (...args) => __awaiter(this, void 0, void 0, function* () {
3053
+ if (property === 'post' && args[0] === '/SASLogon/oauth/token')
3054
+ return value.apply(target, args);
3055
+ try {
3056
+ args[positions[property]] = yield provider();
3057
+ }
3058
+ catch (error) {
3059
+ throw new TokenProviderError(error);
3060
+ }
3061
+ return value.apply(target, args);
3062
+ });
3063
+ }
3064
+ return value.bind(target);
3065
+ }
3066
+ });
3067
+ const client = new SASViyaApiClient(this.serverUrl, this.rootFolderName, this.contextName, requestClient);
3068
+ client.hasTokenProvider = true;
3069
+ client.providerBase = base;
3070
+ client.debug = this.debug;
3071
+ return client;
3072
+ }
3028
3073
  /**
3029
3074
  * A helper method used to call appendRequest method of RequestClient
3030
3075
  * @param response - response from sasjs request
@@ -3198,6 +3243,12 @@ class SASViyaApiClient {
3198
3243
  */
3199
3244
  executeScript(jobPath_1, linesOfCode_1, contextName_1, authConfig_1) {
3200
3245
  return __awaiter(this, arguments, void 0, function* (jobPath, linesOfCode, contextName, authConfig, data = null, debug = false, expectWebout = false, waitForResult = true, pollOptions, printPid = false, variables, onTokensRefreshed) {
3246
+ if (authConfig &&
3247
+ 'grantType' in authConfig &&
3248
+ authConfig.grantType === 'client_credentials' &&
3249
+ !this.hasTokenProvider) {
3250
+ return this.withAccessTokenProvider(() => __awaiter(this, void 0, void 0, function* () { return (yield (0, getTokens_1.getTokens)(this.requestClient, authConfig)).access_token; })).executeScript(jobPath, linesOfCode, contextName, authConfig, data, debug, expectWebout, waitForResult, pollOptions, printPid, variables, onTokensRefreshed);
3251
+ }
3201
3252
  return (0, executeOnComputeApi_1.executeOnComputeApi)(this.requestClient, this.sessionManager, this.rootFolderName, jobPath, linesOfCode, contextName, authConfig, data, debug, expectWebout, waitForResult, pollOptions, printPid, variables, onTokensRefreshed);
3202
3253
  });
3203
3254
  }
@@ -3782,6 +3833,12 @@ class SASViyaApiClient {
3782
3833
  */
3783
3834
  executeComputeJob(sasJob_1, contextName_1, debug_1, data_1, authConfig_1) {
3784
3835
  return __awaiter(this, arguments, void 0, function* (sasJob, contextName, debug, data, authConfig, waitForResult = true, expectWebout = false, pollOptions, printPid = false, variables, onTokensRefreshed) {
3836
+ if (authConfig &&
3837
+ 'grantType' in authConfig &&
3838
+ authConfig.grantType === 'client_credentials' &&
3839
+ !this.hasTokenProvider) {
3840
+ return this.withAccessTokenProvider(() => __awaiter(this, void 0, void 0, function* () { return (yield (0, getTokens_1.getTokens)(this.requestClient, authConfig)).access_token; })).executeComputeJob(sasJob, contextName, debug, data, authConfig, waitForResult, expectWebout, pollOptions, printPid, variables, onTokensRefreshed);
3841
+ }
3785
3842
  let access_token = (authConfig || {}).access_token;
3786
3843
  if (authConfig) {
3787
3844
  ;
@@ -3840,6 +3897,12 @@ class SASViyaApiClient {
3840
3897
  executeJob(sasJob, contextName, debug, data, authConfig, onTokensRefreshed) {
3841
3898
  return __awaiter(this, void 0, void 0, function* () {
3842
3899
  var _a, _b, _c;
3900
+ if (authConfig &&
3901
+ 'grantType' in authConfig &&
3902
+ authConfig.grantType === 'client_credentials' &&
3903
+ !this.hasTokenProvider) {
3904
+ return this.withAccessTokenProvider(() => __awaiter(this, void 0, void 0, function* () { return (yield (0, getTokens_1.getTokens)(this.requestClient, authConfig)).access_token; })).executeJob(sasJob, contextName, debug, data, authConfig, onTokensRefreshed);
3905
+ }
3843
3906
  let access_token = (authConfig || {}).access_token;
3844
3907
  if (authConfig) {
3845
3908
  ;
@@ -3991,7 +4054,8 @@ class SASViyaApiClient {
3991
4054
  const { result: folder } = yield this.requestClient
3992
4055
  .get(`${this.serverUrl}${url}`, accessToken)
3993
4056
  .catch((err) => {
3994
- if (err instanceof errors_1.CertificateError)
4057
+ if (err instanceof errors_1.CertificateError ||
4058
+ err instanceof TokenProviderError)
3995
4059
  throw err;
3996
4060
  return { result: null };
3997
4061
  });
@@ -4030,7 +4094,8 @@ class SASViyaApiClient {
4030
4094
  const { result: folder } = yield this.requestClient
4031
4095
  .get(`${this.serverUrl}${url}`, accessToken)
4032
4096
  .catch((err) => {
4033
- if (err instanceof errors_1.CertificateError)
4097
+ if (err instanceof errors_1.CertificateError ||
4098
+ err instanceof TokenProviderError)
4034
4099
  throw err;
4035
4100
  return { result: null };
4036
4101
  });
@@ -4791,6 +4856,8 @@ class SASjs {
4791
4856
  return __awaiter(this, arguments, void 0, function* (serviceJson, appLoc, serverUrl, accessToken, isForced = false, onProgress) {
4792
4857
  var _a, _b, _c;
4793
4858
  this.isMethodSupported('deployServicePack', [types_2.ServerType.SasViya]);
4859
+ const tokenProvider = typeof accessToken === 'function' ? accessToken : undefined;
4860
+ const staticToken = typeof accessToken === 'string' ? accessToken : undefined;
4794
4861
  let sasApiClient = null;
4795
4862
  if (serverUrl !== undefined || appLoc !== undefined) {
4796
4863
  if (serverUrl === undefined)
@@ -4839,14 +4906,16 @@ class SASjs {
4839
4906
  if (serverUrl === this.sasjsConfig.serverUrl)
4840
4907
  deploymentClient.copyCsrfFrom(this.requestClient);
4841
4908
  deploymentClient.restrictDeploymentTransport();
4842
- const api = new SASViyaApiClient_1.SASViyaApiClient(serverUrl, appLoc, this.sasjsConfig.contextName, deploymentClient);
4909
+ let api = new SASViyaApiClient_1.SASViyaApiClient(serverUrl, appLoc, this.sasjsConfig.contextName, deploymentClient);
4910
+ if (tokenProvider)
4911
+ api = api.withAccessTokenProvider(tokenProvider);
4843
4912
  (_a = this.sasViyaApiClient) === null || _a === void 0 ? void 0 : _a.invalidateFolderCache();
4844
4913
  try {
4845
- const { parentId, recycled } = yield api.recycleDeploymentFolder(appLoc, accessToken);
4914
+ const { parentId, recycled } = yield api.recycleDeploymentFolder(appLoc, staticToken);
4846
4915
  try {
4847
4916
  const parent = appLoc.slice(0, appLoc.lastIndexOf('/'));
4848
4917
  const name = appLoc.slice(appLoc.lastIndexOf('/') + 1);
4849
- const root = yield api.createFolder(name, parent, `/folders/folders/${parentId}`, accessToken, false);
4918
+ const root = yield api.createFolder(name, parent, `/folders/folders/${parentId}`, staticToken, false);
4850
4919
  if (!root ||
4851
4920
  root.name !== name ||
4852
4921
  root.parentFolderUri !== `/folders/folders/${parentId}` ||
@@ -4854,7 +4923,7 @@ class SASjs {
4854
4923
  typeof root.id !== 'string' ||
4855
4924
  !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(root.id))
4856
4925
  throw new Error('Invalid created app folder identity');
4857
- yield this.createFoldersAndServices(appLoc, serviceJson.members, accessToken, api, false, {
4926
+ yield this.createFoldersAndServices(appLoc, serviceJson.members, staticToken, api, false, {
4858
4927
  onProgress,
4859
4928
  index: 0,
4860
4929
  total: countMembers(serviceJson.members),
@@ -4878,7 +4947,9 @@ class SASjs {
4878
4947
  serviceJson.members[0].members.sort((member) => member.type === 'folder' ? -1 : 1);
4879
4948
  }
4880
4949
  const members = serviceJson.members;
4881
- yield this.createFoldersAndServices(appLoc, members, accessToken, sasApiClient, isForced, { onProgress, index: 0, total: countMembers(members), strict: false });
4950
+ if (tokenProvider)
4951
+ sasApiClient = (sasApiClient || this.sasViyaApiClient).withAccessTokenProvider(tokenProvider);
4952
+ yield this.createFoldersAndServices(appLoc, members, staticToken, sasApiClient, isForced, { onProgress, index: 0, total: countMembers(members), strict: false });
4882
4953
  });
4883
4954
  }
4884
4955
  /**
@@ -7070,8 +7141,90 @@ const auth_1 = __webpack_require__(6072);
7070
7141
  const types_1 = __webpack_require__(3631);
7071
7142
  const refreshTokensForViya_1 = __webpack_require__(5747);
7072
7143
  const refreshTokensForSasjs_1 = __webpack_require__(6725);
7144
+ const getTokenRequestErrorPrefix_1 = __webpack_require__(1087);
7145
+ const errors_1 = __webpack_require__(7388);
7073
7146
  const host_1 = __webpack_require__(5334);
7074
7147
  const apiBasePath_1 = __webpack_require__(6838);
7148
+ const clientTokens = new WeakMap();
7149
+ /**
7150
+ * Returns the auth configuration for a Viya client-credentials identity,
7151
+ * requesting an access token when there is none or the held one has expired.
7152
+ * This grant has no refresh token.
7153
+ *
7154
+ * The token is also written to `authConfig.access_token`, as the user-token
7155
+ * path below does: code further down an execution chain (the job poll, for
7156
+ * one) reads the token from the shared `authConfig`, not from this return
7157
+ * value.
7158
+ *
7159
+ * A token's lifetime is counted from the moment the request was sent, so the
7160
+ * held token is dropped no later than the server's own expiry. No further
7161
+ * margin is subtracted. A response that states no `expires_in` is never held:
7162
+ * the next call requests a new token.
7163
+ * @param requestClient - the pre-configured HTTP request client
7164
+ * @param authConfig - the client ID and secret, with `grantType` set to
7165
+ * `client_credentials`
7166
+ * @param serverType - must be SASVIYA.
7167
+ */
7168
+ function getClientCredentialsTokens(requestClient, authConfig, serverType) {
7169
+ return __awaiter(this, void 0, void 0, function* () {
7170
+ const { client, secret } = authConfig;
7171
+ if (serverType !== types_1.ServerType.SasViya)
7172
+ throw new Error('Client credentials require SAS Viya');
7173
+ if (!client || !secret)
7174
+ throw new Error('Client credentials require a client and secret');
7175
+ const baseUrl = requestClient.getBaseUrl();
7176
+ let state = clientTokens.get(authConfig);
7177
+ if (!state ||
7178
+ state.client !== client ||
7179
+ state.secret !== secret ||
7180
+ state.baseUrl !== baseUrl) {
7181
+ state = { token: '', expiresAt: 0, client, secret, baseUrl };
7182
+ clientTokens.set(authConfig, state);
7183
+ }
7184
+ let access_token;
7185
+ if (!state.token || Date.now() >= state.expiresAt) {
7186
+ if (!state.pending) {
7187
+ const tokenState = state;
7188
+ const requestedAt = Date.now();
7189
+ const pair = `${client}:${secret}`;
7190
+ const url = '/SASLogon/oauth/token';
7191
+ const data = 'grant_type=client_credentials';
7192
+ const headers = {
7193
+ Authorization: 'Basic ' +
7194
+ (typeof Buffer === 'undefined'
7195
+ ? btoa(pair)
7196
+ : Buffer.from(pair).toString('base64')),
7197
+ 'Content-Type': 'application/x-www-form-urlencoded'
7198
+ };
7199
+ state.pending = requestClient
7200
+ .post(url, data, undefined, 'application/x-www-form-urlencoded', headers)
7201
+ .catch((err) => {
7202
+ if (err instanceof errors_1.CertificateError)
7203
+ throw err;
7204
+ throw (0, getTokenRequestErrorPrefix_1.tokenRequestErrorMessage)(err, 'fetching access token', 'getTokens', types_1.ServerType.SasViya, url, data, headers, client, secret);
7205
+ })
7206
+ .then(({ result }) => {
7207
+ if (!(result === null || result === void 0 ? void 0 : result.access_token))
7208
+ throw new Error('Client credentials response did not contain an access token');
7209
+ const expiresAt = requestedAt + (Number(result.expires_in) || 0) * 1000;
7210
+ if (result.expires_in != null && Date.now() >= expiresAt)
7211
+ throw new Error('Client credentials access token expired before receipt');
7212
+ tokenState.token = result.access_token;
7213
+ tokenState.expiresAt = expiresAt;
7214
+ return tokenState.token;
7215
+ })
7216
+ .finally(() => {
7217
+ tokenState.pending = undefined;
7218
+ });
7219
+ }
7220
+ access_token = yield state.pending;
7221
+ }
7222
+ else
7223
+ access_token = state.token;
7224
+ authConfig.access_token = access_token;
7225
+ return Object.assign(Object.assign({}, authConfig), { access_token });
7226
+ });
7227
+ }
7075
7228
  /**
7076
7229
  * Returns the auth configuration, refreshing the tokens if necessary.
7077
7230
  * This function can only be used by Node, if a server type is SASVIYA.
@@ -7085,6 +7238,9 @@ const apiBasePath_1 = __webpack_require__(6838);
7085
7238
  */
7086
7239
  function getTokens(requestClient_1, authConfig_1) {
7087
7240
  return __awaiter(this, arguments, void 0, function* (requestClient, authConfig, serverType = types_1.ServerType.SasViya, onTokensRefreshed, apiBasePath = apiBasePath_1.DEFAULT_API_BASE_PATH) {
7241
+ if ('grantType' in authConfig &&
7242
+ authConfig.grantType === 'client_credentials')
7243
+ return getClientCredentialsTokens(requestClient, authConfig, serverType);
7088
7244
  const logger = (0, host_1.getLogger)();
7089
7245
  // Note: client/secret are NOT mutated. The sas.cli public-client fallback
7090
7246
  // is applied only to the refresh call itself, so a caller that round-trips
@@ -8469,6 +8625,7 @@ const types_1 = __webpack_require__(3631);
8469
8625
  const errors_1 = __webpack_require__(7388);
8470
8626
  const generateFileUploadForm_1 = __webpack_require__(7673);
8471
8627
  const generateTableUploadForm_1 = __webpack_require__(93);
8628
+ const getTokens_1 = __webpack_require__(9609);
8472
8629
  const utils_1 = __webpack_require__(9266);
8473
8630
  const JobExecutor_1 = __webpack_require__(1101);
8474
8631
  const unauthenticatedRequestMessage_1 = __webpack_require__(2021);
@@ -8489,10 +8646,12 @@ class WebJobExecutor extends JobExecutor_1.BaseJobExecutor {
8489
8646
  : sasJob
8490
8647
  : sasJob;
8491
8648
  let apiUrl = `${config.serverUrl}${this.jobsPath}/?${'_program=' + program}`;
8649
+ const clientCredentials = config.serverType === types_1.ServerType.SasViya &&
8650
+ (authConfig === null || authConfig === void 0 ? void 0 : authConfig.grantType) === 'client_credentials';
8492
8651
  if (config.serverType === types_1.ServerType.SasViya) {
8493
8652
  let jobUri;
8494
8653
  try {
8495
- jobUri = yield this.getJobUri(program);
8654
+ jobUri = yield this.getJobUri(program, clientCredentials ? authConfig : undefined);
8496
8655
  }
8497
8656
  catch (e) {
8498
8657
  return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
@@ -8597,8 +8756,11 @@ class WebJobExecutor extends JobExecutor_1.BaseJobExecutor {
8597
8756
  const contentType = formData instanceof form_data_1.default && typeof FormData === 'undefined'
8598
8757
  ? `multipart/form-data; boundary=${formData.getHeaders()['content-type']}`
8599
8758
  : 'multipart/form-data';
8759
+ const accessToken = clientCredentials && authConfig
8760
+ ? (yield (0, getTokens_1.getTokens)(this.requestClient, authConfig)).access_token
8761
+ : authConfig === null || authConfig === void 0 ? void 0 : authConfig.access_token;
8600
8762
  const requestPromise = new Promise((resolve, reject) => {
8601
- this.requestClient.post(apiUrl, formData, authConfig === null || authConfig === void 0 ? void 0 : authConfig.access_token, contentType)
8763
+ this.requestClient.post(apiUrl, formData, accessToken, contentType)
8602
8764
  .then((res) => __awaiter(this, void 0, void 0, function* () {
8603
8765
  this.requestClient.appendRequest(res, sasJob, config.debug);
8604
8766
  let jsonResponse = res.result;
@@ -8617,7 +8779,10 @@ class WebJobExecutor extends JobExecutor_1.BaseJobExecutor {
8617
8779
  jsonResponse =
8618
8780
  typeof res.result !== 'string' || (0, utils_1.hasWeboutBlob)(res.result)
8619
8781
  ? yield (0, utils_1.parseSasViyaLogDebugResponse)(res.result)
8620
- : yield (0, utils_1.parseSasViyaDebugResponse)(res.result, this.requestClient, this.serverUrl);
8782
+ : yield (0, utils_1.parseSasViyaDebugResponse)(res.result, this.requestClient, this.serverUrl, clientCredentials && authConfig
8783
+ ? (yield (0, getTokens_1.getTokens)(this.requestClient, authConfig))
8784
+ .access_token
8785
+ : authConfig === null || authConfig === void 0 ? void 0 : authConfig.access_token);
8621
8786
  break;
8622
8787
  case types_1.ServerType.Sas9:
8623
8788
  jsonResponse =
@@ -8669,7 +8834,7 @@ class WebJobExecutor extends JobExecutor_1.BaseJobExecutor {
8669
8834
  }
8670
8835
  return requestParams;
8671
8836
  }
8672
- getJobUri(sasJob) {
8837
+ getJobUri(sasJob, authConfig) {
8673
8838
  return __awaiter(this, void 0, void 0, function* () {
8674
8839
  if (!this.sasViyaApiClient)
8675
8840
  return '';
@@ -8684,7 +8849,10 @@ class WebJobExecutor extends JobExecutor_1.BaseJobExecutor {
8684
8849
  if (!jobName) {
8685
8850
  throw new Error('Job name is empty, null or undefined.');
8686
8851
  }
8687
- const locJobs = yield this.sasViyaApiClient.getJobsInFolder(folderPath);
8852
+ const api = authConfig
8853
+ ? this.sasViyaApiClient.withAccessTokenProvider(() => __awaiter(this, void 0, void 0, function* () { return (yield (0, getTokens_1.getTokens)(this.requestClient, authConfig)).access_token; }))
8854
+ : this.sasViyaApiClient;
8855
+ const locJobs = yield api.getJobsInFolder(folderPath);
8688
8856
  if (locJobs) {
8689
8857
  const job = locJobs.find((el) => el.name === jobName && el.contentType === 'jobDefinition');
8690
8858
  if (job) {
@@ -12129,7 +12297,7 @@ const extractWeboutBlob_1 = __webpack_require__(5286);
12129
12297
  * @param serverUrl
12130
12298
  * @returns
12131
12299
  */
12132
- const parseSasViyaDebugResponse = (response, requestClient, serverUrl) => __awaiter(void 0, void 0, void 0, function* () {
12300
+ const parseSasViyaDebugResponse = (response, requestClient, serverUrl, accessToken) => __awaiter(void 0, void 0, void 0, function* () {
12133
12301
  // On viya 3.5, iframe is like <iframe style="width: 99%; height: 500px" src="..."></iframe>
12134
12302
  // On viya 4, iframe is like <iframe style="width: 99%; height: 500px; background-color:Canvas;" src=...></iframe>
12135
12303
  const iframeStart = response.split(/<iframe style="width: 99%; height: 500px" src="|<iframe style="width: 99%; height: 500px; background-color:Canvas;" src=/)[1];
@@ -12138,7 +12306,7 @@ const parseSasViyaDebugResponse = (response, requestClient, serverUrl) => __awai
12138
12306
  : null;
12139
12307
  if (jsonUrl) {
12140
12308
  return requestClient
12141
- .get(serverUrl + jsonUrl, undefined, 'text/plain')
12309
+ .get(serverUrl + jsonUrl, accessToken, 'text/plain')
12142
12310
  .then((res) => (0, utils_1.getValidJson)(res.result));
12143
12311
  }
12144
12312
  // Fallback: some Viya configurations inline the webout via a
package/index.d.ts CHANGED
@@ -6,4 +6,5 @@ export * from './SAS9ApiClient';
6
6
  export * from './SASjsApiClient';
7
7
  export * from './request/SasjsRequestClient';
8
8
  export type { OnTokensRefreshed } from './auth/getTokens';
9
+ export type { AuthConfig } from './auth/AuthConfig';
9
10
  export default SASjs;
@@ -1,4 +1,4 @@
1
- import { AuthConfig } from '@sasjs/utils/types';
1
+ import { AuthConfig } from '../auth/AuthConfig';
2
2
  import { SASViyaApiClient } from '../SASViyaApiClient';
3
3
  import { BaseJobExecutor } from './JobExecutor';
4
4
  export declare class ComputeJobExecutor extends BaseJobExecutor {
@@ -1,4 +1,4 @@
1
- import { AuthConfig } from '@sasjs/utils/types';
1
+ import { AuthConfig } from '../auth/AuthConfig';
2
2
  import { SASViyaApiClient } from '../SASViyaApiClient';
3
3
  import { ExtraResponseAttributes } from '@sasjs/utils/types';
4
4
  import { BaseJobExecutor } from './JobExecutor';
@@ -1,4 +1,5 @@
1
- import { AuthConfig, ServerType } from '@sasjs/utils/types';
1
+ import { AuthConfig } from '../auth/AuthConfig';
2
+ import { ServerType } from '@sasjs/utils/types';
2
3
  import { ExtraResponseAttributes } from '@sasjs/utils/types';
3
4
  export type ExecuteFunction = () => Promise<any>;
4
5
  export interface JobExecutor {
@@ -1,4 +1,5 @@
1
- import { AuthConfig, ExtraResponseAttributes } from '@sasjs/utils/types';
1
+ import { AuthConfig } from '../auth/AuthConfig';
2
+ import { ExtraResponseAttributes } from '@sasjs/utils/types';
2
3
  import { RequestClient } from '../request/RequestClient';
3
4
  import { BaseJobExecutor } from './JobExecutor';
4
5
  export declare class SasjsJobExecutor extends BaseJobExecutor {
@@ -1,4 +1,5 @@
1
- import { AuthConfig, ExtraResponseAttributes, ServerType } from '@sasjs/utils/types';
1
+ import { AuthConfig } from '../auth/AuthConfig';
2
+ import { ExtraResponseAttributes, ServerType } from '@sasjs/utils/types';
2
3
  import { RequestClient } from '../request/RequestClient';
3
4
  import { SASViyaApiClient } from '../SASViyaApiClient';
4
5
  import { BaseJobExecutor } from './JobExecutor';
@@ -18,6 +18,7 @@ const types_1 = require("@sasjs/utils/types");
18
18
  const errors_1 = require("../types/errors");
19
19
  const generateFileUploadForm_1 = require("../file/generateFileUploadForm");
20
20
  const generateTableUploadForm_1 = require("../file/generateTableUploadForm");
21
+ const getTokens_1 = require("../auth/getTokens");
21
22
  const utils_1 = require("../utils");
22
23
  const JobExecutor_1 = require("./JobExecutor");
23
24
  const unauthenticatedRequestMessage_1 = require("./unauthenticatedRequestMessage");
@@ -38,10 +39,12 @@ class WebJobExecutor extends JobExecutor_1.BaseJobExecutor {
38
39
  : sasJob
39
40
  : sasJob;
40
41
  let apiUrl = `${config.serverUrl}${this.jobsPath}/?${'_program=' + program}`;
42
+ const clientCredentials = config.serverType === types_1.ServerType.SasViya &&
43
+ (authConfig === null || authConfig === void 0 ? void 0 : authConfig.grantType) === 'client_credentials';
41
44
  if (config.serverType === types_1.ServerType.SasViya) {
42
45
  let jobUri;
43
46
  try {
44
- jobUri = yield this.getJobUri(program);
47
+ jobUri = yield this.getJobUri(program, clientCredentials ? authConfig : undefined);
45
48
  }
46
49
  catch (e) {
47
50
  return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
@@ -146,8 +149,11 @@ class WebJobExecutor extends JobExecutor_1.BaseJobExecutor {
146
149
  const contentType = formData instanceof form_data_1.default && typeof FormData === 'undefined'
147
150
  ? `multipart/form-data; boundary=${formData.getHeaders()['content-type']}`
148
151
  : 'multipart/form-data';
152
+ const accessToken = clientCredentials && authConfig
153
+ ? (yield (0, getTokens_1.getTokens)(this.requestClient, authConfig)).access_token
154
+ : authConfig === null || authConfig === void 0 ? void 0 : authConfig.access_token;
149
155
  const requestPromise = new Promise((resolve, reject) => {
150
- this.requestClient.post(apiUrl, formData, authConfig === null || authConfig === void 0 ? void 0 : authConfig.access_token, contentType)
156
+ this.requestClient.post(apiUrl, formData, accessToken, contentType)
151
157
  .then((res) => __awaiter(this, void 0, void 0, function* () {
152
158
  this.requestClient.appendRequest(res, sasJob, config.debug);
153
159
  let jsonResponse = res.result;
@@ -166,7 +172,10 @@ class WebJobExecutor extends JobExecutor_1.BaseJobExecutor {
166
172
  jsonResponse =
167
173
  typeof res.result !== 'string' || (0, utils_1.hasWeboutBlob)(res.result)
168
174
  ? yield (0, utils_1.parseSasViyaLogDebugResponse)(res.result)
169
- : yield (0, utils_1.parseSasViyaDebugResponse)(res.result, this.requestClient, this.serverUrl);
175
+ : yield (0, utils_1.parseSasViyaDebugResponse)(res.result, this.requestClient, this.serverUrl, clientCredentials && authConfig
176
+ ? (yield (0, getTokens_1.getTokens)(this.requestClient, authConfig))
177
+ .access_token
178
+ : authConfig === null || authConfig === void 0 ? void 0 : authConfig.access_token);
170
179
  break;
171
180
  case types_1.ServerType.Sas9:
172
181
  jsonResponse =
@@ -218,7 +227,7 @@ class WebJobExecutor extends JobExecutor_1.BaseJobExecutor {
218
227
  }
219
228
  return requestParams;
220
229
  }
221
- getJobUri(sasJob) {
230
+ getJobUri(sasJob, authConfig) {
222
231
  return __awaiter(this, void 0, void 0, function* () {
223
232
  if (!this.sasViyaApiClient)
224
233
  return '';
@@ -233,7 +242,10 @@ class WebJobExecutor extends JobExecutor_1.BaseJobExecutor {
233
242
  if (!jobName) {
234
243
  throw new Error('Job name is empty, null or undefined.');
235
244
  }
236
- const locJobs = yield this.sasViyaApiClient.getJobsInFolder(folderPath);
245
+ const api = authConfig
246
+ ? this.sasViyaApiClient.withAccessTokenProvider(() => __awaiter(this, void 0, void 0, function* () { return (yield (0, getTokens_1.getTokens)(this.requestClient, authConfig)).access_token; }))
247
+ : this.sasViyaApiClient;
248
+ const locJobs = yield api.getJobsInFolder(folderPath);
237
249
  if (locJobs) {
238
250
  const job = locJobs.find((el) => el.name === jobName && el.contentType === 'jobDefinition');
239
251
  if (job) {
package/package.json CHANGED
@@ -105,7 +105,7 @@
105
105
  "es-define-property": "npm:@socketregistry/es-define-property@1.0.7",
106
106
  "es-set-tostringtag": "npm:@socketregistry/es-set-tostringtag@1.0.10",
107
107
  "function-bind": "npm:@socketregistry/function-bind@1.0.7",
108
- "glob": "14.0.3",
108
+ "glob": "14.0.6",
109
109
  "gopd": "npm:@socketregistry/gopd@1.0.7",
110
110
  "has-symbols": "npm:@socketregistry/has-symbols@1.0.7",
111
111
  "has-tostringtag": "npm:@socketregistry/has-tostringtag@1.0.7",
@@ -113,14 +113,14 @@
113
113
  "is-core-module": "npm:@socketregistry/is-core-module@1.0.11",
114
114
  "is-unicode-supported": "npm:@socketregistry/is-unicode-supported@1.0.5",
115
115
  "isarray": "npm:@socketregistry/isarray@1.0.8",
116
- "minimatch": "11.0.4",
116
+ "minimatch": "11.0.8",
117
117
  "object-assign": "npm:@socketregistry/object-assign@1.0.5",
118
118
  "path-parse": "npm:@socketregistry/path-parse@1.0.8",
119
119
  "safe-buffer": "npm:@socketregistry/safe-buffer@1.0.9",
120
120
  "safer-buffer": "npm:@socketregistry/safer-buffer@1.0.10",
121
121
  "side-channel": "npm:@socketregistry/side-channel@1.0.10"
122
122
  },
123
- "version": "6.2.1",
123
+ "version": "6.3.0",
124
124
  "engines": {
125
125
  "node": ">=22"
126
126
  },
@@ -9,4 +9,4 @@ import { RequestClient } from '../request/RequestClient';
9
9
  * @param serverUrl
10
10
  * @returns
11
11
  */
12
- export declare const parseSasViyaDebugResponse: (response: string, requestClient: RequestClient, serverUrl: string) => Promise<object>;
12
+ export declare const parseSasViyaDebugResponse: (response: string, requestClient: RequestClient, serverUrl: string, accessToken?: string) => Promise<object>;
@@ -22,7 +22,7 @@ const extractWeboutBlob_1 = require("./extractWeboutBlob");
22
22
  * @param serverUrl
23
23
  * @returns
24
24
  */
25
- const parseSasViyaDebugResponse = (response, requestClient, serverUrl) => __awaiter(void 0, void 0, void 0, function* () {
25
+ const parseSasViyaDebugResponse = (response, requestClient, serverUrl, accessToken) => __awaiter(void 0, void 0, void 0, function* () {
26
26
  // On viya 3.5, iframe is like <iframe style="width: 99%; height: 500px" src="..."></iframe>
27
27
  // On viya 4, iframe is like <iframe style="width: 99%; height: 500px; background-color:Canvas;" src=...></iframe>
28
28
  const iframeStart = response.split(/<iframe style="width: 99%; height: 500px" src="|<iframe style="width: 99%; height: 500px; background-color:Canvas;" src=/)[1];
@@ -31,7 +31,7 @@ const parseSasViyaDebugResponse = (response, requestClient, serverUrl) => __awai
31
31
  : null;
32
32
  if (jsonUrl) {
33
33
  return requestClient
34
- .get(serverUrl + jsonUrl, undefined, 'text/plain')
34
+ .get(serverUrl + jsonUrl, accessToken, 'text/plain')
35
35
  .then((res) => (0, utils_1.getValidJson)(res.result));
36
36
  }
37
37
  // Fallback: some Viya configurations inline the webout via a