@sasjs/adapter 4.19.4 → 5.1.1

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 (418) 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 -15
  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/createTSDocs.js +0 -35
  157. package/cypress.config.js +0 -18
  158. package/example.html +0 -109
  159. package/file/spec/generateFileUploadForm.spec.d.ts +0 -1
  160. package/file/spec/generateTableUploadForm.spec.d.ts +0 -1
  161. package/index-dev.js +0 -80394
  162. package/job-execution/spec/ComputeJobExecutor.spec.d.ts +0 -1
  163. package/job-execution/spec/JesJobExecutor.spec.d.ts +0 -1
  164. package/job-execution/spec/Sas9JobExecutor.spec.d.ts +0 -1
  165. package/job-execution/spec/SasjsJobExecutor.spec.d.ts +0 -1
  166. package/job-execution/spec/WebJobExecutor.debug.spec.d.ts +0 -1
  167. package/job-execution/spec/WebJobExecutor.spec.d.ts +0 -1
  168. package/job-execution/spec/executionTasks.spec.d.ts +0 -1
  169. package/minified_sas9.js +0 -14039
  170. package/node/ContextManager.d.ts +0 -41
  171. package/node/SAS9ApiClient.d.ts +0 -30
  172. package/node/SASViyaApiClient.d.ts +0 -298
  173. package/node/SASjs.d.ts +0 -387
  174. package/node/SASjsApiClient.d.ts +0 -65
  175. package/node/SessionManager.d.ts +0 -115
  176. package/node/api/viya/executeOnComputeApi.d.ts +0 -21
  177. package/node/api/viya/getFileStream.d.ts +0 -2
  178. package/node/api/viya/pollJobState.d.ts +0 -57
  179. package/node/api/viya/saveLog.d.ts +0 -15
  180. package/node/api/viya/uploadTables.d.ts +0 -13
  181. package/node/api/viya/writeStream.d.ts +0 -2
  182. package/node/auth/AuthManager.d.ts +0 -49
  183. package/node/auth/getAccessTokenForSasjs.d.ts +0 -11
  184. package/node/auth/getAccessTokenForViya.d.ts +0 -10
  185. package/node/auth/getTokenRequestErrorPrefix.d.ts +0 -44
  186. package/node/auth/getTokens.d.ts +0 -22
  187. package/node/auth/index.d.ts +0 -4
  188. package/node/auth/isAuthorizeFormRequired.d.ts +0 -1
  189. package/node/auth/isLoginRequired.d.ts +0 -1
  190. package/node/auth/loginHeader.d.ts +0 -17
  191. package/node/auth/openWebPage.d.ts +0 -6
  192. package/node/auth/refreshTokensForSasjs.d.ts +0 -10
  193. package/node/auth/refreshTokensForViya.d.ts +0 -11
  194. package/node/auth/verifySas9Login.d.ts +0 -3
  195. package/node/auth/verifySasViyaLogin.d.ts +0 -4
  196. package/node/file/generateFileUploadForm.d.ts +0 -11
  197. package/node/file/generateTableUploadForm.d.ts +0 -5
  198. package/node/job-execution/ComputeJobExecutor.d.ts +0 -8
  199. package/node/job-execution/FileUploader.d.ts +0 -9
  200. package/node/job-execution/JesJobExecutor.d.ts +0 -9
  201. package/node/job-execution/JobExecutor.d.ts +0 -17
  202. package/node/job-execution/Sas9JobExecutor.d.ts +0 -19
  203. package/node/job-execution/SasjsJobExecutor.d.ts +0 -9
  204. package/node/job-execution/WebJobExecutor.d.ts +0 -18
  205. package/node/job-execution/index.d.ts +0 -7
  206. package/node/request/RequestClient.d.ts +0 -125
  207. package/node/request/Sas9RequestClient.d.ts +0 -25
  208. package/node/request/SasjsRequestClient.d.ts +0 -12
  209. package/node/types/Context.d.ts +0 -42
  210. package/node/types/CsrfToken.d.ts +0 -4
  211. package/node/types/ExecuteScript.d.ts +0 -4
  212. package/node/types/File.d.ts +0 -7
  213. package/node/types/FileResource.d.ts +0 -32
  214. package/node/types/Folder.d.ts +0 -7
  215. package/node/types/Job.d.ts +0 -14
  216. package/node/types/JobDefinition.d.ts +0 -3
  217. package/node/types/JobResult.d.ts +0 -3
  218. package/node/types/Link.d.ts +0 -7
  219. package/node/types/LogStatistics.d.ts +0 -4
  220. package/node/types/Login.d.ts +0 -14
  221. package/node/types/PollOptions.d.ts +0 -8
  222. package/node/types/RequestClient.d.ts +0 -46
  223. package/node/types/SASjsConfig.d.ts +0 -94
  224. package/node/types/Session.d.ts +0 -30
  225. package/node/types/Tables.d.ts +0 -7
  226. package/node/types/UploadFile.d.ts +0 -8
  227. package/node/types/WriteStream.d.ts +0 -7
  228. package/node/types/errors/ArgumentError.d.ts +0 -4
  229. package/node/types/errors/AuthorizeError.d.ts +0 -5
  230. package/node/types/errors/CertificateError.d.ts +0 -3
  231. package/node/types/errors/ComputeJobExecutionError.d.ts +0 -6
  232. package/node/types/errors/ErrorResponse.d.ts +0 -9
  233. package/node/types/errors/InternalServerError.d.ts +0 -3
  234. package/node/types/errors/InvalidJsonError.d.ts +0 -3
  235. package/node/types/errors/InvalidSASjsCsrfError.d.ts +0 -3
  236. package/node/types/errors/JobExecutionError.d.ts +0 -6
  237. package/node/types/errors/JobStatePollError.d.ts +0 -4
  238. package/node/types/errors/JsonParseArrayError.d.ts +0 -3
  239. package/node/types/errors/LoginRequiredError.d.ts +0 -3
  240. package/node/types/errors/NoSessionStateError.d.ts +0 -6
  241. package/node/types/errors/NotFoundError.d.ts +0 -4
  242. package/node/types/errors/RootFolderNotFoundError.d.ts +0 -3
  243. package/node/types/errors/SAS9AuthError.d.ts +0 -3
  244. package/node/types/errors/WeboutResponseError.d.ts +0 -4
  245. package/node/types/errors/index.d.ts +0 -15
  246. package/node/types/index.d.ts +0 -18
  247. package/node/utils/appendExtraResponseAttributes.d.ts +0 -2
  248. package/node/utils/asyncForEach.d.ts +0 -1
  249. package/node/utils/compareTimestamps.d.ts +0 -6
  250. package/node/utils/convertToCsv.d.ts +0 -12
  251. package/node/utils/createAxiosInstance.d.ts +0 -2
  252. package/node/utils/delay.d.ts +0 -1
  253. package/node/utils/extractWeboutBlob.d.ts +0 -13
  254. package/node/utils/fetchLogByChunks.d.ts +0 -20
  255. package/node/utils/formatDataForRequest.d.ts +0 -1
  256. package/node/utils/getFormData.d.ts +0 -2
  257. package/node/utils/getValidJson.d.ts +0 -5
  258. package/node/utils/index.d.ts +0 -25
  259. package/node/utils/isNode.d.ts +0 -1
  260. package/node/utils/isRelativePath.d.ts +0 -1
  261. package/node/utils/isUri.d.ts +0 -5
  262. package/node/utils/isUrl.d.ts +0 -5
  263. package/node/utils/loginPrompt/index.d.ts +0 -1
  264. package/node/utils/needsRetry.d.ts +0 -1
  265. package/node/utils/parseGeneratedCode.d.ts +0 -1
  266. package/node/utils/parseSasViyaLog.d.ts +0 -5
  267. package/node/utils/parseSourceCode.d.ts +0 -1
  268. package/node/utils/parseViyaDebugResponse.d.ts +0 -12
  269. package/node/utils/parseViyaLogDebugResponse.d.ts +0 -8
  270. package/node/utils/parseWeboutResponse.d.ts +0 -1
  271. package/node/utils/sas9/extractUserLongNameSas9.d.ts +0 -6
  272. package/node/utils/serialize.d.ts +0 -1
  273. package/node/utils/splitChunks.d.ts +0 -1
  274. package/node/utils/validateInput.d.ts +0 -14
  275. package/request/spec/SasjsRequestClient.spec.d.ts +0 -1
  276. package/screenshots/session-manager-first-request.png +0 -0
  277. package/screenshots/subsequent-session-request.png +0 -0
  278. package/spec/SAS9ApiClient.spec.d.ts +0 -1
  279. package/spec/SASjs.startComputeJob.spec.d.ts +0 -1
  280. package/spec/SASjsApiClient.spec.d.ts +0 -1
  281. package/src/ContextManager.ts +0 -454
  282. package/src/SAS9ApiClient.ts +0 -100
  283. package/src/SASViyaApiClient.ts +0 -1417
  284. package/src/SASjs.ts +0 -1268
  285. package/src/SASjsApiClient.ts +0 -177
  286. package/src/SessionManager.ts +0 -465
  287. package/src/__mocks__/axios.ts +0 -7
  288. package/src/api/viya/executeOnComputeApi.ts +0 -307
  289. package/src/api/viya/getFileStream.ts +0 -17
  290. package/src/api/viya/pollJobState.ts +0 -393
  291. package/src/api/viya/saveLog.ts +0 -55
  292. package/src/api/viya/spec/mockResponses.ts +0 -75
  293. package/src/api/viya/uploadTables.ts +0 -41
  294. package/src/api/viya/writeStream.ts +0 -16
  295. package/src/auth/AuthManager.ts +0 -387
  296. package/src/auth/getAccessTokenForSasjs.ts +0 -48
  297. package/src/auth/getAccessTokenForViya.ts +0 -61
  298. package/src/auth/getTokenRequestErrorPrefix.ts +0 -88
  299. package/src/auth/getTokens.ts +0 -127
  300. package/src/auth/index.ts +0 -4
  301. package/src/auth/isAuthorizeFormRequired.ts +0 -3
  302. package/src/auth/isLoginRequired.ts +0 -5
  303. package/src/auth/loginHeader.ts +0 -97
  304. package/src/auth/openWebPage.ts +0 -40
  305. package/src/auth/refreshTokensForSasjs.ts +0 -45
  306. package/src/auth/refreshTokensForViya.ts +0 -66
  307. package/src/auth/spec/mockResponses.ts +0 -53
  308. package/src/auth/verifySas9Login.ts +0 -25
  309. package/src/auth/verifySasViyaLogin.ts +0 -43
  310. package/src/file/generateFileUploadForm.ts +0 -48
  311. package/src/file/generateTableUploadForm.ts +0 -50
  312. package/src/index.ts +0 -9
  313. package/src/job-execution/ComputeJobExecutor.ts +0 -76
  314. package/src/job-execution/FileUploader.ts +0 -152
  315. package/src/job-execution/JesJobExecutor.ts +0 -78
  316. package/src/job-execution/JobExecutor.ts +0 -63
  317. package/src/job-execution/Sas9JobExecutor.ts +0 -137
  318. package/src/job-execution/SasjsJobExecutor.ts +0 -152
  319. package/src/job-execution/WebJobExecutor.ts +0 -341
  320. package/src/job-execution/index.ts +0 -7
  321. package/src/minified/sas9/SASjs.ts +0 -274
  322. package/src/minified/sas9/WebJobExecutor.ts +0 -156
  323. package/src/minified/sas9/index.ts +0 -3
  324. package/src/request/RequestClient.ts +0 -941
  325. package/src/request/Sas9RequestClient.ts +0 -132
  326. package/src/request/SasjsRequestClient.ts +0 -82
  327. package/src/test/SAS_server_app.ts +0 -47
  328. package/src/types/Context.ts +0 -39
  329. package/src/types/CsrfToken.ts +0 -4
  330. package/src/types/ExecuteScript.ts +0 -4
  331. package/src/types/File.ts +0 -8
  332. package/src/types/FileResource.ts +0 -33
  333. package/src/types/Folder.ts +0 -8
  334. package/src/types/Job.ts +0 -15
  335. package/src/types/JobDefinition.ts +0 -3
  336. package/src/types/JobResult.ts +0 -3
  337. package/src/types/Link.ts +0 -7
  338. package/src/types/LogStatistics.ts +0 -4
  339. package/src/types/Login.ts +0 -15
  340. package/src/types/PollOptions.ts +0 -9
  341. package/src/types/Process.d.ts +0 -5
  342. package/src/types/RequestClient.ts +0 -55
  343. package/src/types/SASjsConfig.ts +0 -95
  344. package/src/types/Session.ts +0 -34
  345. package/src/types/Tables.ts +0 -29
  346. package/src/types/UploadFile.ts +0 -8
  347. package/src/types/WriteStream.ts +0 -10
  348. package/src/types/errors/ArgumentError.ts +0 -7
  349. package/src/types/errors/AuthorizeError.ts +0 -10
  350. package/src/types/errors/CertificateError.ts +0 -12
  351. package/src/types/errors/ComputeJobExecutionError.ts +0 -12
  352. package/src/types/errors/ErrorResponse.ts +0 -28
  353. package/src/types/errors/InternalServerError.ts +0 -9
  354. package/src/types/errors/InvalidJsonError.ts +0 -7
  355. package/src/types/errors/InvalidSASjsCsrfError.ts +0 -9
  356. package/src/types/errors/JobExecutionError.ts +0 -11
  357. package/src/types/errors/JobStatePollError.ts +0 -14
  358. package/src/types/errors/JsonParseArrayError.ts +0 -7
  359. package/src/types/errors/LoginRequiredError.ts +0 -11
  360. package/src/types/errors/NoSessionStateError.ts +0 -15
  361. package/src/types/errors/NotFoundError.ts +0 -7
  362. package/src/types/errors/RootFolderNotFoundError.ts +0 -24
  363. package/src/types/errors/SAS9AuthError.ts +0 -9
  364. package/src/types/errors/WeboutResponseError.ts +0 -7
  365. package/src/types/errors/index.ts +0 -15
  366. package/src/types/index.ts +0 -18
  367. package/src/types/system/global.d.ts +0 -1
  368. package/src/utils/appendExtraResponseAttributes.ts +0 -22
  369. package/src/utils/asyncForEach.ts +0 -5
  370. package/src/utils/compareTimestamps.ts +0 -9
  371. package/src/utils/convertToCsv.ts +0 -198
  372. package/src/utils/createAxiosInstance.ts +0 -7
  373. package/src/utils/delay.ts +0 -2
  374. package/src/utils/fetchLogByChunks.ts +0 -63
  375. package/src/utils/formatDataForRequest.ts +0 -48
  376. package/src/utils/getFormData.ts +0 -5
  377. package/src/utils/getUserLanguage.ts +0 -10
  378. package/src/utils/getValidJson.ts +0 -23
  379. package/src/utils/index.ts +0 -25
  380. package/src/utils/isIeOrEdge.ts +0 -34
  381. package/src/utils/isNode.ts +0 -4
  382. package/src/utils/isRelativePath.ts +0 -2
  383. package/src/utils/isUri.ts +0 -5
  384. package/src/utils/isUrl.ts +0 -17
  385. package/src/utils/loginPrompt/index.ts +0 -177
  386. package/src/utils/needsRetry.ts +0 -14
  387. package/src/utils/parseGeneratedCode.ts +0 -7
  388. package/src/utils/parseSasViyaLog.ts +0 -12
  389. package/src/utils/parseSourceCode.ts +0 -6
  390. package/src/utils/parseViyaDebugResponse.ts +0 -46
  391. package/src/utils/parseViyaLogDebugResponse.ts +0 -22
  392. package/src/utils/parseWeboutResponse.ts +0 -20
  393. package/src/utils/sas9/extractUserLongNameSas9.ts +0 -31
  394. package/src/utils/serialize.ts +0 -15
  395. package/src/utils/splitChunks.ts +0 -12
  396. package/src/utils/validateInput.ts +0 -93
  397. package/test/ContextManager.spec.d.ts +0 -1
  398. package/test/FileUploader.spec.d.ts +0 -4
  399. package/test/FolderOperations.spec.d.ts +0 -1
  400. package/test/RequestClient.spec.d.ts +0 -1
  401. package/test/SAS_server_app.d.ts +0 -10
  402. package/test/SessionManager.spec.d.ts +0 -1
  403. package/test/getJobsInFolder.spec.d.ts +0 -1
  404. package/test/utils/formatDataForRequest.spec.d.ts +0 -1
  405. package/test/utils/getValidJson.spec.d.ts +0 -1
  406. package/test/utils/isUrl.spec.d.ts +0 -1
  407. package/test/utils/parseGeneratedCode.spec.d.ts +0 -1
  408. package/test/utils/parseSourceCode.spec.d.ts +0 -1
  409. package/types/Tables.spec.d.ts +0 -1
  410. package/types/errors/RootFolderNotFoundError.spec.d.ts +0 -1
  411. package/types/errors/spec/SAS9AuthError.spec.d.ts +0 -1
  412. package/utils/spec/convertToCsv.spec.d.ts +0 -1
  413. package/utils/spec/extractUserLongNameSas9.spec.d.ts +0 -1
  414. package/utils/spec/getFormData.spec.d.ts +0 -1
  415. package/utils/spec/parseSasViyaLog.spec.d.ts +0 -1
  416. package/utils/spec/parseViyaDebugResponse.spec.d.ts +0 -1
  417. package/utils/spec/parseViyaLogDebugResponse.spec.d.ts +0 -1
  418. package/utils/spec/validateInput.spec.d.ts +0 -1
