@sasjs/adapter 6.2.0 → 6.2.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.
@@ -2984,6 +2984,7 @@ exports.SASViyaApiClient = void 0;
2984
2984
  const utils_1 = __webpack_require__(9266);
2985
2985
  const joinFolderPath_1 = __webpack_require__(459);
2986
2986
  const form_data_1 = __importDefault(__webpack_require__(1894));
2987
+ const isNode_1 = __webpack_require__(6308);
2987
2988
  const errors_1 = __webpack_require__(7388);
2988
2989
  const SessionManager_1 = __webpack_require__(8697);
2989
2990
  const ContextManager_1 = __webpack_require__(5372);
@@ -2997,6 +2998,8 @@ const executeOnComputeApi_1 = __webpack_require__(3722);
2997
2998
  const getAccessTokenForViya_1 = __webpack_require__(1674);
2998
2999
  const refreshTokensForViya_1 = __webpack_require__(5747);
2999
3000
  const host_1 = __webpack_require__(5334);
3001
+ const NotFoundError_1 = __webpack_require__(7403);
3002
+ const validateForcedServicePack_1 = __webpack_require__(8297);
3000
3003
  /**
3001
3004
  * A client for interfacing with the SAS Viya REST API.
3002
3005
  *
@@ -3011,11 +3014,16 @@ class SASViyaApiClient {
3011
3014
  this.sessionManager = new SessionManager_1.SessionManager(this.serverUrl, this.contextName, this.requestClient);
3012
3015
  this.contextManager = new ContextManager_1.ContextManager(this.serverUrl, this.requestClient);
3013
3016
  this.folderMap = new Map();
3017
+ this.folderMapGeneration = 0;
3014
3018
  this.fileExtensionMap = new Map();
3015
3019
  this.boolExtensionMap = false; // required in case the map has zero entries
3016
3020
  if (serverUrl)
3017
3021
  (0, utils_1.isUrl)(serverUrl);
3018
3022
  }
3023
+ invalidateFolderCache() {
3024
+ this.folderMapGeneration++;
3025
+ this.folderMap.clear();
3026
+ }
3019
3027
  // after an attempt to populate it.
3020
3028
  /**
3021
3029
  * A helper method used to call appendRequest method of RequestClient
@@ -3262,7 +3270,7 @@ class SASViyaApiClient {
3262
3270
  */
