@sasjs/adapter 4.19.3 → 5.1.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 (419) hide show
  1. package/ContextManager.js +290 -0
  2. package/DISCLOSURE +45 -0
  3. package/README.md +1 -1
  4. package/SAS9ApiClient.d.ts +1 -1
  5. package/SAS9ApiClient.js +90 -0
  6. package/SASViyaApiClient.js +918 -0
  7. package/SASjs.js +794 -0
  8. package/SASjsApiClient.d.ts +1 -0
  9. package/SASjsApiClient.js +132 -0
  10. package/SessionManager.js +353 -0
  11. package/api/viya/executeOnComputeApi.js +198 -0
  12. package/api/viya/getFileStream.js +32 -0
  13. package/api/viya/pollJobState.js +247 -0
  14. package/api/viya/saveLog.js +45 -0
  15. package/api/viya/uploadTables.js +45 -0
  16. package/api/viya/writeStream.js +25 -0
  17. package/auth/AuthManager.js +305 -0
  18. package/auth/getAccessTokenForSasjs.js +43 -0
  19. package/auth/getAccessTokenForViya.js +54 -0
  20. package/auth/getTokenRequestErrorPrefix.js +70 -0
  21. package/auth/getTokens.js +110 -0
  22. package/auth/index.js +20 -0
  23. package/auth/isAuthorizeFormRequired.js +7 -0
  24. package/auth/isLoginRequired.js +9 -0
  25. package/auth/loginHeader.js +87 -0
  26. package/auth/openWebPage.js +31 -0
  27. package/auth/refreshTokensForSasjs.js +42 -0
  28. package/auth/refreshTokensForViya.js +53 -0
  29. package/auth/verifySas9Login.js +32 -0
  30. package/auth/verifySasViyaLogin.js +44 -0
  31. package/dist/minified_sas9.js +10892 -0
  32. package/dist/sasjs-adapter.js +19569 -0
  33. package/file/generateFileUploadForm.js +43 -0
  34. package/file/generateTableUploadForm.js +38 -0
  35. package/index.js +9 -80376
  36. package/job-execution/ComputeJobExecutor.js +55 -0
  37. package/job-execution/FileUploader.js +114 -0
  38. package/job-execution/JesJobExecutor.js +55 -0
  39. package/job-execution/JobExecutor.js +40 -0
  40. package/job-execution/Sas9JobExecutor.d.ts +1 -1
  41. package/job-execution/Sas9JobExecutor.js +115 -0
  42. package/job-execution/SasjsJobExecutor.js +100 -0
  43. package/job-execution/WebJobExecutor.js +254 -0
  44. package/job-execution/index.js +23 -0
  45. package/minified/sas9/SASjs.js +198 -0
  46. package/minified/sas9/WebJobExecutor.js +105 -0
  47. package/minified/sas9/index.js +22 -0
  48. package/node/index.d.ts +2 -9
  49. package/node/index.js +1 -30570
  50. package/package.json +41 -12
  51. package/request/RequestClient.d.ts +1 -1
  52. package/request/RequestClient.js +717 -0
  53. package/request/Sas9RequestClient.d.ts +1 -1
  54. package/request/Sas9RequestClient.js +121 -0
  55. package/request/SasjsRequestClient.js +77 -0
  56. package/types/Context.js +2 -0
  57. package/types/CsrfToken.js +2 -0
  58. package/types/ExecuteScript.js +2 -0
  59. package/types/File.js +2 -0
  60. package/types/FileResource.js +2 -0
  61. package/types/Folder.js +2 -0
  62. package/types/Job.js +2 -0
  63. package/types/JobDefinition.js +2 -0
  64. package/types/JobResult.js +2 -0
  65. package/types/Link.js +2 -0
  66. package/types/LogStatistics.js +2 -0
  67. package/types/Login.js +2 -0
  68. package/types/PollOptions.js +2 -0
  69. package/types/RequestClient.js +2 -0
  70. package/types/SASjsConfig.d.ts +1 -1
  71. package/types/SASjsConfig.js +91 -0
  72. package/types/Session.js +14 -0
  73. package/types/Tables.js +28 -0
  74. package/types/UploadFile.js +2 -0
  75. package/types/WriteStream.d.ts +1 -1
  76. package/types/WriteStream.js +2 -0
  77. package/types/errors/ArgumentError.js +12 -0
  78. package/types/errors/AuthorizeError.js +13 -0
  79. package/types/errors/CertificateError.js +12 -0
  80. package/types/errors/ComputeJobExecutionError.js +13 -0
  81. package/types/errors/ErrorResponse.js +23 -0
  82. package/types/errors/InternalServerError.js +11 -0
  83. package/types/errors/InvalidJsonError.js +11 -0
  84. package/types/errors/InvalidSASjsCsrfError.js +12 -0
  85. package/types/errors/JobExecutionError.js +14 -0
  86. package/types/errors/JobStatePollError.js +12 -0
  87. package/types/errors/JsonParseArrayError.js +11 -0
  88. package/types/errors/LoginRequiredError.js +14 -0
  89. package/types/errors/NoSessionStateError.js +14 -0
  90. package/types/errors/NotFoundError.js +12 -0
  91. package/types/errors/RootFolderNotFoundError.js +22 -0
  92. package/types/errors/SAS9AuthError.js +11 -0
  93. package/types/errors/WeboutResponseError.js +12 -0
  94. package/types/errors/index.js +31 -0
  95. package/types/index.js +34 -0
  96. package/utils/appendExtraResponseAttributes.js +25 -0
  97. package/utils/asyncForEach.js +20 -0
  98. package/utils/compareTimestamps.js +11 -0
  99. package/utils/convertToCsv.js +154 -0
  100. package/utils/createAxiosInstance.d.ts +1 -1
  101. package/utils/createAxiosInstance.js +9 -0
  102. package/utils/delay.js +5 -0
  103. package/{src/utils/extractWeboutBlob.ts → utils/extractWeboutBlob.js} +19 -20
  104. package/utils/fetchLogByChunks.js +56 -0
  105. package/utils/formatDataForRequest.js +39 -0
  106. package/utils/getFormData.js +10 -0
  107. package/{node/utils/getUserLanguage.d.ts → utils/getUserLanguage.js} +5 -1
  108. package/utils/getValidJson.js +27 -0
  109. package/utils/host.d.ts +24 -0
  110. package/utils/host.js +36 -0
  111. package/utils/index.js +41 -0
  112. package/utils/isIeOrEdge.js +30 -0
  113. package/utils/isNode.js +7 -0
  114. package/utils/isRelativePath.js +5 -0
  115. package/utils/isUri.js +9 -0
  116. package/utils/isUrl.js +20 -0
  117. package/utils/loginPrompt/index.js +180 -0
  118. package/utils/needsRetry.js +14 -0
  119. package/utils/parseGeneratedCode.js +10 -0
  120. package/utils/parseSasViyaLog.js +17 -0
  121. package/utils/parseSourceCode.js +9 -0
  122. package/utils/parseViyaDebugResponse.js +46 -0
  123. package/utils/parseViyaLogDebugResponse.js +32 -0
  124. package/utils/parseWeboutResponse.js +22 -0
  125. package/utils/sas9/extractUserLongNameSas9.js +30 -0
  126. package/utils/serialize.js +20 -0
  127. package/utils/splitChunks.js +13 -0
  128. package/utils/validateInput.js +83 -0
  129. package/.env.example +0 -2
  130. package/.git-hooks/commit-msg +0 -39
  131. package/.git-hooks/pre-commit +0 -12
  132. package/.gitattributes +0 -1
  133. package/.pre-commit-config.yaml +0 -25
  134. package/.vscode/settings.json +0 -3
  135. package/SASViyaApiClient.spec.d.ts +0 -1
  136. package/__mocks__/axios.d.ts +0 -3
  137. package/api/viya/spec/executeScript.spec.d.ts +0 -1
  138. package/api/viya/spec/getFileStream.spec.d.ts +0 -1
  139. package/api/viya/spec/mockResponses.d.ts +0 -10
  140. package/api/viya/spec/pollJobState.spec.d.ts +0 -1
  141. package/api/viya/spec/saveLog.spec.d.ts +0 -1
  142. package/api/viya/spec/uploadTables.spec.d.ts +0 -1
  143. package/api/viya/spec/writeStream.spec.d.ts +0 -1
  144. package/auth/spec/AuthManager.spec.d.ts +0 -4
  145. package/auth/spec/getAccessTokenForSasjs.spec.d.ts +0 -1
  146. package/auth/spec/getAccessTokenForViya.spec.d.ts +0 -1
  147. package/auth/spec/getTokenRequestErrorPrefix.spec.d.ts +0 -1
  148. package/auth/spec/getTokens.spec.d.ts +0 -1
  149. package/auth/spec/loginHeader.spec.d.ts +0 -4
  150. package/auth/spec/mockResponses.d.ts +0 -23
  151. package/auth/spec/openWebPage.spec.d.ts +0 -1
  152. package/auth/spec/refreshTokensForSasjs.spec.d.ts +0 -1
  153. package/auth/spec/refreshTokensForViya.spec.d.ts +0 -1
  154. package/auth/spec/verifySas9Login.spec.d.ts +0 -1
  155. package/auth/spec/verifySasViyaLogin.spec.d.ts +0 -1
  156. package/checkNodeVersion.js +0 -16
  157. package/createTSDocs.js +0 -35
  158. package/cypress.config.js +0 -18
  159. package/example.html +0 -109
  160. package/file/spec/generateFileUploadForm.spec.d.ts +0 -1
  161. package/file/spec/generateTableUploadForm.spec.d.ts +0 -1
  162. package/index-dev.js +0 -80394
  163. package/job-execution/spec/ComputeJobExecutor.spec.d.ts +0 -1
  164. package/job-execution/spec/JesJobExecutor.spec.d.ts +0 -1
  165. package/job-execution/spec/Sas9JobExecutor.spec.d.ts +0 -1
  166. package/job-execution/spec/SasjsJobExecutor.spec.d.ts +0 -1
  167. package/job-execution/spec/WebJobExecutor.debug.spec.d.ts +0 -1
  168. package/job-execution/spec/WebJobExecutor.spec.d.ts +0 -1
  169. package/job-execution/spec/executionTasks.spec.d.ts +0 -1
  170. package/minified_sas9.js +0 -14039
  171. package/node/ContextManager.d.ts +0 -41
  172. package/node/SAS9ApiClient.d.ts +0 -30
  173. package/node/SASViyaApiClient.d.ts +0 -298
  174. package/node/SASjs.d.ts +0 -387
  175. package/node/SASjsApiClient.d.ts +0 -65
  176. package/node/SessionManager.d.ts +0 -115
  177. package/node/api/viya/executeOnComputeApi.d.ts +0 -21
  178. package/node/api/viya/getFileStream.d.ts +0 -2
  179. package/node/api/viya/pollJobState.d.ts +0 -57
  180. package/node/api/viya/saveLog.d.ts +0 -15
  181. package/node/api/viya/uploadTables.d.ts +0 -13
  182. package/node/api/viya/writeStream.d.ts +0 -2
  183. package/node/auth/AuthManager.d.ts +0 -49
  184. package/node/auth/getAccessTokenForSasjs.d.ts +0 -11
  185. package/node/auth/getAccessTokenForViya.d.ts +0 -10
  186. package/node/auth/getTokenRequestErrorPrefix.d.ts +0 -44
  187. package/node/auth/getTokens.d.ts +0 -22
  188. package/node/auth/index.d.ts +0 -4
  189. package/node/auth/isAuthorizeFormRequired.d.ts +0 -1
  190. package/node/auth/isLoginRequired.d.ts +0 -1
  191. package/node/auth/loginHeader.d.ts +0 -17
  192. package/node/auth/openWebPage.d.ts +0 -6
  193. package/node/auth/refreshTokensForSasjs.d.ts +0 -10
  194. package/node/auth/refreshTokensForViya.d.ts +0 -11
  195. package/node/auth/verifySas9Login.d.ts +0 -3
  196. package/node/auth/verifySasViyaLogin.d.ts +0 -4
  197. package/node/file/generateFileUploadForm.d.ts +0 -11
  198. package/node/file/generateTableUploadForm.d.ts +0 -5
  199. package/node/job-execution/ComputeJobExecutor.d.ts +0 -8
  200. package/node/job-execution/FileUploader.d.ts +0 -9
  201. package/node/job-execution/JesJobExecutor.d.ts +0 -9
  202. package/node/job-execution/JobExecutor.d.ts +0 -17
  203. package/node/job-execution/Sas9JobExecutor.d.ts +0 -19
  204. package/node/job-execution/SasjsJobExecutor.d.ts +0 -9
  205. package/node/job-execution/WebJobExecutor.d.ts +0 -18
  206. package/node/job-execution/index.d.ts +0 -7
  207. package/node/request/RequestClient.d.ts +0 -125
  208. package/node/request/Sas9RequestClient.d.ts +0 -25
  209. package/node/request/SasjsRequestClient.d.ts +0 -12
  210. package/node/types/Context.d.ts +0 -42
  211. package/node/types/CsrfToken.d.ts +0 -4
  212. package/node/types/ExecuteScript.d.ts +0 -4
  213. package/node/types/File.d.ts +0 -7
  214. package/node/types/FileResource.d.ts +0 -32
  215. package/node/types/Folder.d.ts +0 -7
  216. package/node/types/Job.d.ts +0 -14
  217. package/node/types/JobDefinition.d.ts +0 -3
  218. package/node/types/JobResult.d.ts +0 -3
  219. package/node/types/Link.d.ts +0 -7
  220. package/node/types/LogStatistics.d.ts +0 -4
  221. package/node/types/Login.d.ts +0 -14
  222. package/node/types/PollOptions.d.ts +0 -8
  223. package/node/types/RequestClient.d.ts +0 -46
  224. package/node/types/SASjsConfig.d.ts +0 -94
  225. package/node/types/Session.d.ts +0 -30
  226. package/node/types/Tables.d.ts +0 -7
  227. package/node/types/UploadFile.d.ts +0 -8
  228. package/node/types/WriteStream.d.ts +0 -7
  229. package/node/types/errors/ArgumentError.d.ts +0 -4
  230. package/node/types/errors/AuthorizeError.d.ts +0 -5
  231. package/node/types/errors/CertificateError.d.ts +0 -3
  232. package/node/types/errors/ComputeJobExecutionError.d.ts +0 -6
  233. package/node/types/errors/ErrorResponse.d.ts +0 -9
  234. package/node/types/errors/InternalServerError.d.ts +0 -3
  235. package/node/types/errors/InvalidJsonError.d.ts +0 -3
  236. package/node/types/errors/InvalidSASjsCsrfError.d.ts +0 -3
  237. package/node/types/errors/JobExecutionError.d.ts +0 -6
  238. package/node/types/errors/JobStatePollError.d.ts +0 -4
  239. package/node/types/errors/JsonParseArrayError.d.ts +0 -3
  240. package/node/types/errors/LoginRequiredError.d.ts +0 -3
  241. package/node/types/errors/NoSessionStateError.d.ts +0 -6
  242. package/node/types/errors/NotFoundError.d.ts +0 -4
  243. package/node/types/errors/RootFolderNotFoundError.d.ts +0 -3
  244. package/node/types/errors/SAS9AuthError.d.ts +0 -3
  245. package/node/types/errors/WeboutResponseError.d.ts +0 -4
  246. package/node/types/errors/index.d.ts +0 -15
  247. package/node/types/index.d.ts +0 -18
  248. package/node/utils/appendExtraResponseAttributes.d.ts +0 -2
  249. package/node/utils/asyncForEach.d.ts +0 -1
  250. package/node/utils/compareTimestamps.d.ts +0 -6
  251. package/node/utils/convertToCsv.d.ts +0 -12
  252. package/node/utils/createAxiosInstance.d.ts +0 -2
  253. package/node/utils/delay.d.ts +0 -1
  254. package/node/utils/extractWeboutBlob.d.ts +0 -13
  255. package/node/utils/fetchLogByChunks.d.ts +0 -20
  256. package/node/utils/formatDataForRequest.d.ts +0 -1
  257. package/node/utils/getFormData.d.ts +0 -2
  258. package/node/utils/getValidJson.d.ts +0 -5
  259. package/node/utils/index.d.ts +0 -25
  260. package/node/utils/isNode.d.ts +0 -1
  261. package/node/utils/isRelativePath.d.ts +0 -1
  262. package/node/utils/isUri.d.ts +0 -5
  263. package/node/utils/isUrl.d.ts +0 -5
  264. package/node/utils/loginPrompt/index.d.ts +0 -1
  265. package/node/utils/needsRetry.d.ts +0 -1
  266. package/node/utils/parseGeneratedCode.d.ts +0 -1
  267. package/node/utils/parseSasViyaLog.d.ts +0 -5
  268. package/node/utils/parseSourceCode.d.ts +0 -1
  269. package/node/utils/parseViyaDebugResponse.d.ts +0 -12
  270. package/node/utils/parseViyaLogDebugResponse.d.ts +0 -8
  271. package/node/utils/parseWeboutResponse.d.ts +0 -1
  272. package/node/utils/sas9/extractUserLongNameSas9.d.ts +0 -6
  273. package/node/utils/serialize.d.ts +0 -1
  274. package/node/utils/splitChunks.d.ts +0 -1
  275. package/node/utils/validateInput.d.ts +0 -14
  276. package/request/spec/SasjsRequestClient.spec.d.ts +0 -1
  277. package/screenshots/session-manager-first-request.png +0 -0
  278. package/screenshots/subsequent-session-request.png +0 -0
  279. package/spec/SAS9ApiClient.spec.d.ts +0 -1
  280. package/spec/SASjs.startComputeJob.spec.d.ts +0 -1
  281. package/spec/SASjsApiClient.spec.d.ts +0 -1
  282. package/src/ContextManager.ts +0 -454
  283. package/src/SAS9ApiClient.ts +0 -100
  284. package/src/SASViyaApiClient.ts +0 -1417
  285. package/src/SASjs.ts +0 -1268
  286. package/src/SASjsApiClient.ts +0 -177
  287. package/src/SessionManager.ts +0 -465
  288. package/src/__mocks__/axios.ts +0 -7
  289. package/src/api/viya/executeOnComputeApi.ts +0 -307
  290. package/src/api/viya/getFileStream.ts +0 -17
  291. package/src/api/viya/pollJobState.ts +0 -393
  292. package/src/api/viya/saveLog.ts +0 -55
  293. package/src/api/viya/spec/mockResponses.ts +0 -75
  294. package/src/api/viya/uploadTables.ts +0 -41
  295. package/src/api/viya/writeStream.ts +0 -16
  296. package/src/auth/AuthManager.ts +0 -387
  297. package/src/auth/getAccessTokenForSasjs.ts +0 -48
  298. package/src/auth/getAccessTokenForViya.ts +0 -61
  299. package/src/auth/getTokenRequestErrorPrefix.ts +0 -88
  300. package/src/auth/getTokens.ts +0 -127
  301. package/src/auth/index.ts +0 -4
  302. package/src/auth/isAuthorizeFormRequired.ts +0 -3
  303. package/src/auth/isLoginRequired.ts +0 -5
  304. package/src/auth/loginHeader.ts +0 -97
  305. package/src/auth/openWebPage.ts +0 -40
  306. package/src/auth/refreshTokensForSasjs.ts +0 -45
  307. package/src/auth/refreshTokensForViya.ts +0 -66
  308. package/src/auth/spec/mockResponses.ts +0 -53
  309. package/src/auth/verifySas9Login.ts +0 -25
  310. package/src/auth/verifySasViyaLogin.ts +0 -43
  311. package/src/file/generateFileUploadForm.ts +0 -48
  312. package/src/file/generateTableUploadForm.ts +0 -50
  313. package/src/index.ts +0 -9
  314. package/src/job-execution/ComputeJobExecutor.ts +0 -76
  315. package/src/job-execution/FileUploader.ts +0 -152
  316. package/src/job-execution/JesJobExecutor.ts +0 -78
  317. package/src/job-execution/JobExecutor.ts +0 -63
  318. package/src/job-execution/Sas9JobExecutor.ts +0 -137
  319. package/src/job-execution/SasjsJobExecutor.ts +0 -152
  320. package/src/job-execution/WebJobExecutor.ts +0 -341
  321. package/src/job-execution/index.ts +0 -7
  322. package/src/minified/sas9/SASjs.ts +0 -274
  323. package/src/minified/sas9/WebJobExecutor.ts +0 -156
  324. package/src/minified/sas9/index.ts +0 -3
  325. package/src/request/RequestClient.ts +0 -941
  326. package/src/request/Sas9RequestClient.ts +0 -132
  327. package/src/request/SasjsRequestClient.ts +0 -82
  328. package/src/test/SAS_server_app.ts +0 -47
  329. package/src/types/Context.ts +0 -39
  330. package/src/types/CsrfToken.ts +0 -4
  331. package/src/types/ExecuteScript.ts +0 -4
  332. package/src/types/File.ts +0 -8
  333. package/src/types/FileResource.ts +0 -33
  334. package/src/types/Folder.ts +0 -8
  335. package/src/types/Job.ts +0 -15
  336. package/src/types/JobDefinition.ts +0 -3
  337. package/src/types/JobResult.ts +0 -3
  338. package/src/types/Link.ts +0 -7
  339. package/src/types/LogStatistics.ts +0 -4
  340. package/src/types/Login.ts +0 -15
  341. package/src/types/PollOptions.ts +0 -9
  342. package/src/types/Process.d.ts +0 -5
  343. package/src/types/RequestClient.ts +0 -55
  344. package/src/types/SASjsConfig.ts +0 -95
  345. package/src/types/Session.ts +0 -34
  346. package/src/types/Tables.ts +0 -29
  347. package/src/types/UploadFile.ts +0 -8
  348. package/src/types/WriteStream.ts +0 -10
  349. package/src/types/errors/ArgumentError.ts +0 -7
  350. package/src/types/errors/AuthorizeError.ts +0 -10
  351. package/src/types/errors/CertificateError.ts +0 -12
  352. package/src/types/errors/ComputeJobExecutionError.ts +0 -12
  353. package/src/types/errors/ErrorResponse.ts +0 -28
  354. package/src/types/errors/InternalServerError.ts +0 -9
  355. package/src/types/errors/InvalidJsonError.ts +0 -7
  356. package/src/types/errors/InvalidSASjsCsrfError.ts +0 -9
  357. package/src/types/errors/JobExecutionError.ts +0 -11
  358. package/src/types/errors/JobStatePollError.ts +0 -14
  359. package/src/types/errors/JsonParseArrayError.ts +0 -7
  360. package/src/types/errors/LoginRequiredError.ts +0 -11
  361. package/src/types/errors/NoSessionStateError.ts +0 -15
  362. package/src/types/errors/NotFoundError.ts +0 -7
  363. package/src/types/errors/RootFolderNotFoundError.ts +0 -24
  364. package/src/types/errors/SAS9AuthError.ts +0 -9
  365. package/src/types/errors/WeboutResponseError.ts +0 -7
  366. package/src/types/errors/index.ts +0 -15
  367. package/src/types/index.ts +0 -18
  368. package/src/types/system/global.d.ts +0 -1
  369. package/src/utils/appendExtraResponseAttributes.ts +0 -22
  370. package/src/utils/asyncForEach.ts +0 -5
  371. package/src/utils/compareTimestamps.ts +0 -9
  372. package/src/utils/convertToCsv.ts +0 -198
  373. package/src/utils/createAxiosInstance.ts +0 -7
  374. package/src/utils/delay.ts +0 -2
  375. package/src/utils/fetchLogByChunks.ts +0 -63
  376. package/src/utils/formatDataForRequest.ts +0 -48
  377. package/src/utils/getFormData.ts +0 -5
  378. package/src/utils/getUserLanguage.ts +0 -10
  379. package/src/utils/getValidJson.ts +0 -23
  380. package/src/utils/index.ts +0 -25
  381. package/src/utils/isIeOrEdge.ts +0 -34
  382. package/src/utils/isNode.ts +0 -4
  383. package/src/utils/isRelativePath.ts +0 -2
  384. package/src/utils/isUri.ts +0 -5
  385. package/src/utils/isUrl.ts +0 -17
  386. package/src/utils/loginPrompt/index.ts +0 -177
  387. package/src/utils/needsRetry.ts +0 -14
  388. package/src/utils/parseGeneratedCode.ts +0 -7
  389. package/src/utils/parseSasViyaLog.ts +0 -12
  390. package/src/utils/parseSourceCode.ts +0 -6
  391. package/src/utils/parseViyaDebugResponse.ts +0 -46
  392. package/src/utils/parseViyaLogDebugResponse.ts +0 -22
  393. package/src/utils/parseWeboutResponse.ts +0 -20
  394. package/src/utils/sas9/extractUserLongNameSas9.ts +0 -31
  395. package/src/utils/serialize.ts +0 -15
  396. package/src/utils/splitChunks.ts +0 -12
  397. package/src/utils/validateInput.ts +0 -93
  398. package/test/ContextManager.spec.d.ts +0 -1
  399. package/test/FileUploader.spec.d.ts +0 -4
  400. package/test/FolderOperations.spec.d.ts +0 -1
  401. package/test/RequestClient.spec.d.ts +0 -1
  402. package/test/SAS_server_app.d.ts +0 -10
  403. package/test/SessionManager.spec.d.ts +0 -1
  404. package/test/getJobsInFolder.spec.d.ts +0 -1
  405. package/test/utils/formatDataForRequest.spec.d.ts +0 -1
  406. package/test/utils/getValidJson.spec.d.ts +0 -1
  407. package/test/utils/isUrl.spec.d.ts +0 -1
  408. package/test/utils/parseGeneratedCode.spec.d.ts +0 -1
  409. package/test/utils/parseSourceCode.spec.d.ts +0 -1
  410. package/types/Tables.spec.d.ts +0 -1
  411. package/types/errors/RootFolderNotFoundError.spec.d.ts +0 -1
  412. package/types/errors/spec/SAS9AuthError.spec.d.ts +0 -1
  413. package/utils/spec/convertToCsv.spec.d.ts +0 -1
  414. package/utils/spec/extractUserLongNameSas9.spec.d.ts +0 -1
  415. package/utils/spec/getFormData.spec.d.ts +0 -1
  416. package/utils/spec/parseSasViyaLog.spec.d.ts +0 -1
  417. package/utils/spec/parseViyaDebugResponse.spec.d.ts +0 -1
  418. package/utils/spec/parseViyaLogDebugResponse.spec.d.ts +0 -1
  419. package/utils/spec/validateInput.spec.d.ts +0 -1