@@ -1,941 +0,0 @@
1
- import {
2
- AxiosError,
3
- AxiosInstance,
4
- AxiosRequestConfig,
5
- AxiosRequestHeaders,
6
- AxiosResponse
7
- } from 'axios'
8
- import * as https from 'https'
9
- import { CsrfToken } from '..'
10
- import { isAuthorizeFormRequired, isLogInRequired } from '../auth'
11
- import {
12
- AuthorizeError,
13
- LoginRequiredError,
14
- NotFoundError,
15
- InternalServerError,
16
- JobExecutionError,
17
- CertificateError
18
- } from '../types/errors'
19
- import { SASjsRequest, HttpClient, VerboseMode } from '../types'
20
- import { parseWeboutResponse } from '../utils/parseWeboutResponse'
21
- import { prefixMessage } from '@sasjs/utils/error'
22
- import { SAS9AuthError } from '../types/errors/SAS9AuthError'
23
- import {
24
- parseGeneratedCode,
25
- parseSourceCode,
26
- createAxiosInstance
27
- } from '../utils'
28
- import { InvalidSASjsCsrfError } from '../types/errors/InvalidSASjsCsrfError'
29
- import { inspect } from 'util'
30
-
31
- const getLogger = () =>
32
- (typeof process !== 'undefined' && process.logger) || console
33
-
34
- export class RequestClient implements HttpClient {
35
- private requests: SASjsRequest[] = []
36
- private requestsLimit: number = 10
37
- private httpInterceptor?: number
38
- private verboseMode: VerboseMode = false
39
-
40
- protected csrfToken: CsrfToken = { headerName: '', value: '' }
41
- protected fileUploadCsrfToken: CsrfToken | undefined
42
- protected httpClient!: AxiosInstance
43
- private isRecoveringFromNetworkError = false
44
-
45
- constructor(
46
- protected baseUrl: string,
47
- httpsAgentOptions?: https.AgentOptions,
48
- requestsLimit?: number,
49
- verboseMode?: VerboseMode
50
- ) {
51
- this.createHttpClient(baseUrl, httpsAgentOptions)
52
-
53
- if (requestsLimit) this.requestsLimit = requestsLimit
54
-
55
- if (verboseMode) {
56
- this.setVerboseMode(verboseMode)
57
- this.enableVerboseMode()
58
- }
59
- }
60
-
61
- public setConfig(baseUrl: string, httpsAgentOptions?: https.AgentOptions) {
62
- this.createHttpClient(baseUrl, httpsAgentOptions)
63
- }
64
-
65
- public saveLocalStorageToken(accessToken: string, refreshToken: string) {
66
- localStorage.setItem('accessToken', accessToken)
67
- localStorage.setItem('refreshToken', refreshToken)
68
- }
69
-
70
- public getCsrfToken(type: 'general' | 'file' = 'general') {
71
- return type === 'file' ? this.fileUploadCsrfToken : this.csrfToken
72
- }
73
-
74
- public clearCsrfTokens() {
75
- this.csrfToken = { headerName: '', value: '' }
76
- this.fileUploadCsrfToken = { headerName: '', value: '' }
77
- }
78
-
79
- public clearLocalStorageTokens() {
80
- localStorage.setItem('accessToken', '')
81
- localStorage.setItem('refreshToken', '')
82
- }
83
-
84
- public resetInMemoryAuthState() {
85
- this.clearCsrfTokens()
86
- if (typeof localStorage !== 'undefined') {
87
- this.clearLocalStorageTokens()
88
- }
89
- if (typeof document !== 'undefined') {
90
- this.clearAllCookies()
91
- }
92
- }
93
-
94
- private clearAllCookies() {
95
- const cookies = document.cookie.split(';')
96
- for (const cookie of cookies) {
97
- const name = cookie.split('=')[0].trim()
98
- if (!name) continue
99
- document.cookie = `${name}=; Max-Age=0; Path=/;`
100
- }
101
- }
102
-
103
- public getBaseUrl() {
104
- return this.httpClient.defaults.baseURL || ''
105
- }
106
-
107
- /**
108
- * this method returns all requests, an array of SASjsRequest type
109
- * @returns SASjsRequest[]
110
- */
111
- public getRequests = () => this.requests
112
-
113
- /**
114
- * this method clears the requests array, i.e set to empty
115
- */
116
- public clearRequests = () => {
117
- this.requests = []
118
- }
119
-
120
- /**
121
- * this method appends the response from sasjs request to requests array
122
- * @param response - response from sasjs request
123
- * @param program - name of program
124
- * @param debug - a boolean that indicates whether debug was enabled or not
125
- */
126
- public appendRequest(response: any, program: string, debug: boolean) {
127
- let sourceCode = ''
128
- let generatedCode = ''
129
- let sasWork = null
130
-
131
- if (debug) {
132
- if (response?.log) {
133
- sourceCode = parseSourceCode(response.log)
134
- generatedCode = parseGeneratedCode(response.log)
135
-
136
- if (response?.result) {
137
- sasWork = response.result.WORK
138
- } else {
139
- sasWork = response.log
140
- }
141
- } else if (response?.result) {
142
- // We parse only if it's a string, otherwise it would throw error
143
- if (typeof response.result === 'string') {
144
- sourceCode = parseSourceCode(response.result)
145
- generatedCode = parseGeneratedCode(response.result)
146
- }
147
-
148
- sasWork = response.result.WORK
149
- }
150
- }
151
-
152
- const stringifiedResult =
153
- typeof response?.result === 'string'
154
- ? response?.result
155
- : JSON.stringify(response?.result, null, 2)
156
-
157
- this.requests.push({
158
- logFile: response?.log || stringifiedResult || response,
159
- serviceLink: program,
160
- timestamp: new Date(),
161
- sourceCode,
162
- generatedCode,
163
- SASWORK: sasWork
164
- })
165
-
166
- if (this.requests.length > this.requestsLimit) {
167
- this.requests.splice(0, 1)
168
- }
169
- }
170
-
171
- public async get<T>(
172
- url: string,
173
- accessToken: string | undefined,
174
- contentType: string = 'application/json',
175
- overrideHeaders: { [key: string]: string | number } = {},
176
- debug: boolean = false
177
- ): Promise<{ result: T; etag: string; status: number }> {
178
- const headers = {
179
- ...this.getHeaders(accessToken, contentType),
180
- ...overrideHeaders
181
- }
182
-
183
- const requestConfig: AxiosRequestConfig = {
184
- headers,
185
- responseType: contentType === 'text/plain' ? 'text' : 'json',
186
- withXSRFToken: true
187
- }
188
-
189
- if (contentType === 'text/plain') {
190
- requestConfig.transformResponse = undefined
191
- }
192
-
193
- return this.httpClient
194
- .get<T>(url, requestConfig)
195
- .then((response) => {
196
- throwIfError(response)
197
-
198
- return this.parseResponse<T>(response)
199
- })
200
- .catch(async (e: any) => {
201
- return await this.handleError(
202
- e,
203
- () =>
204
- this.get<T>(url, accessToken, contentType, overrideHeaders).catch(
205
- (err) => {
206
- throw prefixMessage(
207
- err,
208
- 'Error while executing handle error callback. '
209
- )
210
- }
211
- ),
212
- debug
213
- )
214
- })
215
- }
216
-
217
- /**
218
- * @param contentType Newer version of Axios is more strict so if you don't
219
- * set the contentType to `form data` while sending a FormData object
220
- * application/json will be used by default, axios won’t treat it as FormData.
221
- * Instead, it serializes data as JSON—resulting in a payload like
222
- * {"sometable":{}} and we lose the multipart/form-data formatting.
223
- */
224
- public async post<T>(
225
- url: string,
226
- data: any,
227
- accessToken: string | undefined,
228
- contentType = 'application/json',
229
- overrideHeaders: { [key: string]: string | number } = {},
230
- additionalSettings: { [key: string]: string | number } = {}
231
- ): Promise<{ result: T; etag: string }> {
232
- const headers = {
233
- ...this.getHeaders(accessToken, contentType),
234
- ...overrideHeaders
235
- }
236
-
237
- return this.httpClient
238
- .post<T>(url, data, {
239
- headers,
240
- withXSRFToken: true,
241
- ...additionalSettings
242
- })
243
- .then((response) => {
244
- throwIfError(response)
245
-
246
- return this.parseResponse<T>(response)
247
- })
248
- .catch(async (e: any) => {
249
- return await this.handleError(e, () =>
250
- this.post<T>(url, data, accessToken, contentType, overrideHeaders)
251
- )
252
- })
253
- }
254
-
255
- public async put<T>(
256
- url: string,
257
- data: any,
258
- accessToken: string | undefined,
259
- overrideHeaders: { [key: string]: string | number } = {}
260
- ): Promise<{ result: T; etag: string }> {
261
- const headers = {
262
- ...this.getHeaders(accessToken, 'application/json'),
263
- ...overrideHeaders
264
- }
265
-
266
- return this.httpClient
267
- .put<T>(url, data, { headers, withXSRFToken: true })
268
- .then((response) => {
269
- throwIfError(response)
270
- return this.parseResponse<T>(response)
271
- })
272
- .catch(async (e: any) => {
273
- return await this.handleError(e, () =>
274
- this.put<T>(url, data, accessToken, overrideHeaders)
275
- )
276
- })
277
- }
278
-
279
- public async delete<T>(
280
- url: string,
281
- accessToken?: string
282
- ): Promise<{ result: T; etag: string }> {
283
- const headers = this.getHeaders(accessToken, 'application/json')
284
-
285
- return this.httpClient
286
- .delete<T>(url, { headers, withXSRFToken: true })
287
- .then((response) => {
288
- throwIfError(response)
289
- return this.parseResponse<T>(response)
290
- })
291
- .catch(async (e: any) => {
292
- return await this.handleError(e, () => this.delete<T>(url, accessToken))
293
- })
294
- }
295
-
296
- public async patch<T>(
297
- url: string,
298
- data: any = {},
299
- accessToken?: string,
300
- overrideHeaders: { [key: string]: string | number } = {}
301
- ): Promise<{ result: T; etag: string }> {
302
- const headers = {
303
- ...this.getHeaders(accessToken, 'application/json'),
304
- ...overrideHeaders
305
- }
306
-
307
- return this.httpClient
308
- .patch<T>(url, data, { headers, withXSRFToken: true })
309
- .then((response) => {
310
- throwIfError(response)
311
- return this.parseResponse<T>(response)
312
- })
313
- .catch(async (e: any) => {
314
- return await this.handleError(e, () =>
315
- this.patch<T>(url, data, accessToken)
316
- )
317
- })
318
- }
319
-
320
- public async uploadFile(
321
- url: string,
322
- content: string,
323
- accessToken?: string
324
- ): Promise<any> {
325
- const headers = this.getHeaders(accessToken, 'application/json')
326
-
327
- if (this.fileUploadCsrfToken?.value) {
328
- headers[this.fileUploadCsrfToken.headerName] =
329
- this.fileUploadCsrfToken.value
330
- }
331
-
332
- try {
333
- const response = await this.httpClient.post(url, content, {
334
- headers,
335
- transformRequest: (requestBody) => requestBody
336
- })
337
-
338
- return {
339
- result: response.data,
340
- etag: response.headers['etag'] as string
341
- }
342
- } catch (e: any) {
343
- const response = e.response as AxiosResponse
344
- if (response?.status === 403 || response?.status === 449) {
345
- this.parseAndSetFileUploadCsrfToken(response)
346
-
347
- if (this.fileUploadCsrfToken) {
348
- return this.uploadFile(url, content, accessToken)
349
- }
350
- throw e
351
- }
352
- throw e
353
- }
354
- }
355
-
356
- public authorize = async (response: string) => {
357
- let authUrl: string | null = null
358
- const params: any = {}
359
-
360
- const responseBody = response.split('<body>')[1].split('</body>')[0]
361
- const bodyElement = document.createElement('div')
362
- bodyElement.innerHTML = responseBody
363
-
364
- const form = bodyElement.querySelector('#application_authorization')
365
- authUrl = form ? this.baseUrl + form.getAttribute('action') : null
366
-
367
- const inputs: any = form?.querySelectorAll('input')
368
-
369
- for (const input of inputs) {
370
- if (input.name === 'user_oauth_approval') {
371
- input.value = 'true'
372
- }
373
-
374
- params[input.name] = input.value
375
- }
376
-
377
- const csrfTokenKey = Object.keys(params).find((k) =>
378
- k?.toLowerCase().includes('csrf')
379
- )
380
-
381
- if (csrfTokenKey) {
382
- this.csrfToken.value = params[csrfTokenKey]
383
- this.csrfToken.headerName = this.csrfToken.headerName || 'x-csrf-token'
384
- }
385
-
386
- const formData = new FormData()
387
-
388
- for (const key in params) {
389
- if (params.hasOwnProperty(key)) {
390
- formData.append(key, params[key])
391
- }
392
- }
393
-
394
- if (!authUrl) {
395
- throw new Error('Auth Form URL is null or undefined.')
396
- }
397
-
398
- return await this.httpClient
399
- .post(authUrl, formData, {
400
- responseType: 'text',
401
- headers: { Accept: '*/*', 'Content-Type': 'text/plain' }
402
- })
403
- .then((res) => res.data)
404
- .catch((error) => {
405
- const logger = getLogger()
406
- logger.error(error)
407
- })
408
- }
409
-
410
- /**
411
- * Adds colors to the string.
412
- * If verboseMode is set to 'bleached', colors should be disabled
413
- * @param str - string to be prettified.
414
- * @returns - prettified string
415
- */
416
- private prettifyString = (str: any) =>
417
- inspect(str, { colors: this.verboseMode !== 'bleached' })
418
-
419
- /**
420
- * Formats HTTP request/response body.
421
- * @param body - HTTP request/response body.
422
- * @returns - formatted string.
423
- */
424
- private parseInterceptedBody = (body: any) => {
425
- if (!body) return ''
426
-
427
- let parsedBody
428
-
429
- // Tries to parse body into JSON object.
430
- if (typeof body === 'string') {
431
- try {
432
- parsedBody = JSON.parse(body)
433
- } catch (error) {
434
- parsedBody = body
435
- }
436
- } else {
437
- parsedBody = body
438
- }
439
-
440
- const bodyLines = this.prettifyString(parsedBody).split('\n')
441
-
442
- // Leaves first 50 lines
443
- if (bodyLines.length > 51) {
444
- bodyLines.splice(50)
445
- bodyLines.push('...')
446
- }
447
-
448
- return bodyLines.join('\n')
449
- }
450
-
451
- private handleAxiosResponse = (response: AxiosResponse) => {
452
- const { status, config, request, data } = response
453
-
454
- const reqHeaders = request?._header ?? 'Not provided\n'
455
- const rawHeaders = request?.res?.rawHeaders ?? ['Not provided']
456
-
457
- const resHeaders = this.formatHeaders(rawHeaders)
458
- const parsedResBody = this.parseInterceptedBody(data)
459
-
460
- process.logger?.info(`HTTP Request (first 50 lines):
461
- ${reqHeaders}${this.parseInterceptedBody(config.data)}
462
-
463
- HTTP Response Code: ${this.prettifyString(status)}
464
-
465
- HTTP Response (first 50 lines):
466
- ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
467
- `)
468
-
469
- return response
470
- }
471
-
472
- private handleAxiosError = (error: AxiosError) => {
473
- // Message indicating absent value.
474
- const noValueMessage = 'Not provided'
475
- const { response, request, config } = error
476
-
477
- // Fallback request object that can be safely used to form request summary.
478
- // _header is not present in responses with status 1**
479
- // rawHeaders are not present in responses with status 1**
480
- let fallbackRequest = {
481
- _header: `${noValueMessage}\n`,
482
- res: { rawHeaders: [noValueMessage] }
483
- }
484
-
485
- if (request) {
486
- fallbackRequest = {
487
- _header:
488
- request._header ?? request._currentRequest?._header ?? noValueMessage,
489
- res: { rawHeaders: request.res?.rawHeaders ?? [noValueMessage] }
490
- }
491
- }
492
-
493
- // Fallback response object that can be safely used to form response summary.
494
- let fallbackResponse = response || {
495
- status: noValueMessage,
496
- request: fallbackRequest,
497
- config: config || {
498
- data: noValueMessage,
499
- headers: {} as AxiosRequestHeaders
500
- },
501
- data: noValueMessage
502
- }
503
-
504
- const { status, request: req, data: resData } = fallbackResponse
505
- const { _header: reqHeaders, res } = req
506
-
507
- const resHeaders = this.formatHeaders(res.rawHeaders)
508
- const parsedResBody = this.parseInterceptedBody(resData)
509
-
510
- process.logger?.info(`HTTP Request (first 50 lines):
511
- ${reqHeaders}${this.parseInterceptedBody(config?.data)}
512
-
513
- HTTP Response Code: ${this.prettifyString(status)}
514
-
515
- HTTP Response (first 50 lines):
516
- ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
517
- `)
518
-
519
- return error
520
- }
521
-
522
- // Converts an array of strings into a single string with the following format:
523
- // <headerName>: <headerValue>
524
- private formatHeaders = (rawHeaders: string[]): string => {
525
- return rawHeaders.reduce((acc, value, i) => {
526
- if (i % 2 === 0) {
527
- acc += `${i === 0 ? '' : '\n'}${value}`
528
- } else {
529
- acc += `: ${value}`
530
- }
531
- return acc
532
- }, '')
533
- }
534
-
535
- /**
536
- * Sets verbose mode.
537
- * @param verboseMode - value of the verbose mode, can be true, false or bleached(without extra colors).
538
- */
539
- public setVerboseMode = (verboseMode: VerboseMode) => {
540
- this.verboseMode = verboseMode
541
-
542
- if (this.verboseMode) this.enableVerboseMode()
543
- else this.disableVerboseMode()
544
- }
545
-
546
- /**
547
- * Turns on verbose mode to log every HTTP response.
548
- * @param successCallBack - function that should be triggered on every HTTP response with the status 2**.
549
- * @param errorCallBack - function that should be triggered on every HTTP response with the status different from 2**.
550
- */
551
- public enableVerboseMode = (
552
- successCallBack = this.handleAxiosResponse,
553
- errorCallBack = this.handleAxiosError
554
- ) => {
555
- this.httpInterceptor = this.httpClient.interceptors.response.use(
556
- successCallBack,
557
- errorCallBack
558
- )
559
- }
560
-
561
- /**
562
- * Turns off verbose mode to log every HTTP response.
563
- */
564
- public disableVerboseMode = () => {
565
- if (this.httpInterceptor) {
566
- this.httpClient.interceptors.response.eject(this.httpInterceptor)
567
- }
568
- }
569
-
570
- protected getHeaders = (
571
- accessToken: string | undefined,
572
- contentType: string
573
- ) => {
574
- const headers: any = {}
575
-
576
- if (contentType !== 'application/x-www-form-urlencoded') {
577
- headers['Content-Type'] = contentType
578
- }
579
-
580
- if (contentType === 'application/json') {
581
- headers.Accept = 'application/json'
582
- } else {
583
- headers.Accept = '*/*'
584
- }
585
- if (accessToken) {
586
- headers.Authorization = `Bearer ${accessToken}`
587
- }
588
- if (this.csrfToken.headerName && this.csrfToken.value) {
589
- headers[this.csrfToken.headerName] = this.csrfToken.value
590
- }
591
-
592
- return headers
593
- }
594
-
595
- protected parseAndSetFileUploadCsrfToken = (response: AxiosResponse) => {
596
- const token = this.parseCsrfToken(response)
597
-
598
- if (token) {
599
- this.fileUploadCsrfToken = token
600
- }
601
- }
602
-
603
- protected parseAndSetCsrfToken = (response: AxiosResponse) => {
604
- const token = this.parseCsrfToken(response)
605
-
606
- if (token) {
607
- this.csrfToken = token
608
- }
609
- }
610
-
611
- private parseCsrfToken = (response: AxiosResponse): CsrfToken | undefined => {
612
- const tokenHeader = (
613
- response.headers['x-csrf-header'] as string
614
- )?.toLowerCase()
615
-
616
- if (tokenHeader) {
617
- const token = response.headers[tokenHeader]
618
- const csrfToken = {
619
- headerName: tokenHeader,
620
- value: token || ''
621
- }
622
-
623
- return csrfToken
624
- }
625
- }
626
-
627
- protected handleError = async (
628
- e: any,
629
- callback: any,
630
- debug: boolean = false
631
- ) => {
632
- const response = e.response as AxiosResponse
633
-
634
- if (e instanceof AuthorizeError) {
635
- const res = await this.httpClient
636
- .get(e.confirmUrl, {
637
- responseType: 'text',
638
- headers: { 'Content-Type': 'text/plain', Accept: '*/*' }
639
- })
640
- .catch((err) => {
641
- throw prefixMessage(err, 'Error while getting error confirmUrl. ')
642
- })
643
-
644
- if (isAuthorizeFormRequired(res?.data as string)) {
645
- await this.authorize(res.data as string).catch((err) => {
646
- throw prefixMessage(err, 'Error while authorizing request. ')
647
- })
648
- }
649
-
650
- return await callback().catch((err: any) => {
651
- throw prefixMessage(
652
- err,
653
- 'Error while executing callback in handleError. '
654
- )
655
- })
656
- }
657
-
658
- if (e instanceof LoginRequiredError) {
659
- this.clearCsrfTokens()
660
-
661
- throw e
662
- }
663
-
664
- if (e instanceof InvalidSASjsCsrfError) {
665
- // Fetching root and creating CSRF cookie
666
- await this.httpClient
667
- .get('/', {
668
- withXSRFToken: true
669
- })
670
- .then((response) => {
671
- const cookie =
672
- /<script>document.cookie = '(XSRF-TOKEN=.*; Max-Age=86400; SameSite=Strict; Path=\/;)'<\/script>/.exec(
673
- response.data
674
- )?.[1]
675
-
676
- if (cookie) document.cookie = cookie
677
- })
678
- .catch((err) => {
679
- throw prefixMessage(err, 'Error while re-fetching CSRF token.')
680
- })
681
-
682
- return await callback().catch((err: any) => {
683
- throw prefixMessage(
684
- err,
685
- 'Error while executing callback in handleError. '
686
- )
687
- })
688
- }
689
-
690
- if (response?.status === 403 || response?.status === 449) {
691
- this.parseAndSetCsrfToken(response)
692
-
693
- if (this.csrfToken.headerName && this.csrfToken.value) {
694
- return await callback().catch((err: any) => {
695
- throw prefixMessage(
696
- err,
697
- 'Error while executing callback in handleError. '
698
- )
699
- })
700
- }
701
-
702
- throw e
703
- } else if (response?.status === 404) {
704
- throw new NotFoundError(response.config.url!)
705
- } else if (response?.status === 502) {
706
- if (debug) throw new InternalServerError()
707
- else return
708
- }
709
-
710
- if (e.isAxiosError && e.code === 'UNABLE_TO_VERIFY_LEAF_SIGNATURE') {
711
- throw new CertificateError(e.message)
712
- }
713
-
714
- if (
715
- e.isAxiosError &&
716
- !response &&
717
- e.code === 'ERR_NETWORK' &&
718
- !this.isRecoveringFromNetworkError
719
- ) {
720
- // Opaque ERR_NETWORK usually means the server rejected stale credentials.
721
- // Wipe in-memory auth state, re-establish session via GET /,
722
- // then retry the original request.
723
- this.resetInMemoryAuthState()
724
- this.isRecoveringFromNetworkError = true
725
- try {
726
- // Re-establish session and CSRF cookie
727
- const rootResponse = await this.httpClient
728
- .get('/', { withXSRFToken: true })
729
- .catch((err) => err.response)
730
-
731
- if (rootResponse?.data) {
732
- const cookie =
733
- /<script>document.cookie = '(XSRF-TOKEN=.*; Max-Age=86400; SameSite=Strict; Path=\/;)'<\/script>/.exec(
734
- rootResponse.data
735
- )?.[1]
736
-
737
- if (cookie && typeof document !== 'undefined') {
738
- document.cookie = cookie
739
- }
740
-
741
- this.parseAndSetCsrfToken(rootResponse)
742
- }
743
-
744
- return await callback()
745
- } catch {
746
- // Session could not be recovered — surface LoginRequiredError
747
- throw new LoginRequiredError()
748
- } finally {
749
- this.isRecoveringFromNetworkError = false
750
- }
751
- }
752
-
753
- if (e.message) throw e
754
- else throw prefixMessage(e, 'Error while handling error. ')
755
- }
756
-
757
- protected parseResponse<T>(response: AxiosResponse<any>) {
758
- const etag = response?.headers ? response.headers['etag'] : ''
759
- let parsedResponse
760
- let includeSAS9Log: boolean = false
761
-
762
- try {
763
- if (typeof response.data === 'string') {
764
- parsedResponse = JSON.parse(response.data)
765
- } else {
766
- parsedResponse = response.data
767
- }
768
- } catch {
769
- try {
770
- parsedResponse = JSON.parse(parseWeboutResponse(response.data))
771
- } catch {
772
- parsedResponse = response.data
773
- }
774
-
775
- includeSAS9Log = true
776
- }
777
-
778
- let responseToReturn: {
779
- result: T
780
- etag: any
781
- log?: string
782
- status: number
783
- } = {
784
- result: parsedResponse as T,
785
- etag,
786
- status: response.status
787
- }
788
-
789
- if (includeSAS9Log) {
790
- responseToReturn.log = response.data
791
- }
792
-
793
- return responseToReturn
794
- }
795
-
796
- private createHttpClient(
797
- baseUrl: string,
798
- httpsAgentOptions?: https.AgentOptions
799
- ) {
800
- const httpsAgent = httpsAgentOptions
801
- ? new https.Agent(httpsAgentOptions)
802
- : undefined
803
-
804
- this.httpClient = createAxiosInstance(baseUrl, httpsAgent)
805
-
806
- this.httpClient.defaults.validateStatus = (status) => {
807
- return status >= 200 && status <= 401
808
- }
809
- }
810
- }
811
-
812
- export const throwIfError = (response: AxiosResponse) => {
813
- switch (response.status) {
814
- case 400:
815
- if (
816
- typeof response.data === 'object' &&
817
- response.data.error === 'invalid_grant'
818
- ) {
819
- // In SASVIYA when trying to get access token, if auth code is wrong status code will be 400 so in such case we return login required error.
820
- throw new LoginRequiredError(response.data)
821
- }
822
-
823
- if (
824
- typeof response.data === 'string' &&
825
- response.data.toLowerCase() === 'invalid csrf token!'
826
- ) {
827
- throw new InvalidSASjsCsrfError()
828
- }
829
- break
830
- case 401:
831
- if (typeof response.data === 'object') {
832
- throw new LoginRequiredError(response.data)
833
- } else {
834
- throw new LoginRequiredError()
835
- }
836
- }
837
-
838
- if (response.data?.entityID?.includes('login')) {
839
- throw new LoginRequiredError()
840
- }
841
-
842
- if (
843
- typeof response.data === 'string' &&
844
- isAuthorizeFormRequired(response.data)
845
- ) {
846
- throw new AuthorizeError(
847
- 'Authorization required',
848
- response.request.responseURL
849
- )
850
- }
851
-
852
- if (
853
- typeof response.data === 'string' &&
854
- isLogInRequired(response.data) &&
855
- !response.config?.url?.includes('/SASLogon/login')
856
- ) {
857
- throw new LoginRequiredError()
858
- }
859
- if (response.data?.auth_request) {
860
- const authorizeRequestUrl = response.request.responseURL
861
- throw new AuthorizeError(response.data.message, authorizeRequestUrl)
862
- }
863
-
864
- if (response.config?.url?.includes('sasAuthError')) {
865
- throw new SAS9AuthError()
866
- }
867
-
868
- const error = parseError(response.data as string)
869
-
870
- if (error) {
871
- throw error
872
- }
873
- }
874
-
875
- const parseError = (data: string) => {
876
- if (!data) return null
877
-
878
- try {
879
- const responseJson = JSON.parse(data?.replace(/[\n\r]/g, ' '))
880
- if (responseJson.errorCode && responseJson.message) {
881
- return new JobExecutionError(
882
- responseJson.errorCode,
883
- responseJson.message,
884
- data?.replace(/[\n\r]/g, ' ')
885
- )
886
- }
887
- } catch (_) {}
888
-
889
- try {
890
- const hasError = data?.includes('{"errorCode')
891
- if (hasError) {
892
- const parts = data.split('{"errorCode')
893
- if (parts.length > 1) {
894
- const error = '{"errorCode' + parts[1].split('"}')[0] + '"}'
895
- const errorJson = JSON.parse(error.replace(/[\n\r]/g, ' '))
896
- return new JobExecutionError(
897
- errorJson.errorCode,
898
- errorJson.message,
899
- data?.replace(/[\n\r]/g, '\n')
900
- )
901
- }
902
- }
903
- } catch (_) {}
904
-
905
- try {
906
- const hasError = !!data?.match(/stored process not found: /i)
907
- if (hasError) {
908
- const parts = data.split(/stored process not found: /i)
909
- if (parts.length > 1) {
910
- const storedProcessPath = parts[1].split('<i>')[1].split('</i>')[0]
911
- const message = storedProcessPath.endsWith('runner')
912
- ? `SASJS runner not found. Here's the link (https://cli.sasjs.io/auth/#sasjs-runner) to the SAS code for registering the SASjs runner`
913
- : `Stored process not found: ${storedProcessPath}`
914
- return new JobExecutionError(500, message, '')
915
- }
916
- }
917
- } catch (_) {}
918
-
919
- try {
920
- // There are some edge cases in which the SAS mp_abort macro
921
- // (https://core.sasjs.io/mp__abort_8sas.html) is unable to
922
- // provide a clean exit. In this case the JSON response will
923
- // be wrapped in >>weboutBEGIN<< and >>weboutEND<< strings.
924
- // Therefore, if the first string exists, we won't throw an
925
- // error just yet (the parser may yet throw one instead)
926
- const hasError =
927
- !data?.match(/>>weboutBEGIN<</) &&
928
- !!data?.match(/Stored Process Error/i) &&
929
- !!data?.match(/This request completed with errors./i)
930
- if (hasError) {
931
- const parts = data.split('<h2>SAS Log</h2>')
932
- if (parts.length > 1) {
933
- const log = parts[1].split('<pre>')[1].split('</pre>')[0]
934
- const message = `This request completed with errors.`
935
- return new JobExecutionError(500, message, log)
936
- }
937
- }
938
- } catch (_) {}
939
-
940
- return null
941
- }