3263
3271
  createFile(fileName, contentBuffer, parentFolderPath, parentFolderUri, accessToken) {
3264
3272
  return __awaiter(this, void 0, void 0, function* () {
3265
- var _a;
3273
+ var _a, _b, _c, _d, _e, _f;
3266
3274
  if (!parentFolderPath && !parentFolderUri) {
3267
3275
  throw new Error('Path or URI of the parent folder is required.');
3268
3276
  }
@@ -3273,8 +3281,18 @@ class SASViyaApiClient {
3273
3281
  Accept: 'application/vnd.sas.file+json',
3274
3282
  'Content-Disposition': `filename="${fileName}";`
3275
3283
  };
3276
- const formData = new form_data_1.default();
3277
- formData.append('file', contentBuffer, fileName);
3284
+ const formData = (0, isNode_1.isNode)() ? new form_data_1.default() : new FormData();
3285
+ if (!(0, isNode_1.isNode)()) {
3286
+ const bytes = typeof contentBuffer === 'string'
3287
+ ? contentBuffer
3288
+ : new Uint8Array(contentBuffer.buffer, contentBuffer.byteOffset, contentBuffer.byteLength).slice();
3289
+ formData.append('file', new Blob([bytes]), fileName);
3290
+ }
3291
+ else if (ArrayBuffer.isView(contentBuffer)) {
3292
+ formData.append('file', Buffer.from(contentBuffer.buffer, contentBuffer.byteOffset, contentBuffer.byteLength), fileName);
3293
+ }
3294
+ else
3295
+ formData.append('file', contentBuffer, fileName);
3278
3296
  /** Query Viya for file metadata based on extension type. */
3279
3297
  // typeDefName - Viya accepts this property during the file creation
3280
3298
  let typeDefName = undefined;
@@ -3289,7 +3307,15 @@ class SASViyaApiClient {
3289
3307
  // Populate the file extension map
3290
3308
  // 1. Get Viya's response to this api call
3291
3309
  const typesQueryUrl = `/types/types?limit=999999`;
3292
- const response = (yield this.requestClient.get(typesQueryUrl, accessToken)).result;
3310
+ const typesResult = yield this.requestClient.get(typesQueryUrl, accessToken);
3311
+ if (this.requestClient.isDeploymentTransport() &&
3312
+ (!typesResult ||
3313
+ !Number.isInteger(typesResult.status) ||
3314
+ typesResult.status < 200 ||
3315
+ typesResult.status >= 300 ||
3316
+ !Array.isArray((_b = typesResult.result) === null || _b === void 0 ? void 0 : _b.items)))
3317
+ throw new Error('File type registry did not return success');
3318
+ const response = typesResult.result;
3293
3319
  // 2. Filter the returned items that have file extensions into a map
3294
3320
  // using forEach as an item may relate to multiple file extensions.
3295
3321
  response.items
@@ -3324,18 +3350,50 @@ class SASViyaApiClient {
3324
3350
  }
3325
3351
  }
3326
3352
  // Create the file
3327
- 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);
3353
+ const createFileResponse = yield this.requestClient.post(`/files/files?parentFolderUri=${parentFolderUri}&typeDefName=${typeDefName !== null && typeDefName !== void 0 ? typeDefName : 'file'}#rawUpload`, formData, accessToken, (0, isNode_1.isNode)()
3354
+ ? 'multipart/form-data; boundary=' + formData.getBoundary()
3355
+ : 'multipart/form-data', headers);
3356
+ if (!createFileResponse ||
3357
+ typeof createFileResponse.status !== 'number' ||
3358
+ createFileResponse.status < 200 ||
3359
+ createFileResponse.status >= 300 ||
3360
+ (this.requestClient.isDeploymentTransport() &&
3361
+ createFileResponse.status !== 201))
3362
+ throw new Error('File creation did not return success');
3328
3363
  // If a patch was created...
3329
3364
  if (filePatch) {
3330
3365
  try {
3366
+ const links = (_d = (_c = createFileResponse.result) === null || _c === void 0 ? void 0 : _c.links) === null || _d === void 0 ? void 0 : _d.filter((e) => e.method == 'PATCH' && e.rel == 'patch');
3367
+ let fileUri = (_e = links === null || links === void 0 ? void 0 : links[0]) === null || _e === void 0 ? void 0 : _e.uri;
3368
+ if (typeof fileUri !== 'string' || !fileUri)
3369
+ throw new Error('Missing file metadata patch link');
3331
3370
  const patchHeaders = {
3332
3371
  Accept: 'application/json',
3333
3372
  'If-Match': '*'
3334
3373
  };
3335
- // Get the URI of the newly created file
3336
- const fileUri = createFileResponse.result.links.filter((e) => e.method == 'PATCH' && e.rel == 'patch')[0].uri;
3374
+ if (this.requestClient.isDeploymentTransport()) {
3375
+ const id = (_f = createFileResponse.result) === null || _f === void 0 ? void 0 : _f.id;
3376
+ const etag = createFileResponse.etag;
3377
+ if (typeof id !== 'string' ||
3378
+ !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id) ||
3379
+ (links === null || links === void 0 ? void 0 : links.length) !== 1 ||
3380
+ fileUri !== `/files/files/${id}` ||
3381
+ typeof etag !== 'string' ||
3382
+ !/^"[\x21\x23-\x7e\x80-\xff]+"$/.test(etag))
3383
+ throw new Error('Invalid created file identity, patch link or ETag');
3384
+ patchHeaders['If-Match'] = etag;
3385
+ fileUri = `/files/files/${id}`;
3386
+ }
3337
3387
  // and apply the patch
3338
- return (yield this.requestClient.patch(`${fileUri}`, filePatch, accessToken, patchHeaders)).result;
3388
+ const patched = yield this.requestClient.patch(`${fileUri}`, filePatch, accessToken, patchHeaders);
3389
+ if (!patched ||
3390
+ (this.requestClient.isDeploymentTransport() &&
3391
+ (typeof patched.status !== 'number' ||
3392
+ !Number.isInteger(patched.status))) ||
3393
+ patched.status < 200 ||
3394
+ patched.status >= 300)
3395
+ throw new Error('File metadata patch did not return success');
3396
+ return patched.result;
3339
3397
  }
3340
3398
  catch (e) {
3341
3399
  throw new Error(`Error patching file ${fileName}.\n${e.message}`);
@@ -3344,6 +3402,175 @@ class SASViyaApiClient {
3344
3402
  return createFileResponse.result;
3345
3403
  });
3346
3404
  }
3405
+ /** Recycle exactly the validated app folder; caller must own the scope exclusively. */
3406
+ recycleDeploymentFolder(path, accessToken) {
3407
+ return __awaiter(this, void 0, void 0, function* () {
3408
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3409
+ this.requestClient.restrictDeploymentTransport();
3410
+ (0, validateForcedServicePack_1.validateForcedServicePack)(path, { members: [] });
3411
+ const requireFolder = (response, expectedName) => {
3412
+ if (!response ||
3413
+ response.status < 200 ||
3414
+ response.status >= 300 ||
3415
+ !Number.isInteger(response.status) ||
3416
+ !response.result ||
3417
+ typeof response.result.id !== 'string' ||
3418
+ !uuid.test(response.result.id) ||
3419
+ (expectedName !== undefined && response.result.name !== expectedName))
3420
+ throw new Error('Invalid folder response during deployment');
3421
+ return response.result;
3422
+ };
3423
+ const parentPath = path.slice(0, path.lastIndexOf('/'));
3424
+ const name = path.slice(path.lastIndexOf('/') + 1);
3425
+ const lookup = (folderPath) => __awaiter(this, void 0, void 0, function* () {
3426
+ try {
3427
+ const response = yield this.requestClient.get(`${this.serverUrl}/folders/folders/@item?path=${encodeURIComponent(folderPath)}`, accessToken);
3428
+ if (!response)
3429
+ throw new Error('No response to folder lookup');
3430
+ return response;
3431
+ }
3432
+ catch (e) {
3433
+ if (e instanceof NotFoundError_1.NotFoundError)
3434
+ return null;
3435
+ throw e;
3436
+ }
3437
+ });
3438
+ const parent = requireFolder(yield lookup(parentPath), parentPath.split('/').pop());
3439
+ // Accept the user home and its personal folder as parents, never targets.
3440
+ const isUserHome = /^\/users\/[^/]+$/i.test(parentPath);
3441
+ const isPersonalFolder = /^\/users\/[^/]+\/my folder$/i.test(parentPath);
3442
+ if (parent.type !== 'folder' &&
3443
+ !(isUserHome && ['myFolder', 'userFolder'].includes(parent.type)) &&
3444
+ !(isPersonalFolder && parent.type === 'myFolder'))
3445
+ throw new Error('Cannot safely identify deployment parent folder');
3446
+ const existing = yield lookup(path);
3447
+ if (existing === null)
3448
+ return { parentId: parent.id, recycled: undefined };
3449
+ const folder = requireFolder(existing, name);
3450
+ if (!existing)
3451
+ throw new Error('Invalid folder response during deployment');
3452
+ if (folder.id === parent.id ||
3453
+ folder.type !== 'folder' ||
3454
+ folder.parentFolderUri !== `/folders/folders/${parent.id}` ||
3455
+ typeof existing.etag !== 'string' ||
3456
+ !/^(W\/)?"[\x21\x23-\x7e\x80-\xff]+"$/.test(existing.etag))
3457
+ throw new Error('Cannot safely identify deployment folder');
3458
+ const bin = requireFolder(yield this.requestClient.get(`${this.serverUrl}/folders/folders/@myRecycleBin`, accessToken));
3459
+ if (bin.type !== 'trashFolder' ||
3460
+ bin.id === folder.id ||
3461
+ bin.id === parent.id)
3462
+ throw new Error('Invalid recycle bin');
3463
+ // A UUID keeps the destination name bounded even for long app names.
3464
+ const recycleName = folder.id;
3465
+ const url = `${this.serverUrl}/folders/folders/${bin.id}/members?limit=100&start=`;
3466
+ const requireEmptyNextPage = (start, total) => __awaiter(this, void 0, void 0, function* () {
3467
+ var _a;
3468
+ const page = yield this.requestClient.get(url + start, accessToken);
3469
+ if (!Number.isInteger(page === null || page === void 0 ? void 0 : page.status) ||
3470
+ page.status < 200 ||
3471
+ page.status >= 300 ||
3472
+ !Array.isArray((_a = page.result) === null || _a === void 0 ? void 0 : _a.items) ||
3473
+ page.result.items.length !== 0 ||
3474
+ page.result.count !== total)
3475
+ throw new Error('Ambiguous recycle bin listing count');
3476
+ });
3477
+ let start = 0;
3478
+ let total;
3479
+ do {
3480
+ const page = yield this.requestClient.get(url + start, accessToken);
3481
+ if (!page ||
3482
+ page.status < 200 ||
3483
+ page.status >= 300 ||
3484
+ !Number.isInteger(page.status) ||
3485
+ !page.result ||
3486
+ !Array.isArray(page.result.items) ||
3487
+ !Number.isSafeInteger(page.result.count) ||
3488
+ page.result.count < 0 ||
3489
+ (total !== undefined && page.result.count !== total) ||
3490
+ page.result.items.length > 100 ||
3491
+ start + page.result.items.length > page.result.count)
3492
+ throw new Error('Invalid recycle bin listing');
3493
+ total = page.result.count;
3494
+ if (page.result.items.some((item) => !item ||
3495
+ typeof item.name !== 'string' ||
3496
+ typeof item.uri !== 'string' ||
3497
+ item.name.toLowerCase() === recycleName.toLowerCase() ||
3498
+ item.uri === `/folders/folders/${folder.id}`))
3499
+ throw new Error('Recycle destination collision or invalid member');
3500
+ if (!page.result.items.length && start < total)
3501
+ throw new Error('Incomplete recycle bin listing');
3502
+ start += page.result.items.length;
3503
+ // A full terminal page cannot prove that there are no further members.
3504
+ if (start === total && page.result.items.length === 100)
3505
+ yield requireEmptyNextPage(start, total);
3506
+ } while (start < total);
3507
+ const identity = `/folders/folders/${folder.id}`;
3508
+ try {
3509
+ // PUT replaces the folder; retain all writable fields from the GET.
3510
+ const moved = yield this.requestClient.put(`${this.serverUrl}${identity}`, Object.assign(Object.assign(Object.assign({ name: recycleName, type: folder.type }, (folder.description !== undefined && {
3511
+ description: folder.description
3512
+ })), (folder.version !== undefined && { version: folder.version })), { parentFolderUri: `/folders/folders/${bin.id}` }), accessToken, { 'If-Match': existing.etag });
3513
+ requireFolder(moved);
3514
+ if (moved.result.id !== folder.id ||
3515
+ moved.result.name !== recycleName ||
3516
+ moved.result.type !== 'folder' ||
3517
+ moved.result.parentFolderUri !== `/folders/folders/${bin.id}`)
3518
+ throw new Error('Moved folder identity mismatch');
3519
+ }
3520
+ catch (e) {
3521
+ throw new Error(`Recycle move failed or outcome unknown for ${path}; inspect recycle bin /folders/folders/${bin.id} for ${identity} as '${recycleName}' before retrying. ${e instanceof Error ? e.message : ''}`);
3522
+ }
3523
+ try {
3524
+ const confirmed = yield lookup(path);
3525
+ if (confirmed !== null)
3526
+ throw new Error('Original path is still occupied');
3527
+ let position = 0;
3528
+ let expected;
3529
+ let matches = 0;
3530
+ do {
3531
+ const page = yield this.requestClient.get(url + position, accessToken);
3532
+ const data = page === null || page === void 0 ? void 0 : page.result;
3533
+ if (!page ||
3534
+ !Number.isInteger(page.status) ||
3535
+ page.status < 200 ||
3536
+ page.status >= 300 ||
3537
+ !data ||
3538
+ !Array.isArray(data.items) ||
3539
+ !Number.isSafeInteger(data.count) ||
3540
+ data.count < 0 ||
3541
+ (expected !== undefined && data.count !== expected) ||
3542
+ data.items.length > 100 ||
3543
+ position + data.items.length > data.count ||
3544
+ (!data.items.length && position < data.count))
3545
+ throw new Error('Invalid recycle listing after move');
3546
+ expected = data.count;
3547
+ for (const item of data.items) {
3548
+ if (!item ||
3549
+ typeof item.name !== 'string' ||
3550
+ typeof item.uri !== 'string')
3551
+ throw new Error('Invalid recycle member after move');
3552
+ if (item.uri === identity && item.name === recycleName)
3553
+ matches++;
3554
+ else if (item.uri === identity ||
3555
+ item.name.toLowerCase() === recycleName.toLowerCase())
3556
+ throw new Error('Ambiguous recycle member after move');
3557
+ }
3558
+ position += data.items.length;
3559
+ if (position === expected && data.items.length === 100)
3560
+ yield requireEmptyNextPage(position, expected);
3561
+ } while (position < expected);
3562
+ if (matches !== 1)
3563
+ throw new Error('Moved folder not found in recycle bin');
3564
+ }
3565
+ catch (e) {
3566
+ throw new Error(`Recycle move outcome could not be verified for ${path}; inspect ${identity} in recycle bin ${bin.id} before retrying. ${e instanceof Error ? e.message : ''}`);
3567
+ }
3568
+ return {
3569
+ parentId: parent.id,
3570
+ recycled: { identity, recycleName, binId: bin.id }
3571
+ };
3572
+ });
3573
+ }
3347
3574
  /**
3348
3575
  * Creates a folder. Path to or URI of the parent folder is required.
3349
3576
  * @param folderName - the name of the new folder.
@@ -3375,20 +3602,14 @@ class SASViyaApiClient {
3375
3602
  parentFolderUri = `/folders/folders/${parentFolder.id}`;
3376
3603
  }
3377
3604
  }
3378
- // The forced delete of the folder being created is keyed on its path, not on
3379
- // how the parent was found: a caller that supplies the parent's URI (the
3380
- // service pack deploy does, to save a lookup per member) still expects an
3381
- // existing folder of this name to be replaced rather than refused with 409.
3382
- // When the parent itself did not exist there is nothing here to delete, and
3383
- // the lookup is a 404 the caller never sees.
3605
+ // Resolve the child by path even when the caller supplied its parent URI.
3384
3606
  if (isForced && parentFolderPath) {
3385
3607
  const folderPath = (0, joinFolderPath_1.joinFolderPath)(parentFolderPath, folderName);
3386
3608
  const folderUri = yield this.getFolderUri(folderPath, accessToken);
3387
- if (folderUri) {
3609
+ if (folderUri)
3388
3610
  yield this.deleteFolder(folderPath, accessToken);
3389
- }
3390
3611
  }
3391
- const { result: createFolderResponse } = yield this.requestClient
3612
+ const createResponse = yield this.requestClient
3392
3613
  .post(`/folders/folders?parentFolderUri=${parentFolderUri}`, {
3393
3614
  name: folderName,
3394
3615
  type: 'folder'
@@ -3407,6 +3628,16 @@ class SASViyaApiClient {
3407
3628
  }
3408
3629
  throw err;
3409
3630
  });
3631
+ if (!createResponse ||
3632
+ typeof createResponse.status !== 'number' ||
3633
+ createResponse.status < 200 ||
3634
+ createResponse.status >= 300 ||
3635
+ (this.requestClient.isDeploymentTransport() &&
3636
+ createResponse.status !== 201) ||
3637
+ !createResponse.result ||
3638
+ !createResponse.result.id)
3639
+ throw new Error('Folder creation did not return success');
3640
+ const createFolderResponse = createResponse.result;
3410
3641
  // The POST answered with the folder it created, so there is nothing to look up:
3411
3642
  // a new folder has no members, and re-reading it by a path joined here by hand
3412
3643
  // is how the doubled slash in adapter#974 reached the server.
@@ -3716,6 +3947,7 @@ class SASViyaApiClient {
3716
3947
  if (this.folderMap.get(path)) {
3717
3948
  return;
3718
3949
  }
3950
+ const generation = this.folderMapGeneration;
3719
3951
  const url = '/folders/folders/@item?path=' + path;
3720
3952
  const { result: folder } = yield this.requestClient
3721
3953
  .get(`${url}`, accessToken)
@@ -3732,6 +3964,9 @@ class SASViyaApiClient {
3732
3964
  throw (0, error_1.prefixMessage)(err, 'Error while getting members. ');
3733
3965
  });
3734
3966
  const itemsAtRoot = members.items;
3967
+ if (generation !== this.folderMapGeneration) {
3968
+ return this.populateFolderMap(path, accessToken);
3969
+ }
3735
3970
  this.folderMap.set(path, itemsAtRoot);
3736
3971
  });
3737
3972
  }
@@ -3954,6 +4189,7 @@ const types_2 = __webpack_require__(3631);
3954
4189
  const RequestClient_1 = __webpack_require__(8816);
3955
4190
  const SasjsRequestClient_1 = __webpack_require__(7560);
3956
4191
  const job_execution_1 = __webpack_require__(1391);
4192
+ const validateForcedServicePack_1 = __webpack_require__(8297);
3957
4193
  const defaultConfig = {
3958
4194
  serverUrl: '',
3959
4195
  // The one name the adapter needs for SASjs Server: the mount its routes sit
@@ -4548,24 +4784,23 @@ class SASjs {
4548
4784
  * If not provided, is taken from SASjsConfig.
4549
4785
  * @param accessToken - an optional access token to be passed in when
4550
4786
  * using this function from the command line.
4551
- * @param isForced - flag that indicates if target folder already exists, it and all subfolders have to be deleted.
4552
- * @param onProgress - optional callback invoked once per member, immediately
4553
- * before the member is written, with its name, folder, type and position. A
4554
- * Viya deploy is one REST call per folder, file and job definition, run in
4555
- * sequence, so this is the only signal a caller has that a large pack is
4556
- * still moving rather than hung.
4787
+ * @param isForced - move the entire existing appLoc to the recycle bin before deploying (including content omitted from this pack); defaults to false. Requires exclusive control of appLoc, its parent and recycle bin. A failure may leave an incomplete app; see README for recovery.
4788
+ * @param onProgress - called immediately before each pack member is written, with its name, folder, type and 1-based position.
4557
4789
  */
4558
4790
  deployServicePack(serviceJson_1, appLoc_1, serverUrl_1, accessToken_1) {
4559
4791
  return __awaiter(this, arguments, void 0, function* (serviceJson, appLoc, serverUrl, accessToken, isForced = false, onProgress) {
4792
+ var _a, _b, _c;
4560
4793
  this.isMethodSupported('deployServicePack', [types_2.ServerType.SasViya]);
4561
4794
  let sasApiClient = null;
4562
- if (serverUrl || appLoc) {
4563
- if (!serverUrl)
4795
+ if (serverUrl !== undefined || appLoc !== undefined) {
4796
+ if (serverUrl === undefined)
4564
4797
  serverUrl = this.sasjsConfig.serverUrl;
4565
- if (!appLoc)
4798
+ if (appLoc === undefined)
4566
4799
  appLoc = this.sasjsConfig.appLoc;
4567
4800
  if (this.sasjsConfig.serverType === types_2.ServerType.SasViya) {
4568
- sasApiClient = new SASViyaApiClient_1.SASViyaApiClient(serverUrl, appLoc, this.sasjsConfig.contextName, this.requestClient);
4801
+ sasApiClient = new SASViyaApiClient_1.SASViyaApiClient(serverUrl, appLoc, this.sasjsConfig.contextName, serverUrl === this.sasjsConfig.serverUrl
4802
+ ? this.requestClient
4803
+ : new RequestClient_1.RequestClient(serverUrl, this.sasjsConfig.httpsAgentOptions));
4569
4804
  sasApiClient.debug = this.sasjsConfig.debug;
4570
4805
  }
4571
4806
  else if (this.sasjsConfig.serverType === types_2.ServerType.Sas9) {
@@ -4583,16 +4818,67 @@ class SASjs {
4583
4818
  serverUrl = sasClientConfig.serverUrl;
4584
4819
  appLoc = sasClientConfig.rootFolderName;
4585
4820
  }
4821
+ const safeServer = (() => {
4822
+ try {
4823
+ const origin = new URL(serverUrl || (typeof location !== 'undefined' ? location.href : ''));
4824
+ return ((origin.protocol === 'https:' || origin.protocol === 'http:') &&
4825
+ !origin.username &&
4826
+ !origin.password &&
4827
+ !origin.search &&
4828
+ !origin.hash);
4829
+ }
4830
+ catch (_a) {
4831
+ return false;
4832
+ }
4833
+ })();
4834
+ if (isForced && !safeServer)
4835
+ throw new Error('Invalid deployment server URL');
4836
+ if (isForced) {
4837
+ (0, validateForcedServicePack_1.validateForcedServicePack)(appLoc, serviceJson);
4838
+ const deploymentClient = new RequestClient_1.RequestClient(serverUrl, this.sasjsConfig.httpsAgentOptions);
4839
+ if (serverUrl === this.sasjsConfig.serverUrl)
4840
+ deploymentClient.copyCsrfFrom(this.requestClient);
4841
+ deploymentClient.restrictDeploymentTransport();
4842
+ const api = new SASViyaApiClient_1.SASViyaApiClient(serverUrl, appLoc, this.sasjsConfig.contextName, deploymentClient);
4843
+ (_a = this.sasViyaApiClient) === null || _a === void 0 ? void 0 : _a.invalidateFolderCache();
4844
+ try {
4845
+ const { parentId, recycled } = yield api.recycleDeploymentFolder(appLoc, accessToken);
4846
+ try {
4847
+ const parent = appLoc.slice(0, appLoc.lastIndexOf('/'));
4848
+ const name = appLoc.slice(appLoc.lastIndexOf('/') + 1);
4849
+ const root = yield api.createFolder(name, parent, `/folders/folders/${parentId}`, accessToken, false);
4850
+ if (!root ||
4851
+ root.name !== name ||
4852
+ root.parentFolderUri !== `/folders/folders/${parentId}` ||
4853
+ root.type !== 'folder' ||
4854
+ typeof root.id !== 'string' ||
4855
+ !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(root.id))
4856
+ throw new Error('Invalid created app folder identity');
4857
+ yield this.createFoldersAndServices(appLoc, serviceJson.members, accessToken, api, false, {
4858
+ onProgress,
4859
+ index: 0,
4860
+ total: countMembers(serviceJson.members),
4861
+ strict: true
4862
+ }, `/folders/folders/${root.id}`);
4863
+ }
4864
+ catch (e) {
4865
+ const recovery = recycled
4866
+ ? `Original folder ${recycled.identity} is in recycle bin ${recycled.binId} as '${recycled.recycleName}'.`
4867
+ : 'No prior folder was recycled.';
4868
+ throw new Error(`Deployment may be partial at ${appLoc}. ${recovery} ${e instanceof Error ? e.message : String(e)}`);
4869
+ }
4870
+ }
4871
+ finally {
4872
+ (_b = this.sasViyaApiClient) === null || _b === void 0 ? void 0 : _b.invalidateFolderCache();
4873
+ }
4874
+ return;
4875
+ }
4586
4876
  // members of type 'folder' should be processed first
4587
- if (serviceJson.members[0].members) {
4877
+ if ((_c = serviceJson.members[0]) === null || _c === void 0 ? void 0 : _c.members) {
4588
4878
  serviceJson.members[0].members.sort((member) => member.type === 'folder' ? -1 : 1);
4589
4879
  }
4590
4880
  const members = serviceJson.members;
4591
- yield this.createFoldersAndServices(appLoc, members, accessToken, sasApiClient, isForced, {
4592
- onProgress,
4593
- index: 0,
4594
- total: countMembers(members)
4595
- });
4881
+ yield this.createFoldersAndServices(appLoc, members, accessToken, sasApiClient, isForced, { onProgress, index: 0, total: countMembers(members), strict: false });
4596
4882
  });
4597
4883
  }
4598
4884
  /**
@@ -4743,33 +5029,43 @@ class SASjs {
4743
5029
  createFoldersAndServices(parentFolder_1, membersJson_1, accessToken_1, sasApiClient_1, isForced_1) {
4744
5030
  return __awaiter(this, arguments, void 0, function* (parentFolder, membersJson, accessToken, sasApiClient, isForced, progress = {
4745
5031
  index: 0,
4746
- total: countMembers(membersJson)
5032
+ total: countMembers(membersJson),
5033
+ strict: false
4747
5034
  }, parentFolderUri) {
4748
5035
  yield (0, utils_1.asyncForEach)(membersJson, (member) => __awaiter(this, void 0, void 0, function* () {
5036
+ let childUri;
4749
5037
  switch (member.type) {
4750
5038
  case 'folder': {
4751
5039
  reportMember(progress, 'folder', member.name, parentFolder);
4752
5040
  const folder = yield this.createFolder(member.name, parentFolder, parentFolderUri, accessToken, sasApiClient, isForced);
4753
- if (member.members && member.members.length) {
4754
- const folderPath = `${parentFolder}/${member.name}`;
4755
- yield this.createFoldersAndServices(folderPath, member.members, accessToken, sasApiClient, isForced, progress,
4756
- // the folder the deploy has just created, so its children do not
4757
- // each resolve the same path back to a URI
4758
- (folder === null || folder === void 0 ? void 0 : folder.id) ? `/folders/folders/${folder.id}` : undefined);
5041
+ if (progress.strict) {
5042
+ if (!folder ||
5043
+ folder.name !== member.name ||
5044
+ folder.parentFolderUri !== parentFolderUri ||
5045
+ folder.type !== 'folder' ||
5046
+ typeof folder.id !== 'string' ||
5047
+ !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(folder.id))
5048
+ throw new Error('Invalid created folder identity');
4759
5049
  }
5050
+ childUri = (folder === null || folder === void 0 ? void 0 : folder.id) ? `/folders/folders/${folder.id}` : undefined;
4760
5051
  break;
4761
5052
  }
4762
5053
  case 'file':
4763
5054
  reportMember(progress, 'file', member.name, parentFolder);
4764
5055
  yield this.createFile(member.name, member.code, parentFolder, parentFolderUri, accessToken, sasApiClient);
4765
5056
  break;
4766
- case 'service':
5057
+ case 'service': {
4767
5058
  reportMember(progress, 'service', member.name, parentFolder);
4768
- yield this.createJobDefinition(member.name, member.code, parentFolder, parentFolderUri, accessToken, sasApiClient);
5059
+ const response = yield this.createJobDefinition(member.name, member.code, parentFolder, parentFolderUri, accessToken, sasApiClient);
5060
+ if (progress.strict && (!response || response.status !== 201))
5061
+ throw new Error('Job definition creation did not return success');
4769
5062
  break;
5063
+ }
4770
5064
  default:
4771
5065
  throw new Error(`Unidentified member '${member.name}' provided.`);
4772
5066
  }
5067
+ if (member.type === 'folder' && member.members && member.members.length)
5068
+ yield this.createFoldersAndServices(`${parentFolder}/${member.name}`, member.members, accessToken, sasApiClient, isForced, progress, childUri);
4773
5069
  }));
4774
5070
  });
4775
5071
  }
@@ -8497,6 +8793,7 @@ class RequestClient {
8497
8793
  this.verboseMode = false;
8498
8794
  this.csrfToken = { headerName: '', value: '' };
8499
8795
  this.isRecoveringFromNetworkError = false;
8796
+ this.deploymentTransport = false;
8500
8797
  this.mockReadiness = (0, mockReadiness_1.captureMockReadiness)();
8501
8798
  /**
8502
8799
  * this method returns all requests, an array of SASjsRequest type
@@ -8730,8 +9027,19 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
8730
9027
  }
8731
9028
  };
8732
9029
  this.handleError = (e_1, callback_1, ...args_1) => __awaiter(this, [e_1, callback_1, ...args_1], void 0, function* (e, callback, debug = false) {
8733
- var _a;
9030
+ var _a, _b;
8734
9031
  const response = e.response;
9032
+ // A missing response may mean a write succeeded or a redirect was blocked.
9033
+ // Retrying would repeat an operation whose outcome is unknown.
9034
+ if (this.deploymentTransport && !response && e.isAxiosError) {
9035
+ throw (0, responseReceived_1.markResponseReceived)(e, false);
9036
+ }
9037
+ // These recovery callbacks recursively replay the original operation and can
9038
+ // repeat an uncertain deployment write. Only the bounded CSRF challenge
9039
+ // retry below is permitted on the restricted transport.
9040
+ if (this.deploymentTransport &&
9041
+ (e instanceof errors_1.AuthorizeError || e instanceof InvalidSASjsCsrfError_1.InvalidSASjsCsrfError))
9042
+ throw e;
8735
9043
  if (e instanceof errors_1.AuthorizeError) {
8736
9044
  const res = yield this.httpClient
8737
9045
  .get(e.confirmUrl, {
@@ -8774,6 +9082,26 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
8774
9082
  });
8775
9083
  }
8776
9084
  if ((response === null || response === void 0 ? void 0 : response.status) === 403 || (response === null || response === void 0 ? void 0 : response.status) === 449) {
9085
+ if (this.deploymentTransport) {
9086
+ const challenge = this.parseCsrfToken(response);
9087
+ const previous = challenge && ((_a = response.config.headers) === null || _a === void 0 ? void 0 : _a.get(challenge.headerName));
9088
+ if (!(challenge === null || challenge === void 0 ? void 0 : challenge.headerName) ||
9089
+ !/^x-[a-z0-9-]*(?:csrf|xsrf)[a-z0-9-]*$/.test(challenge.headerName) ||
9090
+ !challenge.value ||
9091
+ previous === challenge.value)
9092
+ throw (0, responseReceived_1.markResponseReceived)(e, true);
9093
+ this.csrfToken = challenge;
9094
+ try {
9095
+ const config = response.config;
9096
+ config.headers.set(challenge.headerName, challenge.value);
9097
+ const retried = yield this.httpClient.request(config);
9098
+ (0, exports.throwIfError)(retried);
9099
+ return this.parseResponse(retried);
9100
+ }
9101
+ catch (retryError) {
9102
+ throw (0, responseReceived_1.markResponseReceived)(retryError, Boolean(retryError.response));
9103
+ }
9104
+ }
8777
9105
  this.parseAndSetCsrfToken(response);
8778
9106
  if (this.csrfToken.headerName && this.csrfToken.value) {
8779
9107
  return yield callback().catch((err) => {
@@ -8809,7 +9137,7 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
8809
9137
  .get('/', { withXSRFToken: true })
8810
9138
  .catch((err) => err.response);
8811
9139
  if (rootResponse === null || rootResponse === void 0 ? void 0 : rootResponse.data) {
8812
- const cookie = (_a = /<script>document.cookie = '(XSRF-TOKEN=.*; Max-Age=86400; SameSite=Strict; Path=\/;)'<\/script>/.exec(rootResponse.data)) === null || _a === void 0 ? void 0 : _a[1];
9140
+ const cookie = (_b = /<script>document.cookie = '(XSRF-TOKEN=.*; Max-Age=86400; SameSite=Strict; Path=\/;)'<\/script>/.exec(rootResponse.data)) === null || _b === void 0 ? void 0 : _b[1];
8813
9141
  if (cookie && typeof document !== 'undefined') {
8814
9142
  document.cookie = cookie;
8815
9143
  }
@@ -8818,10 +9146,7 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
8818
9146
  return yield callback();
8819
9147
  }
8820
9148
  catch (retryError) {
8821
- // Session could not be recovered — surface LoginRequiredError. The
8822
- // retry itself may have reached the server and been refused, which is
8823
- // not the same as never arriving: the marker follows the retry's own
8824
- // answer, not the opaque network error that started this.
9149
+ // Session could not be recovered — surface LoginRequiredError
8825
9150
  throw (0, responseReceived_1.markResponseReceived)(new errors_1.LoginRequiredError(), (0, responseReceived_1.responseWasReceived)(retryError));
8826
9151
  }
8827
9152
  finally {
@@ -8841,6 +9166,7 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
8841
9166
  }
8842
9167
  }
8843
9168
  setConfig(baseUrl, httpsAgentOptions) {
9169
+ this.deploymentTransport = false;
8844
9170
  this.createHttpClient(baseUrl, httpsAgentOptions);
8845
9171
  }
8846
9172
  saveLocalStorageToken(accessToken, refreshToken) {
@@ -8876,6 +9202,45 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
8876
9202
  document.cookie = `${name}=; Max-Age=0; Path=/;`;
8877
9203
  }
8878
9204
  }
9205
+ copyCsrfFrom(source) {
9206
+ const locationBase = typeof location !== 'undefined' ? location.href : undefined;
9207
+ const targetUrl = new URL(this.getBaseUrl() || locationBase || '', locationBase);
9208
+ const sourceUrl = new URL(source.getBaseUrl() || locationBase || '', locationBase);
9209
+ if (targetUrl.origin !== sourceUrl.origin)
9210
+ throw new Error('Cannot copy cross-origin CSRF state');
9211
+ this.csrfToken = Object.assign({}, source.csrfToken);
9212
+ }
9213
+ /** Restrict a dedicated deployment client to its origin and prohibit redirects. */
9214
+ restrictDeploymentTransport() {
9215
+ const locationBase = typeof location !== 'undefined' ? location.href : undefined;
9216
+ const base = new URL(this.getBaseUrl() || locationBase || '', locationBase);
9217
+ this.httpClient.defaults.maxRedirects = 0;
9218
+ if (!(0, isNode_1.isNode)()) {
9219
+ if (typeof Request === 'undefined' ||
9220
+ new Request(base.href, { redirect: 'error' }).redirect !== 'error')
9221
+ throw new Error('Safe deployment requires fetch redirect support');
9222
+ this.httpClient.defaults.adapter = 'fetch';
9223
+ this.httpClient.defaults.fetchOptions = { redirect: 'error' };
9224
+ }
9225
+ this.httpClient.interceptors.request.use((config) => {
9226
+ if (config.data &&
9227
+ typeof config.data.getBuffer === 'function' &&
9228
+ typeof config.data.getBoundary === 'function') {
9229
+ const boundary = config.data.getBoundary();
9230
+ config.data = config.data.getBuffer();
9231
+ config.headers.set('Content-Type', `multipart/form-data; boundary=${boundary}`);
9232
+ }
9233
+ const url = new URL(config.url || '', config.baseURL || base.href);
9234
+ if (url.origin !== base.origin ||
9235
+ /[\\\u0000-\u001f\u007f]/.test(config.url || ''))
9236
+ throw new Error('Unsafe deployment request URL');
9237
+ return config;
9238
+ });
9239
+ this.deploymentTransport = true;
9240
+ }
9241
+ isDeploymentTransport() {
9242
+ return this.deploymentTransport;
9243
+ }
8879
9244
  getBaseUrl() {
8880
9245
  return this.httpClient.defaults.baseURL || '';
8881
9246
  }
@@ -9007,7 +9372,7 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
9007
9372
  return this.parseResponse(response);
9008
9373
  })
9009
9374
  .catch((e) => __awaiter(this, void 0, void 0, function* () {
9010
- return yield this.handleError(e, () => this.patch(url, data, accessToken));
9375
+ return yield this.handleError(e, () => this.patch(url, data, accessToken, overrideHeaders));
9011
9376
  }));
9012
9377
  });
9013
9378
  }