@@ -0,0 +1,918 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.SASViyaApiClient = void 0;
16
+ const utils_1 = require("./utils");
17
+ const form_data_1 = __importDefault(require("form-data"));
18
+ const errors_1 = require("./types/errors");
19
+ const SessionManager_1 = require("./SessionManager");
20
+ const ContextManager_1 = require("./ContextManager");
21
+ const types_1 = require("@sasjs/utils/types");
22
+ const isAuthorizeFormRequired_1 = require("./auth/isAuthorizeFormRequired");
23
+ const error_1 = require("@sasjs/utils/error");
24
+ const pollJobState_1 = require("./api/viya/pollJobState");
25
+ const getTokens_1 = require("./auth/getTokens");
26
+ const uploadTables_1 = require("./api/viya/uploadTables");
27
+ const executeOnComputeApi_1 = require("./api/viya/executeOnComputeApi");
28
+ const getAccessTokenForViya_1 = require("./auth/getAccessTokenForViya");
29
+ const refreshTokensForViya_1 = require("./auth/refreshTokensForViya");
30
+ const host_1 = require("./utils/host");
31
+ /**
32
+ * A client for interfacing with the SAS Viya REST API.
33
+ *
34
+ */
35
+ class SASViyaApiClient {
36
+ constructor(serverUrl, rootFolderName, contextName, requestClient) {
37
+ this.serverUrl = serverUrl;
38
+ this.rootFolderName = rootFolderName;
39
+ this.contextName = contextName;
40
+ this.requestClient = requestClient;
41
+ this._debug = false;
42
+ this.sessionManager = new SessionManager_1.SessionManager(this.serverUrl, this.contextName, this.requestClient);
43
+ this.contextManager = new ContextManager_1.ContextManager(this.serverUrl, this.requestClient);
44
+ this.folderMap = new Map();
45
+ this.fileExtensionMap = new Map();
46
+ this.boolExtensionMap = false; // required in case the map has zero entries
47
+ if (serverUrl)
48
+ (0, utils_1.isUrl)(serverUrl);
49
+ }
50
+ // after an attempt to populate it.
51
+ /**
52
+ * A helper method used to call appendRequest method of RequestClient
53
+ * @param response - response from sasjs request
54
+ * @param program - name of program
55
+ * @param debug - a boolean that indicates whether debug was enabled or not
56
+ */
57
+ appendRequest(response, program, debug) {
58
+ this.requestClient.appendRequest(response, program, debug);
59
+ }
60
+ get debug() {
61
+ return this._debug;
62
+ }
63
+ set debug(value) {
64
+ this._debug = value;
65
+ if (this.sessionManager) {
66
+ this.sessionManager.debug = value;
67
+ }
68
+ }
69
+ /**
70
+ * Returns a list of jobs in the currently set root folder.
71
+ */
72
+ getJobsInFolder(folderPath) {
73
+ return __awaiter(this, void 0, void 0, function* () {
74
+ const path = (0, utils_1.isRelativePath)(folderPath)
75
+ ? `${this.rootFolderName}/${folderPath}`
76
+ : folderPath;
77
+ if (this.folderMap.get(path)) {
78
+ return this.folderMap.get(path);
79
+ }
80
+ yield this.populateFolderMap(path);
81
+ return this.folderMap.get(path);
82
+ });
83
+ }
84
+ /**
85
+ * Returns an object containing the server URL and root folder name.
86
+ */
87
+ getConfig() {
88
+ return {
89
+ serverUrl: this.serverUrl,
90
+ rootFolderName: this.rootFolderName
91
+ };
92
+ }
93
+ /**
94
+ * Updates server URL and root folder name, if it was not set.
95
+ * @param serverUrl - the URL of the server.
96
+ * @param rootFolderName - the name for root folder.
97
+ */
98
+ setConfig(serverUrl, rootFolderName) {
99
+ if (serverUrl)
100
+ this.serverUrl = serverUrl;
101
+ if (rootFolderName)
102
+ this.rootFolderName = rootFolderName;
103
+ }
104
+ /**
105
+ * Returns all available compute contexts on this server.
106
+ * @param accessToken - an access token for an authorized user.
107
+ */
108
+ getComputeContexts(accessToken) {
109
+ return __awaiter(this, void 0, void 0, function* () {
110
+ return yield this.contextManager.getComputeContexts(accessToken);
111
+ });
112
+ }
113
+ /**
114
+ * Returns default(system) compute contexts.
115
+ */
116
+ getDefaultComputeContexts() {
117
+ return this.contextManager.getDefaultComputeContexts;
118
+ }
119
+ /**
120
+ * Returns all available launcher contexts on this server.
121
+ * @param accessToken - an access token for an authorized user.
122
+ */
123
+ getLauncherContexts(accessToken) {
124
+ return __awaiter(this, void 0, void 0, function* () {
125
+ return yield this.contextManager.getLauncherContexts(accessToken);
126
+ });
127
+ }
128
+ /**
129
+ * Returns all compute contexts on this server that the user has access to.
130
+ * @param authConfig - an access token, refresh token, client and secret for an authorized user.
131
+ */
132
+ getExecutableContexts(authConfig) {
133
+ return __awaiter(this, void 0, void 0, function* () {
134
+ const bindedExecuteScript = this.executeScript.bind(this);
135
+ return yield this.contextManager.getExecutableContexts(bindedExecuteScript, authConfig);
136
+ });
137
+ }
138
+ /**
139
+ * Creates a session on the given context.
140
+ * @param contextName - the name of the context to create a session on.
141
+ * @param accessToken - an access token for an authorized user.
142
+ */
143
+ createSession(contextName, accessToken) {
144
+ return __awaiter(this, void 0, void 0, function* () {
145
+ const headers = {
146
+ 'Content-Type': 'application/json'
147
+ };
148
+ if (accessToken) {
149
+ headers.Authorization = `Bearer ${accessToken}`;
150
+ }
151
+ const { result: contexts } = yield this.requestClient.get(`/compute/contexts?limit=10000`, accessToken);
152
+ const executionContext = contexts.items && contexts.items.length
153
+ ? contexts.items.find((c) => c.name === contextName)
154
+ : null;
155
+ if (!executionContext) {
156
+ throw new Error(`Execution context ${contextName} not found.`);
157
+ }
158
+ const { result: createdSession } = yield this.requestClient.post(`/compute/contexts/${executionContext.id}/sessions`, {}, accessToken);
159
+ return createdSession;
160
+ });
161
+ }
162
+ /**
163
+ * Creates a compute context on the given server.
164
+ * @param contextName - the name of the context to be created.
165
+ * @param launchContextName - the name of the launcher context used by the compute service.
166
+ * @param sharedAccountId - the ID of the account to run the servers for this context.
167
+ * @param autoExecLines - the lines of code to execute during session initialization.
168
+ * @param accessToken - an access token for an authorized user.
169
+ * @param authorizedUsers - an optional list of authorized user IDs.
170
+ */
171
+ createComputeContext(contextName, launchContextName, sharedAccountId, autoExecLines, accessToken, authorizedUsers) {
172
+ return __awaiter(this, void 0, void 0, function* () {
173
+ return yield this.contextManager.createComputeContext(contextName, launchContextName, sharedAccountId, autoExecLines, accessToken, authorizedUsers);
174
+ });
175
+ }
176
+ /**
177
+ * Creates a launcher context on the given server.
178
+ * @param contextName - the name of the context to be created.
179
+ * @param description - the description of the context to be created.
180
+ * @param launchType - launch type of the context to be created.
181
+ * @param accessToken - an access token for an authorized user.
182
+ */
183
+ createLauncherContext(contextName, description, launchType = 'direct', accessToken) {
184
+ return __awaiter(this, void 0, void 0, function* () {
185
+ return yield this.contextManager.createLauncherContext(contextName, description, launchType, accessToken);
186
+ });
187
+ }
188
+ /**
189
+ * Updates a compute context on the given server.
190
+ * @param contextName - the original name of the context to be updated.
191
+ * @param editedContext - an object with the properties to be updated.
192
+ * @param accessToken - an access token for an authorized user.
193
+ */
194
+ editComputeContext(contextName, editedContext, accessToken) {
195
+ return __awaiter(this, void 0, void 0, function* () {
196
+ return yield this.contextManager.editComputeContext(contextName, editedContext, accessToken);
197
+ });
198
+ }
199
+ /**
200
+ * Deletes a compute context on the given server.
201
+ * @param contextName - the name of the context to be deleted.
202
+ * @param accessToken - an access token for an authorized user.
203
+ */
204
+ deleteComputeContext(contextName, accessToken) {
205
+ return __awaiter(this, void 0, void 0, function* () {
206
+ return yield this.contextManager.deleteComputeContext(contextName, accessToken);
207
+ });
208
+ }
209
+ /**
210
+ * Executes code on the current SAS Viya server.
211
+ * @param jobPath - the path to the file being submitted for execution.
212
+ * @param linesOfCode - an array of code lines to execute.
213
+ * @param contextName - the context to execute the code in.
214
+ * @param authConfig - an object containing an access token, refresh token, client ID and secret.
215
+ * @param data - execution data.
216
+ * @param debug - when set to true, the log will be returned.
217
+ * @param expectWebout - when set to true, the automatic _webout fileref will be checked for content, and that content returned. This fileref is used when the Job contains a SASjs web request (as opposed to executing arbitrary SAS code).
218
+ * @param waitForResult - when set to true, function will return the session
219
+ * @param pollOptions - an object that represents poll interval(milliseconds) and maximum amount of attempts. Object example: { maxPollCount: 24 * 60 * 60, pollInterval: 1000 }. More information available at src/api/viya/pollJobState.ts.
220
+ * @param printPid - a boolean that indicates whether the function should print (PID) of the started job.
221
+ * @param variables - an object that represents macro variables.
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
+ */
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* () {
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
+ });
228
+ }
229
+ /**
230
+ * Fetches the file content for a file in the specified folder.
231
+ *
232
+ * @param folderPath - the full path to the folder containing the file. eg: /Public/folder1/folder2
233
+ * @param fileName - the name of the file in the `folderPath`
234
+ * @param accessToken - an access token for authorizing the request
235
+ */
236
+ getFileContent(folderPath, fileName, accessToken) {
237
+ return __awaiter(this, void 0, void 0, function* () {
238
+ const fileUri = yield this.getFileUri(folderPath, fileName, accessToken).catch((err) => {
239
+ throw (0, error_1.prefixMessage)(err, `Error while getting file URI for: ${fileName} in folder: ${folderPath}. `);
240
+ });
241
+ return yield this.requestClient
242
+ .get(`${this.serverUrl}${fileUri}/content`, accessToken)
243
+ .then((res) => res.result);
244
+ });
245
+ }
246
+ /**
247
+ * Updates the file content for a file in the specified folder.
248
+ *
249
+ * @param folderPath - the full path to the folder containing the file. eg: /Public/folder1/folder2
250
+ * @param fileName - the name of the file in the `folderPath`
251
+ * @param content - the new content to be written to the file
252
+ * @param accessToken - an access token for authorizing the request
253
+ */
254
+ updateFileContent(folderPath, fileName, content, accessToken) {
255
+ return __awaiter(this, void 0, void 0, function* () {
256
+ const fileUri = yield this.getFileUri(folderPath, fileName, accessToken).catch((err) => {
257
+ throw (0, error_1.prefixMessage)(err, `Error while getting file URI for: ${fileName} in folder: ${folderPath}. `);
258
+ });
259
+ // Fetch the file resource details to get the Etag and content type
260
+ const { result: originalFileResource, etag } = yield this.requestClient.get(`${this.serverUrl}${fileUri}`, accessToken);
261
+ if (!originalFileResource || !etag)
262
+ throw new Error(`File ${fileName} does not have an ETag, or request failed.`);
263
+ return yield this.requestClient
264
+ .put(`${this.serverUrl}${fileUri}/content`, content, accessToken, {
265
+ 'If-Match': etag,
266
+ 'Content-Type': originalFileResource.contentType
267
+ })
268
+ .then((res) => res.result);
269
+ });
270
+ }
271
+ /**
272
+ * Fetches a folder. Path to the folder is required.
273
+ * @param folderPath - the absolute path to the folder.
274
+ * @param accessToken - an access token for authorizing the request.
275
+ */
276
+ getFolder(folderPath, accessToken) {
277
+ return __awaiter(this, void 0, void 0, function* () {
278
+ return yield this.requestClient
279
+ .get(`/folders/folders/@item?path=${folderPath}`, accessToken)
280
+ .then((res) => res.result);
281
+ });
282
+ }
283
+ /**
284
+ * Creates a file. Path to or URI of the parent folder is required.
285
+ * @param fileName - the name of the new file.
286
+ * @param contentBuffer - the content of the new file in Buffer.
287
+ * @param parentFolderPath - the full path to the parent folder. If not
288
+ * provided, the parentFolderUri must be provided.
289
+ * @param parentFolderUri - the URI (eg /folders/folders/UUID) of the parent
290
+ * folder. If not provided, the parentFolderPath must be provided.
291
+ * @param accessToken - an access token for authorizing the request.
292
+ */
293
+ createFile(fileName, contentBuffer, parentFolderPath, parentFolderUri, accessToken) {
294
+ var _a;
295
+ return __awaiter(this, void 0, void 0, function* () {
296
+ if (!parentFolderPath && !parentFolderUri) {
297
+ throw new Error('Path or URI of the parent folder is required.');
298
+ }
299
+ if (!parentFolderUri && parentFolderPath) {
300
+ parentFolderUri = yield this.getFolderUri(parentFolderPath, accessToken);
301
+ }
302
+ const headers = {
303
+ Accept: 'application/vnd.sas.file+json',
304
+ 'Content-Disposition': `filename="${fileName}";`
305
+ };
306
+ const formData = new form_data_1.default();
307
+ formData.append('file', contentBuffer, fileName);
308
+ /** Query Viya for file metadata based on extension type. */
309
+ // typeDefName - Viya accepts this property during the file creation
310
+ let typeDefName = undefined;
311
+ // Additional properties are supplied by a patch.
312
+ let filePatch = undefined;
313
+ // The patching process requires properties related to the file-extension
314
+ const fileExtension = (_a = fileName
315
+ .split('.')
316
+ .pop()) === null || _a === void 0 ? void 0 : _a.toLowerCase();
317
+ if (fileExtension) {
318
+ if (!this.boolExtensionMap) {
319
+ // Populate the file extension map
320
+ // 1. Get Viya's response to this api call
321
+ const typesQueryUrl = `/types/types?limit=999999`;
322
+ const response = (yield this.requestClient.get(typesQueryUrl, accessToken)).result;
323
+ // 2. Filter the returned items that have file extensions into a map
324
+ // using forEach as an item may relate to multiple file extensions.
325
+ response.items
326
+ .filter((e) => e.extensions)
327
+ .forEach((e) => {
328
+ var _a;
329
+ (_a = e.extensions) === null || _a === void 0 ? void 0 : _a.forEach((ext) => {
330
+ this.fileExtensionMap.set(ext, {
331
+ // `name` becomes the typeDefName value at file creation time.
332
+ // `name` is ignored here if it is not populated in the map, or
333
+ // has a blank/empty value.
334
+ typeDefName: e.name
335
+ ? e.name.trim().length
336
+ ? e.name.trim()
337
+ : undefined
338
+ : undefined,
339
+ properties: e.properties
340
+ });
341
+ });
342
+ });
343
+ // 3. Toggle the flag to avoid repeating this step
344
+ this.boolExtensionMap = true;
345
+ }
346
+ // Query the map for the current file extension
347
+ const fileExtInfo = this.fileExtensionMap.get(fileExtension);
348
+ if (fileExtInfo) {
349
+ // If the extension was found in the map, record the typeDefName and
350
+ // create a patch if a properties object was returned.
351
+ typeDefName = fileExtInfo.typeDefName;
352
+ if (fileExtInfo.properties)
353
+ filePatch = { name: fileName, properties: fileExtInfo.properties };
354
+ }
355
+ }
356
+ // Create the file
357
+ const createFileResponse = yield this.requestClient.post(`/files/files?parentFolderUri=${parentFolderUri}&typeDefName=${typeDefName !== null && typeDefName !== void 0 ? typeDefName : 'file'}#rawUpload`, formData, accessToken, 'multipart/form-data; boundary=' + formData._boundary, headers);
358
+ // If a patch was created...
359
+ if (filePatch) {
360
+ try {
361
+ const patchHeaders = {
362
+ Accept: 'application/json',
363
+ 'If-Match': '*'
364
+ };
365
+ // Get the URI of the newly created file
366
+ const fileUri = createFileResponse.result.links.filter((e) => e.method == 'PATCH' && e.rel == 'patch')[0].uri;
367
+ // and apply the patch
368
+ return (yield this.requestClient.patch(`${fileUri}`, filePatch, accessToken, patchHeaders)).result;
369
+ }
370
+ catch (e) {
371
+ throw new Error(`Error patching file ${fileName}.\n${e.message}`);
372
+ }
373
+ }
374
+ return createFileResponse.result;
375
+ });
376
+ }
377
+ /**
378
+ * Creates a folder. Path to or URI of the parent folder is required.
379
+ * @param folderName - the name of the new folder.
380
+ * @param parentFolderPath - the full path to the parent folder. If not
381
+ * provided, the parentFolderUri must be provided.
382
+ * @param parentFolderUri - the URI (eg /folders/folders/UUID) of the parent
383
+ * folder. If not provided, the parentFolderPath must be provided.
384
+ * @param accessToken - an access token for authorizing the request.
385
+ * @param isForced - flag that indicates if target folder already exists, it and all subfolders have to be deleted.
386
+ */
387
+ createFolder(folderName, parentFolderPath, parentFolderUri, accessToken, isForced) {
388
+ return __awaiter(this, void 0, void 0, function* () {
389
+ const logger = (0, host_1.getLogger)();
390
+ if (!parentFolderPath && !parentFolderUri) {
391
+ throw new Error('Path or URI of the parent folder is required.');
392
+ }
393
+ if (!parentFolderUri && parentFolderPath) {
394
+ parentFolderUri = yield this.getFolderUri(parentFolderPath, accessToken);
395
+ if (!parentFolderUri) {
396
+ logger.info(`Parent folder at path '${parentFolderPath}' is not present.`);
397
+ const newParentFolderPath = parentFolderPath.substring(0, parentFolderPath.lastIndexOf('/'));
398
+ const newFolderName = `${parentFolderPath.split('/').pop()}`;
399
+ if (newParentFolderPath === '') {
400
+ throw new errors_1.RootFolderNotFoundError(parentFolderPath, this.serverUrl, accessToken);
401
+ }
402
+ logger.info(`Creating parent folder:\n'${newFolderName}' in '${newParentFolderPath}'`);
403
+ const parentFolder = yield this.createFolder(newFolderName, newParentFolderPath, undefined, accessToken);
404
+ logger.info(`Parent folder '${newFolderName}' has been successfully created.`);
405
+ parentFolderUri = `/folders/folders/${parentFolder.id}`;
406
+ }
407
+ else if (isForced) {
408
+ const folderPath = parentFolderPath + '/' + folderName;
409
+ const folderUri = yield this.getFolderUri(folderPath, accessToken);
410
+ if (folderUri) {
411
+ yield this.deleteFolder(parentFolderPath + '/' + folderName, accessToken);
412
+ }
413
+ }
414
+ }
415
+ const { result: createFolderResponse } = yield this.requestClient
416
+ .post(`/folders/folders?parentFolderUri=${parentFolderUri}`, {
417
+ name: folderName,
418
+ type: 'folder'
419
+ }, accessToken)
420
+ .catch((err) => {
421
+ const { message, response } = err;
422
+ if (message && response && response.data && response.data.message) {
423
+ const { status } = response;
424
+ const { message: responseMessage } = response.data;
425
+ const messages = [message, responseMessage].map((mes) => /\.$/.test(mes) ? mes : `${mes}.`);
426
+ if (!isForced && status === 409) {
427
+ messages.push(`To override, please set "isForced" to "true".`);
428
+ }
429
+ const errMessage = messages.join(' ');
430
+ throw errMessage;
431
+ }
432
+ throw err;
433
+ });
434
+ // update folder map with newly created folder.
435
+ yield this.populateFolderMap(`${parentFolderPath}/${folderName}`, accessToken);
436
+ return createFolderResponse;
437
+ });
438
+ }
439
+ /**
440
+ * Creates a Job in the specified folder (or folder uri).
441
+ * @param parentFolderPath - the location of the new job.
442
+ * @param parentFolderUri - the URI location of the new job. The function is a
443
+ * little faster if the folder URI is supplied instead of the path.
444
+ * @param jobName - the name of the new job to be created.
445
+ * @param code - the SAS code for the new job.
446
+ */
447
+ createJobDefinition(jobName, code, parentFolderPath, parentFolderUri, accessToken) {
448
+ return __awaiter(this, void 0, void 0, function* () {
449
+ if (!parentFolderPath && !parentFolderUri) {
450
+ throw new Error(`Path to or URI of the parent folder is required.`);
451
+ }
452
+ if (!parentFolderUri && parentFolderPath) {
453
+ parentFolderUri = yield this.getFolderUri(parentFolderPath, accessToken);
454
+ }
455
+ return yield this.requestClient.post(`${this.serverUrl}/jobDefinitions/definitions?parentFolderUri=${parentFolderUri}`, {
456
+ name: jobName,
457
+ parameters: [
458
+ {
459
+ name: '_addjesbeginendmacros',
460
+ type: 'CHARACTER',
461
+ defaultValue: 'false'
462
+ }
463
+ ],
464
+ type: 'Compute',
465
+ code
466
+ }, accessToken);
467
+ });
468
+ }
469
+ /**
470
+ * Performs a login redirect and returns an auth code for the given client.
471
+ * @param clientId - the client ID to authenticate with.
472
+ */
473
+ getAuthCode(clientId) {
474
+ return __awaiter(this, void 0, void 0, function* () {
475
+ const authUrl = `${this.serverUrl}/SASLogon/oauth/authorize?client_id=${clientId}&response_type=code`;
476
+ const authCode = yield this.requestClient
477
+ .get(authUrl, undefined, 'text/plain')
478
+ .then((response) => response.result)
479
+ .then((response) => __awaiter(this, void 0, void 0, function* () {
480
+ let code = '';
481
+ if ((0, isAuthorizeFormRequired_1.isAuthorizeFormRequired)(response)) {
482
+ const formResponse = yield this.requestClient.authorize(response);
483
+ const responseBody = formResponse
484
+ .split('<body>')[1]
485
+ .split('</body>')[0];
486
+ const bodyElement = document.createElement('div');
487
+ bodyElement.innerHTML = responseBody;
488
+ code = bodyElement.querySelector('.infobox h4').innerText;
489
+ return code;
490
+ }
491
+ else {
492
+ const responseBody = response.split('<body>')[1].split('</body>')[0];
493
+ const bodyElement = document.createElement('div');
494
+ bodyElement.innerHTML = responseBody;
495
+ if (bodyElement) {
496
+ code = bodyElement.querySelector('.infobox h4').innerText;
497
+ }
498
+ return code;
499
+ }
500
+ }))
501
+ .catch(() => null);
502
+ return authCode;
503
+ });
504
+ }
505
+ /**
506
+ * Exchanges the auth code for an access token for the given client.
507
+ * @param clientId - the client ID to authenticate with.
508
+ * @param clientSecret - the client secret to authenticate with.
509
+ * @param authCode - the auth code received from the server.
510
+ */
511
+ getAccessToken(clientId, clientSecret, authCode) {
512
+ return __awaiter(this, void 0, void 0, function* () {
513
+ return (0, getAccessTokenForViya_1.getAccessTokenForViya)(this.requestClient, clientId, clientSecret, authCode);
514
+ });
515
+ }
516
+ /**
517
+ * Exchanges the refresh token for an access token for the given client.
518
+ * This method can only be used by Node.
519
+ * @param clientId - the client ID to authenticate with.
520
+ * @param clientSecret - the client secret to authenticate with.
521
+ * @param refreshToken - the refresh token received from the server.
522
+ */
523
+ refreshTokens(clientId, clientSecret, refreshToken) {
524
+ return __awaiter(this, void 0, void 0, function* () {
525
+ return (0, refreshTokensForViya_1.refreshTokensForViya)(this.requestClient, clientId, clientSecret, refreshToken);
526
+ });
527
+ }
528
+ /**
529
+ * Deletes the client representing the supplied ID.
530
+ * @param clientId - the client ID to authenticate with.
531
+ * @param accessToken - an access token for authorizing the request.
532
+ */
533
+ deleteClient(clientId, accessToken) {
534
+ return __awaiter(this, void 0, void 0, function* () {
535
+ const url = this.serverUrl + `/oauth/clients/${clientId}`;
536
+ const headers = {};
537
+ if (accessToken) {
538
+ headers.Authorization = `Bearer ${accessToken}`;
539
+ }
540
+ const deleteResponse = yield this.requestClient.delete(url, accessToken);
541
+ return deleteResponse.result;
542
+ });
543
+ }
544
+ /**
545
+ * Executes a job via the SAS Viya Compute API.
546
+ * @param sasJob - the relative path to the job.
547
+ * @param contextName - the name of the context where the job is to be executed.
548
+ * @param debug - sets the _debug flag in the job arguments.
549
+ * @param data - any data to be passed in as input to the job.
550
+ * @param accessToken - an optional access token for an authorized user.
551
+ * @param waitForResult - a boolean indicating if the function should wait for a result.
552
+ * @param expectWebout - a boolean indicating whether to expect a _webout response.
553
+ * @param pollOptions - an object that represents poll interval(milliseconds) and maximum amount of attempts. Object example: { maxPollCount: 24 * 60 * 60, pollInterval: 1000 }. More information available at src/api/viya/pollJobState.ts.
554
+ * @param printPid - a boolean that indicates whether the function should print (PID) of the started job.
555
+ * @param variables - an object that represents macro variables.
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* () {
559
+ let access_token = (authConfig || {}).access_token;
560
+ if (authConfig) {
561
+ ;
562
+ ({ access_token } = yield (0, getTokens_1.getTokens)(this.requestClient, authConfig, types_1.ServerType.SasViya, onTokensRefreshed));
563
+ }
564
+ if ((0, utils_1.isRelativePath)(sasJob) && !this.rootFolderName) {
565
+ throw new Error('Relative paths cannot be used without specifying a root folder name');
566
+ }
567
+ const folderPathParts = sasJob.split('/');
568
+ const jobName = folderPathParts.pop();
569
+ const folderPath = folderPathParts.join('/');
570
+ const fullFolderPath = (0, utils_1.isRelativePath)(sasJob)
571
+ ? `${this.rootFolderName}/${folderPath}`
572
+ : folderPath;
573
+ yield this.populateFolderMap(fullFolderPath, access_token).catch((err) => {
574
+ throw (0, error_1.prefixMessage)(err, 'Error while populating folder map. ');
575
+ });
576
+ const jobFolder = this.folderMap.get(fullFolderPath);
577
+ if (!jobFolder) {
578
+ throw new Error(`The folder '${fullFolderPath}' was not found on '${this.serverUrl}'`);
579
+ }
580
+ const jobToExecute = jobFolder === null || jobFolder === void 0 ? void 0 : jobFolder.find((item) => item.name === jobName);
581
+ if (!jobToExecute) {
582
+ throw new Error(`Job was not found.`);
583
+ }
584
+ let code = jobToExecute === null || jobToExecute === void 0 ? void 0 : jobToExecute.code;
585
+ if (!code) {
586
+ const jobDefinitionLink = jobToExecute === null || jobToExecute === void 0 ? void 0 : jobToExecute.links.find((l) => l.rel === 'getResource');
587
+ if (!jobDefinitionLink) {
588
+ throw new Error(`URI of job definition was not found.`);
589
+ }
590
+ const { result: jobDefinition } = yield this.requestClient
591
+ .get(`${this.serverUrl}${jobDefinitionLink.href}`, access_token)
592
+ .catch((err) => {
593
+ throw (0, error_1.prefixMessage)(err, 'Error while getting job definition. ');
594
+ });
595
+ code = jobDefinition.code;
596
+ // Adds code to existing job definition
597
+ jobToExecute.code = code;
598
+ }
599
+ if (!code)
600
+ code = '';
601
+ const linesToExecute = code.replace(/\r\n/g, '\n').split('\n');
602
+ return yield this.executeScript(sasJob, linesToExecute, contextName, authConfig, data, debug, expectWebout, waitForResult, pollOptions, printPid, variables, onTokensRefreshed);
603
+ });
604
+ }
605
+ /**
606
+ * Executes a job via the SAS Viya Job Execution API
607
+ * @param sasJob - the relative or absolute path to the job.
608
+ * @param contextName - the name of the context where the job is to be executed.
609
+ * @param debug - sets the _debug flag in the job arguments.
610
+ * @param data - any data to be passed in as input to the job.
611
+ * @param accessToken - an optional access token for an authorized user.
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
+ */
614
+ executeJob(sasJob, contextName, debug, data, authConfig, onTokensRefreshed) {
615
+ var _a, _b, _c;
616
+ return __awaiter(this, void 0, void 0, function* () {
617
+ let access_token = (authConfig || {}).access_token;
618
+ if (authConfig) {
619
+ ;
620
+ ({ access_token } = yield (0, getTokens_1.getTokens)(this.requestClient, authConfig, types_1.ServerType.SasViya, onTokensRefreshed));
621
+ }
622
+ if ((0, utils_1.isRelativePath)(sasJob) && !this.rootFolderName) {
623
+ throw new Error('Relative paths cannot be used without specifying a root folder name.');
624
+ }
625
+ const folderPathParts = sasJob.split('/');
626
+ const jobName = folderPathParts.pop();
627
+ const folderPath = folderPathParts.join('/');
628
+ const fullFolderPath = (0, utils_1.isRelativePath)(sasJob)
629
+ ? `${this.rootFolderName}/${folderPath}`
630
+ : folderPath;
631
+ yield this.populateFolderMap(fullFolderPath, access_token);
632
+ const jobFolder = this.folderMap.get(fullFolderPath);
633
+ if (!jobFolder) {
634
+ throw new Error(`The folder '${fullFolderPath}' was not found on '${this.serverUrl}'.`);
635
+ }
636
+ const jobToExecute = jobFolder === null || jobFolder === void 0 ? void 0 : jobFolder.find((item) => item.name === jobName);
637
+ let files = [];
638
+ if (data && Object.keys(data).length) {
639
+ files = yield this.uploadTables(data, access_token);
640
+ }
641
+ if (!jobToExecute)
642
+ throw new Error(`Job was not found.`);
643
+ const jobDefinitionLink = (_a = jobToExecute === null || jobToExecute === void 0 ? void 0 : jobToExecute.links.find((l) => l.rel === 'getResource')) === null || _a === void 0 ? void 0 : _a.href;
644
+ const { result: jobDefinition } = yield this.requestClient.get(`${this.serverUrl}${jobDefinitionLink}`, access_token);
645
+ const jobArguments = {
646
+ _contextName: contextName,
647
+ _program: `${fullFolderPath}/${jobName}`,
648
+ _webin_file_count: files.length,
649
+ _OMITJSONLISTING: true,
650
+ _OMITJSONLOG: true,
651
+ _omitSessionResults: false,
652
+ _OMITTEXTLISTING: true,
653
+ _OMITTEXTLOG: true
654
+ };
655
+ if (debug) {
656
+ jobArguments['_OMITTEXTLOG'] = 'false';
657
+ jobArguments['_omitSessionResults'] = 'false';
658
+ jobArguments['_DEBUG'] = 131;
659
+ }
660
+ files.forEach((fileInfo, index) => {
661
+ jobArguments[`_webin_fileuri${index + 1}`] =
662
+ `/files/files/${fileInfo.file.id}`;
663
+ jobArguments[`_webin_name${index + 1}`] = fileInfo.tableName;
664
+ });
665
+ // Viya JES requires arguments to be Map<String,String>; coerce booleans/numbers.
666
+ const stringifiedArguments = {};
667
+ for (const k of Object.keys(jobArguments)) {
668
+ stringifiedArguments[k] = String(jobArguments[k]);
669
+ }
670
+ const postJobRequestBody = {
671
+ name: `exec-${jobName}`,
672
+ description: 'Powered by SASjs',
673
+ jobDefinition,
674
+ arguments: stringifiedArguments
675
+ };
676
+ const { result: postedJob } = yield this.requestClient.post(`${this.serverUrl}/jobExecution/jobs?_action=wait`, postJobRequestBody, access_token);
677
+ const jobStatus = yield this.pollJobState(postedJob, authConfig, undefined, onTokensRefreshed).catch((err) => {
678
+ throw (0, error_1.prefixMessage)(err, 'Error while polling job status. ');
679
+ });
680
+ const { result: currentJob } = yield this.requestClient.get(`${this.serverUrl}/jobExecution/jobs/${postedJob.id}`, access_token);
681
+ let jobResult;
682
+ let log;
683
+ const resultLink = currentJob.results['_webout.json'];
684
+ const logLink = currentJob.links.find((l) => l.rel === 'log');
685
+ if (resultLink) {
686
+ jobResult = yield this.requestClient.get(`${this.serverUrl}${resultLink}/content`, access_token, 'text/plain');
687
+ }
688
+ if (debug && logLink) {
689
+ log = yield this.requestClient
690
+ .get(`${this.serverUrl}${logLink.href}/content`, access_token)
691
+ .then((res) => res.result.items.map((i) => i.line).join('\n'));
692
+ }
693
+ if (jobStatus === 'failed') {
694
+ throw new errors_1.JobExecutionError((_b = currentJob.error) === null || _b === void 0 ? void 0 : _b.errorCode, (_c = currentJob.error) === null || _c === void 0 ? void 0 : _c.message, log);
695
+ }
696
+ const executionResult = {
697
+ result: jobResult === null || jobResult === void 0 ? void 0 : jobResult.result,
698
+ log
699
+ };
700
+ const { error } = currentJob;
701
+ if (error)
702
+ executionResult.error = error;
703
+ return executionResult;
704
+ });
705
+ }
706
+ populateFolderMap(folderPath, accessToken) {
707
+ return __awaiter(this, void 0, void 0, function* () {
708
+ const path = (0, utils_1.isRelativePath)(folderPath)
709
+ ? `${this.rootFolderName}/${folderPath}`
710
+ : folderPath;
711
+ if (this.folderMap.get(path)) {
712
+ return;
713
+ }
714
+ const url = '/folders/folders/@item?path=' + path;
715
+ const { result: folder } = yield this.requestClient
716
+ .get(`${url}`, accessToken)
717
+ .catch((err) => {
718
+ throw (0, error_1.prefixMessage)(err, 'Error while getting folder. ');
719
+ });
720
+ if (!folder) {
721
+ throw new Error(`The path ${path} does not exist on ${this.serverUrl}`);
722
+ }
723
+ const { result: members } = yield this.requestClient
724
+ .get(`/folders/folders/${folder.id}/members?limit=${folder.memberCount < 500 ? 500 : folder.memberCount}`, // this is a fix for https://github.com/sasjs/adapter/issues/669
725
+ accessToken)
726
+ .catch((err) => {
727
+ throw (0, error_1.prefixMessage)(err, 'Error while getting members. ');
728
+ });
729
+ const itemsAtRoot = members.items;
730
+ this.folderMap.set(path, itemsAtRoot);
731
+ });
732
+ }
733
+ pollJobState(postedJob, authConfig, pollOptions, onTokensRefreshed) {
734
+ return __awaiter(this, void 0, void 0, function* () {
735
+ return (0, pollJobState_1.pollJobState)(this.requestClient, postedJob, this.debug, authConfig, pollOptions, undefined, onTokensRefreshed);
736
+ });
737
+ }
738
+ uploadTables(data, accessToken) {
739
+ return __awaiter(this, void 0, void 0, function* () {
740
+ return (0, uploadTables_1.uploadTables)(this.requestClient, data, accessToken);
741
+ });
742
+ }
743
+ getFolderDetails(folderPath, accessToken) {
744
+ return __awaiter(this, void 0, void 0, function* () {
745
+ const url = (0, utils_1.isUri)(folderPath)
746
+ ? folderPath
747
+ : `/folders/folders/@item?path=${folderPath}`;
748
+ const { result: folder } = yield this.requestClient
749
+ .get(`${this.serverUrl}${url}`, accessToken)
750
+ .catch((err) => {
751
+ if (err instanceof errors_1.CertificateError)
752
+ throw err;
753
+ return { result: null };
754
+ });
755
+ if (!folder)
756
+ return undefined;
757
+ return folder;
758
+ });
759
+ }
760
+ getFolderUri(folderPath, accessToken) {
761
+ return __awaiter(this, void 0, void 0, function* () {
762
+ const folderDetails = yield this.getFolderDetails(folderPath, accessToken);
763
+ if (!folderDetails)
764
+ return undefined;
765
+ return `/folders/folders/${folderDetails.id}`;
766
+ });
767
+ }
768
+ getFileUri(folderPath, fileName, accessToken) {
769
+ var _a;
770
+ return __awaiter(this, void 0, void 0, function* () {
771
+ const folderMembers = yield this.listFolder(folderPath, accessToken, 1000, {
772
+ returnDetails: true
773
+ }).catch((err) => {
774
+ throw (0, error_1.prefixMessage)(err, `Error while listing folder: ${folderPath}. `);
775
+ });
776
+ if (!folderMembers || !folderMembers.length)
777
+ throw new Error(`No members found in folder: ${folderPath}`);
778
+ const fileUri = (_a = folderMembers.find((member) => member.name === fileName)) === null || _a === void 0 ? void 0 : _a.uri;
779
+ if (!fileUri)
780
+ throw new Error(`File ${fileName} not found in folder: ${folderPath}`);
781
+ return fileUri;
782
+ });
783
+ }
784
+ getRecycleBinUri(accessToken) {
785
+ return __awaiter(this, void 0, void 0, function* () {
786
+ const url = '/folders/folders/@myRecycleBin';
787
+ const { result: folder } = yield this.requestClient
788
+ .get(`${this.serverUrl}${url}`, accessToken)
789
+ .catch((err) => {
790
+ if (err instanceof errors_1.CertificateError)
791
+ throw err;
792
+ return { result: null };
793
+ });
794
+ if (!folder)
795
+ return undefined;
796
+ return `/folders/folders/${folder.id}`;
797
+ });
798
+ }
799
+ /**
800
+ * Returns a JSON representation of a compute context.
801
+ * @example: { "createdBy": "admin", "links": [...], "id": "ID", "version": 2, "name": "context1" }
802
+ * @param contextName - the name of the context to return.
803
+ * @param accessToken - an access token for an authorized user.
804
+ */
805
+ getComputeContextByName(contextName, accessToken) {
806
+ return __awaiter(this, void 0, void 0, function* () {
807
+ return yield this.contextManager.getComputeContextByName(contextName, accessToken);
808
+ });
809
+ }
810
+ /**
811
+ * Returns a JSON representation of a compute context.
812
+ * @param contextId - an id of the context to return.
813
+ * @param accessToken - an access token for an authorized user.
814
+ */
815
+ getComputeContextById(contextId, accessToken) {
816
+ return __awaiter(this, void 0, void 0, function* () {
817
+ return yield this.contextManager.getComputeContextById(contextId, accessToken);
818
+ });
819
+ }
820
+ /**
821
+ * Lists children folders/files for given Viya folder.
822
+ * @param sourceFolder - the full path (eg `/Public/example/myFolder`) or URI of the source folder listed. Providing URI instead of path will save one extra request.
823
+ * @param accessToken - an access token for authorizing the request.
824
+ * @param {Object} [options] - Additional options.
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
+ */
827
+ listFolder(sourceFolder, accessToken, limit = 20, options) {
828
+ return __awaiter(this, void 0, void 0, function* () {
829
+ // checks if 'sourceFolder' is already a URI
830
+ const sourceFolderUri = (0, utils_1.isUri)(sourceFolder)
831
+ ? sourceFolder
832
+ : yield this.getFolderUri(sourceFolder, accessToken);
833
+ const { result: members } = yield this.requestClient.get(`${this.serverUrl}${sourceFolderUri}/members?limit=${limit}`, accessToken);
834
+ let membersToReturn = [];
835
+ if (members && members.items) {
836
+ // If returnDetails is true, return full member details
837
+ if (options === null || options === void 0 ? void 0 : options.returnDetails) {
838
+ membersToReturn = members.items;
839
+ }
840
+ else {
841
+ // If returnDetails is false, return only member names
842
+ membersToReturn = members.items.map((item) => item.name);
843
+ }
844
+ }
845
+ // Return members without Etag
846
+ return membersToReturn;
847
+ });
848
+ }
849
+ /**
850
+ * Moves Viya folder to a new location. The folder may be renamed at the same time.
851
+ * @param sourceFolder - the full path (eg `/Public/example/myFolder`) or URI of the source folder to be moved. Providing URI instead of path will save one extra request.
852
+ * @param targetParentFolder - the full path or URI of the _parent_ folder to which the `sourceFolder` will be moved (eg `/Public/newDestination`). To move a folder, a user has to have write permissions in targetParentFolder. Providing URI instead of the path will save one extra request.
853
+ * @param targetFolderName - the name of the "moved" folder. If left blank, the original folder name will be used (eg `myFolder` in `/Public/newDestination/myFolder` for the example above). Optional field.
854
+ * @param accessToken - an access token for authorizing the request.
855
+ */
856
+ moveFolder(sourceFolder, targetParentFolder, targetFolderName, accessToken) {
857
+ return __awaiter(this, void 0, void 0, function* () {
858
+ // If target path is an existing folder, than keep source folder name, othervise rename it with given target folder name
859
+ const sourceFolderName = sourceFolder.split('/').pop();
860
+ const targetFolderDetails = yield this.getFolderDetails(targetParentFolder, accessToken);
861
+ if (!targetFolderDetails) {
862
+ let targetParentFolderArr = targetParentFolder.split('/');
863
+ targetParentFolderArr.splice(targetParentFolderArr.length - 1, 1);
864
+ targetParentFolder = targetParentFolderArr.join('/');
865
+ }
866
+ else {
867
+ targetFolderName = sourceFolderName;
868
+ }
869
+ // checks if 'sourceFolder' is already an URI
870
+ const sourceFolderUri = yield this.getFolderUri(sourceFolder, accessToken);
871
+ // checks if 'targetParentFolder' is already a URI
872
+ const targetParentFolderUri = yield this.getFolderUri(targetParentFolder, accessToken);
873
+ if (!sourceFolderUri) {
874
+ return undefined;
875
+ }
876
+ const sourceFolderId = sourceFolderUri === null || sourceFolderUri === void 0 ? void 0 : sourceFolderUri.split('/').pop();
877
+ const { result: folder } = yield this.requestClient
878
+ .patch(`${this.serverUrl}${sourceFolderUri}`, {
879
+ id: sourceFolderId,
880
+ name: targetFolderName,
881
+ parentFolderUri: targetParentFolderUri
882
+ }, accessToken)
883
+ .catch((err) => {
884
+ if (err.code && err.code === 'ENOTFOUND') {
885
+ const notFoundError = {
886
+ body: {
887
+ message: `Folder '${sourceFolder
888
+ .split('/')
889
+ .pop()}' was not found.`
890
+ }
891
+ };
892
+ throw notFoundError;
893
+ }
894
+ throw err;
895
+ });
896
+ if (!folder)
897
+ return undefined;
898
+ return folder;
899
+ });
900
+ }
901
+ /**
902
+ * For performance (and in case of accidental error) the `deleteFolder` function does not actually delete the folder (and all its content and subfolder content). Instead the folder is simply moved to the recycle bin. Deletion time will be added to the folder name.
903
+ * @param folderPath - the full path (eg `/Public/example/deleteThis`) of the folder to be deleted.
904
+ * @param accessToken - an access token for authorizing the request.
905
+ */
906
+ deleteFolder(folderPath, accessToken) {
907
+ return __awaiter(this, void 0, void 0, function* () {
908
+ const recycleBinUri = yield this.getRecycleBinUri(accessToken);
909
+ const folderName = folderPath.split('/').pop() || '';
910
+ const date = new Date();
911
+ const timeMark = date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
912
+ const deletedFolderName = folderName + ' ' + timeMark;
913
+ const movedFolder = yield this.moveFolder(folderPath, recycleBinUri, deletedFolderName, accessToken);
914
+ return movedFolder;
915
+ });
916
+ }
917
+ }
918
+ exports.SASViyaApiClient = SASViyaApiClient;