@@ -9099,17 +9464,6 @@ exports.RequestClient = RequestClient;
9099
9464
  * included here.
9100
9465
  */
9101
9466
  const isTokenRefreshUrl = (url) => !!url && /(^|\/)auth\/refresh(\?|$)/.test(url);
9102
- /**
9103
- * Raises the error a response status implies, marked as one built from a
9104
- * response.
9105
- *
9106
- * The marking has to happen here: every error below is a new object carrying
9107
- * the body, so the axios error - the thing that knew a response had arrived -
9108
- * is gone by the time a caller catches it (sasjs/adapter#895). A 401 from a
9109
- * refresh route is named by `throwForStatus` as a rejected refresh token
9110
- * (sasjs/adapter#975); this marks it as an answer that arrived, so a transport
9111
- * failure and a refusal are not reported with the same title.
9112
- */
9113
9467
  const throwIfError = (response) => {
9114
9468
  try {
9115
9469
  throwForStatus(response);
@@ -11957,6 +12311,88 @@ const splitChunks = (content) => {
11957
12311
  exports.splitChunks = splitChunks;
11958
12312
 
11959
12313
 
12314
+ /***/ },
12315
+
12316
+ /***/ 8297
12317
+ (__unused_webpack_module, exports) {
12318
+
12319
+ "use strict";
12320
+ var __webpack_unused_export__;
12321
+
12322
+ __webpack_unused_export__ = ({ value: true });
12323
+ exports.validateForcedServicePack = validateForcedServicePack;
12324
+ /** Validate the entire destructive deployment scope before making any request. */
12325
+ function validateForcedServicePack(appLoc, pack) {
12326
+ const safeName = (value) => typeof value === 'string' &&
12327
+ value.length > 0 &&
12328
+ value.trim() === value &&
12329
+ value !== '.' &&
12330
+ value !== '..' &&
12331
+ !/[\/\\%?#\u0000-\u001f\u007f]/.test(value) &&
12332
+ !/[. ]$/.test(value) &&
12333
+ !/[\u200b-\u200f\u202a-\u202e\u2060-\u206f\ufeff]/.test(value);
12334
+ if (typeof appLoc !== 'string' || !appLoc.startsWith('/'))
12335
+ throw new Error('Invalid forced deployment appLoc');
12336
+ const parts = appLoc.slice(1).split('/');
12337
+ if (parts.length < 2 ||
12338
+ !parts.every(safeName) ||
12339
+ /^(home|homes|user|my folder|myfolder|@myfolder|@myrecyclebin)$/i.test(parts[0]) ||
12340
+ (/^users$/i.test(parts[0]) && parts.length < 3) ||
12341
+ (/^users$/i.test(parts[0]) &&
12342
+ parts.length === 3 &&
12343
+ /^my folder$/i.test(parts[2])) ||
12344
+ parts.slice(1).some((part) => /^users$/i.test(part)))
12345
+ throw new Error('Unsafe forced deployment appLoc');
12346
+ const seen = new Set();
12347
+ const validate = (members) => {
12348
+ if (!Array.isArray(members))
12349
+ throw new Error('Invalid service pack members');
12350
+ if (seen.has(members))
12351
+ throw new Error('Cyclic service pack');
12352
+ seen.add(members);
12353
+ const names = new Set();
12354
+ for (const member of members) {
12355
+ if (!member || typeof member !== 'object' || !safeName(member.name))
12356
+ throw new Error('Invalid service pack member name');
12357
+ const name = member.name.toLowerCase();
12358
+ if (names.has(name))
12359
+ throw new Error('Ambiguous service pack member name');
12360
+ names.add(name);
12361
+ if (member.type === 'folder') {
12362
+ if (member.members !== undefined)
12363
+ validate(member.members);
12364
+ }
12365
+ else if (member.type === 'service') {
12366
+ if (Array.from(member.name).length > 100)
12367
+ throw new Error('Invalid service name: exceeds 100 characters');
12368
+ if (typeof member.code !== 'string')
12369
+ throw new Error('Invalid service code');
12370
+ if (member.members !== undefined)
12371
+ throw new Error('Invalid service members');
12372
+ }
12373
+ else if (member.type === 'file') {
12374
+ // The existing file API sends this name verbatim in a quoted HTTP header.
12375
+ // Without a verified Viya encoding contract, reject unsafe values before
12376
+ // the destructive move rather than silently rename or escape them.
12377
+ if (!/^[\x20-\x21\x23-\x7e]+$/.test(member.name))
12378
+ throw new Error('Invalid file name for forced deployment HTTP header');
12379
+ if (typeof member.code !== 'string' && !ArrayBuffer.isView(member.code))
12380
+ throw new Error('Invalid file content');
12381
+ if (member.members !== undefined)
12382
+ throw new Error('Invalid file members');
12383
+ }
12384
+ else {
12385
+ throw new Error('Invalid service pack member type');
12386
+ }
12387
+ }
12388
+ seen.delete(members);
12389
+ };
12390
+ if (!pack || typeof pack !== 'object')
12391
+ throw new Error('Invalid service pack');
12392
+ validate(pack.members);
12393
+ }
12394
+
12395
+
11960
12396
  /***/ },
11961
12397
 
11962
12398
  /***/ 8128