From cae7786489d7579a937e88d626c4c4dd51749143 Mon Sep 17 00:00:00 2001 From: Shailesh Hande Date: Wed, 27 May 2026 11:26:48 +0530 Subject: [PATCH] Added the paramter to set the status based on the prev result config --- action.yml | 4 + dist/api/http-request.js | 140 --- dist/api/veracode-hmac.js | 73 -- dist/app-config.js | 23 - dist/checks.js | 18 - dist/index.js | 1077 +++++++++------------ dist/inputs.d.ts | 1 + dist/inputs.js | 99 -- dist/main.js | 73 -- dist/namespaces/Checks.js | 19 - dist/namespaces/VeracodeApplication.js | 2 - dist/namespaces/VeracodePipelineResult.js | 2 - dist/namespaces/VeracodePolicyResult.js | 2 - dist/services/application-service.js | 380 -------- dist/services/check-service.js | 16 - dist/services/findings-service.js | 81 -- dist/services/pipeline-results-service.js | 393 -------- dist/services/policy-results-services.js | 193 ---- dist/services/policy-service.js | 51 - src/inputs.ts | 4 +- src/services/policy-results-services.ts | 33 + 21 files changed, 501 insertions(+), 2183 deletions(-) delete mode 100644 dist/api/http-request.js delete mode 100644 dist/api/veracode-hmac.js delete mode 100644 dist/app-config.js delete mode 100644 dist/checks.js delete mode 100644 dist/inputs.js delete mode 100644 dist/main.js delete mode 100644 dist/namespaces/Checks.js delete mode 100644 dist/namespaces/VeracodeApplication.js delete mode 100644 dist/namespaces/VeracodePipelineResult.js delete mode 100644 dist/namespaces/VeracodePolicyResult.js delete mode 100644 dist/services/application-service.js delete mode 100644 dist/services/check-service.js delete mode 100644 dist/services/findings-service.js delete mode 100644 dist/services/pipeline-results-service.js delete mode 100644 dist/services/policy-results-services.js delete mode 100644 dist/services/policy-service.js diff --git a/action.yml b/action.yml index a692776..58445a8 100644 --- a/action.yml +++ b/action.yml @@ -97,6 +97,10 @@ inputs: description: 'Specifies the platform environment type — use CLOUD for GitHub.com or ENTERPRISE for GitHub Enterprise Server (GHES).' default: 'CLOUD' required: false + wait_for_scan_completion: + description: 'Wait for the Veracode Static Scan to complete and poll for the final results. If set to false, the scan will be submitted asynchronously and the workflow will continue immediately.' + default: 'true' + required: false runs: using: 'node20' diff --git a/dist/api/http-request.js b/dist/api/http-request.js deleted file mode 100644 index 76b6154..0000000 --- a/dist/api/http-request.js +++ /dev/null @@ -1,140 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getResourceByAttribute = getResourceByAttribute; -exports.deleteResourceById = deleteResourceById; -exports.postResourceByAttribute = postResourceByAttribute; -const core = __importStar(require("@actions/core")); -const veracode_hmac_1 = require("./veracode-hmac"); -const app_config_1 = __importDefault(require("../app-config")); -async function getResourceByAttribute(vid, vkey, resource) { - const resourceUri = resource.resourceUri; - const queryAttribute = resource.queryAttribute; - const queryValue = resource.queryValue; - const queryAttribute1 = resource.queryAttribute1; - const queryValue1 = resource.queryValue1; - let host = app_config_1.default.hostName.veracode.us; - if (vid.startsWith('vera01ei-')) { - host = app_config_1.default.hostName.veracode.eu; - vid = vid.split('-')[1] || ''; - vkey = vkey.split('-')[1] || ''; - } - let urlQueryParams = queryAttribute !== '' ? `?${queryAttribute}=${queryValue}` : ''; - if (queryAttribute1) { - urlQueryParams = urlQueryParams + `&${queryAttribute1}=${queryValue1}`; - } - const queryUrl = resourceUri + urlQueryParams; - const headers = { - Authorization: (0, veracode_hmac_1.calculateAuthorizationHeader)({ - id: vid, - key: vkey, - host: host, - url: queryUrl, - method: 'GET', - }), - }; - const appUrl = `https://${host}${resourceUri}${urlQueryParams}`; - try { - const response = await fetch(appUrl, { headers }); - const data = await response.json(); - return data; - } - catch (error) { - throw new Error(`Failed to fetch resource: ${error}`); - } -} -async function deleteResourceById(vid, vkey, resource) { - const resourceUri = resource.resourceUri; - const resourceId = resource.resourceId; - let host = app_config_1.default.hostName.veracode.us; - if (vid.startsWith('vera01ei-')) { - host = app_config_1.default.hostName.veracode.eu; - vid = vid.split('-')[1] || ''; - vkey = vkey.split('-')[1] || ''; - } - const queryUrl = `${resourceUri}/${resourceId}`; - const headers = { - Authorization: (0, veracode_hmac_1.calculateAuthorizationHeader)({ - id: vid, - key: vkey, - host: host, - url: queryUrl, - method: 'DELETE', - }), - }; - const appUrl = `https://${host}${resourceUri}/${resourceId}`; - try { - await fetch(appUrl, { method: 'DELETE', headers }); - } - catch (error) { - console.log(error); - throw new Error(`Failed to delete resource: ${error}`); - } -} -async function postResourceByAttribute(vid, vkey, scanReport) { - const resourceUri = app_config_1.default.api.veracode.relayServiceUri; - const host = app_config_1.default.hostName.veracode.us; - if (vid.startsWith('vera01')) { - vid = vid.split('-')[1] || ''; - vkey = vkey.split('-')[1] || ''; - } - const headers = { - Authorization: (0, veracode_hmac_1.calculateAuthorizationHeader)({ - id: vid, - key: vkey, - host: host, - url: resourceUri, - method: 'POST', - }), - 'Content-Type': 'application/json', - }; - try { - const appUrl = `https://${host}${resourceUri}`; - const response = await fetch(appUrl, { - method: 'POST', - headers: headers, - body: scanReport, - }); - const data = await response.json(); - core.info(`Scan report response: ${JSON.stringify(data)}`); - return data; - } - catch (error) { - throw new Error(`Failed to post resource: ${error}`); - } -} diff --git a/dist/api/veracode-hmac.js b/dist/api/veracode-hmac.js deleted file mode 100644 index ec258d0..0000000 --- a/dist/api/veracode-hmac.js +++ /dev/null @@ -1,73 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.calculateAuthorizationHeader = calculateAuthorizationHeader; -const sjcl_1 = __importDefault(require("sjcl")); -const crypto = __importStar(require("crypto")); -const authorizationScheme = 'VERACODE-HMAC-SHA-256'; -const requestVersion = 'vcode_request_version_1'; -const nonceSize = 16; -function computeHashHex(message, key_hex) { - const key_bits = sjcl_1.default.codec.hex.toBits(key_hex); - const hmac_bits = new sjcl_1.default.misc.hmac(key_bits, sjcl_1.default.hash.sha256).mac(message); - const hmac = sjcl_1.default.codec.hex.fromBits(hmac_bits); - return hmac; -} -function calulateDataSignature(apiKeyBytes, nonceBytes, dateStamp, data) { - const kNonce = computeHashHex(nonceBytes, apiKeyBytes); - const kDate = computeHashHex(dateStamp, kNonce); - const kSig = computeHashHex(requestVersion, kDate); - const kFinal = computeHashHex(data, kSig); - return kFinal; -} -function newNonce() { - return crypto.randomBytes(nonceSize).toString('hex').toUpperCase(); -} -function toHexBinary(input) { - return sjcl_1.default.codec.hex.fromBits(sjcl_1.default.codec.utf8String.toBits(input)); -} -function calculateAuthorizationHeader(params) { - const uriString = params.url; - const data = `id=${params.id}&host=${params.host}&url=${uriString}&method=${params.method}`; - const dateStamp = Date.now().toString(); - const nonceBytes = newNonce(); - const dataSignature = calulateDataSignature(params.key, nonceBytes, dateStamp, data); - const authorizationParam = `id=${params.id},ts=${dateStamp},nonce=${toHexBinary(nonceBytes)},sig=${dataSignature}`; - const header = authorizationScheme + ' ' + authorizationParam; - return header; -} diff --git a/dist/app-config.js b/dist/app-config.js deleted file mode 100644 index 127e19e..0000000 --- a/dist/app-config.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const appConfig = { - hostName: { - veracode: { - us: 'api.veracode.com', - eu: 'api.veracode.eu' - }, - github: 'api.github.com' - }, - api: { - veracode: { - applicationUri: '/appsec/v1/applications', - findingsUri: '/appsec/v2/applications', - sandboxUri: '/appsec/v1/applications/${appGuid}/sandboxes', - selfUserUri: '/api/authn/v2/users/self', - policyUri: '/appsec/v1/policies', - relayServiceUri: '/vrm-relay-service/api/scan-report', - }, - github: '' - } -}; -exports.default = appConfig; diff --git a/dist/checks.js b/dist/checks.js deleted file mode 100644 index 545daf4..0000000 --- a/dist/checks.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.updateChecks = updateChecks; -async function updateChecks(octokit, checksStatic, conclusion, annotations, summary) { - const data = { - owner: checksStatic.owner, - repo: checksStatic.repo, - check_run_id: checksStatic.check_run_id, - status: checksStatic.status, - conclusion: conclusion, - output: { - annotations: annotations, - title: 'Veracode Static Code Analysis', - summary: summary, - }, - }; - await octokit.checks.update(data); -} diff --git a/dist/index.js b/dist/index.js index df02a14..495e6ac 100644 --- a/dist/index.js +++ b/dist/index.js @@ -29861,153 +29861,153 @@ module.exports = Zip; /***/ 73057: /***/ ((module) => { -function isBuffer(value) { +function isBuffer (value) { return Buffer.isBuffer(value) || value instanceof Uint8Array } -function isEncoding(encoding) { +function isEncoding (encoding) { return Buffer.isEncoding(encoding) } -function alloc(size, fill, encoding) { +function alloc (size, fill, encoding) { return Buffer.alloc(size, fill, encoding) } -function allocUnsafe(size) { +function allocUnsafe (size) { return Buffer.allocUnsafe(size) } -function allocUnsafeSlow(size) { +function allocUnsafeSlow (size) { return Buffer.allocUnsafeSlow(size) } -function byteLength(string, encoding) { +function byteLength (string, encoding) { return Buffer.byteLength(string, encoding) } -function compare(a, b) { +function compare (a, b) { return Buffer.compare(a, b) } -function concat(buffers, totalLength) { +function concat (buffers, totalLength) { return Buffer.concat(buffers, totalLength) } -function copy(source, target, targetStart, start, end) { +function copy (source, target, targetStart, start, end) { return toBuffer(source).copy(target, targetStart, start, end) } -function equals(a, b) { +function equals (a, b) { return toBuffer(a).equals(b) } -function fill(buffer, value, offset, end, encoding) { +function fill (buffer, value, offset, end, encoding) { return toBuffer(buffer).fill(value, offset, end, encoding) } -function from(value, encodingOrOffset, length) { +function from (value, encodingOrOffset, length) { return Buffer.from(value, encodingOrOffset, length) } -function includes(buffer, value, byteOffset, encoding) { +function includes (buffer, value, byteOffset, encoding) { return toBuffer(buffer).includes(value, byteOffset, encoding) } -function indexOf(buffer, value, byfeOffset, encoding) { +function indexOf (buffer, value, byfeOffset, encoding) { return toBuffer(buffer).indexOf(value, byfeOffset, encoding) } -function lastIndexOf(buffer, value, byteOffset, encoding) { +function lastIndexOf (buffer, value, byteOffset, encoding) { return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding) } -function swap16(buffer) { +function swap16 (buffer) { return toBuffer(buffer).swap16() } -function swap32(buffer) { +function swap32 (buffer) { return toBuffer(buffer).swap32() } -function swap64(buffer) { +function swap64 (buffer) { return toBuffer(buffer).swap64() } -function toBuffer(buffer) { +function toBuffer (buffer) { if (Buffer.isBuffer(buffer)) return buffer return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength) } -function toString(buffer, encoding, start, end) { +function toString (buffer, encoding, start, end) { return toBuffer(buffer).toString(encoding, start, end) } -function write(buffer, string, offset, length, encoding) { +function write (buffer, string, offset, length, encoding) { return toBuffer(buffer).write(string, offset, length, encoding) } -function readDoubleBE(buffer, offset) { - return toBuffer(buffer).readDoubleBE(offset) -} - -function readDoubleLE(buffer, offset) { - return toBuffer(buffer).readDoubleLE(offset) +function writeDoubleLE (buffer, value, offset) { + return toBuffer(buffer).writeDoubleLE(value, offset) } -function readFloatBE(buffer, offset) { - return toBuffer(buffer).readFloatBE(offset) +function writeFloatLE (buffer, value, offset) { + return toBuffer(buffer).writeFloatLE(value, offset) } -function readFloatLE(buffer, offset) { - return toBuffer(buffer).readFloatLE(offset) +function writeUInt32LE (buffer, value, offset) { + return toBuffer(buffer).writeUInt32LE(value, offset) } -function readInt32BE(buffer, offset) { - return toBuffer(buffer).readInt32BE(offset) +function writeInt32LE (buffer, value, offset) { + return toBuffer(buffer).writeInt32LE(value, offset) } -function readInt32LE(buffer, offset) { - return toBuffer(buffer).readInt32LE(offset) +function readDoubleLE (buffer, offset) { + return toBuffer(buffer).readDoubleLE(offset) } -function readUInt32BE(buffer, offset) { - return toBuffer(buffer).readUInt32BE(offset) +function readFloatLE (buffer, offset) { + return toBuffer(buffer).readFloatLE(offset) } -function readUInt32LE(buffer, offset) { +function readUInt32LE (buffer, offset) { return toBuffer(buffer).readUInt32LE(offset) } -function writeDoubleBE(buffer, value, offset) { - return toBuffer(buffer).writeDoubleBE(value, offset) +function readInt32LE (buffer, offset) { + return toBuffer(buffer).readInt32LE(offset) } -function writeDoubleLE(buffer, value, offset) { - return toBuffer(buffer).writeDoubleLE(value, offset) +function writeDoubleBE (buffer, value, offset) { + return toBuffer(buffer).writeDoubleBE(value, offset) } -function writeFloatBE(buffer, value, offset) { +function writeFloatBE (buffer, value, offset) { return toBuffer(buffer).writeFloatBE(value, offset) } -function writeFloatLE(buffer, value, offset) { - return toBuffer(buffer).writeFloatLE(value, offset) +function writeUInt32BE (buffer, value, offset) { + return toBuffer(buffer).writeUInt32BE(value, offset) } -function writeInt32BE(buffer, value, offset) { +function writeInt32BE (buffer, value, offset) { return toBuffer(buffer).writeInt32BE(value, offset) } -function writeInt32LE(buffer, value, offset) { - return toBuffer(buffer).writeInt32LE(value, offset) +function readDoubleBE (buffer, offset) { + return toBuffer(buffer).readDoubleBE(offset) } -function writeUInt32BE(buffer, value, offset) { - return toBuffer(buffer).writeUInt32BE(value, offset) +function readFloatBE (buffer, offset) { + return toBuffer(buffer).readFloatBE(offset) } -function writeUInt32LE(buffer, value, offset) { - return toBuffer(buffer).writeUInt32LE(value, offset) +function readUInt32BE (buffer, offset) { + return toBuffer(buffer).readUInt32BE(offset) +} + +function readInt32BE (buffer, offset) { + return toBuffer(buffer).readInt32BE(offset) } module.exports = { @@ -30032,22 +30032,23 @@ module.exports = { toBuffer, toString, write, - readDoubleBE, + writeDoubleLE, + writeFloatLE, + writeUInt32LE, + writeInt32LE, readDoubleLE, - readFloatBE, readFloatLE, - readInt32BE, - readInt32LE, - readUInt32BE, readUInt32LE, + readInt32LE, writeDoubleBE, - writeDoubleLE, writeFloatBE, - writeFloatLE, - writeInt32BE, - writeInt32LE, writeUInt32BE, - writeUInt32LE + writeInt32BE, + readDoubleBE, + readFloatBE, + readUInt32BE, + readInt32BE + } @@ -36443,14 +36444,6 @@ module.exports.defineEventAttribute = defineEventAttribute //# sourceMappingURL=event-target-shim.js.map -/***/ }), - -/***/ 29580: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = __nccwpck_require__(24434) - - /***/ }), /***/ 13587: @@ -54503,7 +54496,7 @@ b){var c={},d;for(d=0;d { -const { EventEmitter } = __nccwpck_require__(29580) +const { EventEmitter } = __nccwpck_require__(24434) const STREAM_DESTROYED = new Error('Stream was destroyed') const PREMATURE_CLOSE = new Error('Premature close') @@ -57998,6 +57991,19 @@ function _generateTmpName(opts) { return path.join(tmpDir, opts.dir, name); } +/** + * Check the prefix and postfix options + * + * @private + */ +function _assertPath(path) { + if (path.includes("..")) { + throw new Error("Relative value not allowed"); + } + + return path; +} + /** * Asserts and sanitizes the basic options. * @@ -58012,8 +58018,9 @@ function _assertOptionsBase(options) { // must not fail on valid . or .. or similar such constructs const basename = path.basename(name); - if (basename === '..' || basename === '.' || basename !== name) + if (basename === '..' || basename === '.' || basename !== name) { throw new Error(`name option must not contain a path, found "${name}".`); + } } /* istanbul ignore else */ @@ -58034,8 +58041,9 @@ function _assertOptionsBase(options) { options.unsafeCleanup = !!options.unsafeCleanup; // for completeness' sake only, also keep (multiple) blanks if the user, purportedly sane, requests us to - options.prefix = _isUndefined(options.prefix) ? '' : options.prefix; - options.postfix = _isUndefined(options.postfix) ? '' : options.postfix; + options.prefix = _isUndefined(options.prefix) ? '' : _assertPath(options.prefix); + options.postfix = _isUndefined(options.postfix) ? '' : _assertPath(options.postfix); + options.template = _isUndefined(options.template) ? undefined : _assertPath(options.template); } /** @@ -58051,7 +58059,7 @@ function _getRelativePath(option, name, tmpDir, cb) { const relativePath = path.relative(tmpDir, resolvedPath); - if (!resolvedPath.startsWith(tmpDir)) { + if (relativePath.startsWith('..') || path.isAbsolute(relativePath)) { return cb(new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`)); } @@ -58070,7 +58078,7 @@ function _getRelativePathSync(option, name, tmpDir) { const resolvedPath = _resolvePathSync(name, tmpDir); const relativePath = path.relative(tmpDir, resolvedPath); - if (!resolvedPath.startsWith(tmpDir)) { + if (relativePath.startsWith('..') || path.isAbsolute(relativePath)) { throw new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`); } @@ -85348,6 +85356,7 @@ const parseInputs = (getInput) => { const gitRepositoryUrl = getInput('gitRepositoryUrl'); const trim_to_size = getInput('trim_to_size'); const platformType = getInput('platformType'); + const wait_for_scan_completion = getInput('wait_for_scan_completion') === 'true'; if (source_repository && source_repository.split('/').length !== 2) { throw new Error('source_repository needs to be in the {owner}/{repo} format'); } @@ -85357,7 +85366,7 @@ const parseInputs = (getInput) => { policyname, path, start_line: +start_line, end_line: +end_line, break_build_invalid_policy, filter_mitigated_flaws, check_run_name, head_sha, branch, event_type, issue_trigger_flow, workflow_app, line_number_slop: +line_number_slop, pipeline_scan_flaw_filter, filtered_results_file, - gitRepositoryUrl, trim_to_size: +trim_to_size, platformType + gitRepositoryUrl, trim_to_size: +trim_to_size, platformType, wait_for_scan_completion }; }; exports.parseInputs = parseInputs; @@ -86487,6 +86496,23 @@ async function preparePolicyResults(inputs) { await (0, check_service_1.updateChecks)(octokit, checkStatic, inputs.fail_checks_on_error ? Checks.Conclusion.Failure : Checks.Conclusion.Success, [], 'Token, check_run_id and source_repository are required.'); return; } + const submittedMessage = 'Static Scan Submitted. Please check the Veracode Platform for results.'; + if (String(inputs.wait_for_scan_completion).toLowerCase() === 'false') { + try { + core.info(submittedMessage); + await (0, check_service_1.updateChecks)(octokit, checkStatic, inputs.fail_checks_on_error + ? Checks.Conclusion.Failure + : Checks.Conclusion.Success, [], submittedMessage); + } + catch (error) { + core.debug(`Error while updating the checks: ${error}`); + core.setFailed('Error while updating the checks'); + await (0, check_service_1.updateChecks)(octokit, checkStatic, inputs.fail_checks_on_error + ? Checks.Conclusion.Failure + : Checks.Conclusion.Success, [], 'Error while updating the checks.'); + } + return; + } let findingsArray = []; let resultsUrl = ''; try { @@ -87118,7 +87144,6 @@ exports.AzureKeyCredential = void 0; * the underlying key value. */ class AzureKeyCredential { - _key; /** * The value of the key to be used in authentication */ @@ -87170,8 +87195,6 @@ const core_util_1 = __nccwpck_require__(87779); * the underlying name and key values. */ class AzureNamedKeyCredential { - _key; - _name; /** * The value of the key to be used in authentication. */ @@ -87246,7 +87269,6 @@ const core_util_1 = __nccwpck_require__(87779); * the underlying signature value. */ class AzureSASCredential { - _signature; /** * The value of the shared access signature to be used in authentication */ @@ -87409,7 +87431,7 @@ function parseCAEChallenge(challenges) { const challengeParts = `${challenge.trim()}, `.split('", ').filter((x) => x); const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split('="'))); // Key-value pairs to plain object: - return keyValuePairs.reduce((a, b) => ({ ...a, ...b }), {}); + return keyValuePairs.reduce((a, b) => (Object.assign(Object.assign({}, a), b)), {}); }); } /** @@ -87442,6 +87464,7 @@ function parseCAEChallenge(challenges) { * ``` */ async function authorizeRequestOnClaimChallenge(onChallengeOptions) { + var _a; const { scopes, response } = onChallengeOptions; const logger = onChallengeOptions.logger || log_js_1.logger; const challenge = response.headers.get("WWW-Authenticate"); @@ -87461,7 +87484,7 @@ async function authorizeRequestOnClaimChallenge(onChallengeOptions) { if (!accessToken) { return false; } - onChallengeOptions.request.headers.set("Authorization", `${accessToken.tokenType ?? "Bearer"} ${accessToken.token}`); + onChallengeOptions.request.headers.set("Authorization", `${(_a = accessToken.tokenType) !== null && _a !== void 0 ? _a : "Bearer"} ${accessToken.token}`); return true; } //# sourceMappingURL=authorizeRequestOnClaimChallenge.js.map @@ -87501,6 +87524,7 @@ function isUuid(text) { * Handling has specific features for storage that departs to the general AAD challenge docs. **/ const authorizeRequestOnTenantChallenge = async (challengeOptions) => { + var _a; const requestOptions = requestToOptions(challengeOptions.request); const challenge = getChallenge(challengeOptions.response); if (challenge) { @@ -87510,14 +87534,11 @@ const authorizeRequestOnTenantChallenge = async (challengeOptions) => { if (!tenantId) { return false; } - const accessToken = await challengeOptions.getAccessToken(challengeScopes, { - ...requestOptions, - tenantId, - }); + const accessToken = await challengeOptions.getAccessToken(challengeScopes, Object.assign(Object.assign({}, requestOptions), { tenantId })); if (!accessToken) { return false; } - challengeOptions.request.headers.set(Constants.HeaderConstants.AUTHORIZATION, `${accessToken.tokenType ?? "Bearer"} ${accessToken.token}`); + challengeOptions.request.headers.set(Constants.HeaderConstants.AUTHORIZATION, `${(_a = accessToken.tokenType) !== null && _a !== void 0 ? _a : "Bearer"} ${accessToken.token}`); return true; } return false; @@ -87577,7 +87598,7 @@ function parseChallenge(challenge) { const challengeParts = `${bearerChallenge.trim()} `.split(" ").filter((x) => x); const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split("="))); // Key-value pairs to plain object: - return keyValuePairs.reduce((a, b) => ({ ...a, ...b }), {}); + return keyValuePairs.reduce((a, b) => (Object.assign(Object.assign({}, a), b)), {}); } /** * Extracts the options form a Pipeline Request for later re-use @@ -87668,15 +87689,16 @@ exports.deserializationPolicyName = "deserializationPolicy"; * This policy handles parsing out responses according to OperationSpecs on the request. */ function deserializationPolicy(options = {}) { - const jsonContentTypes = options.expectedContentTypes?.json ?? defaultJsonContentTypes; - const xmlContentTypes = options.expectedContentTypes?.xml ?? defaultXmlContentTypes; + var _a, _b, _c, _d, _e, _f, _g; + const jsonContentTypes = (_b = (_a = options.expectedContentTypes) === null || _a === void 0 ? void 0 : _a.json) !== null && _b !== void 0 ? _b : defaultJsonContentTypes; + const xmlContentTypes = (_d = (_c = options.expectedContentTypes) === null || _c === void 0 ? void 0 : _c.xml) !== null && _d !== void 0 ? _d : defaultXmlContentTypes; const parseXML = options.parseXML; const serializerOptions = options.serializerOptions; const updatedOptions = { xml: { - rootName: serializerOptions?.xml.rootName ?? "", - includeRoot: serializerOptions?.xml.includeRoot ?? false, - xmlCharKey: serializerOptions?.xml.xmlCharKey ?? interfaces_js_1.XML_CHARKEY, + rootName: (_e = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _e !== void 0 ? _e : "", + includeRoot: (_f = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _f !== void 0 ? _f : false, + xmlCharKey: (_g = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _g !== void 0 ? _g : interfaces_js_1.XML_CHARKEY, }, }; return { @@ -87691,13 +87713,13 @@ function getOperationResponseMap(parsedResponse) { let result; const request = parsedResponse.request; const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request); - const operationSpec = operationInfo?.operationSpec; + const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec; if (operationSpec) { - if (!operationInfo?.operationResponseGetter) { + if (!(operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter)) { result = operationSpec.responses[parsedResponse.status]; } else { - result = operationInfo?.operationResponseGetter(operationSpec, parsedResponse); + result = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter(operationSpec, parsedResponse); } } return result; @@ -87705,7 +87727,7 @@ function getOperationResponseMap(parsedResponse) { function shouldDeserializeResponse(parsedResponse) { const request = parsedResponse.request; const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request); - const shouldDeserialize = operationInfo?.shouldDeserialize; + const shouldDeserialize = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.shouldDeserialize; let result; if (shouldDeserialize === undefined) { result = true; @@ -87724,7 +87746,7 @@ async function deserializeResponseBody(jsonContentTypes, xmlContentTypes, respon return parsedResponse; } const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(parsedResponse.request); - const operationSpec = operationInfo?.operationSpec; + const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec; if (!operationSpec || !operationSpec.responses) { return parsedResponse; } @@ -87775,6 +87797,7 @@ function isOperationSpecEmpty(operationSpec) { (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default")); } function handleErrorResponse(parsedResponse, operationSpec, responseSpec, options) { + var _a, _b, _c, _d, _e; const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300; const isExpectedStatusCode = isOperationSpecEmpty(operationSpec) ? isSuccessByStatus @@ -87789,8 +87812,8 @@ function handleErrorResponse(parsedResponse, operationSpec, responseSpec, option return { error: null, shouldReturnResponse: false }; } } - const errorResponseSpec = responseSpec ?? operationSpec.responses.default; - const initialErrorMessage = parsedResponse.request.streamResponseStatusCodes?.has(parsedResponse.status) + const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default; + const initialErrorMessage = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status)) ? `Unexpected status code: ${parsedResponse.status}` : parsedResponse.bodyAsText; const error = new core_rest_pipeline_1.RestError(initialErrorMessage, { @@ -87802,11 +87825,11 @@ function handleErrorResponse(parsedResponse, operationSpec, responseSpec, option // and the parsed body doesn't look like an error object, // we should fail so we just throw the parsed response if (!errorResponseSpec && - !(parsedResponse.parsedBody?.error?.code && parsedResponse.parsedBody?.error?.message)) { + !(((_c = (_b = parsedResponse.parsedBody) === null || _b === void 0 ? void 0 : _b.error) === null || _c === void 0 ? void 0 : _c.code) && ((_e = (_d = parsedResponse.parsedBody) === null || _d === void 0 ? void 0 : _d.error) === null || _e === void 0 ? void 0 : _e.message))) { throw error; } - const defaultBodyMapper = errorResponseSpec?.bodyMapper; - const defaultHeadersMapper = errorResponseSpec?.headersMapper; + const defaultBodyMapper = errorResponseSpec === null || errorResponseSpec === void 0 ? void 0 : errorResponseSpec.bodyMapper; + const defaultHeadersMapper = errorResponseSpec === null || errorResponseSpec === void 0 ? void 0 : errorResponseSpec.headersMapper; try { // If error response has a body, try to deserialize it using default body mapper. // Then try to extract error code & message from it @@ -87845,7 +87868,8 @@ function handleErrorResponse(parsedResponse, operationSpec, responseSpec, option return { error, shouldReturnResponse: false }; } async function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts, parseXML) { - if (!operationResponse.request.streamResponseStatusCodes?.has(operationResponse.status) && + var _a; + if (!((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) && operationResponse.bodyAsText) { const text = operationResponse.bodyAsText; const contentType = operationResponse.headers.get("Content-Type") || ""; @@ -88149,7 +88173,7 @@ const serializationPolicy_js_1 = __nccwpck_require__(56234); * @param options - Options to customize the created pipeline. */ function createClientPipeline(options = {}) { - const pipeline = (0, core_rest_pipeline_1.createPipelineFromOptions)(options ?? {}); + const pipeline = (0, core_rest_pipeline_1.createPipelineFromOptions)(options !== null && options !== void 0 ? options : {}); if (options.credentialOptions) { pipeline.addPolicy((0, core_rest_pipeline_1.bearerTokenAuthenticationPolicy)({ credential: options.credentialOptions.credential, @@ -88196,8 +88220,8 @@ function serializationPolicy(options = {}) { name: exports.serializationPolicyName, async sendRequest(request, next) { const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request); - const operationSpec = operationInfo?.operationSpec; - const operationArguments = operationInfo?.operationArguments; + const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec; + const operationArguments = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationArguments; if (operationSpec && operationArguments) { serializeHeaders(request, operationArguments, operationSpec); serializeRequestBody(request, operationArguments, operationSpec, stringifyXML); @@ -88210,6 +88234,7 @@ function serializationPolicy(options = {}) { * @internal */ function serializeHeaders(request, operationArguments, operationSpec) { + var _a, _b; if (operationSpec.headerParameters) { for (const headerParameter of operationSpec.headerParameters) { let headerValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, headerParameter); @@ -88228,7 +88253,7 @@ function serializeHeaders(request, operationArguments, operationSpec) { } } } - const customHeaders = operationArguments.options?.requestOptions?.customHeaders; + const customHeaders = (_b = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.requestOptions) === null || _b === void 0 ? void 0 : _b.customHeaders; if (customHeaders) { for (const customHeaderName of Object.keys(customHeaders)) { request.headers.set(customHeaderName, customHeaders[customHeaderName]); @@ -88241,12 +88266,13 @@ function serializeHeaders(request, operationArguments, operationSpec) { function serializeRequestBody(request, operationArguments, operationSpec, stringifyXML = function () { throw new Error("XML serialization unsupported!"); }) { - const serializerOptions = operationArguments.options?.serializerOptions; + var _a, _b, _c, _d, _e; + const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; const updatedOptions = { xml: { - rootName: serializerOptions?.xml.rootName ?? "", - includeRoot: serializerOptions?.xml.includeRoot ?? false, - xmlCharKey: serializerOptions?.xml.xmlCharKey ?? interfaces_js_1.XML_CHARKEY, + rootName: (_b = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _b !== void 0 ? _b : "", + includeRoot: (_c = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _c !== void 0 ? _c : false, + xmlCharKey: (_d = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _d !== void 0 ? _d : interfaces_js_1.XML_CHARKEY, }, }; const xmlCharKey = updatedOptions.xml.xmlCharKey; @@ -88276,7 +88302,7 @@ function serializeRequestBody(request, operationArguments, operationSpec, string } } else if (typeName === serializer_js_1.MapperTypeNames.String && - (operationSpec.contentType?.match("text/plain") || operationSpec.mediaType === "text")) { + (((_e = operationSpec.contentType) === null || _e === void 0 ? void 0 : _e.match("text/plain")) || operationSpec.mediaType === "text")) { // the String serializer has validated that request body is a string // so just send the string. return; @@ -88345,8 +88371,6 @@ const base64 = tslib_1.__importStar(__nccwpck_require__(20741)); const interfaces_js_1 = __nccwpck_require__(56058); const utils_js_1 = __nccwpck_require__(31193); class SerializerImpl { - modelMappers; - isXML; constructor(modelMappers = {}, isXML = false) { this.modelMappers = modelMappers; this.isXML = isXML; @@ -88413,11 +88437,12 @@ class SerializerImpl { * @returns A valid serialized Javascript object */ serialize(mapper, object, objectName, options = { xml: {} }) { + var _a, _b, _c; const updatedOptions = { xml: { - rootName: options.xml.rootName ?? "", - includeRoot: options.xml.includeRoot ?? false, - xmlCharKey: options.xml.xmlCharKey ?? interfaces_js_1.XML_CHARKEY, + rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "", + includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false, + xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : interfaces_js_1.XML_CHARKEY, }, }; let payload = {}; @@ -88499,13 +88524,14 @@ class SerializerImpl { * @returns A valid deserialized Javascript object */ deserialize(mapper, responseBody, objectName, options = { xml: {} }) { + var _a, _b, _c, _d; const updatedOptions = { xml: { - rootName: options.xml.rootName ?? "", - includeRoot: options.xml.includeRoot ?? false, - xmlCharKey: options.xml.xmlCharKey ?? interfaces_js_1.XML_CHARKEY, + rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "", + includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false, + xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : interfaces_js_1.XML_CHARKEY, }, - ignoreUnknownProperties: options.ignoreUnknownProperties ?? false, + ignoreUnknownProperties: (_d = options.ignoreUnknownProperties) !== null && _d !== void 0 ? _d : false, }; if (responseBody === undefined || responseBody === null) { if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) { @@ -88771,6 +88797,7 @@ function serializeDateTypes(typeName, value, objectName) { return value; } function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) { + var _a; if (!Array.isArray(object)) { throw new Error(`${objectName} must be of type Array.`); } @@ -88783,7 +88810,7 @@ function serializeSequenceType(serializer, mapper, object, objectName, isXml, op // not have *all* properties declared (like uberParent), // so let's try to look up the full definition by name. if (elementType.type.name === "Composite" && elementType.type.className) { - elementType = serializer.modelMappers[elementType.type.className] ?? elementType; + elementType = (_a = serializer.modelMappers[elementType.type.className]) !== null && _a !== void 0 ? _a : elementType; } const tempArray = []; for (let i = 0; i < object.length; i++) { @@ -88793,7 +88820,7 @@ function serializeSequenceType(serializer, mapper, object, objectName, isXml, op ? `xmlns:${elementType.xmlNamespacePrefix}` : "xmlns"; if (elementType.type.name === "Composite") { - tempArray[i] = { ...serializedValue }; + tempArray[i] = Object.assign({}, serializedValue); tempArray[i][interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; } else { @@ -88842,7 +88869,7 @@ function resolveAdditionalProperties(serializer, mapper, objectName) { const additionalProperties = mapper.type.additionalProperties; if (!additionalProperties && mapper.type.className) { const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); - return modelMapper?.type.additionalProperties; + return modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.additionalProperties; } return additionalProperties; } @@ -88871,7 +88898,7 @@ function resolveModelProperties(serializer, mapper, objectName) { if (!modelMapper) { throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`); } - modelProps = modelMapper?.type.modelProperties; + modelProps = modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.modelProperties; if (!modelProps) { throw new Error(`modelProperties cannot be null or undefined in the ` + `mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`); @@ -88919,10 +88946,7 @@ function serializeCompositeType(serializer, mapper, object, objectName, isXml, o const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns"; - parentObject[interfaces_js_1.XML_ATTRKEY] = { - ...parentObject[interfaces_js_1.XML_ATTRKEY], - [xmlnsKey]: mapper.xmlNamespace, - }; + parentObject[interfaces_js_1.XML_ATTRKEY] = Object.assign(Object.assign({}, parentObject[interfaces_js_1.XML_ATTRKEY]), { [xmlnsKey]: mapper.xmlNamespace }); } const propertyObjectName = propertyMapper.serializedName !== "" ? objectName + "." + propertyMapper.serializedName @@ -88980,7 +89004,7 @@ function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) { return serializedValue; } else { - const result = { ...serializedValue }; + const result = Object.assign({}, serializedValue); result[interfaces_js_1.XML_ATTRKEY] = xmlNamespace; return result; } @@ -88994,7 +89018,8 @@ function isSpecialXmlProperty(propertyName, options) { return [interfaces_js_1.XML_ATTRKEY, options.xml.xmlCharKey].includes(propertyName); } function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) { - const xmlCharKey = options.xml.xmlCharKey ?? interfaces_js_1.XML_CHARKEY; + var _a, _b; + const xmlCharKey = (_a = options.xml.xmlCharKey) !== null && _a !== void 0 ? _a : interfaces_js_1.XML_CHARKEY; if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName"); } @@ -89053,7 +89078,7 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, xmlName is "Cors" and xmlElementName is"CorsRule". */ const wrapped = responseBody[xmlName]; - const elementList = wrapped?.[xmlElementName] ?? []; + const elementList = (_b = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _b !== void 0 ? _b : []; instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options); handledPropertyNames.push(xmlName); } @@ -89161,6 +89186,7 @@ function deserializeDictionaryType(serializer, mapper, responseBody, objectName, return responseBody; } function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) { + var _a; let element = mapper.type.element; if (!element || typeof element !== "object") { throw new Error(`element" metadata for an Array must be defined in the ` + @@ -89175,7 +89201,7 @@ function deserializeSequenceType(serializer, mapper, responseBody, objectName, o // not have *all* properties declared (like uberParent), // so let's try to look up the full definition by name. if (element.type.name === "Composite" && element.type.className) { - element = serializer.modelMappers[element.type.className] ?? element; + element = (_a = serializer.modelMappers[element.type.className]) !== null && _a !== void 0 ? _a : element; } const tempArray = []; for (let i = 0; i < responseBody.length; i++) { @@ -89208,6 +89234,7 @@ function getIndexDiscriminator(discriminators, discriminatorValue, typeName) { return undefined; } function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) { + var _a; const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); if (polymorphicDiscriminator) { let discriminatorName = polymorphicDiscriminator[polymorphicPropertyName]; @@ -89217,7 +89244,7 @@ function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyNam discriminatorName = discriminatorName.replace(/\\/gi, ""); } const discriminatorValue = object[discriminatorName]; - const typeName = mapper.type.uberParent ?? mapper.type.className; + const typeName = (_a = mapper.type.uberParent) !== null && _a !== void 0 ? _a : mapper.type.className; if (typeof discriminatorValue === "string" && typeName) { const polymorphicMapper = getIndexDiscriminator(serializer.modelMappers.discriminators, discriminatorValue, typeName); if (polymorphicMapper) { @@ -89284,42 +89311,21 @@ const log_js_1 = __nccwpck_require__(89994); * Initializes a new instance of the ServiceClient. */ class ServiceClient { - /** - * If specified, this is the base URI that requests will be made against for this ServiceClient. - * If it is not specified, then all OperationSpecs must contain a baseUrl property. - */ - _endpoint; - /** - * The default request content type for the service. - * Used if no requestContentType is present on an OperationSpec. - */ - _requestContentType; - /** - * Set to true if the request is sent over HTTP instead of HTTPS - */ - _allowInsecureConnection; - /** - * The HTTP client that will be used to send requests. - */ - _httpClient; - /** - * The pipeline used by this client to make requests - */ - pipeline; /** * The ServiceClient constructor * @param options - The service client options that govern the behavior of the client. */ constructor(options = {}) { + var _a, _b; this._requestContentType = options.requestContentType; - this._endpoint = options.endpoint ?? options.baseUri; + this._endpoint = (_a = options.endpoint) !== null && _a !== void 0 ? _a : options.baseUri; if (options.baseUri) { log_js_1.logger.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead."); } this._allowInsecureConnection = options.allowInsecureConnection; this._httpClient = options.httpClient || (0, httpClientCache_js_1.getCachedDefaultHttpClient)(); this.pipeline = options.pipeline || createDefaultPipeline(options); - if (options.additionalPolicies?.length) { + if ((_b = options.additionalPolicies) === null || _b === void 0 ? void 0 : _b.length) { for (const { policy, position } of options.additionalPolicies) { // Sign happens after Retry and is commonly needed to occur // before policies that intercept post-retry. @@ -89398,17 +89404,17 @@ class ServiceClient { try { const rawResponse = await this.sendRequest(request); const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[rawResponse.status]); - if (options?.onResponse) { + if (options === null || options === void 0 ? void 0 : options.onResponse) { options.onResponse(rawResponse, flatResponse); } return flatResponse; } catch (error) { - if (typeof error === "object" && error?.response) { + if (typeof error === "object" && (error === null || error === void 0 ? void 0 : error.response)) { const rawResponse = error.response; const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[error.statusCode] || operationSpec.responses["default"]); error.details = flatResponse; - if (options?.onResponse) { + if (options === null || options === void 0 ? void 0 : options.onResponse) { options.onResponse(rawResponse, flatResponse, error); } } @@ -89422,10 +89428,7 @@ function createDefaultPipeline(options) { const credentialOptions = options.credential && credentialScopes ? { credentialScopes, credential: options.credential } : undefined; - return (0, pipeline_js_1.createClientPipeline)({ - ...options, - credentialOptions, - }); + return (0, pipeline_js_1.createClientPipeline)(Object.assign(Object.assign({}, options), { credentialOptions })); } function getCredentialScopes(options) { if (options.credentialScopes) { @@ -89525,8 +89528,9 @@ function replaceAll(input, replacements) { return result; } function calculateUrlReplacements(operationSpec, operationArguments, fallbackObject) { + var _a; const result = new Map(); - if (operationSpec.urlParameters?.length) { + if ((_a = operationSpec.urlParameters) === null || _a === void 0 ? void 0 : _a.length) { for (const urlParameter of operationSpec.urlParameters) { let urlParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, urlParameter, fallbackObject); const parameterPathString = (0, interfaceHelpers_js_1.getPathStringFromParameter)(urlParameter); @@ -89570,9 +89574,10 @@ function appendPath(url, pathToAppend) { return parsedUrl.toString(); } function calculateQueryParameters(operationSpec, operationArguments, fallbackObject) { + var _a; const result = new Map(); const sequenceParams = new Set(); - if (operationSpec.queryParameters?.length) { + if ((_a = operationSpec.queryParameters) === null || _a === void 0 ? void 0 : _a.length) { for (const queryParameter of operationSpec.queryParameters) { if (queryParameter.mapper.type.name === "Sequence" && queryParameter.mapper.serializedName) { sequenceParams.add(queryParameter.mapper.serializedName); @@ -89733,7 +89738,7 @@ function isPrimitiveBody(value, mapperTypeName) { (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || - mapperTypeName?.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i) !== + (mapperTypeName === null || mapperTypeName === void 0 ? void 0 : mapperTypeName.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i)) !== null || value === undefined || value === null)); @@ -89770,21 +89775,14 @@ function isValidUuid(uuid) { * @internal */ function handleNullableResponseAndWrappableBody(responseObject) { - const combinedHeadersAndBody = { - ...responseObject.headers, - ...responseObject.body, - }; + const combinedHeadersAndBody = Object.assign(Object.assign({}, responseObject.headers), responseObject.body); if (responseObject.hasNullableType && Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0) { return responseObject.shouldWrapBody ? { body: null } : null; } else { return responseObject.shouldWrapBody - ? { - ...responseObject.headers, - body: responseObject.body, - } - : combinedHeadersAndBody; + ? Object.assign(Object.assign({}, responseObject.headers), { body: responseObject.body }) : combinedHeadersAndBody; } } /** @@ -89796,35 +89794,29 @@ function handleNullableResponseAndWrappableBody(responseObject) { * @internal */ function flattenResponse(fullResponse, responseSpec) { + var _a, _b; const parsedHeaders = fullResponse.parsedHeaders; // head methods never have a body, but we return a boolean set to body property // to indicate presence/absence of the resource if (fullResponse.request.method === "HEAD") { - return { - ...parsedHeaders, - body: fullResponse.parsedBody, - }; + return Object.assign(Object.assign({}, parsedHeaders), { body: fullResponse.parsedBody }); } const bodyMapper = responseSpec && responseSpec.bodyMapper; - const isNullable = Boolean(bodyMapper?.nullable); - const expectedBodyTypeName = bodyMapper?.type.name; + const isNullable = Boolean(bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.nullable); + const expectedBodyTypeName = bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.type.name; /** If the body is asked for, we look at the expected body type to handle it */ if (expectedBodyTypeName === "Stream") { - return { - ...parsedHeaders, - blobBody: fullResponse.blobBody, - readableStreamBody: fullResponse.readableStreamBody, - }; + return Object.assign(Object.assign({}, parsedHeaders), { blobBody: fullResponse.blobBody, readableStreamBody: fullResponse.readableStreamBody }); } const modelProperties = (expectedBodyTypeName === "Composite" && bodyMapper.type.modelProperties) || {}; const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === ""); if (expectedBodyTypeName === "Sequence" || isPageableResponse) { - const arrayResponse = fullResponse.parsedBody ?? []; + const arrayResponse = (_a = fullResponse.parsedBody) !== null && _a !== void 0 ? _a : []; for (const key of Object.keys(modelProperties)) { if (modelProperties[key].serializedName) { - arrayResponse[key] = fullResponse.parsedBody?.[key]; + arrayResponse[key] = (_b = fullResponse.parsedBody) === null || _b === void 0 ? void 0 : _b[key]; } } if (parsedHeaders) { @@ -89868,12 +89860,13 @@ const response_js_1 = __nccwpck_require__(38153); */ class ExtendedServiceClient extends core_client_1.ServiceClient { constructor(options) { + var _a, _b; super(options); - if (options.keepAliveOptions?.enable === false && + if (((_a = options.keepAliveOptions) === null || _a === void 0 ? void 0 : _a.enable) === false && !(0, disableKeepAlivePolicy_js_1.pipelineContainsDisableKeepAlivePolicy)(this.pipeline)) { this.pipeline.addPolicy((0, disableKeepAlivePolicy_js_1.createDisableKeepAlivePolicy)()); } - if (options.redirectOptions?.handleRedirects === false) { + if (((_b = options.redirectOptions) === null || _b === void 0 ? void 0 : _b.handleRedirects) === false) { this.pipeline.removePolicy({ name: core_rest_pipeline_1.redirectPolicyName, }); @@ -89887,7 +89880,8 @@ class ExtendedServiceClient extends core_client_1.ServiceClient { * @returns */ async sendOperationRequest(operationArguments, operationSpec) { - const userProvidedCallBack = operationArguments?.options?.onResponse; + var _a; + const userProvidedCallBack = (_a = operationArguments === null || operationArguments === void 0 ? void 0 : operationArguments.options) === null || _a === void 0 ? void 0 : _a.onResponse; let lastResponse; function onResponse(rawResponse, flatResponse, error) { lastResponse = rawResponse; @@ -89895,10 +89889,7 @@ class ExtendedServiceClient extends core_client_1.ServiceClient { userProvidedCallBack(rawResponse, flatResponse, error); } } - operationArguments.options = { - ...operationArguments.options, - onResponse, - }; + operationArguments.options = Object.assign(Object.assign({}, operationArguments.options), { onResponse }); const result = await super.sendOperationRequest(operationArguments, operationSpec); if (lastResponse) { Object.defineProperty(result, "_response", { @@ -90085,7 +90076,7 @@ const originalResponse = Symbol("Original FullOperationResponse"); function toCompatResponse(response, options) { let request = (0, util_js_1.toWebResourceLike)(response.request); let headers = (0, util_js_1.toHttpHeadersLike)(response.headers); - if (options?.createProxy) { + if (options === null || options === void 0 ? void 0 : options.createProxy) { return new Proxy(response, { get(target, prop, receiver) { if (prop === "headers") { @@ -90111,11 +90102,8 @@ function toCompatResponse(response, options) { }); } else { - return { - ...response, - request, - headers, - }; + return Object.assign(Object.assign({}, response), { request, + headers }); } } /** @@ -90131,11 +90119,7 @@ function toPipelineResponse(compatResponse) { return response; } else { - return { - ...compatResponse, - headers, - request: (0, util_js_1.toPipelineRequest)(compatResponse.request), - }; + return Object.assign(Object.assign({}, compatResponse), { headers, request: (0, util_js_1.toPipelineRequest)(compatResponse.request) }); } } //# sourceMappingURL=response.js.map @@ -90198,7 +90182,8 @@ function toPipelineRequest(webResource, options = {}) { } } function toWebResourceLike(request, options) { - const originalRequest = options?.originalRequest ?? request; + var _a; + const originalRequest = (_a = options === null || options === void 0 ? void 0 : options.originalRequest) !== null && _a !== void 0 ? _a : request; const webResource = { url: request.url, method: request.method, @@ -90226,7 +90211,7 @@ function toWebResourceLike(request, options) { /** do nothing */ }, }; - if (options?.createProxy) { + if (options === null || options === void 0 ? void 0 : options.createProxy) { return new Proxy(webResource, { get(target, prop, receiver) { if (prop === originalRequestSymbol) { @@ -90292,7 +90277,6 @@ function getHeaderKey(headerName) { * A collection of HTTP header key/value pairs. */ class HttpHeaders { - _headersMap; constructor(rawHeaders) { this._headersMap = {}; if (rawHeaders) { @@ -91787,7 +91771,7 @@ exports.buildCreatePoller = buildCreatePoller; // Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DEFAULT_RETRY_POLICY_COUNT = exports.SDK_VERSION = void 0; -exports.SDK_VERSION = "1.22.1"; +exports.SDK_VERSION = "1.22.0"; exports.DEFAULT_RETRY_POLICY_COUNT = 3; //# sourceMappingURL=constants.js.map @@ -91822,6 +91806,7 @@ const wrapAbortSignalLikePolicy_js_1 = __nccwpck_require__(37466); * @param options - Options to configure a custom pipeline. */ function createPipelineFromOptions(options) { + var _a; const pipeline = (0, pipeline_js_1.createEmptyPipeline)(); if (core_util_1.isNodeLike) { if (options.agent) { @@ -91836,13 +91821,13 @@ function createPipelineFromOptions(options) { pipeline.addPolicy((0, wrapAbortSignalLikePolicy_js_1.wrapAbortSignalLikePolicy)()); pipeline.addPolicy((0, formDataPolicy_js_1.formDataPolicy)(), { beforePolicies: [multipartPolicy_js_1.multipartPolicyName] }); pipeline.addPolicy((0, userAgentPolicy_js_1.userAgentPolicy)(options.userAgentOptions)); - pipeline.addPolicy((0, setClientRequestIdPolicy_js_1.setClientRequestIdPolicy)(options.telemetryOptions?.clientRequestIdHeaderName)); + pipeline.addPolicy((0, setClientRequestIdPolicy_js_1.setClientRequestIdPolicy)((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.clientRequestIdHeaderName)); // The multipart policy is added after policies with no phase, so that // policies can be added between it and formDataPolicy to modify // properties (e.g., making the boundary constant in recorded tests). pipeline.addPolicy((0, multipartPolicy_js_1.multipartPolicy)(), { afterPhase: "Deserialize" }); pipeline.addPolicy((0, defaultRetryPolicy_js_1.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" }); - pipeline.addPolicy((0, tracingPolicy_js_1.tracingPolicy)({ ...options.userAgentOptions, ...options.loggingOptions }), { + pipeline.addPolicy((0, tracingPolicy_js_1.tracingPolicy)(Object.assign(Object.assign({}, options.userAgentOptions), options.loggingOptions)), { afterPhase: "Retry", }); if (core_util_1.isNodeLike) { @@ -91886,7 +91871,7 @@ function createDefaultHttpClient() { return await client.sendRequest(request); } finally { - cleanup?.(); + cleanup === null || cleanup === void 0 ? void 0 : cleanup(); } }, }; @@ -92105,12 +92090,13 @@ const log_js_1 = __nccwpck_require__(80544); exports.auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy"; const AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary"; async function sendAuthorizeRequest(options) { + var _a, _b; const { scopes, getAccessToken, request } = options; const getTokenOptions = { abortSignal: request.abortSignal, tracingOptions: request.tracingOptions, }; - return (await getAccessToken(scopes, getTokenOptions))?.token ?? ""; + return (_b = (_a = (await getAccessToken(scopes, getTokenOptions))) === null || _a === void 0 ? void 0 : _a.token) !== null && _b !== void 0 ? _b : ""; } /** * A policy for external tokens to `x-ms-authorization-auxiliary` header. @@ -92229,6 +92215,7 @@ function isChallengeResponse(response) { * If this method returns true, the underlying request will be sent once again. */ async function authorizeRequestOnCaeChallenge(onChallengeOptions, caeClaims) { + var _a; const { scopes } = onChallengeOptions; const accessToken = await onChallengeOptions.getAccessToken(scopes, { enableCae: true, @@ -92237,7 +92224,7 @@ async function authorizeRequestOnCaeChallenge(onChallengeOptions, caeClaims) { if (!accessToken) { return false; } - onChallengeOptions.request.headers.set("Authorization", `${accessToken.tokenType ?? "Bearer"} ${accessToken.token}`); + onChallengeOptions.request.headers.set("Authorization", `${(_a = accessToken.tokenType) !== null && _a !== void 0 ? _a : "Bearer"} ${accessToken.token}`); return true; } /** @@ -92245,11 +92232,12 @@ async function authorizeRequestOnCaeChallenge(onChallengeOptions, caeClaims) { * then apply it to the Authorization header of a request as a Bearer token. */ function bearerTokenAuthenticationPolicy(options) { + var _a, _b, _c; const { credential, scopes, challengeCallbacks } = options; const logger = options.logger || log_js_1.logger; const callbacks = { - authorizeRequest: challengeCallbacks?.authorizeRequest?.bind(challengeCallbacks) ?? defaultAuthorizeRequest, - authorizeRequestOnChallenge: challengeCallbacks?.authorizeRequestOnChallenge?.bind(challengeCallbacks), + authorizeRequest: (_b = (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) === null || _a === void 0 ? void 0 : _a.bind(challengeCallbacks)) !== null && _b !== void 0 ? _b : defaultAuthorizeRequest, + authorizeRequestOnChallenge: (_c = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge) === null || _c === void 0 ? void 0 : _c.bind(challengeCallbacks), }; // This function encapsulates the entire process of reliably retrieving the token // The options are left out of the public API until there's demand to configure this. @@ -92396,12 +92384,13 @@ function parseChallenges(challenges) { * @internal */ function getCaeChallengeClaims(challenges) { + var _a; if (!challenges) { return; } // Find all challenges present in the header const parsedChallenges = parseChallenges(challenges); - return parsedChallenges.find((x) => x.scheme === "Bearer" && x.params.claims && x.params.error === "insufficient_claims")?.params.claims; + return (_a = parsedChallenges.find((x) => x.scheme === "Bearer" && x.params.claims && x.params.error === "insufficient_claims")) === null || _a === void 0 ? void 0 : _a.params.claims; } //# sourceMappingURL=bearerTokenAuthenticationPolicy.js.map @@ -92533,10 +92522,7 @@ exports.logPolicyName = policies_1.logPolicyName; * @param options - Options to configure logPolicy. */ function logPolicy(options = {}) { - return (0, policies_1.logPolicy)({ - logger: log_js_1.logger.info, - ...options, - }); + return (0, policies_1.logPolicy)(Object.assign({ logger: log_js_1.logger.info }, options)); } //# sourceMappingURL=logPolicy.js.map @@ -92705,10 +92691,7 @@ function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_ // Cast is required since the TSP runtime retry strategy type is slightly different // very deep down (using real AbortSignal vs. AbortSignalLike in RestError). // In practice the difference doesn't actually matter. - return (0, policies_1.retryPolicy)(strategies, { - logger: retryPolicyLogger, - ...options, - }); + return (0, policies_1.retryPolicy)(strategies, Object.assign({ logger: retryPolicyLogger }, options)); } //# sourceMappingURL=retryPolicy.js.map @@ -92870,6 +92853,7 @@ function tracingPolicy(options = {}) { return { name: exports.tracingPolicyName, async sendRequest(request, next) { + var _a; if (!tracingClient) { return next(request); } @@ -92883,7 +92867,7 @@ function tracingPolicy(options = {}) { if (userAgent) { spanAttributes["http.user_agent"] = userAgent; } - const { span, tracingContext } = tryCreateSpan(tracingClient, request, spanAttributes) ?? {}; + const { span, tracingContext } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {}; if (!span || !tracingContext) { return next(request); } @@ -93045,7 +93029,7 @@ function wrapAbortSignalLikePolicy() { return await next(request); } finally { - cleanup?.(); + cleanup === null || cleanup === void 0 ? void 0 : cleanup(); } }, }; @@ -93165,22 +93149,14 @@ function getRawContent(blob) { * @param options - optional metadata about the file, e.g. file name, file size, MIME type. */ function createFileFromStream(stream, name, options = {}) { - return { - ...unimplementedMethods, - type: options.type ?? "", - lastModified: options.lastModified ?? new Date().getTime(), - webkitRelativePath: options.webkitRelativePath ?? "", - size: options.size ?? -1, - name, - stream: () => { + var _a, _b, _c, _d; + return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : new Date().getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: (_d = options.size) !== null && _d !== void 0 ? _d : -1, name, stream: () => { const s = stream(); if (isNodeReadableStream(s)) { throw new Error("Not supported: a Node stream was provided as input to createFileFromStream."); } return s; - }, - [rawContent]: stream, - }; + }, [rawContent]: stream }); } /** * Create an object that implements the File interface. This object is intended to be @@ -93194,18 +93170,9 @@ function createFileFromStream(stream, name, options = {}) { * @param options - optional metadata about the file, e.g. file name, file size, MIME type. */ function createFile(content, name, options = {}) { + var _a, _b, _c; if (core_util_1.isNodeLike) { - return { - ...unimplementedMethods, - type: options.type ?? "", - lastModified: options.lastModified ?? new Date().getTime(), - webkitRelativePath: options.webkitRelativePath ?? "", - size: content.byteLength, - name, - arrayBuffer: async () => content.buffer, - stream: () => new Blob([content]).stream(), - [rawContent]: () => content, - }; + return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : new Date().getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: content.byteLength, name, arrayBuffer: async () => content.buffer, stream: () => new Blob([content]).stream(), [rawContent]: () => content }); } else { return new File([content], name, options); @@ -93250,7 +93217,7 @@ async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) { try { return await getAccessToken(); } - catch { + catch (_a) { return null; } } @@ -93288,10 +93255,7 @@ function createTokenCycler(credential, tokenCyclerOptions) { let refreshWorker = null; let token = null; let tenantId; - const options = { - ...exports.DEFAULT_CYCLER_OPTIONS, - ...tokenCyclerOptions, - }; + const options = Object.assign(Object.assign({}, exports.DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); /** * This little holder defines several predicates that we use to construct * the rules of refreshing the token. @@ -93308,13 +93272,14 @@ function createTokenCycler(credential, tokenCyclerOptions) { * window and not already refreshing) */ get shouldRefresh() { + var _a; if (cycler.isRefreshing) { return false; } - if (token?.refreshAfterTimestamp && token.refreshAfterTimestamp < Date.now()) { + if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) { return true; } - return (token?.expiresOnTimestamp ?? 0) - options.refreshWindowInMs < Date.now(); + return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now(); }, /** * Produces true if the cycler MUST refresh (null or nearly-expired @@ -93329,6 +93294,7 @@ function createTokenCycler(credential, tokenCyclerOptions) { * running. */ function refresh(scopes, getTokenOptions) { + var _a; if (!cycler.isRefreshing) { // We bind `scopes` here to avoid passing it around a lot const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); @@ -93336,7 +93302,7 @@ function createTokenCycler(credential, tokenCyclerOptions) { // before the refresh can be considered done. refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs, // If we don't have a token, then we should timeout immediately - token?.expiresOnTimestamp ?? Date.now()) + (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now()) .then((_token) => { refreshWorker = null; token = _token; @@ -93441,8 +93407,8 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getHeaderName = getHeaderName; exports.setPlatformSpecificData = setPlatformSpecificData; const tslib_1 = __nccwpck_require__(61860); -const node_os_1 = tslib_1.__importDefault(__nccwpck_require__(48161)); -const node_process_1 = tslib_1.__importDefault(__nccwpck_require__(1708)); +const os = tslib_1.__importStar(__nccwpck_require__(48161)); +const process = tslib_1.__importStar(__nccwpck_require__(1708)); /** * @internal */ @@ -93453,8 +93419,8 @@ function getHeaderName() { * @internal */ async function setPlatformSpecificData(map) { - if (node_process_1.default && node_process_1.default.versions) { - const versions = node_process_1.default.versions; + if (process && process.versions) { + const versions = process.versions; if (versions.bun) { map.set("Bun", versions.bun); } @@ -93465,7 +93431,7 @@ async function setPlatformSpecificData(map) { map.set("Node", versions.node); } } - map.set("OS", `(${node_os_1.default.arch()}-${node_os_1.default.type()}-${node_os_1.default.release()})`); + map.set("OS", `(${os.arch()}-${os.type()}-${os.release()})`); } //# sourceMappingURL=userAgentPlatform.js.map @@ -93646,12 +93612,8 @@ const tracingContext_js_1 = __nccwpck_require__(79186); function createTracingClient(options) { const { namespace, packageName, packageVersion } = options; function startSpan(name, operationOptions, spanOptions) { - const startSpanResult = (0, instrumenter_js_1.getInstrumenter)().startSpan(name, { - ...spanOptions, - packageName: packageName, - packageVersion: packageVersion, - tracingContext: operationOptions?.tracingOptions?.tracingContext, - }); + var _a; + const startSpanResult = (0, instrumenter_js_1.getInstrumenter)().startSpan(name, Object.assign(Object.assign({}, spanOptions), { packageName: packageName, packageVersion: packageVersion, tracingContext: (_a = operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext })); let tracingContext = startSpanResult.tracingContext; const span = startSpanResult.span; if (!tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)) { @@ -93659,7 +93621,7 @@ function createTracingClient(options) { } span.setAttribute("az.namespace", tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)); const updatedOptions = Object.assign({}, operationOptions, { - tracingOptions: { ...operationOptions?.tracingOptions, tracingContext }, + tracingOptions: Object.assign(Object.assign({}, operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions), { tracingContext }), }); return { span, @@ -93748,7 +93710,6 @@ function createTracingContext(options = {}) { } /** @internal */ class TracingContextImpl { - _contextMap; constructor(initialContext) { this._contextMap = initialContext instanceof TracingContextImpl @@ -93787,17 +93748,18 @@ exports.cancelablePromiseRace = cancelablePromiseRace; * promise.race() wrapper that aborts rest of promises as soon as the first promise settles. */ async function cancelablePromiseRace(abortablePromiseBuilders, options) { + var _a, _b; const aborter = new AbortController(); function abortHandler() { aborter.abort(); } - options?.abortSignal?.addEventListener("abort", abortHandler); + (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler); try { return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); } finally { aborter.abort(); - options?.abortSignal?.removeEventListener("abort", abortHandler); + (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler); } } //# sourceMappingURL=aborterUtils.js.map @@ -93821,20 +93783,20 @@ const abort_controller_1 = __nccwpck_require__(83134); * @returns A promise that can be aborted. */ function createAbortablePromise(buildPromise, options) { - const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options ?? {}; + const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; return new Promise((resolve, reject) => { function rejectOnAbort() { - reject(new abort_controller_1.AbortError(abortErrorMsg ?? "The operation was aborted.")); + reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); } function removeListeners() { - abortSignal?.removeEventListener("abort", onAbort); + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); } function onAbort() { - cleanupBeforeAbort?.(); + cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); removeListeners(); rejectOnAbort(); } - if (abortSignal?.aborted) { + if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { return rejectOnAbort(); } try { @@ -93849,7 +93811,7 @@ function createAbortablePromise(buildPromise, options) { catch (err) { reject(err); } - abortSignal?.addEventListener("abort", onAbort); + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); }); } //# sourceMappingURL=createAbortablePromise.js.map @@ -93877,13 +93839,13 @@ const StandardAbortMessage = "The delay was aborted."; */ function delay(timeInMs, options) { let token; - const { abortSignal, abortErrorMsg } = options ?? {}; + const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve) => { token = setTimeout(resolve, timeInMs); }, { cleanupBeforeAbort: () => clearTimeout(token), abortSignal, - abortErrorMsg: abortErrorMsg ?? StandardAbortMessage, + abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage, }); } /** @@ -125337,8 +125299,9 @@ const checkEnvironment_js_1 = __nccwpck_require__(85086); * @param options - Client options */ function getClient(endpoint, clientOptions = {}) { - const pipeline = clientOptions.pipeline ?? (0, clientHelpers_js_1.createDefaultPipeline)(clientOptions); - if (clientOptions.additionalPolicies?.length) { + var _a, _b, _c; + const pipeline = (_a = clientOptions.pipeline) !== null && _a !== void 0 ? _a : (0, clientHelpers_js_1.createDefaultPipeline)(clientOptions); + if ((_b = clientOptions.additionalPolicies) === null || _b === void 0 ? void 0 : _b.length) { for (const { policy, position } of clientOptions.additionalPolicies) { // Sign happens after Retry and is commonly needed to occur // before policies that intercept post-retry. @@ -125349,9 +125312,9 @@ function getClient(endpoint, clientOptions = {}) { } } const { allowInsecureConnection, httpClient } = clientOptions; - const endpointUrl = clientOptions.endpoint ?? endpoint; + const endpointUrl = (_c = clientOptions.endpoint) !== null && _c !== void 0 ? _c : endpoint; const client = (path, ...args) => { - const getUrl = (requestOptions) => (0, urlHelpers_js_1.buildRequestUrl)(endpointUrl, path, args, { allowInsecureConnection, ...requestOptions }); + const getUrl = (requestOptions) => (0, urlHelpers_js_1.buildRequestUrl)(endpointUrl, path, args, Object.assign({ allowInsecureConnection }, requestOptions)); return { get: (requestOptions = {}) => { return buildOperation("GET", getUrl(requestOptions), pipeline, requestOptions, allowInsecureConnection, httpClient); @@ -125386,22 +125349,23 @@ function getClient(endpoint, clientOptions = {}) { }; } function buildOperation(method, url, pipeline, options, allowInsecureConnection, httpClient) { - allowInsecureConnection = options.allowInsecureConnection ?? allowInsecureConnection; + var _a; + allowInsecureConnection = (_a = options.allowInsecureConnection) !== null && _a !== void 0 ? _a : allowInsecureConnection; return { then: function (onFulfilled, onrejected) { - return (0, sendRequest_js_1.sendRequest)(method, url, pipeline, { ...options, allowInsecureConnection }, httpClient).then(onFulfilled, onrejected); + return (0, sendRequest_js_1.sendRequest)(method, url, pipeline, Object.assign(Object.assign({}, options), { allowInsecureConnection }), httpClient).then(onFulfilled, onrejected); }, async asBrowserStream() { if (checkEnvironment_js_1.isNodeLike) { throw new Error("`asBrowserStream` is supported only in the browser environment. Use `asNodeStream` instead to obtain the response body stream. If you require a Web stream of the response in Node, consider using `Readable.toWeb` on the result of `asNodeStream`."); } else { - return (0, sendRequest_js_1.sendRequest)(method, url, pipeline, { ...options, allowInsecureConnection, responseAsStream: true }, httpClient); + return (0, sendRequest_js_1.sendRequest)(method, url, pipeline, Object.assign(Object.assign({}, options), { allowInsecureConnection, responseAsStream: true }), httpClient); } }, async asNodeStream() { if (checkEnvironment_js_1.isNodeLike) { - return (0, sendRequest_js_1.sendRequest)(method, url, pipeline, { ...options, allowInsecureConnection, responseAsStream: true }, httpClient); + return (0, sendRequest_js_1.sendRequest)(method, url, pipeline, Object.assign(Object.assign({}, options), { allowInsecureConnection, responseAsStream: true }), httpClient); } else { throw new Error("`isNodeStream` is not supported in the browser environment. Use `asBrowserStream` to obtain the response body stream."); @@ -125474,6 +125438,7 @@ function escapeDispositionField(value) { return JSON.stringify(value); } function getContentDisposition(descriptor) { + var _a; const contentDispositionHeader = getHeaderValue(descriptor, "content-disposition"); if (contentDispositionHeader) { return contentDispositionHeader; @@ -125483,7 +125448,7 @@ function getContentDisposition(descriptor) { descriptor.filename === undefined) { return undefined; } - const dispositionType = descriptor.dispositionType ?? "form-data"; + const dispositionType = (_a = descriptor.dispositionType) !== null && _a !== void 0 ? _a : "form-data"; let disposition = dispositionType; if (descriptor.name) { disposition += `; name=${escapeDispositionField(descriptor.name)}`; @@ -125522,9 +125487,10 @@ function normalizeBody(body, contentType) { throw new restError_js_1.RestError(`Unsupported body/content-type combination: ${body}, ${contentType}`); } function buildBodyPart(descriptor) { + var _a; const contentType = getPartContentType(descriptor); const contentDisposition = getContentDisposition(descriptor); - const headers = (0, httpHeaders_js_1.createHttpHeaders)(descriptor.headers ?? {}); + const headers = (0, httpHeaders_js_1.createHttpHeaders)((_a = descriptor.headers) !== null && _a !== void 0 ? _a : {}); if (contentType) { headers.set("content-type", contentType); } @@ -125559,14 +125525,15 @@ exports.operationOptionsToRequestParameters = operationOptionsToRequestParameter * @returns the result of the conversion in RequestParameters of RLC layer */ function operationOptionsToRequestParameters(options) { + var _a, _b, _c, _d, _e, _f; return { - allowInsecureConnection: options.requestOptions?.allowInsecureConnection, - timeout: options.requestOptions?.timeout, - skipUrlEncoding: options.requestOptions?.skipUrlEncoding, + allowInsecureConnection: (_a = options.requestOptions) === null || _a === void 0 ? void 0 : _a.allowInsecureConnection, + timeout: (_b = options.requestOptions) === null || _b === void 0 ? void 0 : _b.timeout, + skipUrlEncoding: (_c = options.requestOptions) === null || _c === void 0 ? void 0 : _c.skipUrlEncoding, abortSignal: options.abortSignal, - onUploadProgress: options.requestOptions?.onUploadProgress, - onDownloadProgress: options.requestOptions?.onDownloadProgress, - headers: { ...options.requestOptions?.headers }, + onUploadProgress: (_d = options.requestOptions) === null || _d === void 0 ? void 0 : _d.onUploadProgress, + onDownloadProgress: (_e = options.requestOptions) === null || _e === void 0 ? void 0 : _e.onDownloadProgress, + headers: Object.assign({}, (_f = options.requestOptions) === null || _f === void 0 ? void 0 : _f.headers), onResponse: options.onResponse, }; } @@ -125586,23 +125553,25 @@ exports.createRestError = createRestError; const restError_js_1 = __nccwpck_require__(9758); const httpHeaders_js_1 = __nccwpck_require__(4220); function createRestError(messageOrResponse, response) { + var _a, _b, _c; const resp = typeof messageOrResponse === "string" ? response : messageOrResponse; - const internalError = resp.body?.error ?? resp.body; + const internalError = (_b = (_a = resp.body) === null || _a === void 0 ? void 0 : _a.error) !== null && _b !== void 0 ? _b : resp.body; const message = typeof messageOrResponse === "string" ? messageOrResponse - : (internalError?.message ?? `Unexpected status code: ${resp.status}`); + : ((_c = internalError === null || internalError === void 0 ? void 0 : internalError.message) !== null && _c !== void 0 ? _c : `Unexpected status code: ${resp.status}`); return new restError_js_1.RestError(message, { statusCode: statusCodeToNumber(resp.status), - code: internalError?.code, + code: internalError === null || internalError === void 0 ? void 0 : internalError.code, request: resp.request, response: toPipelineResponse(resp), }); } function toPipelineResponse(response) { + var _a; return { headers: (0, httpHeaders_js_1.createHttpHeaders)(response.headers), request: response.request, - status: statusCodeToNumber(response.status) ?? -1, + status: (_a = statusCodeToNumber(response.status)) !== null && _a !== void 0 ? _a : -1, }; } function statusCodeToNumber(statusCode) { @@ -125638,16 +125607,17 @@ const multipart_js_1 = __nccwpck_require__(18240); * @returns returns and HttpResponse */ async function sendRequest(method, url, pipeline, options = {}, customHttpClient) { - const httpClient = customHttpClient ?? (0, clientHelpers_js_1.getCachedDefaultHttpsClient)(); + var _a; + const httpClient = customHttpClient !== null && customHttpClient !== void 0 ? customHttpClient : (0, clientHelpers_js_1.getCachedDefaultHttpsClient)(); const request = buildPipelineRequest(method, url, options); try { const response = await pipeline.sendRequest(httpClient, request); const headers = response.headers.toJSON(); - const stream = response.readableStreamBody ?? response.browserStreamBody; + const stream = (_a = response.readableStreamBody) !== null && _a !== void 0 ? _a : response.browserStreamBody; const parsedBody = options.responseAsStream || stream !== undefined ? undefined : getResponseBody(response); - const body = stream ?? parsedBody; - if (options?.onResponse) { - options.onResponse({ ...response, request, rawHeaders: headers, parsedBody }); + const body = stream !== null && stream !== void 0 ? stream : parsedBody; + if (options === null || options === void 0 ? void 0 : options.onResponse) { + options.onResponse(Object.assign(Object.assign({}, response), { request, rawHeaders: headers, parsedBody })); } return { request, @@ -125661,7 +125631,7 @@ async function sendRequest(method, url, pipeline, options = {}, customHttpClient const { response } = e; const rawHeaders = response.headers.toJSON(); // UNBRANDED DIFFERENCE: onResponse callback does not have a second __legacyError property - options?.onResponse({ ...response, request, rawHeaders }, e); + options === null || options === void 0 ? void 0 : options.onResponse(Object.assign(Object.assign({}, response), { request, rawHeaders }), e); } throw e; } @@ -125672,9 +125642,8 @@ async function sendRequest(method, url, pipeline, options = {}, customHttpClient * @returns returns the content-type */ function getRequestContentType(options = {}) { - return (options.contentType ?? - options.headers?.["content-type"] ?? - getContentType(options.body)); + var _a, _b, _c; + return ((_c = (_a = options.contentType) !== null && _a !== void 0 ? _a : (_b = options.headers) === null || _b === void 0 ? void 0 : _b["content-type"]) !== null && _c !== void 0 ? _c : getContentType(options.body)); } /** * Function to determine the content-type of a body @@ -125700,17 +125669,14 @@ function getContentType(body) { return "application/json"; } function buildPipelineRequest(method, url, options = {}) { + var _a, _b, _c; const requestContentType = getRequestContentType(options); const { body, multipartBody } = getRequestBody(options.body, requestContentType); const hasContent = body !== undefined || multipartBody !== undefined; - const headers = (0, httpHeaders_js_1.createHttpHeaders)({ - ...(options.headers ? options.headers : {}), - accept: options.accept ?? options.headers?.accept ?? "application/json", - ...(hasContent && - requestContentType && { - "content-type": requestContentType, - }), - }); + const headers = (0, httpHeaders_js_1.createHttpHeaders)(Object.assign(Object.assign(Object.assign({}, (options.headers ? options.headers : {})), { accept: (_c = (_a = options.accept) !== null && _a !== void 0 ? _a : (_b = options.headers) === null || _b === void 0 ? void 0 : _b.accept) !== null && _c !== void 0 ? _c : "application/json" }), (hasContent && + requestContentType && { + "content-type": requestContentType, + }))); return (0, pipelineRequest_js_1.createPipelineRequest)({ url, method, @@ -125766,10 +125732,11 @@ function getRequestBody(body, contentType = "") { * Prepares the response body */ function getResponseBody(response) { + var _a, _b; // Set the default response type - const contentType = response.headers.get("content-type") ?? ""; + const contentType = (_a = response.headers.get("content-type")) !== null && _a !== void 0 ? _a : ""; const firstType = contentType.split(";")[0]; - const bodyToParse = response.bodyAsText ?? ""; + const bodyToParse = (_b = response.bodyAsText) !== null && _b !== void 0 ? _b : ""; if (firstType === "text/plain") { return String(bodyToParse); } @@ -125789,8 +125756,9 @@ function getResponseBody(response) { } } function createParseError(response, err) { + var _a; const msg = `Error "${err}" occurred while parsing the response body - ${response.bodyAsText}.`; - const errCode = err.code ?? restError_js_1.RestError.PARSE_ERROR; + const errCode = (_a = err.code) !== null && _a !== void 0 ? _a : restError_js_1.RestError.PARSE_ERROR; return new restError_js_1.RestError(msg, { code: errCode, statusCode: response.status, @@ -125876,6 +125844,7 @@ function getQueryParamValue(key, allowReserved, style, param) { return `${allowReserved ? key : encodeURIComponent(key)}=${value}`; } function appendQueryParams(url, options = {}) { + var _a, _b, _c, _d; if (!options.queryParameters) { return url; } @@ -125889,18 +125858,18 @@ function appendQueryParams(url, options = {}) { } const hasMetadata = isQueryParameterWithOptions(param); const rawValue = hasMetadata ? param.value : param; - const explode = hasMetadata ? (param.explode ?? false) : false; + const explode = hasMetadata ? ((_a = param.explode) !== null && _a !== void 0 ? _a : false) : false; const style = hasMetadata && param.style ? param.style : "form"; if (explode) { if (Array.isArray(rawValue)) { for (const item of rawValue) { - paramStrings.push(getQueryParamValue(key, options.skipUrlEncoding ?? false, style, item)); + paramStrings.push(getQueryParamValue(key, (_b = options.skipUrlEncoding) !== null && _b !== void 0 ? _b : false, style, item)); } } else if (typeof rawValue === "object") { // For object explode, the name of the query parameter is ignored and we use the object key instead for (const [actualKey, value] of Object.entries(rawValue)) { - paramStrings.push(getQueryParamValue(actualKey, options.skipUrlEncoding ?? false, style, value)); + paramStrings.push(getQueryParamValue(actualKey, (_c = options.skipUrlEncoding) !== null && _c !== void 0 ? _c : false, style, value)); } } else { @@ -125909,7 +125878,7 @@ function appendQueryParams(url, options = {}) { } } else { - paramStrings.push(getQueryParamValue(key, options.skipUrlEncoding ?? false, style, rawValue)); + paramStrings.push(getQueryParamValue(key, (_d = options.skipUrlEncoding) !== null && _d !== void 0 ? _d : false, style, rawValue)); } } if (parsedUrl.search !== "") { @@ -125919,6 +125888,7 @@ function appendQueryParams(url, options = {}) { return parsedUrl.toString(); } function buildBaseUrl(endpoint, options) { + var _a; if (!options.pathParameters) { return endpoint; } @@ -125934,13 +125904,14 @@ function buildBaseUrl(endpoint, options) { if (!options.skipUrlEncoding) { value = encodeURIComponent(param); } - endpoint = replaceAll(endpoint, `{${key}}`, value) ?? ""; + endpoint = (_a = replaceAll(endpoint, `{${key}}`, value)) !== null && _a !== void 0 ? _a : ""; } return endpoint; } function buildRoutePath(routePath, pathParameters, options = {}) { + var _a; for (const pathParam of pathParameters) { - const allowReserved = typeof pathParam === "object" && (pathParam.allowReserved ?? false); + const allowReserved = typeof pathParam === "object" && ((_a = pathParam.allowReserved) !== null && _a !== void 0 ? _a : false); let value = typeof pathParam === "object" ? pathParam.value : pathParam; if (!options.skipUrlEncoding && !allowReserved) { value = encodeURIComponent(value); @@ -125972,7 +125943,7 @@ function replaceAll(value, searchValue, replaceValue) { // Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DEFAULT_RETRY_POLICY_COUNT = exports.SDK_VERSION = void 0; -exports.SDK_VERSION = "0.3.1"; +exports.SDK_VERSION = "0.3.0"; exports.DEFAULT_RETRY_POLICY_COUNT = 3; //# sourceMappingURL=constants.js.map @@ -126072,7 +126043,6 @@ function* headerIterator(map) { } } class HttpHeadersImpl { - _headersMap; constructor(rawHeaders) { this._headersMap = new Map(); if (rawHeaders) { @@ -126096,7 +126066,8 @@ class HttpHeadersImpl { * @param name - The name of the header. This value is case-insensitive. */ get(name) { - return this._headersMap.get(normalizeName(name))?.value; + var _a; + return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value; } /** * Get whether or not this header collection contains a header entry for the provided header name. @@ -126240,13 +126211,14 @@ function enable(namespaces) { enabledString = namespaces; enabledNamespaces = []; skippedNamespaces = []; - const namespaceList = namespaces.split(",").map((ns) => ns.trim()); + const wildcard = /\*/g; + const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); for (const ns of namespaceList) { if (ns.startsWith("-")) { - skippedNamespaces.push(ns.substring(1)); + skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); } else { - enabledNamespaces.push(ns); + enabledNamespaces.push(new RegExp(`^${ns}$`)); } } for (const instance of debuggers) { @@ -126258,110 +126230,17 @@ function enabled(namespace) { return true; } for (const skipped of skippedNamespaces) { - if (namespaceMatches(namespace, skipped)) { + if (skipped.test(namespace)) { return false; } } for (const enabledNamespace of enabledNamespaces) { - if (namespaceMatches(namespace, enabledNamespace)) { + if (enabledNamespace.test(namespace)) { return true; } } return false; } -/** - * Given a namespace, check if it matches a pattern. - * Patterns only have a single wildcard character which is *. - * The behavior of * is that it matches zero or more other characters. - */ -function namespaceMatches(namespace, patternToMatch) { - // simple case, no pattern matching required - if (patternToMatch.indexOf("*") === -1) { - return namespace === patternToMatch; - } - let pattern = patternToMatch; - // normalize successive * if needed - if (patternToMatch.indexOf("**") !== -1) { - const patternParts = []; - let lastCharacter = ""; - for (const character of patternToMatch) { - if (character === "*" && lastCharacter === "*") { - continue; - } - else { - lastCharacter = character; - patternParts.push(character); - } - } - pattern = patternParts.join(""); - } - let namespaceIndex = 0; - let patternIndex = 0; - const patternLength = pattern.length; - const namespaceLength = namespace.length; - let lastWildcard = -1; - let lastWildcardNamespace = -1; - while (namespaceIndex < namespaceLength && patternIndex < patternLength) { - if (pattern[patternIndex] === "*") { - lastWildcard = patternIndex; - patternIndex++; - if (patternIndex === patternLength) { - // if wildcard is the last character, it will match the remaining namespace string - return true; - } - // now we let the wildcard eat characters until we match the next literal in the pattern - while (namespace[namespaceIndex] !== pattern[patternIndex]) { - namespaceIndex++; - // reached the end of the namespace without a match - if (namespaceIndex === namespaceLength) { - return false; - } - } - // now that we have a match, let's try to continue on - // however, it's possible we could find a later match - // so keep a reference in case we have to backtrack - lastWildcardNamespace = namespaceIndex; - namespaceIndex++; - patternIndex++; - continue; - } - else if (pattern[patternIndex] === namespace[namespaceIndex]) { - // simple case: literal pattern matches so keep going - patternIndex++; - namespaceIndex++; - } - else if (lastWildcard >= 0) { - // special case: we don't have a literal match, but there is a previous wildcard - // which we can backtrack to and try having the wildcard eat the match instead - patternIndex = lastWildcard + 1; - namespaceIndex = lastWildcardNamespace + 1; - // we've reached the end of the namespace without a match - if (namespaceIndex === namespaceLength) { - return false; - } - // similar to the previous logic, let's keep going until we find the next literal match - while (namespace[namespaceIndex] !== pattern[patternIndex]) { - namespaceIndex++; - if (namespaceIndex === namespaceLength) { - return false; - } - } - lastWildcardNamespace = namespaceIndex; - namespaceIndex++; - patternIndex++; - continue; - } - else { - return false; - } - } - const namespaceDone = namespaceIndex === namespace.length; - const patternDone = patternIndex === pattern.length; - // this is to detect the case of an unneeded final wildcard - // e.g. the pattern `ab*` should match the string `ab` - const trailingWildCard = patternIndex === pattern.length - 1 && pattern[patternIndex] === "*"; - return namespaceDone && (patternDone || trailingWildCard); -} function disable() { const result = enabledString || ""; enable(""); @@ -126432,9 +126311,9 @@ exports.log = log; const tslib_1 = __nccwpck_require__(61860); const node_os_1 = __nccwpck_require__(48161); const node_util_1 = tslib_1.__importDefault(__nccwpck_require__(57975)); -const node_process_1 = tslib_1.__importDefault(__nccwpck_require__(1708)); +const process = tslib_1.__importStar(__nccwpck_require__(1708)); function log(message, ...args) { - node_process_1.default.stderr.write(`${node_util_1.default.format(message, ...args)}${node_os_1.EOL}`); + process.stderr.write(`${node_util_1.default.format(message, ...args)}${node_os_1.EOL}`); } //# sourceMappingURL=log.js.map @@ -126591,9 +126470,9 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getBodyLength = getBodyLength; exports.createNodeHttpClient = createNodeHttpClient; const tslib_1 = __nccwpck_require__(61860); -const node_http_1 = tslib_1.__importDefault(__nccwpck_require__(37067)); -const node_https_1 = tslib_1.__importDefault(__nccwpck_require__(44708)); -const node_zlib_1 = tslib_1.__importDefault(__nccwpck_require__(38522)); +const http = tslib_1.__importStar(__nccwpck_require__(37067)); +const https = tslib_1.__importStar(__nccwpck_require__(44708)); +const zlib = tslib_1.__importStar(__nccwpck_require__(38522)); const node_stream_1 = __nccwpck_require__(57075); const AbortError_js_1 = __nccwpck_require__(99992); const httpHeaders_js_1 = __nccwpck_require__(4220); @@ -126624,8 +126503,6 @@ function isArrayBuffer(body) { return body && typeof body.byteLength === "number"; } class ReportTransform extends node_stream_1.Transform { - loadedBytes = 0; - progressCallback; // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type _transform(chunk, _encoding, callback) { this.push(chunk); @@ -126640,6 +126517,7 @@ class ReportTransform extends node_stream_1.Transform { } constructor(progressCallback) { super(); + this.loadedBytes = 0; this.progressCallback = progressCallback; } } @@ -126648,13 +126526,15 @@ class ReportTransform extends node_stream_1.Transform { * @internal */ class NodeHttpClient { - cachedHttpAgent; - cachedHttpsAgents = new WeakMap(); + constructor() { + this.cachedHttpsAgents = new WeakMap(); + } /** * Makes a request over an underlying transport layer and returns the response. * @param request - The request to be made. */ async sendRequest(request) { + var _a, _b, _c; const abortController = new AbortController(); let abortListener; if (request.abortSignal) { @@ -126677,7 +126557,7 @@ class NodeHttpClient { }, request.timeout); } const acceptEncoding = request.headers.get("Accept-Encoding"); - const shouldDecompress = acceptEncoding?.includes("gzip") || acceptEncoding?.includes("deflate"); + const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate")); let body = typeof request.body === "function" ? request.body() : request.body; if (body && !request.headers.has("Content-Length")) { const bodyLength = getBodyLength(body); @@ -126706,7 +126586,7 @@ class NodeHttpClient { clearTimeout(timeoutId); } const headers = getResponseHeaders(res); - const status = res.statusCode ?? 0; + const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0; const response = { status, headers, @@ -126732,8 +126612,8 @@ class NodeHttpClient { } if ( // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code - request.streamResponseStatusCodes?.has(Number.POSITIVE_INFINITY) || - request.streamResponseStatusCodes?.has(response.status)) { + ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) || + ((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status))) { response.readableStreamBody = responseStream; } else { @@ -126754,9 +126634,10 @@ class NodeHttpClient { } Promise.all([uploadStreamDone, downloadStreamDone]) .then(() => { + var _a; // eslint-disable-next-line promise/always-return if (abortListener) { - request.abortSignal?.removeEventListener("abort", abortListener); + (_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener); } }) .catch((e) => { @@ -126766,25 +126647,19 @@ class NodeHttpClient { } } makeRequest(request, abortController, body) { + var _a; const url = new URL(request.url); const isInsecure = url.protocol !== "https:"; if (isInsecure && !request.allowInsecureConnection) { throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`); } - const agent = request.agent ?? this.getOrCreateAgent(request, isInsecure); - const options = { - agent, - hostname: url.hostname, - path: `${url.pathname}${url.search}`, - port: url.port, - method: request.method, - headers: request.headers.toJSON({ preserveCase: true }), - ...request.requestOverrides, - }; + const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure); + const options = Object.assign({ agent, hostname: url.hostname, path: `${url.pathname}${url.search}`, port: url.port, method: request.method, headers: request.headers.toJSON({ preserveCase: true }) }, request.requestOverrides); return new Promise((resolve, reject) => { - const req = isInsecure ? node_http_1.default.request(options, resolve) : node_https_1.default.request(options, resolve); + const req = isInsecure ? http.request(options, resolve) : https.request(options, resolve); req.once("error", (err) => { - reject(new restError_js_1.RestError(err.message, { code: err.code ?? restError_js_1.RestError.REQUEST_SEND_ERROR, request })); + var _a; + reject(new restError_js_1.RestError(err.message, { code: (_a = err.code) !== null && _a !== void 0 ? _a : restError_js_1.RestError.REQUEST_SEND_ERROR, request })); }); abortController.signal.addEventListener("abort", () => { const abortError = new AbortError_js_1.AbortError("The operation was aborted. Rejecting from abort signal callback while making request."); @@ -126813,16 +126688,17 @@ class NodeHttpClient { }); } getOrCreateAgent(request, isInsecure) { + var _a; const disableKeepAlive = request.disableKeepAlive; // Handle Insecure requests first if (isInsecure) { if (disableKeepAlive) { // keepAlive:false is the default so we don't need a custom Agent - return node_http_1.default.globalAgent; + return http.globalAgent; } if (!this.cachedHttpAgent) { // If there is no cached agent create a new one and cache it. - this.cachedHttpAgent = new node_http_1.default.Agent({ keepAlive: true }); + this.cachedHttpAgent = new http.Agent({ keepAlive: true }); } return this.cachedHttpAgent; } @@ -126830,10 +126706,10 @@ class NodeHttpClient { if (disableKeepAlive && !request.tlsSettings) { // When there are no tlsSettings and keepAlive is false // we don't need a custom agent - return node_https_1.default.globalAgent; + return https.globalAgent; } // We use the tlsSettings to index cached clients - const tlsSettings = request.tlsSettings ?? DEFAULT_TLS_SETTINGS; + const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS; // Get the cached agent or create a new one with the // provided values for keepAlive and tlsSettings let agent = this.cachedHttpsAgents.get(tlsSettings); @@ -126841,12 +126717,9 @@ class NodeHttpClient { return agent; } log_js_1.logger.info("No cached TLS Agent exist, creating a new Agent"); - agent = new node_https_1.default.Agent({ + agent = new https.Agent(Object.assign({ // keepAlive is true if disableKeepAlive is false. - keepAlive: !disableKeepAlive, - // Since we are spreading, if no tslSettings were provided, nothing is added to the agent options. - ...tlsSettings, - }); + keepAlive: !disableKeepAlive }, tlsSettings)); this.cachedHttpsAgents.set(tlsSettings, agent); return agent; } @@ -126870,12 +126743,12 @@ function getResponseHeaders(res) { function getDecodedResponseStream(stream, headers) { const contentEncoding = headers.get("Content-Encoding"); if (contentEncoding === "gzip") { - const unzip = node_zlib_1.default.createGunzip(); + const unzip = zlib.createGunzip(); stream.pipe(unzip); return unzip; } else if (contentEncoding === "deflate") { - const inflate = node_zlib_1.default.createInflate(); + const inflate = zlib.createInflate(); stream.pipe(inflate); return inflate; } @@ -126896,7 +126769,7 @@ function streamToText(stream) { resolve(Buffer.concat(buffer).toString("utf8")); }); stream.on("error", (e) => { - if (e && e?.name === "AbortError") { + if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") { reject(e); } else { @@ -126955,10 +126828,10 @@ const ValidPhaseNames = new Set(["Deserialize", "Serialize", "Retry", "Sign"]); * @internal */ class HttpPipeline { - _policies = []; - _orderedPolicies; constructor(policies) { - this._policies = policies?.slice(0) ?? []; + var _a; + this._policies = []; + this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; this._orderedPolicies = undefined; } addPolicy(policy, options = {}) { @@ -127223,43 +127096,25 @@ exports.createPipelineRequest = createPipelineRequest; const httpHeaders_js_1 = __nccwpck_require__(4220); const uuidUtils_js_1 = __nccwpck_require__(5023); class PipelineRequestImpl { - url; - method; - headers; - timeout; - withCredentials; - body; - multipartBody; - formData; - streamResponseStatusCodes; - enableBrowserStreams; - proxySettings; - disableKeepAlive; - abortSignal; - requestId; - allowInsecureConnection; - onUploadProgress; - onDownloadProgress; - requestOverrides; - authSchemes; constructor(options) { + var _a, _b, _c, _d, _e, _f, _g; this.url = options.url; this.body = options.body; - this.headers = options.headers ?? (0, httpHeaders_js_1.createHttpHeaders)(); - this.method = options.method ?? "GET"; - this.timeout = options.timeout ?? 0; + this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : (0, httpHeaders_js_1.createHttpHeaders)(); + this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET"; + this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0; this.multipartBody = options.multipartBody; this.formData = options.formData; - this.disableKeepAlive = options.disableKeepAlive ?? false; + this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false; this.proxySettings = options.proxySettings; this.streamResponseStatusCodes = options.streamResponseStatusCodes; - this.withCredentials = options.withCredentials ?? false; + this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false; this.abortSignal = options.abortSignal; this.onUploadProgress = options.onUploadProgress; this.onDownloadProgress = options.onDownloadProgress; this.requestId = options.requestId || (0, uuidUtils_js_1.randomUUID)(); - this.allowInsecureConnection = options.allowInsecureConnection ?? false; - this.enableBrowserStreams = options.enableBrowserStreams ?? false; + this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false; + this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false; this.requestOverrides = options.requestOverrides; this.authSchemes = options.authSchemes; } @@ -127331,9 +127186,10 @@ function apiKeyAuthenticationPolicy(options) { return { name: exports.apiKeyAuthenticationPolicyName, async sendRequest(request, next) { + var _a, _b; // Ensure allowInsecureConnection is explicitly set when sending request to non-https URLs (0, checkInsecureConnection_js_1.ensureSecureConnection)(request, options); - const scheme = (request.authSchemes ?? options.authSchemes)?.find((x) => x.kind === "apiKey"); + const scheme = (_b = ((_a = request.authSchemes) !== null && _a !== void 0 ? _a : options.authSchemes)) === null || _b === void 0 ? void 0 : _b.find((x) => x.kind === "apiKey"); // Skip adding authentication header if no API key authentication scheme is found if (!scheme) { return next(request); @@ -127373,9 +127229,10 @@ function basicAuthenticationPolicy(options) { return { name: exports.basicAuthenticationPolicyName, async sendRequest(request, next) { + var _a, _b; // Ensure allowInsecureConnection is explicitly set when sending request to non-https URLs (0, checkInsecureConnection_js_1.ensureSecureConnection)(request, options); - const scheme = (request.authSchemes ?? options.authSchemes)?.find((x) => x.kind === "http" && x.scheme === "basic"); + const scheme = (_b = ((_a = request.authSchemes) !== null && _a !== void 0 ? _a : options.authSchemes)) === null || _b === void 0 ? void 0 : _b.find((x) => x.kind === "http" && x.scheme === "basic"); // Skip adding authentication header if no basic authentication scheme is found if (!scheme) { return next(request); @@ -127413,9 +127270,10 @@ function bearerAuthenticationPolicy(options) { return { name: exports.bearerAuthenticationPolicyName, async sendRequest(request, next) { + var _a, _b; // Ensure allowInsecureConnection is explicitly set when sending request to non-https URLs (0, checkInsecureConnection_js_1.ensureSecureConnection)(request, options); - const scheme = (request.authSchemes ?? options.authSchemes)?.find((x) => x.kind === "http" && x.scheme === "bearer"); + const scheme = (_b = ((_a = request.authSchemes) !== null && _a !== void 0 ? _a : options.authSchemes)) === null || _b === void 0 ? void 0 : _b.find((x) => x.kind === "http" && x.scheme === "bearer"); // Skip adding authentication header if no bearer authentication scheme is found if (!scheme) { return next(request); @@ -127469,7 +127327,7 @@ function allowInsecureConnection(request, options) { function emitInsecureConnectionWarning() { const warning = "Sending token over insecure transport. Assume any token issued is compromised."; log_js_1.logger.warning(warning); - if (typeof process?.emitWarning === "function" && !insecureConnectionWarningEmmitted) { + if (typeof (process === null || process === void 0 ? void 0 : process.emitWarning) === "function" && !insecureConnectionWarningEmmitted) { insecureConnectionWarningEmmitted = true; process.emitWarning(warning); } @@ -127514,9 +127372,10 @@ function oauth2AuthenticationPolicy(options) { return { name: exports.oauth2AuthenticationPolicyName, async sendRequest(request, next) { + var _a, _b; // Ensure allowInsecureConnection is explicitly set when sending request to non-https URLs (0, checkInsecureConnection_js_1.ensureSecureConnection)(request, options); - const scheme = (request.authSchemes ?? options.authSchemes)?.find((x) => x.kind === "oauth2"); + const scheme = (_b = ((_a = request.authSchemes) !== null && _a !== void 0 ? _a : options.authSchemes)) === null || _b === void 0 ? void 0 : _b.find((x) => x.kind === "oauth2"); // Skip adding authentication header if no OAuth2 authentication scheme is found if (!scheme) { return next(request); @@ -127592,10 +127451,11 @@ exports.defaultRetryPolicyName = "defaultRetryPolicy"; * - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay. */ function defaultRetryPolicy(options = {}) { + var _a; return { name: exports.defaultRetryPolicyName, sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)(), (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(options)], { - maxRetries: options.maxRetries ?? constants_js_1.DEFAULT_RETRY_POLICY_COUNT, + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT, }).sendRequest, }; } @@ -127625,13 +127485,11 @@ exports.exponentialRetryPolicyName = "exponentialRetryPolicy"; * @param options - Options that configure retry logic. */ function exponentialRetryPolicy(options = {}) { + var _a; return (0, retryPolicy_js_1.retryPolicy)([ - (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)({ - ...options, - ignoreSystemErrors: true, - }), + (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreSystemErrors: true })), ], { - maxRetries: options.maxRetries ?? constants_js_1.DEFAULT_RETRY_POLICY_COUNT, + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT, }); } //# sourceMappingURL=exponentialRetryPolicy.js.map @@ -127656,9 +127514,10 @@ const httpHeaders_js_1 = __nccwpck_require__(4220); */ exports.formDataPolicyName = "formDataPolicy"; function formDataToFormDataMap(formData) { + var _a; const formDataMap = {}; for (const [key, value] of formData.entries()) { - formDataMap[key] ??= []; + (_a = formDataMap[key]) !== null && _a !== void 0 ? _a : (formDataMap[key] = []); formDataMap[key].push(value); } return formDataMap; @@ -127709,7 +127568,7 @@ async function prepareFormData(formData, request) { // content type is specified and is not multipart/form-data. Exit. return; } - request.headers.set("Content-Type", contentType ?? "multipart/form-data"); + request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data"); // set body to MultipartRequestBody using content from FormDataMap const parts = []; for (const [fieldName, values] of Object.entries(formData)) { @@ -127821,7 +127680,8 @@ exports.logPolicyName = "logPolicy"; * @param options - Options to configure logPolicy. */ function logPolicy(options = {}) { - const logger = options.logger ?? log_js_1.logger.info; + var _a; + const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info; const sanitizer = new sanitizer_js_1.Sanitizer({ additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, additionalAllowedQueryParameters: options.additionalAllowedQueryParameters, @@ -127932,6 +127792,7 @@ function multipartPolicy() { return { name: exports.multipartPolicyName, async sendRequest(request, next) { + var _a; if (!request.multipartBody) { return next(request); } @@ -127939,7 +127800,7 @@ function multipartPolicy() { throw new Error("multipartBody and regular body cannot be set at the same time"); } let boundary = request.multipartBody.boundary; - const contentTypeHeader = request.headers.get("Content-Type") ?? "multipart/mixed"; + const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed"; const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/); if (!parsedHeader) { throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`); @@ -127948,7 +127809,7 @@ function multipartPolicy() { if (parsedBoundary && boundary && parsedBoundary !== boundary) { throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`); } - boundary ??= parsedBoundary; + boundary !== null && boundary !== void 0 ? boundary : (boundary = parsedBoundary); if (boundary) { assertValidBoundary(boundary); } @@ -128025,7 +127886,7 @@ function isBypassed(uri, noProxyList, bypassedMap) { return false; } const host = new URL(uri).hostname; - if (bypassedMap?.has(host)) { + if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { return bypassedMap.get(host); } let isBypassedFlag = false; @@ -128048,7 +127909,7 @@ function isBypassed(uri, noProxyList, bypassedMap) { } } } - bypassedMap?.set(host, isBypassedFlag); + bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); return isBypassedFlag; } function loadNoProxy() { @@ -128098,7 +127959,7 @@ function getUrlFromProxySettings(settings) { try { parsedProxyUrl = new URL(settings.host); } - catch { + catch (_a) { throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`); } parsedProxyUrl.port = String(settings.port); @@ -128153,9 +128014,10 @@ function proxyPolicy(proxySettings, options) { return { name: exports.proxyPolicyName, async sendRequest(request, next) { + var _a; if (!request.proxySettings && defaultProxy && - !isBypassed(request.url, options?.customNoProxyList ?? exports.globalNoProxyList, options?.customNoProxyList ? undefined : globalBypassedMap)) { + !isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : exports.globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? undefined : globalBypassedMap)) { setProxyAgentOnRequest(request, cachedAgents, defaultProxy); } else if (request.proxySettings) { @@ -128258,6 +128120,7 @@ function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_ return { name: retryPolicyName, async sendRequest(request, next) { + var _a, _b; let response; let responseError; let retryCount = -1; @@ -128281,12 +128144,12 @@ function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_ } response = responseError.response; } - if (request.abortSignal?.aborted) { + if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { logger.error(`Retry ${retryCount}: Request aborted.`); const abortError = new AbortError_js_1.AbortError(); throw abortError; } - if (retryCount >= (options.maxRetries ?? constants_js_1.DEFAULT_RETRY_POLICY_COUNT)) { + if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : constants_js_1.DEFAULT_RETRY_POLICY_COUNT)) { logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`); if (responseError) { throw responseError; @@ -128370,15 +128233,13 @@ exports.systemErrorRetryPolicyName = "systemErrorRetryPolicy"; * @param options - Options that customize the policy. */ function systemErrorRetryPolicy(options = {}) { + var _a; return { name: exports.systemErrorRetryPolicyName, sendRequest: (0, retryPolicy_js_1.retryPolicy)([ - (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)({ - ...options, - ignoreHttpStatusCodes: true, - }), + (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreHttpStatusCodes: true })), ], { - maxRetries: options.maxRetries ?? constants_js_1.DEFAULT_RETRY_POLICY_COUNT, + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT, }).sendRequest, }; } @@ -128414,10 +128275,11 @@ exports.throttlingRetryPolicyName = "throttlingRetryPolicy"; * @param options - Options that configure retry logic. */ function throttlingRetryPolicy(options = {}) { + var _a; return { name: exports.throttlingRetryPolicyName, sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)()], { - maxRetries: options.maxRetries ?? constants_js_1.DEFAULT_RETRY_POLICY_COUNT, + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT, }).sendRequest, }; } @@ -128513,39 +128375,6 @@ const errorSanitizer = new sanitizer_js_1.Sanitizer(); * A custom error type for failed pipeline requests. */ class RestError extends Error { - /** - * Something went wrong when making the request. - * This means the actual request failed for some reason, - * such as a DNS issue or the connection being lost. - */ - static REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; - /** - * This means that parsing the response from the server failed. - * It may have been malformed. - */ - static PARSE_ERROR = "PARSE_ERROR"; - /** - * The code of the error itself (use statics on RestError if possible.) - */ - code; - /** - * The HTTP status code of the request (if applicable.) - */ - statusCode; - /** - * The request that was made. - * This property is non-enumerable. - */ - request; - /** - * The response received (if any.) - * This property is non-enumerable. - */ - response; - /** - * Bonus property set by the throw site. - */ - details; constructor(message, options = {}) { super(message); this.name = "RestError"; @@ -128557,24 +128386,12 @@ class RestError extends Error { // JSON.stringify and console.log. Object.defineProperty(this, "request", { value: options.request, enumerable: false }); Object.defineProperty(this, "response", { value: options.response, enumerable: false }); - // Only include useful agent information in the request for logging, as the full agent object - // may contain large binary data. - const agent = this.request?.agent - ? { - maxFreeSockets: this.request.agent.maxFreeSockets, - maxSockets: this.request.agent.maxSockets, - } - : undefined; // Logging method for util.inspect in Node Object.defineProperty(this, inspect_js_1.custom, { value: () => { // Extract non-enumerable properties and add them back. This is OK since in this output the request and // response get sanitized. - return `RestError: ${this.message} \n ${errorSanitizer.sanitize({ - ...this, - request: { ...this.request, agent }, - response: this.response, - })}`; + return `RestError: ${this.message} \n ${errorSanitizer.sanitize(Object.assign(Object.assign({}, this), { request: this.request, response: this.response }))}`; }, enumerable: false, }); @@ -128582,6 +128399,17 @@ class RestError extends Error { } } exports.RestError = RestError; +/** + * Something went wrong when making the request. + * This means the actual request failed for some reason, + * such as a DNS issue or the connection being lost. + */ +RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; +/** + * This means that parsing the response from the server failed. + * It may have been malformed. + */ +RestError.PARSE_ERROR = "PARSE_ERROR"; /** * Typeguard for RestError * @param e - Something caught by a catch clause. @@ -128618,8 +128446,9 @@ const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64; * - Or otherwise if the outgoing request fails (408, greater or equal than 500, except for 501 and 505). */ function exponentialRetryStrategy(options = {}) { - const retryInterval = options.retryDelayInMs ?? DEFAULT_CLIENT_RETRY_INTERVAL; - const maxRetryInterval = options.maxRetryDelayInMs ?? DEFAULT_CLIENT_MAX_RETRY_INTERVAL; + var _a, _b; + const retryInterval = (_a = options.retryDelayInMs) !== null && _a !== void 0 ? _a : DEFAULT_CLIENT_RETRY_INTERVAL; + const maxRetryInterval = (_b = options.maxRetryDelayInMs) !== null && _b !== void 0 ? _b : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; return { name: "exponentialRetryStrategy", retry({ retryCount, response, responseError }) { @@ -128727,7 +128556,7 @@ function getRetryAfterInMs(response) { // negative diff would mean a date in the past, so retry asap with 0 milliseconds return Number.isFinite(diff) ? Math.max(0, diff) : undefined; } - catch { + catch (_a) { return undefined; } } @@ -128795,6 +128624,7 @@ function stringToUint8Array(value, format) { // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +var _a, _b, _c, _d; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isReactNative = exports.isNodeRuntime = exports.isNodeLike = exports.isBun = exports.isDeno = exports.isWebWorker = exports.isBrowser = void 0; /** @@ -128806,10 +128636,10 @@ exports.isBrowser = typeof window !== "undefined" && typeof window.document !== * A constant that indicates whether the environment the code is running is a Web Worker. */ exports.isWebWorker = typeof self === "object" && - typeof self?.importScripts === "function" && - (self.constructor?.name === "DedicatedWorkerGlobalScope" || - self.constructor?.name === "ServiceWorkerGlobalScope" || - self.constructor?.name === "SharedWorkerGlobalScope"); + typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && + (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || + ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || + ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); /** * A constant that indicates whether the environment the code is running is Deno. */ @@ -128825,7 +128655,7 @@ exports.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined" */ exports.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && - Boolean(globalThis.process.versions?.node); + Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node); /** * A constant that indicates whether the environment the code is running is Node.JS. */ @@ -128834,7 +128664,7 @@ exports.isNodeRuntime = exports.isNodeLike && !exports.isBun && !exports.isDeno; * A constant that indicates whether the environment the code is running is in React-Native. */ // https://github.com/facebook/react-native/blob/main/packages/react-native/Libraries/Core/setUpNavigator.js -exports.isReactNative = typeof navigator !== "undefined" && navigator?.product === "ReactNative"; +exports.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative"; //# sourceMappingURL=checkEnvironment.js.map /***/ }), @@ -128848,22 +128678,25 @@ exports.isReactNative = typeof navigator !== "undefined" && navigator?.product = // Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.concat = concat; +const tslib_1 = __nccwpck_require__(61860); const stream_1 = __nccwpck_require__(2203); const typeGuards_js_1 = __nccwpck_require__(48505); -async function* streamAsyncIterator() { - const reader = this.getReader(); - try { - while (true) { - const { done, value } = await reader.read(); - if (done) { - return; +function streamAsyncIterator() { + return tslib_1.__asyncGenerator(this, arguments, function* streamAsyncIterator_1() { + const reader = this.getReader(); + try { + while (true) { + const { done, value } = yield tslib_1.__await(reader.read()); + if (done) { + return yield tslib_1.__await(void 0); + } + yield yield tslib_1.__await(value); } - yield value; } - } - finally { - reader.releaseLock(); - } + finally { + reader.releaseLock(); + } + }); } function makeAsyncIterable(webStream) { if (!webStream[Symbol.asyncIterator]) { @@ -128905,12 +128738,27 @@ function toStream(source) { async function concat(sources) { return function () { const streams = sources.map((x) => (typeof x === "function" ? x() : x)).map(toStream); - return stream_1.Readable.from((async function* () { - for (const stream of streams) { - for await (const chunk of stream) { - yield chunk; + return stream_1.Readable.from((function () { + return tslib_1.__asyncGenerator(this, arguments, function* () { + var _a, e_1, _b, _c; + for (const stream of streams) { + try { + for (var _d = true, stream_2 = (e_1 = void 0, tslib_1.__asyncValues(stream)), stream_2_1; stream_2_1 = yield tslib_1.__await(stream_2.next()), _a = stream_2_1.done, !_a; _d = true) { + _c = stream_2_1.value; + _d = false; + const chunk = _c; + yield yield tslib_1.__await(chunk); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_d && !_a && (_b = stream_2.return)) yield tslib_1.__await(_b.call(stream_2)); + } + finally { if (e_1) throw e_1.error; } + } } - } + }); })()); }; } @@ -129000,10 +128848,10 @@ function delay(delayInMs, value, options) { let timer = undefined; let onAborted = undefined; const rejectOnAbort = () => { - return reject(new AbortError_js_1.AbortError(options?.abortErrorMsg ? options?.abortErrorMsg : StandardAbortMessage)); + return reject(new AbortError_js_1.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage)); }; const removeListeners = () => { - if (options?.abortSignal && onAborted) { + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) { options.abortSignal.removeEventListener("abort", onAborted); } }; @@ -129014,14 +128862,14 @@ function delay(delayInMs, value, options) { removeListeners(); return rejectOnAbort(); }; - if (options?.abortSignal && options.abortSignal.aborted) { + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) { return rejectOnAbort(); } timer = setTimeout(() => { removeListeners(); resolve(value); }, delayInMs); - if (options?.abortSignal) { + if (options === null || options === void 0 ? void 0 : options.abortSignal) { options.abortSignal.addEventListener("abort", onAborted); } }); @@ -129210,8 +129058,6 @@ const defaultAllowedQueryParameters = ["api-version"]; * A utility class to sanitize objects for logging. */ class Sanitizer { - allowedHeaderNames; - allowedQueryParameters; constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [], } = {}) { allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); @@ -129228,11 +129074,7 @@ class Sanitizer { return JSON.stringify(obj, (key, value) => { // Ensure Errors include their interesting non-enumerable members if (value instanceof Error) { - return { - ...value, - name: value.name, - message: value.message, - }; + return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); } if (key === "headers") { return this.sanitizeHeaders(value); @@ -129441,8 +129283,8 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getHeaderName = getHeaderName; exports.setPlatformSpecificData = setPlatformSpecificData; const tslib_1 = __nccwpck_require__(61860); -const node_os_1 = tslib_1.__importDefault(__nccwpck_require__(48161)); -const node_process_1 = tslib_1.__importDefault(__nccwpck_require__(1708)); +const os = tslib_1.__importStar(__nccwpck_require__(48161)); +const process = tslib_1.__importStar(__nccwpck_require__(1708)); /** * @internal */ @@ -129453,8 +129295,8 @@ function getHeaderName() { * @internal */ async function setPlatformSpecificData(map) { - if (node_process_1.default && node_process_1.default.versions) { - const versions = node_process_1.default.versions; + if (process && process.versions) { + const versions = process.versions; if (versions.bun) { map.set("Bun", versions.bun); } @@ -129465,7 +129307,7 @@ async function setPlatformSpecificData(map) { map.set("Node", versions.node); } } - map.set("OS", `(${node_os_1.default.arch()}-${node_os_1.default.type()}-${node_os_1.default.release()})`); + map.set("OS", `(${os.arch()}-${os.type()}-${os.release()})`); } //# sourceMappingURL=userAgentPlatform.js.map @@ -129478,11 +129320,12 @@ async function setPlatformSpecificData(map) { // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +var _a; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.randomUUID = randomUUID; const node_crypto_1 = __nccwpck_require__(77598); // NOTE: This is a workaround until we can use `globalThis.crypto.randomUUID` in Node.js 19+. -const uuidFunction = typeof globalThis?.crypto?.randomUUID === "function" +const uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : node_crypto_1.randomUUID; /** @@ -137703,7 +137546,7 @@ module.exports = index; /***/ 50591: /***/ ((module) => { -(()=>{"use strict";var t={d:(e,n)=>{for(var i in n)t.o(n,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:n[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{XMLBuilder:()=>lt,XMLParser:()=>tt,XMLValidator:()=>pt});const n=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",i=new RegExp("^["+n+"]["+n+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function r(t,e){const n=[];let i=e.exec(t);for(;i;){const r=[];r.startIndex=e.lastIndex-i[0].length;const s=i.length;for(let t=0;t"!==t[o]&&" "!==t[o]&&"\t"!==t[o]&&"\n"!==t[o]&&"\r"!==t[o];o++)p+=t[o];if(p=p.trim(),"/"===p[p.length-1]&&(p=p.substring(0,p.length-1),o--),!s(p)){let e;return e=0===p.trim().length?"Invalid space after '<'.":"Tag '"+p+"' is an invalid name.",x("InvalidTag",e,N(t,o))}const c=f(t,o);if(!1===c)return x("InvalidAttr","Attributes for '"+p+"' have open quote.",N(t,o));let b=c.value;if(o=c.index,"/"===b[b.length-1]){const n=o-b.length;b=b.substring(0,b.length-1);const r=g(b,e);if(!0!==r)return x(r.err.code,r.err.msg,N(t,n+r.err.line));i=!0}else if(d){if(!c.tagClosed)return x("InvalidTag","Closing tag '"+p+"' doesn't have proper closing.",N(t,o));if(b.trim().length>0)return x("InvalidTag","Closing tag '"+p+"' can't have attributes or invalid starting.",N(t,a));if(0===n.length)return x("InvalidTag","Closing tag '"+p+"' has not been opened.",N(t,a));{const e=n.pop();if(p!==e.tagName){let n=N(t,e.tagStartPos);return x("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+n.line+", col "+n.col+") instead of closing tag '"+p+"'.",N(t,a))}0==n.length&&(r=!0)}}else{const s=g(b,e);if(!0!==s)return x(s.err.code,s.err.msg,N(t,o-b.length+s.err.line));if(!0===r)return x("InvalidXml","Multiple possible root nodes found.",N(t,o));-1!==e.unpairedTags.indexOf(p)||n.push({tagName:p,tagStartPos:a}),i=!0}for(o++;o0)||x("InvalidXml","Invalid '"+JSON.stringify(n.map((t=>t.tagName)),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):x("InvalidXml","Start tag expected.",1)}function l(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function u(t,e){const n=e;for(;e5&&"xml"===i)return x("InvalidXml","XML declaration allowed only at the start of the document.",N(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}}return e}function h(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){let n=1;for(e+=8;e"===t[e]&&(n--,0===n))break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e"===t[e+2]){e+=2;break}return e}const d='"',p="'";function f(t,e){let n="",i="",r=!1;for(;e"===t[e]&&""===i){r=!0;break}n+=t[e]}return""===i&&{value:n,index:e,tagClosed:r}}const c=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function g(t,e){const n=r(t,c),i={};for(let t=0;t!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,n){return t},captureMetaData:!1};let T;T="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class y{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}add(t,e){"__proto__"===t&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){"__proto__"===t.tagname&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),void 0!==e&&(this.child[this.child.length-1][T]={startIndex:e})}static getMetaDataSymbol(){return T}}class w{constructor(t){this.suppressValidationErr=!t}readDocType(t,e){const n={};if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");{e+=9;let i=1,r=!1,s=!1,o="";for(;e"===t[e]){if(s?"-"===t[e-1]&&"-"===t[e-2]&&(s=!1,i--):i--,0===i)break}else"["===t[e]?r=!0:o+=t[e];else{if(r&&P(t,"!ENTITY",e)){let i,r;e+=7,[i,r,e]=this.readEntityExp(t,e+1,this.suppressValidationErr),-1===r.indexOf("&")&&(n[i]={regx:RegExp(`&${i};`,"g"),val:r})}else if(r&&P(t,"!ELEMENT",e)){e+=8;const{index:n}=this.readElementExp(t,e+1);e=n}else if(r&&P(t,"!ATTLIST",e))e+=8;else if(r&&P(t,"!NOTATION",e)){e+=9;const{index:n}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=n}else{if(!P(t,"!--",e))throw new Error("Invalid DOCTYPE");s=!0}i++,o=""}if(0!==i)throw new Error("Unclosed DOCTYPE")}return{entities:n,i:e}}readEntityExp(t,e){e=I(t,e);let n="";for(;e{for(;e{for(const n of t){if("string"==typeof n&&e===n)return!0;if(n instanceof RegExp&&n.test(e))return!0}}:()=>!1}class D{constructor(t){this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(t,e)=>String.fromCodePoint(Number.parseInt(e,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(t,e)=>String.fromCodePoint(Number.parseInt(e,16))}},this.addExternalEntities=j,this.parseXml=L,this.parseTextData=M,this.resolveNameSpace=F,this.buildAttributesMap=k,this.isItStopNode=Y,this.replaceEntitiesValue=B,this.readStopNodeData=q,this.saveTextToParentTag=R,this.addChild=U,this.ignoreAttributesFn=$(this.options.ignoreAttributes)}}function j(t){const e=Object.keys(t);for(let n=0;n0)){o||(t=this.replaceEntitiesValue(t));const i=this.options.tagValueProcessor(e,t,n,r,s);return null==i?t:typeof i!=typeof t||i!==t?i:this.options.trimValues||t.trim()===t?Z(t,this.options.parseTagValue,this.options.numberParseOptions):t}}function F(t){if(this.options.removeNSPrefix){const e=t.split(":"),n="/"===t.charAt(0)?"/":"";if("xmlns"===e[0])return"";2===e.length&&(t=n+e[1])}return t}const _=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function k(t,e,n){if(!0!==this.options.ignoreAttributes&&"string"==typeof t){const n=r(t,_),i=n.length,s={};for(let t=0;t",o,"Closing Tag is not closed.");let s=t.substring(o+2,e).trim();if(this.options.removeNSPrefix){const t=s.indexOf(":");-1!==t&&(s=s.substr(t+1))}this.options.transformTagName&&(s=this.options.transformTagName(s)),n&&(i=this.saveTextToParentTag(i,n,r));const a=r.substring(r.lastIndexOf(".")+1);if(s&&-1!==this.options.unpairedTags.indexOf(s))throw new Error(`Unpaired tag can not be used as closing tag: `);let l=0;a&&-1!==this.options.unpairedTags.indexOf(a)?(l=r.lastIndexOf(".",r.lastIndexOf(".")-1),this.tagsNodeStack.pop()):l=r.lastIndexOf("."),r=r.substring(0,l),n=this.tagsNodeStack.pop(),i="",o=e}else if("?"===t[o+1]){let e=X(t,o,!1,"?>");if(!e)throw new Error("Pi Tag is not closed.");if(i=this.saveTextToParentTag(i,n,r),this.options.ignoreDeclaration&&"?xml"===e.tagName||this.options.ignorePiTags);else{const t=new y(e.tagName);t.add(this.options.textNodeName,""),e.tagName!==e.tagExp&&e.attrExpPresent&&(t[":@"]=this.buildAttributesMap(e.tagExp,r,e.tagName)),this.addChild(n,t,r,o)}o=e.closeIndex+1}else if("!--"===t.substr(o+1,3)){const e=G(t,"--\x3e",o+4,"Comment is not closed.");if(this.options.commentPropName){const s=t.substring(o+4,e-2);i=this.saveTextToParentTag(i,n,r),n.add(this.options.commentPropName,[{[this.options.textNodeName]:s}])}o=e}else if("!D"===t.substr(o+1,2)){const e=s.readDocType(t,o);this.docTypeEntities=e.entities,o=e.i}else if("!["===t.substr(o+1,2)){const e=G(t,"]]>",o,"CDATA is not closed.")-2,s=t.substring(o+9,e);i=this.saveTextToParentTag(i,n,r);let a=this.parseTextData(s,n.tagname,r,!0,!1,!0,!0);null==a&&(a=""),this.options.cdataPropName?n.add(this.options.cdataPropName,[{[this.options.textNodeName]:s}]):n.add(this.options.textNodeName,a),o=e+2}else{let s=X(t,o,this.options.removeNSPrefix),a=s.tagName;const l=s.rawTagName;let u=s.tagExp,h=s.attrExpPresent,d=s.closeIndex;this.options.transformTagName&&(a=this.options.transformTagName(a)),n&&i&&"!xml"!==n.tagname&&(i=this.saveTextToParentTag(i,n,r,!1));const p=n;p&&-1!==this.options.unpairedTags.indexOf(p.tagname)&&(n=this.tagsNodeStack.pop(),r=r.substring(0,r.lastIndexOf("."))),a!==e.tagname&&(r+=r?"."+a:a);const f=o;if(this.isItStopNode(this.options.stopNodes,r,a)){let e="";if(u.length>0&&u.lastIndexOf("/")===u.length-1)"/"===a[a.length-1]?(a=a.substr(0,a.length-1),r=r.substr(0,r.length-1),u=a):u=u.substr(0,u.length-1),o=s.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(a))o=s.closeIndex;else{const n=this.readStopNodeData(t,l,d+1);if(!n)throw new Error(`Unexpected end of ${l}`);o=n.i,e=n.tagContent}const i=new y(a);a!==u&&h&&(i[":@"]=this.buildAttributesMap(u,r,a)),e&&(e=this.parseTextData(e,a,r,!0,h,!0,!0)),r=r.substr(0,r.lastIndexOf(".")),i.add(this.options.textNodeName,e),this.addChild(n,i,r,f)}else{if(u.length>0&&u.lastIndexOf("/")===u.length-1){"/"===a[a.length-1]?(a=a.substr(0,a.length-1),r=r.substr(0,r.length-1),u=a):u=u.substr(0,u.length-1),this.options.transformTagName&&(a=this.options.transformTagName(a));const t=new y(a);a!==u&&h&&(t[":@"]=this.buildAttributesMap(u,r,a)),this.addChild(n,t,r,f),r=r.substr(0,r.lastIndexOf("."))}else{const t=new y(a);this.tagsNodeStack.push(n),a!==u&&h&&(t[":@"]=this.buildAttributesMap(u,r,a)),this.addChild(n,t,r,f),n=t}i="",o=d}}else i+=t[o];return e.child};function U(t,e,n,i){this.options.captureMetaData||(i=void 0);const r=this.options.updateTag(e.tagname,n,e[":@"]);!1===r||("string"==typeof r?(e.tagname=r,t.addChild(e,i)):t.addChild(e,i))}const B=function(t){if(this.options.processEntities){for(let e in this.docTypeEntities){const n=this.docTypeEntities[e];t=t.replace(n.regx,n.val)}for(let e in this.lastEntities){const n=this.lastEntities[e];t=t.replace(n.regex,n.val)}if(this.options.htmlEntities)for(let e in this.htmlEntities){const n=this.htmlEntities[e];t=t.replace(n.regex,n.val)}t=t.replace(this.ampEntity.regex,this.ampEntity.val)}return t};function R(t,e,n,i){return t&&(void 0===i&&(i=0===e.child.length),void 0!==(t=this.parseTextData(t,e.tagname,n,!1,!!e[":@"]&&0!==Object.keys(e[":@"]).length,i))&&""!==t&&e.add(this.options.textNodeName,t),t=""),t}function Y(t,e,n){const i="*."+n;for(const n in t){const r=t[n];if(i===r||e===r)return!0}return!1}function G(t,e,n,i){const r=t.indexOf(e,n);if(-1===r)throw new Error(i);return r+e.length-1}function X(t,e,n,i=">"){const r=function(t,e,n=">"){let i,r="";for(let s=e;s",n,`${e} is not closed`);if(t.substring(n+2,s).trim()===e&&(r--,0===r))return{tagContent:t.substring(i,n),i:s};n=s}else if("?"===t[n+1])n=G(t,"?>",n+1,"StopNode is not closed.");else if("!--"===t.substr(n+1,3))n=G(t,"--\x3e",n+3,"StopNode is not closed.");else if("!["===t.substr(n+1,2))n=G(t,"]]>",n,"StopNode is not closed.")-2;else{const i=X(t,n,">");i&&((i&&i.tagName)===e&&"/"!==i.tagExp[i.tagExp.length-1]&&r++,n=i.closeIndex)}}function Z(t,e,n){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&function(t,e={}){if(e=Object.assign({},C,e),!t||"string"!=typeof t)return t;let n=t.trim();if(void 0!==e.skipLike&&e.skipLike.test(n))return t;if("0"===t)return 0;if(e.hex&&A.test(n))return function(t){if(parseInt)return parseInt(t,16);if(Number.parseInt)return Number.parseInt(t,16);if(window&&window.parseInt)return window.parseInt(t,16);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(n);if(-1!==n.search(/.+[eE].+/))return function(t,e,n){if(!n.eNotation)return t;const i=e.match(V);if(i){let r=i[1]||"";const s=-1===i[3].indexOf("e")?"E":"e",o=i[2],a=r?t[o.length+1]===s:t[o.length]===s;return o.length>1&&a?t:1!==o.length||!i[3].startsWith(`.${s}`)&&i[3][0]!==s?n.leadingZeros&&!a?(e=(i[1]||"")+i[3],Number(e)):t:Number(e)}return t}(t,n,e);{const r=S.exec(n);if(r){const s=r[1]||"",o=r[2];let a=(i=r[3])&&-1!==i.indexOf(".")?("."===(i=i.replace(/0+$/,""))?i="0":"."===i[0]?i="0"+i:"."===i[i.length-1]&&(i=i.substring(0,i.length-1)),i):i;const l=s?"."===t[o.length+1]:"."===t[o.length];if(!e.leadingZeros&&(o.length>1||1===o.length&&!l))return t;{const i=Number(n),r=String(i);if(0===i||-0===i)return i;if(-1!==r.search(/[eE]/))return e.eNotation?i:t;if(-1!==n.indexOf("."))return"0"===r||r===a||r===`${s}${a}`?i:t;let l=o?a:n;return o?l===r||s+l===r?i:t:l===r||l===s+r?i:t}}return t}var i}(t,n)}return void 0!==t?t:""}const W=y.getMetaDataSymbol();function K(t,e){return Q(t,e)}function Q(t,e,n){let i;const r={};for(let s=0;s0&&(r[e.textNodeName]=i):void 0!==i&&(r[e.textNodeName]=i),r}function z(t){const e=Object.keys(t);for(let t=0;t0&&(n="\n"),nt(t,e,"",n)}function nt(t,e,n,i){let r="",s=!1;for(let o=0;o`,s=!1;continue}if(l===e.commentPropName){r+=i+`\x3c!--${a[l][0][e.textNodeName]}--\x3e`,s=!0;continue}if("?"===l[0]){const t=rt(a[":@"],e),n="?xml"===l?"":i;let o=a[l][0][e.textNodeName];o=0!==o.length?" "+o:"",r+=n+`<${l}${o}${t}?>`,s=!0;continue}let h=i;""!==h&&(h+=e.indentBy);const d=i+`<${l}${rt(a[":@"],e)}`,p=nt(a[l],e,u,h);-1!==e.unpairedTags.indexOf(l)?e.suppressUnpairedNode?r+=d+">":r+=d+"/>":p&&0!==p.length||!e.suppressEmptyNode?p&&p.endsWith(">")?r+=d+`>${p}${i}`:(r+=d+">",p&&""!==i&&(p.includes("/>")||p.includes("`):r+=d+"/>",s=!0}return r}function it(t){const e=Object.keys(t);for(let n=0;n0&&e.processEntities)for(let n=0;n","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function lt(t){this.options=Object.assign({},at,t),!0===this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=$(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=dt),this.processTextOrObjNode=ut,this.options.format?(this.indentate=ht,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function ut(t,e,n,i){const r=this.j2x(t,n+1,i.concat(e));return void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,r.attrStr,n):this.buildObjectNode(r.val,e,r.attrStr,n)}function ht(t){return this.options.indentBy.repeat(t)}function dt(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}lt.prototype.build=function(t){return this.options.preserveOrder?et(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0,[]).val)},lt.prototype.j2x=function(t,e,n){let i="",r="";const s=n.join(".");for(let o in t)if(Object.prototype.hasOwnProperty.call(t,o))if(void 0===t[o])this.isAttribute(o)&&(r+="");else if(null===t[o])this.isAttribute(o)||o===this.options.cdataPropName?r+="":"?"===o[0]?r+=this.indentate(e)+"<"+o+"?"+this.tagEndChar:r+=this.indentate(e)+"<"+o+"/"+this.tagEndChar;else if(t[o]instanceof Date)r+=this.buildTextValNode(t[o],o,"",e);else if("object"!=typeof t[o]){const n=this.isAttribute(o);if(n&&!this.ignoreAttributesFn(n,s))i+=this.buildAttrPairStr(n,""+t[o]);else if(!n)if(o===this.options.textNodeName){let e=this.options.tagValueProcessor(o,""+t[o]);r+=this.replaceEntitiesValue(e)}else r+=this.buildTextValNode(t[o],o,"",e)}else if(Array.isArray(t[o])){const i=t[o].length;let s="",a="";for(let l=0;l"+t+r}},lt.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`>`+this.newLine;if(!1!==this.options.commentPropName&&e===this.options.commentPropName)return this.indentate(i)+`\x3c!--${t}--\x3e`+this.newLine;if("?"===e[0])return this.indentate(i)+"<"+e+n+"?"+this.tagEndChar;{let r=this.options.tagValueProcessor(e,t);return r=this.replaceEntitiesValue(r),""===r?this.indentate(i)+"<"+e+n+this.closeTag(e)+this.tagEndChar:this.indentate(i)+"<"+e+n+">"+r+"0&&this.options.processEntities)for(let e=0;e{"use strict";var t={d:(e,n)=>{for(var i in n)t.o(n,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:n[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{XMLBuilder:()=>ft,XMLParser:()=>st,XMLValidator:()=>mt});const n=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",i=new RegExp("^["+n+"]["+n+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function s(t,e){const n=[];let i=e.exec(t);for(;i;){const s=[];s.startIndex=e.lastIndex-i[0].length;const r=i.length;for(let t=0;t"!==t[o]&&" "!==t[o]&&"\t"!==t[o]&&"\n"!==t[o]&&"\r"!==t[o];o++)f+=t[o];if(f=f.trim(),"/"===f[f.length-1]&&(f=f.substring(0,f.length-1),o--),!r(f)){let e;return e=0===f.trim().length?"Invalid space after '<'.":"Tag '"+f+"' is an invalid name.",x("InvalidTag",e,N(t,o))}const p=c(t,o);if(!1===p)return x("InvalidAttr","Attributes for '"+f+"' have open quote.",N(t,o));let b=p.value;if(o=p.index,"/"===b[b.length-1]){const n=o-b.length;b=b.substring(0,b.length-1);const s=g(b,e);if(!0!==s)return x(s.err.code,s.err.msg,N(t,n+s.err.line));i=!0}else if(d){if(!p.tagClosed)return x("InvalidTag","Closing tag '"+f+"' doesn't have proper closing.",N(t,o));if(b.trim().length>0)return x("InvalidTag","Closing tag '"+f+"' can't have attributes or invalid starting.",N(t,a));if(0===n.length)return x("InvalidTag","Closing tag '"+f+"' has not been opened.",N(t,a));{const e=n.pop();if(f!==e.tagName){let n=N(t,e.tagStartPos);return x("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+n.line+", col "+n.col+") instead of closing tag '"+f+"'.",N(t,a))}0==n.length&&(s=!0)}}else{const r=g(b,e);if(!0!==r)return x(r.err.code,r.err.msg,N(t,o-b.length+r.err.line));if(!0===s)return x("InvalidXml","Multiple possible root nodes found.",N(t,o));-1!==e.unpairedTags.indexOf(f)||n.push({tagName:f,tagStartPos:a}),i=!0}for(o++;o0)||x("InvalidXml","Invalid '"+JSON.stringify(n.map((t=>t.tagName)),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):x("InvalidXml","Start tag expected.",1)}function l(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function u(t,e){const n=e;for(;e5&&"xml"===i)return x("InvalidXml","XML declaration allowed only at the start of the document.",N(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}}return e}function h(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){let n=1;for(e+=8;e"===t[e]&&(n--,0===n))break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e"===t[e+2]){e+=2;break}return e}const d='"',f="'";function c(t,e){let n="",i="",s=!1;for(;e"===t[e]&&""===i){s=!0;break}n+=t[e]}return""===i&&{value:n,index:e,tagClosed:s}}const p=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function g(t,e){const n=s(t,p),i={};for(let t=0;t!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,n){return t},captureMetaData:!1};let y;y="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class T{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}add(t,e){"__proto__"===t&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){"__proto__"===t.tagname&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),void 0!==e&&(this.child[this.child.length-1][y]={startIndex:e})}static getMetaDataSymbol(){return y}}function w(t,e){const n={};if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");{e+=9;let i=1,s=!1,r=!1,o="";for(;e"===t[e]){if(r?"-"===t[e-1]&&"-"===t[e-2]&&(r=!1,i--):i--,0===i)break}else"["===t[e]?s=!0:o+=t[e];else{if(s&&C(t,"!ENTITY",e)){let i,s;e+=7,[i,s,e]=O(t,e+1),-1===s.indexOf("&")&&(n[i]={regx:RegExp(`&${i};`,"g"),val:s})}else if(s&&C(t,"!ELEMENT",e)){e+=8;const{index:n}=S(t,e+1);e=n}else if(s&&C(t,"!ATTLIST",e))e+=8;else if(s&&C(t,"!NOTATION",e)){e+=9;const{index:n}=A(t,e+1);e=n}else{if(!C(t,"!--",e))throw new Error("Invalid DOCTYPE");r=!0}i++,o=""}if(0!==i)throw new Error("Unclosed DOCTYPE")}return{entities:n,i:e}}const P=(t,e)=>{for(;e{for(const n of t){if("string"==typeof n&&e===n)return!0;if(n instanceof RegExp&&n.test(e))return!0}}:()=>!1}class k{constructor(t){this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(t,e)=>String.fromCodePoint(Number.parseInt(e,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(t,e)=>String.fromCodePoint(Number.parseInt(e,16))}},this.addExternalEntities=F,this.parseXml=X,this.parseTextData=L,this.resolveNameSpace=B,this.buildAttributesMap=G,this.isItStopNode=Z,this.replaceEntitiesValue=R,this.readStopNodeData=J,this.saveTextToParentTag=q,this.addChild=Y,this.ignoreAttributesFn=_(this.options.ignoreAttributes)}}function F(t){const e=Object.keys(t);for(let n=0;n0)){o||(t=this.replaceEntitiesValue(t));const i=this.options.tagValueProcessor(e,t,n,s,r);return null==i?t:typeof i!=typeof t||i!==t?i:this.options.trimValues||t.trim()===t?H(t,this.options.parseTagValue,this.options.numberParseOptions):t}}function B(t){if(this.options.removeNSPrefix){const e=t.split(":"),n="/"===t.charAt(0)?"/":"";if("xmlns"===e[0])return"";2===e.length&&(t=n+e[1])}return t}const U=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function G(t,e,n){if(!0!==this.options.ignoreAttributes&&"string"==typeof t){const n=s(t,U),i=n.length,r={};for(let t=0;t",r,"Closing Tag is not closed.");let o=t.substring(r+2,e).trim();if(this.options.removeNSPrefix){const t=o.indexOf(":");-1!==t&&(o=o.substr(t+1))}this.options.transformTagName&&(o=this.options.transformTagName(o)),n&&(i=this.saveTextToParentTag(i,n,s));const a=s.substring(s.lastIndexOf(".")+1);if(o&&-1!==this.options.unpairedTags.indexOf(o))throw new Error(`Unpaired tag can not be used as closing tag: `);let l=0;a&&-1!==this.options.unpairedTags.indexOf(a)?(l=s.lastIndexOf(".",s.lastIndexOf(".")-1),this.tagsNodeStack.pop()):l=s.lastIndexOf("."),s=s.substring(0,l),n=this.tagsNodeStack.pop(),i="",r=e}else if("?"===t[r+1]){let e=z(t,r,!1,"?>");if(!e)throw new Error("Pi Tag is not closed.");if(i=this.saveTextToParentTag(i,n,s),this.options.ignoreDeclaration&&"?xml"===e.tagName||this.options.ignorePiTags);else{const t=new T(e.tagName);t.add(this.options.textNodeName,""),e.tagName!==e.tagExp&&e.attrExpPresent&&(t[":@"]=this.buildAttributesMap(e.tagExp,s,e.tagName)),this.addChild(n,t,s,r)}r=e.closeIndex+1}else if("!--"===t.substr(r+1,3)){const e=W(t,"--\x3e",r+4,"Comment is not closed.");if(this.options.commentPropName){const o=t.substring(r+4,e-2);i=this.saveTextToParentTag(i,n,s),n.add(this.options.commentPropName,[{[this.options.textNodeName]:o}])}r=e}else if("!D"===t.substr(r+1,2)){const e=w(t,r);this.docTypeEntities=e.entities,r=e.i}else if("!["===t.substr(r+1,2)){const e=W(t,"]]>",r,"CDATA is not closed.")-2,o=t.substring(r+9,e);i=this.saveTextToParentTag(i,n,s);let a=this.parseTextData(o,n.tagname,s,!0,!1,!0,!0);null==a&&(a=""),this.options.cdataPropName?n.add(this.options.cdataPropName,[{[this.options.textNodeName]:o}]):n.add(this.options.textNodeName,a),r=e+2}else{let o=z(t,r,this.options.removeNSPrefix),a=o.tagName;const l=o.rawTagName;let u=o.tagExp,h=o.attrExpPresent,d=o.closeIndex;this.options.transformTagName&&(a=this.options.transformTagName(a)),n&&i&&"!xml"!==n.tagname&&(i=this.saveTextToParentTag(i,n,s,!1));const f=n;f&&-1!==this.options.unpairedTags.indexOf(f.tagname)&&(n=this.tagsNodeStack.pop(),s=s.substring(0,s.lastIndexOf("."))),a!==e.tagname&&(s+=s?"."+a:a);const c=r;if(this.isItStopNode(this.options.stopNodes,s,a)){let e="";if(u.length>0&&u.lastIndexOf("/")===u.length-1)"/"===a[a.length-1]?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),u=a):u=u.substr(0,u.length-1),r=o.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(a))r=o.closeIndex;else{const n=this.readStopNodeData(t,l,d+1);if(!n)throw new Error(`Unexpected end of ${l}`);r=n.i,e=n.tagContent}const i=new T(a);a!==u&&h&&(i[":@"]=this.buildAttributesMap(u,s,a)),e&&(e=this.parseTextData(e,a,s,!0,h,!0,!0)),s=s.substr(0,s.lastIndexOf(".")),i.add(this.options.textNodeName,e),this.addChild(n,i,s,c)}else{if(u.length>0&&u.lastIndexOf("/")===u.length-1){"/"===a[a.length-1]?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),u=a):u=u.substr(0,u.length-1),this.options.transformTagName&&(a=this.options.transformTagName(a));const t=new T(a);a!==u&&h&&(t[":@"]=this.buildAttributesMap(u,s,a)),this.addChild(n,t,s,c),s=s.substr(0,s.lastIndexOf("."))}else{const t=new T(a);this.tagsNodeStack.push(n),a!==u&&h&&(t[":@"]=this.buildAttributesMap(u,s,a)),this.addChild(n,t,s,c),n=t}i="",r=d}}else i+=t[r];return e.child};function Y(t,e,n,i){this.options.captureMetaData||(i=void 0);const s=this.options.updateTag(e.tagname,n,e[":@"]);!1===s||("string"==typeof s?(e.tagname=s,t.addChild(e,i)):t.addChild(e,i))}const R=function(t){if(this.options.processEntities){for(let e in this.docTypeEntities){const n=this.docTypeEntities[e];t=t.replace(n.regx,n.val)}for(let e in this.lastEntities){const n=this.lastEntities[e];t=t.replace(n.regex,n.val)}if(this.options.htmlEntities)for(let e in this.htmlEntities){const n=this.htmlEntities[e];t=t.replace(n.regex,n.val)}t=t.replace(this.ampEntity.regex,this.ampEntity.val)}return t};function q(t,e,n,i){return t&&(void 0===i&&(i=0===e.child.length),void 0!==(t=this.parseTextData(t,e.tagname,n,!1,!!e[":@"]&&0!==Object.keys(e[":@"]).length,i))&&""!==t&&e.add(this.options.textNodeName,t),t=""),t}function Z(t,e,n){const i="*."+n;for(const n in t){const s=t[n];if(i===s||e===s)return!0}return!1}function W(t,e,n,i){const s=t.indexOf(e,n);if(-1===s)throw new Error(i);return s+e.length-1}function z(t,e,n,i=">"){const s=function(t,e,n=">"){let i,s="";for(let r=e;r",n,`${e} is not closed`);if(t.substring(n+2,r).trim()===e&&(s--,0===s))return{tagContent:t.substring(i,n),i:r};n=r}else if("?"===t[n+1])n=W(t,"?>",n+1,"StopNode is not closed.");else if("!--"===t.substr(n+1,3))n=W(t,"--\x3e",n+3,"StopNode is not closed.");else if("!["===t.substr(n+1,2))n=W(t,"]]>",n,"StopNode is not closed.")-2;else{const i=z(t,n,">");i&&((i&&i.tagName)===e&&"/"!==i.tagExp[i.tagExp.length-1]&&s++,n=i.closeIndex)}}function H(t,e,n){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&function(t,e={}){if(e=Object.assign({},V,e),!t||"string"!=typeof t)return t;let n=t.trim();if(void 0!==e.skipLike&&e.skipLike.test(n))return t;if("0"===t)return 0;if(e.hex&&j.test(n))return function(t){if(parseInt)return parseInt(t,16);if(Number.parseInt)return Number.parseInt(t,16);if(window&&window.parseInt)return window.parseInt(t,16);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(n);if(-1!==n.search(/.+[eE].+/))return function(t,e,n){if(!n.eNotation)return t;const i=e.match(M);if(i){let s=i[1]||"";const r=-1===i[3].indexOf("e")?"E":"e",o=i[2],a=s?t[o.length+1]===r:t[o.length]===r;return o.length>1&&a?t:1!==o.length||!i[3].startsWith(`.${r}`)&&i[3][0]!==r?n.leadingZeros&&!a?(e=(i[1]||"")+i[3],Number(e)):t:Number(e)}return t}(t,n,e);{const s=D.exec(n);if(s){const r=s[1]||"",o=s[2];let a=(i=s[3])&&-1!==i.indexOf(".")?("."===(i=i.replace(/0+$/,""))?i="0":"."===i[0]?i="0"+i:"."===i[i.length-1]&&(i=i.substring(0,i.length-1)),i):i;const l=r?"."===t[o.length+1]:"."===t[o.length];if(!e.leadingZeros&&(o.length>1||1===o.length&&!l))return t;{const i=Number(n),s=String(i);if(0===i||-0===i)return i;if(-1!==s.search(/[eE]/))return e.eNotation?i:t;if(-1!==n.indexOf("."))return"0"===s||s===a||s===`${r}${a}`?i:t;let l=o?a:n;return o?l===s||r+l===s?i:t:l===s||l===r+s?i:t}}return t}var i}(t,n)}return void 0!==t?t:""}const K=T.getMetaDataSymbol();function Q(t,e){return tt(t,e)}function tt(t,e,n){let i;const s={};for(let r=0;r0&&(s[e.textNodeName]=i):void 0!==i&&(s[e.textNodeName]=i),s}function et(t){const e=Object.keys(t);for(let t=0;t0&&(n="\n"),ot(t,e,"",n)}function ot(t,e,n,i){let s="",r=!1;for(let o=0;o`,r=!1;continue}if(l===e.commentPropName){s+=i+`\x3c!--${a[l][0][e.textNodeName]}--\x3e`,r=!0;continue}if("?"===l[0]){const t=lt(a[":@"],e),n="?xml"===l?"":i;let o=a[l][0][e.textNodeName];o=0!==o.length?" "+o:"",s+=n+`<${l}${o}${t}?>`,r=!0;continue}let h=i;""!==h&&(h+=e.indentBy);const d=i+`<${l}${lt(a[":@"],e)}`,f=ot(a[l],e,u,h);-1!==e.unpairedTags.indexOf(l)?e.suppressUnpairedNode?s+=d+">":s+=d+"/>":f&&0!==f.length||!e.suppressEmptyNode?f&&f.endsWith(">")?s+=d+`>${f}${i}`:(s+=d+">",f&&""!==i&&(f.includes("/>")||f.includes("`):s+=d+"/>",r=!0}return s}function at(t){const e=Object.keys(t);for(let n=0;n0&&e.processEntities)for(let n=0;n","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function ft(t){this.options=Object.assign({},dt,t),!0===this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=_(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=gt),this.processTextOrObjNode=ct,this.options.format?(this.indentate=pt,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function ct(t,e,n,i){const s=this.j2x(t,n+1,i.concat(e));return void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,s.attrStr,n):this.buildObjectNode(s.val,e,s.attrStr,n)}function pt(t){return this.options.indentBy.repeat(t)}function gt(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}ft.prototype.build=function(t){return this.options.preserveOrder?rt(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0,[]).val)},ft.prototype.j2x=function(t,e,n){let i="",s="";const r=n.join(".");for(let o in t)if(Object.prototype.hasOwnProperty.call(t,o))if(void 0===t[o])this.isAttribute(o)&&(s+="");else if(null===t[o])this.isAttribute(o)||o===this.options.cdataPropName?s+="":"?"===o[0]?s+=this.indentate(e)+"<"+o+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+o+"/"+this.tagEndChar;else if(t[o]instanceof Date)s+=this.buildTextValNode(t[o],o,"",e);else if("object"!=typeof t[o]){const n=this.isAttribute(o);if(n&&!this.ignoreAttributesFn(n,r))i+=this.buildAttrPairStr(n,""+t[o]);else if(!n)if(o===this.options.textNodeName){let e=this.options.tagValueProcessor(o,""+t[o]);s+=this.replaceEntitiesValue(e)}else s+=this.buildTextValNode(t[o],o,"",e)}else if(Array.isArray(t[o])){const i=t[o].length;let r="",a="";for(let l=0;l"+t+s}},ft.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`>`+this.newLine;if(!1!==this.options.commentPropName&&e===this.options.commentPropName)return this.indentate(i)+`\x3c!--${t}--\x3e`+this.newLine;if("?"===e[0])return this.indentate(i)+"<"+e+n+"?"+this.tagEndChar;{let s=this.options.tagValueProcessor(e,t);return s=this.replaceEntitiesValue(s),""===s?this.indentate(i)+"<"+e+n+this.closeTag(e)+this.tagEndChar:this.indentate(i)+"<"+e+n+">"+s+"0&&this.options.processEntities)for(let e=0;e Inputs; export declare const vaildateScanResultsActionInput: (inputs: Inputs) => boolean; diff --git a/dist/inputs.js b/dist/inputs.js deleted file mode 100644 index d4b6a36..0000000 --- a/dist/inputs.js +++ /dev/null @@ -1,99 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ValidateVeracodeApiCreds = exports.ValidatePolicyName = exports.vaildateApplicationProfileInput = exports.vaildateRemoveSandboxInput = exports.vaildateScanResultsActionInput = exports.parseInputs = exports.Actions = void 0; -var Actions; -(function (Actions) { - Actions["GetPolicyNameByProfileName"] = "getPolicyNameByProfileName"; - Actions["PreparePipelineResults"] = "preparePipelineResults"; - Actions["PreparePolicyResults"] = "preparePolicyResults"; - Actions["RemoveSandbox"] = "removeSandbox"; - Actions["ValidateVeracodeApiCreds"] = "validateVeracodeApiCreds"; - Actions["ValidatePolicyName"] = "validatePolicyName"; - Actions["registerBuild"] = "registerBuild"; - Actions["trimSandboxes"] = "trim-sandboxes"; -})(Actions || (exports.Actions = Actions = {})); -const parseInputs = (getInput) => { - const action = getInput('action', { required: true }); - if (!Object.values(Actions).includes(action)) { - throw new Error(`Invalid action: ${action}. It must be one of '${Object.values(Actions).join('\' or \'')}'.`); - } - const vid = getInput('vid'); - const vkey = getInput('vkey'); - const appname = getInput('appname', { required: true }); - const token = getInput('token'); - const check_run_id = getInput('check_run_id'); - const source_repository = getInput('source_repository'); - const fail_checks_on_policy = getInput('fail_checks_on_policy') === 'true'; - const fail_checks_on_error = getInput('fail_checks_on_error') === 'true'; - const filter_mitigated_flaws = getInput('filter_mitigated_flaws') === 'true'; - const sandboxname = getInput('sandboxname'); - const policyname = getInput('policyname'); - const path = getInput('path'); - const start_line = getInput('start_line'); - const end_line = getInput('end_line'); - const break_build_invalid_policy = getInput('break_build_invalid_policy') === 'true'; - const check_run_name = getInput('check_run_name'); - const head_sha = getInput('head_sha'); - const branch = getInput('branch'); - const event_type = getInput('event_type'); - const issue_trigger_flow = getInput('issue_trigger_flow'); - const workflow_app = getInput('workflow_app') === 'true'; - const line_number_slop = getInput('line_number_slop'); - const pipeline_scan_flaw_filter = getInput('pipeline_scan_flaw_filter'); - const filtered_results_file = getInput('filtered_results_file'); - const gitRepositoryUrl = getInput('gitRepositoryUrl'); - const trim_to_size = getInput('trim_to_size'); - const platformType = getInput('platformType'); - if (source_repository && source_repository.split('/').length !== 2) { - throw new Error('source_repository needs to be in the {owner}/{repo} format'); - } - return { - action, token, check_run_id: +check_run_id, vid, vkey, appname, - source_repository, fail_checks_on_policy, fail_checks_on_error, sandboxname, - policyname, path, start_line: +start_line, end_line: +end_line, break_build_invalid_policy, - filter_mitigated_flaws, check_run_name, head_sha, branch, event_type, issue_trigger_flow, - workflow_app, line_number_slop: +line_number_slop, pipeline_scan_flaw_filter, filtered_results_file, - gitRepositoryUrl, trim_to_size: +trim_to_size, platformType - }; -}; -exports.parseInputs = parseInputs; -const vaildateScanResultsActionInput = (inputs) => { - console.log(inputs); - if (!inputs.token || !inputs.check_run_id || !inputs.source_repository) { - return false; - } - return true; -}; -exports.vaildateScanResultsActionInput = vaildateScanResultsActionInput; -const vaildateRemoveSandboxInput = (inputs) => { - console.log(inputs); - if (!inputs.sandboxname) { - return false; - } - return true; -}; -exports.vaildateRemoveSandboxInput = vaildateRemoveSandboxInput; -const vaildateApplicationProfileInput = (inputs) => { - console.log(inputs); - if (!inputs.appname) { - return false; - } - return true; -}; -exports.vaildateApplicationProfileInput = vaildateApplicationProfileInput; -const ValidatePolicyName = (inputs) => { - console.log(inputs); - if (!inputs.path || !inputs.start_line || !inputs.end_line || !inputs.break_build_invalid_policy) { - return false; - } - return true; -}; -exports.ValidatePolicyName = ValidatePolicyName; -const ValidateVeracodeApiCreds = (inputs) => { - console.log(inputs); - if (!inputs.token || !inputs.check_run_id || !inputs.source_repository) { - return false; - } - return true; -}; -exports.ValidateVeracodeApiCreds = ValidateVeracodeApiCreds; diff --git a/dist/main.js b/dist/main.js deleted file mode 100644 index 6c3e5a4..0000000 --- a/dist/main.js +++ /dev/null @@ -1,73 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.run = run; -const core = __importStar(require("@actions/core")); -const inputs_1 = require("./inputs"); -const policyService = __importStar(require("./services/policy-service")); -const pipelineResultsService = __importStar(require("./services/pipeline-results-service")); -const policyResultsService = __importStar(require("./services/policy-results-services")); -const applicationService = __importStar(require("./services/application-service")); -async function run() { - const inputs = (0, inputs_1.parseInputs)(core.getInput); - switch (inputs.action) { - case 'getPolicyNameByProfileName': - await policyService.getPolicyNameByProfileName(inputs); - break; - case 'preparePipelineResults': - await pipelineResultsService.preparePipelineResults(inputs); - break; - case 'preparePolicyResults': - await policyResultsService.preparePolicyResults(inputs); - break; - case 'removeSandbox': - await applicationService.removeSandbox(inputs); - break; - case 'validateVeracodeApiCreds': - await applicationService.validateVeracodeApiCreds(inputs); - break; - case 'validatePolicyName': - await applicationService.validatePolicyName(inputs); - break; - case 'registerBuild': - await applicationService.registerBuild(inputs); - break; - case 'trim-sandboxes': - await applicationService.trimSandboxesFromApplicationProfile(inputs); - break; - default: - core.setFailed(`Invalid action: ${inputs.action}. Allowed actions are: getPolicyNameByProfileName, preparePipelineResults, preparePolicyResults, removeSandbox, validateVeracodeApiCreds, validatePolicyName, registerBuild, and trim-sandboxes.`); - } -} diff --git a/dist/namespaces/Checks.js b/dist/namespaces/Checks.js deleted file mode 100644 index 0b8cfeb..0000000 --- a/dist/namespaces/Checks.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Status = exports.Conclusion = void 0; -var Conclusion; -(function (Conclusion) { - Conclusion["Success"] = "success"; - Conclusion["Failure"] = "failure"; - Conclusion["Neutral"] = "neutral"; - Conclusion["Cancelled"] = "cancelled"; - Conclusion["TimedOut"] = "timed_out"; - Conclusion["ActionRequired"] = "action_required"; - Conclusion["Skipped"] = "skipped"; -})(Conclusion || (exports.Conclusion = Conclusion = {})); -var Status; -(function (Status) { - Status["Queued"] = "queued"; - Status["InProgress"] = "in_progress"; - Status["Completed"] = "completed"; -})(Status || (exports.Status = Status = {})); diff --git a/dist/namespaces/VeracodeApplication.js b/dist/namespaces/VeracodeApplication.js deleted file mode 100644 index c8ad2e5..0000000 --- a/dist/namespaces/VeracodeApplication.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/dist/namespaces/VeracodePipelineResult.js b/dist/namespaces/VeracodePipelineResult.js deleted file mode 100644 index c8ad2e5..0000000 --- a/dist/namespaces/VeracodePipelineResult.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/dist/namespaces/VeracodePolicyResult.js b/dist/namespaces/VeracodePolicyResult.js deleted file mode 100644 index c8ad2e5..0000000 --- a/dist/namespaces/VeracodePolicyResult.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/dist/services/application-service.js b/dist/services/application-service.js deleted file mode 100644 index 575758e..0000000 --- a/dist/services/application-service.js +++ /dev/null @@ -1,380 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getApplicationByName = getApplicationByName; -exports.removeSandbox = removeSandbox; -exports.validateVeracodeApiCreds = validateVeracodeApiCreds; -exports.validatePolicyName = validatePolicyName; -exports.registerBuild = registerBuild; -exports.trimSandboxesFromApplicationProfile = trimSandboxesFromApplicationProfile; -const core = __importStar(require("@actions/core")); -const app_config_1 = __importDefault(require("../app-config")); -const rest_1 = require("@octokit/rest"); -const Checks = __importStar(require("../namespaces/Checks")); -const check_service_1 = require("./check-service"); -const http = __importStar(require("../api/http-request")); -const inputs_1 = require("../inputs"); -const fs = __importStar(require("fs/promises")); -async function getApplicationByName(appname, vid, vkey) { - var _a; - try { - const getApplicationByNameResource = { - resourceUri: app_config_1.default.api.veracode.applicationUri, - queryAttribute: 'name', - queryValue: encodeURIComponent(appname), - }; - const applicationResponse = await http.getResourceByAttribute(vid, vkey, getApplicationByNameResource); - const applications = ((_a = applicationResponse._embedded) === null || _a === void 0 ? void 0 : _a.applications) || []; - if (applications.length === 0) { - core.warning(`No application found with name ${appname}`); - throw new Error(`No application found with name ${appname}`); - } - const filteredApplications = applications.filter(app => { var _a; return ((_a = app.profile) === null || _a === void 0 ? void 0 : _a.name) === appname; }); - if (filteredApplications.length === 0) { - core.warning(`No application found with exact name ${JSON.stringify(appname)}. Returning the first application from the list in the original API query.`); - return applications[0]; - } - else if (filteredApplications.length > 1) { - core.warning(`Multiple applications (${filteredApplications.length}) found with exact name ${JSON.stringify(appname)}. Returning the first application from the filtered list.`); - } - else { - if (applications.length > 1) { - core.info(`One application found with exact name ${JSON.stringify(appname)}. While there were ${JSON.stringify(applications.length)} applications starting with ${JSON.stringify(appname)}.`); - } - else { - core.info(`One application found with exact name ${JSON.stringify(appname)}.`); - } - } - return filteredApplications[0]; - } - catch (error) { - throw error; - } -} -async function getAppGUIDByAppName(inputs) { - if (!(0, inputs_1.vaildateApplicationProfileInput)(inputs)) { - core.setFailed('Application Profile name is required.'); - } - const appname = inputs.appname; - const vid = inputs.vid; - const vkey = inputs.vkey; - let application; - try { - application = await getApplicationByName(appname, vid, vkey); - } - catch (error) { - core.setFailed(`No application found with name ${appname}`); - throw new Error(`No application found with name ${appname}`); - } - const appGuid = application.guid; - return appGuid; -} -async function removeSandbox(inputs) { - if (!(0, inputs_1.vaildateRemoveSandboxInput)(inputs)) { - core.setFailed('sandboxname is required.'); - } - const appGuid = await getAppGUIDByAppName(inputs); - const appname = inputs.appname; - const vid = inputs.vid; - const vkey = inputs.vkey; - const sandboxName = inputs.sandboxname; - let sandboxes; - try { - sandboxes = await getSandboxesByApplicationGuid(appGuid, vid, vkey); - } - catch (error) { - throw new Error(`Error retrieving sandboxes for application ${appname}`); - } - const sandbox = sandboxes.find((s) => s.name === sandboxName); - if (sandbox === undefined) { - core.setFailed(`No sandbox found with name ${sandboxName}`); - return; - } - try { - const removeSandboxResource = { - resourceUri: app_config_1.default.api.veracode.sandboxUri.replace('${appGuid}', appGuid), - resourceId: sandbox.guid, - }; - await http.deleteResourceById(vid, vkey, removeSandboxResource); - } - catch (error) { - core.debug(`Error removing sandbox:${error}`); - core.setFailed(`Error removing sandbox ${sandboxName}`); - } -} -async function getSandboxesByApplicationGuid(appGuid, vid, vkey) { - var _a; - try { - const getSandboxesByApplicationGuidResource = { - resourceUri: app_config_1.default.api.veracode.sandboxUri.replace('${appGuid}', appGuid), - queryAttribute: '', - queryValue: '', - }; - const sandboxResponse = await http.getResourceByAttribute(vid, vkey, getSandboxesByApplicationGuidResource); - return ((_a = sandboxResponse._embedded) === null || _a === void 0 ? void 0 : _a.sandboxes) || []; - } - catch (error) { - console.error(error); - throw error; - } -} -async function validateVeracodeApiCreds(inputs) { - var _a, _b; - const annotations = []; - const repo = inputs.source_repository.split('/'); - const ownership = { - owner: repo[0], - repo: repo[1], - }; - const octokit = new rest_1.Octokit({ - auth: inputs.token, - }); - const checkStatic = { - owner: ownership.owner, - repo: ownership.repo, - check_run_id: inputs.check_run_id, - status: Checks.Status.Completed, - }; - try { - if (!inputs.vid || !inputs.vkey) { - core.setFailed('Missing VERACODE_API_ID / VERACODE_API_KEY secret key.'); - annotations.push({ - path: '/', - start_line: 0, - end_line: 0, - annotation_level: 'failure', - title: 'Missing VERACODE_API_ID / VERACODE_API_KEY secret key.', - message: 'Please configure the VERACODE_API_ID and VERACODE_API_KEY under the organization secrets.', - }); - await (0, check_service_1.updateChecks)(octokit, checkStatic, Checks.Conclusion.Failure, annotations, 'Missing VERACODE_API_ID / VERACODE_API_KEY secret key.'); - return; - } - const getSelfUserDetailsResource = { - resourceUri: app_config_1.default.api.veracode.selfUserUri, - queryAttribute: '', - queryValue: '', - }; - const applicationResponse = await http.getResourceByAttribute(inputs.vid, inputs.vkey, getSelfUserDetailsResource); - if (applicationResponse && ((_a = applicationResponse === null || applicationResponse === void 0 ? void 0 : applicationResponse.api_credentials) === null || _a === void 0 ? void 0 : _a.expiration_ts)) { - core.info(`VERACODE_API_ID and VERACODE_API_KEY is valid, Credentials expiration date - ${JSON.stringify(applicationResponse.api_credentials.expiration_ts)}`); - } - else { - core.setFailed('Invalid/Expired VERACODE_API_ID and VERACODE_API_KEY'); - annotations.push({ - path: '/', - start_line: 0, - end_line: 0, - annotation_level: 'failure', - title: 'Invalid/Expired VERACODE_API_ID and VERACODE_API_KEY.', - message: 'Please check the VERACODE_API_ID and VERACODE_API_KEY configured under the organization secrets.', - }); - await (0, check_service_1.updateChecks)(octokit, checkStatic, Checks.Conclusion.Failure, annotations, 'Invalid/Expired VERACODE_API_ID and VERACODE_API_KEY.'); - return; - } - return (_b = applicationResponse === null || applicationResponse === void 0 ? void 0 : applicationResponse.api_credentials) === null || _b === void 0 ? void 0 : _b.expiration_ts; - } - catch (error) { - core.debug(`Error while validating Veracode API credentials: ${error}`); - await (0, check_service_1.updateChecks)(octokit, checkStatic, Checks.Conclusion.Failure, [], 'Error while validating Veracode API credentials.'); - throw error; - } -} -async function validatePolicyName(inputs) { - var _a, _b; - const annotations = []; - const repo = inputs.source_repository.split('/'); - const ownership = { - owner: repo[0], - repo: repo[1], - }; - const octokit = new rest_1.Octokit({ - auth: inputs.token, - }); - const checkStatic = { - owner: ownership.owner, - repo: ownership.repo, - check_run_id: inputs.check_run_id, - status: Checks.Status.Completed, - }; - try { - if (!inputs.policyname) { - if (inputs.break_build_invalid_policy == true) { - core.setFailed('Missing Veracode Policy name in the config.'); - } - else { - core.error('Missing Veracode Policy name in the config.'); - } - annotations.push({ - path: '/', - start_line: 0, - end_line: 0, - annotation_level: 'failure', - title: 'Missing Veracode Policy name in the config.', - message: 'Please configure the Veracode policy name under the config file.', - }); - await (0, check_service_1.updateChecks)(octokit, checkStatic, Checks.Conclusion.Failure, annotations, 'Missing Veracode Policy name in the config.'); - return; - } - const getPolicyResource = { - resourceUri: app_config_1.default.api.veracode.policyUri, - queryAttribute: 'name', - queryValue: encodeURIComponent(inputs.policyname), - queryAttribute1: 'name_exact', - queryValue1: true, - }; - annotations.push({ - path: inputs.path, - start_line: inputs.start_line, - end_line: inputs.end_line, - annotation_level: 'failure', - title: 'Invalid Veracode Policy name', - message: 'Please check the policy name provided in the config file.', - }); - const applicationResponse = await http.getResourceByAttribute(inputs.vid, inputs.vkey, getPolicyResource); - core.setOutput('total_elements', (_a = applicationResponse === null || applicationResponse === void 0 ? void 0 : applicationResponse.page) === null || _a === void 0 ? void 0 : _a.total_elements); - if (applicationResponse && ((_b = applicationResponse === null || applicationResponse === void 0 ? void 0 : applicationResponse.page) === null || _b === void 0 ? void 0 : _b.total_elements) != 1) { - await (0, check_service_1.updateChecks)(octokit, checkStatic, Checks.Conclusion.Failure, annotations, 'Please check the policy name provided in the config file.'); - if (inputs.break_build_invalid_policy == true) { - core.setFailed('Invalid Veracode Policy name.'); - } - else { - core.error('Invalid Veracode Policy name.'); - } - } - } - catch (error) { - core.debug(`Error while validating invalid policy name: ${error}`); - await (0, check_service_1.updateChecks)(octokit, checkStatic, Checks.Conclusion.Failure, [], 'Error while validating policy name.'); - throw error; - } -} -async function registerBuild(inputs) { - var _a; - const filePath = 'workflow-metadata.json'; - const artifactName = 'workflow-metadata'; - try { - const repo = inputs.source_repository.split('/'); - const ownership = { - owner: repo[0], - repo: repo[1], - }; - const rootDirectory = process.cwd(); - const { DefaultArtifactClient } = require('@actions/artifact'); - const artifactV1 = require('@actions/artifact-v1'); - let artifactClient; - if (inputs.platformType === 'ENTERPRISE') { - artifactClient = artifactV1.create(); - core.info(`Initialized the artifact object using version V1.`); - } - else { - artifactClient = new DefaultArtifactClient(); - core.info(`Initialized the artifact object using version V2.`); - } - const metadata = { - 'check_run_type': inputs.event_type, - 'repository_name': ownership.repo, - 'check_run_id': inputs.check_run_id, - 'branch': inputs.branch, - 'sha': inputs.head_sha, - 'issue_trigger_flow': (_a = inputs.issue_trigger_flow) !== null && _a !== void 0 ? _a : false, - }; - await fs.writeFile(filePath, JSON.stringify(metadata, null, 2)); - await artifactClient.uploadArtifact(artifactName, [filePath], rootDirectory); - core.info(`${artifactName} directory uploaded successfully under the artifact.`); - } - catch (error) { - core.info(`Error while creating the ${artifactName} artifact ${error}`); - } -} -async function trimSandboxesFromApplicationProfile(inputs) { - const appGuid = await getAppGUIDByAppName(inputs); - const appname = inputs.appname; - const vid = inputs.vid; - const vkey = inputs.vkey; - const sandboxName = inputs.sandboxname; - let sandboxes; - try { - sandboxes = await getSandboxesByApplicationGuid(appGuid, vid, vkey); - } - catch (error) { - throw new Error(`Error retrieving sandboxes for application ${appname}`); - } - let sortedSandboxes = sandboxes.sort((sandboxA, sandboxB) => { - let retVal = sandboxA.modified > sandboxB.modified; - return (retVal ? 1 : -1); - }); - if (core.isDebug()) { - core.info('Date match Sandboxes from oldest to newest:'); - core.info('==========================================='); - sortedSandboxes.forEach((sandbox, i) => { - core.info(`[${i}] - ${JSON.stringify(sandbox.name)} => ${sandbox.modified}`); - }); - core.info('-------------------------------------------'); - } - const total_sb_size = sortedSandboxes.length; - const keep_size = inputs.trim_to_size; - let sandboxesToDelete = []; - if (keep_size >= total_sb_size) { - core.info(`Total sandboxes [${total_sb_size}] are equal or less than the trim_to_size input [${JSON.stringify(keep_size)}]. Nothing to delete`); - return; - } - else { - const number_to_delete = total_sb_size - keep_size; - sandboxesToDelete = sortedSandboxes.slice(0, number_to_delete); - } - core.info('Starting to delete sandboxes'); - const deletedSandboxNames = []; - await Promise.all(sandboxesToDelete.map(async (sandbox, i) => { - core.info(`[${i}] - ${JSON.stringify(sandbox.name)} => ${sandbox.modified}, ${sandbox.guid}`); - const removeSandboxResource = { - resourceUri: app_config_1.default.api.veracode.sandboxUri.replace('${appGuid}', appGuid), - resourceId: sandbox.guid, - }; - try { - await http.deleteResourceById(vid, vkey, removeSandboxResource); - core.info(`Sandbox '${JSON.stringify(sandbox.name)}' with GUID [${JSON.stringify(sandbox.guid)}] deleted`); - deletedSandboxNames.push(`'${sandbox.name}' (GUID:${sandbox.guid})`); - } - catch (error) { - core.warning(`Error removing sandbox:${error}`); - core.setFailed(`Error removing sandbox ${sandbox.name}`); - } - })); - core.info(`Deleted Sandboxes names: ${JSON.stringify(deletedSandboxNames)}`); - core.info('---------------------------------'); -} diff --git a/dist/services/check-service.js b/dist/services/check-service.js deleted file mode 100644 index 3fc6c53..0000000 --- a/dist/services/check-service.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.updateChecks = updateChecks; -exports.createChecks = createChecks; -async function updateChecks(octokit, checksStatic, conclusion, annotations, summary) { - const data = Object.assign(Object.assign({ owner: checksStatic.owner, repo: checksStatic.repo, check_run_id: checksStatic.check_run_id, status: checksStatic.status }, (conclusion !== conclusion !== undefined && { conclusion })), { output: { - annotations: annotations, - title: 'Veracode Static Code Analysis', - summary: summary, - } }); - await octokit.checks.update(data); -} -async function createChecks(octokit, owner, repo, name, head_sha) { - const response = await octokit.checks.create({ owner: owner, repo: repo, name: name, head_sha: head_sha }); - return response.data.id; -} diff --git a/dist/services/findings-service.js b/dist/services/findings-service.js deleted file mode 100644 index 52ff34d..0000000 --- a/dist/services/findings-service.js +++ /dev/null @@ -1,81 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getApplicationFindings = getApplicationFindings; -const app_config_1 = __importDefault(require("../app-config")); -const http = __importStar(require("../api/http-request")); -async function getApplicationFindings(appGuid, vid, vkey) { - const getPolicyFindingsByApplicationResource = { - resourceUri: `${app_config_1.default.api.veracode.findingsUri}/${appGuid}/findings`, - queryAttribute: 'size', - queryValue: '1000', - }; - const findingsResponse = await http.getResourceByAttribute(vid, vkey, getPolicyFindingsByApplicationResource); - if (!findingsResponse._embedded) { - console.log('No Policy scan found, lets look for sandbox scan findings'); - const getSandboxGUID = { - resourceUri: `${app_config_1.default.api.veracode.applicationUri}/${appGuid}/sandboxes`, - queryAttribute: '', - queryValue: '', - }; - const sandboxesResponse = await http.getResourceByAttribute(vid, vkey, getSandboxGUID); - if (!sandboxesResponse._embedded) { - console.log('No Policy scan found and no sandbox scan found.'); - return []; - } - else { - const sandboxGuid = sandboxesResponse._embedded.sandboxes[0].guid; - const getPolicyFindingsBySandboxResource = { - resourceUri: `${app_config_1.default.api.veracode.findingsUri}/${appGuid}/findings`, - queryAttribute: 'context', - queryValue: sandboxGuid, - }; - const findingsResponse = await http.getResourceByAttribute(vid, vkey, getPolicyFindingsBySandboxResource); - if (!findingsResponse._embedded) { - console.log('No Policy scan found and no sandbox scan found.'); - return []; - } - else { - return findingsResponse._embedded.findings; - } - } - } - else { - return findingsResponse._embedded.findings; - } -} diff --git a/dist/services/pipeline-results-service.js b/dist/services/pipeline-results-service.js deleted file mode 100644 index a5e35f6..0000000 --- a/dist/services/pipeline-results-service.js +++ /dev/null @@ -1,393 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.preparePipelineResults = preparePipelineResults; -const core = __importStar(require("@actions/core")); -const rest_1 = require("@octokit/rest"); -const fs = __importStar(require("fs/promises")); -const Checks = __importStar(require("../namespaces/Checks")); -const inputs_1 = require("../inputs"); -const check_service_1 = require("./check-service"); -const application_service_1 = require("./application-service"); -const findings_service_1 = require("./findings-service"); -const LINE_NUMBER_SLOP = 3; -function printResults(numberOfPipelineScanFindings, numberOfMitigatedFlaws, numberOfRemainingFlaws) { - core.info(`Pipeline findings: ${numberOfPipelineScanFindings}`); - core.info(`Mitigated findings: ${numberOfMitigatedFlaws}`); - core.info(`Filtered pipeline findings: ${numberOfRemainingFlaws}`); -} -async function preparePipelineResultsNonWorkflowApp(inputs) { - const LINE_NUMBER_SLOP = inputs.line_number_slop; - core.info(`LINE_NUMBER_SLOP: ${LINE_NUMBER_SLOP}`); - const pipelineScanFlawFilter = inputs.pipeline_scan_flaw_filter; - core.info(`Pipeline scan flaw filter: ${pipelineScanFlawFilter}`); - const pipeline_results_file = pipelineScanFlawFilter.includes('policy') - ? 'filtered_results.json' - : 'results.json'; - const filtered_pipeline_results_file = 'filtered_results.json'; - let findingsArray = []; - let veracodePipelineResult; - let filteredPipelineFinding = []; - let filteredVeracodePipelineResult; - try { - const data = await fs.readFile(pipeline_results_file, 'utf-8'); - veracodePipelineResult = JSON.parse(data); - findingsArray = veracodePipelineResult.findings; - if (pipelineScanFlawFilter.includes('policy')) - filteredPipelineFinding = findingsArray; - else { - const filteredData = await fs.readFile(filtered_pipeline_results_file, 'utf-8'); - filteredVeracodePipelineResult = JSON.parse(filteredData); - filteredPipelineFinding = filteredVeracodePipelineResult.findings; - } - } - catch (error) { - core.debug(`Error reading or parsing filtered_results.json:${error}`); - core.setFailed('Error reading or parsing pipeline scan results.'); - return -1; - } - core.info('############################################'); - core.info(`filteredPipelineFinding length: ${filteredPipelineFinding.length}`); - const filePath = 'pipeline_scan_flaw_filter.json'; - const artifactName = 'Veracode Pipeline-Scan Results - Filtered findings'; - const rootDirectory = process.cwd(); - const { DefaultArtifactClient } = require('@actions/artifact'); - const artifactV1 = require('@actions/artifact-v1'); - let artifactClient; - if (inputs.platformType === 'ENTERPRISE') { - artifactClient = artifactV1.create(); - core.info(`Initialized the artifact object using version V1.`); - } - else { - artifactClient = new DefaultArtifactClient(); - core.info(`Initialized the artifact object using version V2.`); - } - if (findingsArray.length === 0 || - pipelineScanFlawFilter === 'all_results' || - pipelineScanFlawFilter === 'policy_violations') { - try { - await fs.writeFile(filePath, JSON.stringify(veracodePipelineResult, null, 2)); - await artifactClient.uploadArtifact(artifactName, [filePath], rootDirectory); - core.info(`${artifactName} directory uploaded successfully under the artifact.`); - } - catch (error) { - core.info(`Error while updating the ${artifactName} artifact ${error}`); - } - printResults(findingsArray.length, 0, findingsArray.length); - return filteredPipelineFinding.length === 0 ? 0 : filteredPipelineFinding.length; - } - let policyFindings = []; - try { - const application = await (0, application_service_1.getApplicationByName)(inputs.appname, inputs.vid, inputs.vkey); - const applicationGuid = application.guid; - policyFindings = await (0, findings_service_1.getApplicationFindings)(applicationGuid, inputs.vid, inputs.vkey); - } - catch (error) { - core.info(`No application found with name ${inputs.appname}`); - policyFindings = []; - } - let policyFindingsToExclude = policyFindings; - core.debug(`policyFindings findings: ${policyFindingsToExclude.length}`); - policyFindingsToExclude.forEach((finding) => { - core.debug(`policyFindings finding: ${JSON.stringify(finding, null, 2)}`); - core.debug(`policyFindings finding: ${finding.finding_details.file_path}`); - core.debug(`policyFindings finding: ${finding.finding_details.file_line_number}`); - core.debug(`policyFindings finding: ${finding.finding_details.cwe.id}`); - core.debug(`policyFindings finding: ${finding.finding_details.cwe.name}`); - core.debug(`policyFindings finding: ${finding.finding_status.status}`); - core.debug(`policyFindings finding: ${finding.finding_status.resolution}`); - core.debug(`policyFindings finding: ${finding.finding_status.resolution_status}`); - core.debug(`policyFindings finding: ${finding.violates_policy}`); - core.debug(`policyFindings finding: ${finding.description}`); - core.debug(`policyFindings finding: ${finding.issue_id}`); - }); - if (pipelineScanFlawFilter.includes('mitigated')) { - policyFindingsToExclude = policyFindings.filter((finding) => finding.finding_status.status === 'CLOSED' && - (finding.finding_status.resolution === 'POTENTIAL_FALSE_POSITIVE' || - finding.finding_status.resolution === 'MITIGATED') && - finding.finding_status.resolution_status === 'APPROVED'); - } - core.debug(`policyFindingsToExclude findings: ${policyFindingsToExclude.length}`); - policyFindingsToExclude.forEach((finding) => { - core.debug(`policyFindingsToExclude finding: ${JSON.stringify(finding, null, 2)}`); - core.debug(`policyFindingsToExclude finding: ${finding.finding_details.file_path}`); - core.debug(`policyFindingsToExclude finding: ${finding.finding_details.file_line_number}`); - core.debug(`policyFindingsToExclude finding: ${finding.finding_details.cwe.id}`); - core.debug(`policyFindingsToExclude finding: ${finding.finding_details.cwe.name}`); - core.debug(`policyFindingsToExclude finding: ${finding.finding_status.status}`); - core.debug(`policyFindingsToExclude finding: ${finding.finding_status.resolution}`); - core.debug(`policyFindingsToExclude finding: ${finding.finding_status.resolution_status}`); - core.debug(`policyFindingsToExclude finding: ${finding.violates_policy}`); - core.debug(`policyFindingsToExclude finding: ${finding.description}`); - core.debug(`policyFindingsToExclude finding: ${finding.issue_id}`); - }); - const filteredFindingsArray = findingsArray.filter((finding) => { - return !policyFindingsToExclude.some((mitigatedFinding) => { - if (mitigatedFinding.finding_details.file_path.charAt(0) === '/') { - mitigatedFinding.finding_details.file_path = mitigatedFinding.finding_details.file_path.substring(1); - } - return (finding.files.source_file.file === mitigatedFinding.finding_details.file_path && - +finding.cwe_id === mitigatedFinding.finding_details.cwe.id && - Math.abs(finding.files.source_file.line - mitigatedFinding.finding_details.file_line_number) <= LINE_NUMBER_SLOP); - }); - }); - core.debug(`filteredFindingsArray findings: ${filteredFindingsArray.length}`); - filteredFindingsArray.forEach((finding) => { - core.debug(`filteredFindingsArray finding: ${JSON.stringify(finding, null, 2)}`); - }); - try { - veracodePipelineResult.findings = filteredFindingsArray; - await fs.writeFile(filePath, JSON.stringify(veracodePipelineResult, null, 2)); - await artifactClient.uploadArtifact(artifactName, [filePath], rootDirectory); - core.info(`${artifactName} directory uploaded successfully under the artifact.`); - } - catch (error) { - core.info(`Error while updating the ${artifactName} artifact ${error}`); - } - core.info('=============================================================='); - printResults(findingsArray.length, policyFindingsToExclude.length, filteredFindingsArray.length); - for (const finding of filteredPipelineFinding) { - core.info(`finding.issue_id: ${finding.issue_id}`); - core.info(`finding.files.source_file.file: ${finding.files.source_file.file}`); - core.info(`finding.files.source_file.line: ${finding.files.source_file.line}`); - } - for (const finding of filteredFindingsArray) { - core.info(`finding.issue_id: ${finding.issue_id}`); - for (const finding2 of filteredPipelineFinding) { - core.info(`finding.issue_id: ${finding.issue_id}`); - core.info(`finding2.issue_id: ${finding2.issue_id}`); - core.info(`finding.files.source_file.file: ${finding.files.source_file.file}`); - core.info(`finding2.files.source_file.file: ${finding2.files.source_file.file}`); - core.info(`finding.files.source_file.line: ${finding.files.source_file.line}`); - core.info(`finding2.files.source_file.line: ${finding2.files.source_file.line}`); - if (finding.issue_id === finding2.issue_id && - finding.files.source_file.file === finding2.files.source_file.file && - finding.files.source_file.line === finding2.files.source_file.line) { - return 1; - } - } - } - return 0; -} -async function preparePipelineResults(inputs) { - const workflow_app = inputs.workflow_app; - if (!workflow_app) { - const hasPolicyViolatedFindings = await preparePipelineResultsNonWorkflowApp(inputs) !== 0; - core.info(`Has policy violated findings: ${hasPolicyViolatedFindings}`); - core.info(`Fail checks on policy: ${inputs.fail_checks_on_policy}`); - if (hasPolicyViolatedFindings && inputs.fail_checks_on_policy) { - core.setFailed('Pipeline scan results contain policy violated findings.'); - } - return; - } - const repo = inputs.source_repository.split('/'); - const ownership = { - owner: repo[0], - repo: repo[1], - }; - const checkStatic = { - owner: ownership.owner, - repo: ownership.repo, - check_run_id: inputs.check_run_id, - status: Checks.Status.Completed, - }; - const octokit = new rest_1.Octokit({ - auth: inputs.token, - }); - if (!(0, inputs_1.vaildateScanResultsActionInput)(inputs)) { - core.setFailed('token, check_run_id and source_repository are required.'); - await (0, check_service_1.updateChecks)(octokit, checkStatic, inputs.fail_checks_on_error ? Checks.Conclusion.Failure : Checks.Conclusion.Success, [], 'Token, check_run_id and source_repository are required.'); - return; - } - let findingsArray = []; - let veracodePipelineResult; - try { - const data = await fs.readFile(inputs.filtered_results_file, 'utf-8'); - const parsedData = JSON.parse(data); - findingsArray = parsedData.findings; - veracodePipelineResult = JSON.parse(data); - } - catch (error) { - core.debug(`Error reading or parsing filtered_results.json:${error}`); - core.setFailed('Error reading or parsing pipeline scan results.'); - await (0, check_service_1.updateChecks)(octokit, checkStatic, inputs.fail_checks_on_error ? Checks.Conclusion.Failure : Checks.Conclusion.Success, [], 'Error reading or parsing pipeline scan results.'); - return; - } - core.info(`Pipeline findings: ${findingsArray.length}`); - const filePath = 'mitigated_' + inputs.filtered_results_file; - const artifactName = 'Veracode Pipeline-Scan Results - ' + inputs.filtered_results_file + ' - Mitigated findings'; - const rootDirectory = process.cwd(); - const { DefaultArtifactClient } = require('@actions/artifact'); - const artifactV1 = require('@actions/artifact-v1'); - let artifactClient; - if (inputs.platformType === 'ENTERPRISE') { - artifactClient = artifactV1.create(); - core.info(`Initialized the artifact object using version V1.`); - } - else { - artifactClient = new DefaultArtifactClient(); - core.info(`Initialized the artifact object using version V2.`); - } - if (findingsArray.length === 0) { - try { - veracodePipelineResult.findings = []; - await fs.writeFile(filePath, JSON.stringify(veracodePipelineResult, null, 2)); - await artifactClient.uploadArtifact(artifactName, [filePath], rootDirectory); - core.info(`${artifactName} directory uploaded successfully under the artifact.`); - } - catch (error) { - core.info(`Error while updating the ${artifactName} artifact ${error}`); - } - core.info('No pipeline findings, exiting and update the github check status to success'); - return; - } - let policyFindings = []; - try { - const application = await (0, application_service_1.getApplicationByName)(inputs.appname, inputs.vid, inputs.vkey); - const applicationGuid = application.guid; - policyFindings = await (0, findings_service_1.getApplicationFindings)(applicationGuid, inputs.vid, inputs.vkey); - } - catch (error) { - core.info(`No application found with name ${inputs.appname}`); - policyFindings = []; - } - core.info(`Policy findings: ${JSON.stringify(policyFindings.length)}`); - const filter_mitigated_flaws = inputs.filter_mitigated_flaws; - let policyFindingsToExlcude = []; - if (filter_mitigated_flaws) { - policyFindingsToExlcude = policyFindings.filter((finding) => { - return (finding.violates_policy === true && - finding.finding_status.status === 'CLOSED' && - (finding.finding_status.resolution === 'POTENTIAL_FALSE_POSITIVE' || - finding.finding_status.resolution === 'MITIGATED') && - finding.finding_status.resolution_status === 'APPROVED'); - }); - } - else { - policyFindingsToExlcude = policyFindings.filter((finding) => { - return finding.violates_policy === true; - }); - } - core.info(`Mitigated policy findings: ${JSON.stringify(policyFindingsToExlcude.length)}`); - const filteredFindingsArray = findingsArray.filter((finding) => { - return !policyFindingsToExlcude.some((mitigatedFinding) => { - if (mitigatedFinding.finding_details.file_path.charAt(0) === '/') { - mitigatedFinding.finding_details.file_path = mitigatedFinding.finding_details.file_path.substring(1); - } - return (finding.files.source_file.file === mitigatedFinding.finding_details.file_path && - +finding.cwe_id === mitigatedFinding.finding_details.cwe.id && - Math.abs(finding.files.source_file.line - mitigatedFinding.finding_details.file_line_number) <= LINE_NUMBER_SLOP); - }); - }); - try { - veracodePipelineResult.findings = filteredFindingsArray; - await fs.writeFile(filePath, JSON.stringify(veracodePipelineResult, null, 2)); - await artifactClient.uploadArtifact(artifactName, [filePath], rootDirectory); - core.info(`${artifactName} directory uploaded successfully under the artifact.`); - } - catch (error) { - core.info(`Error while updating the ${artifactName} artifact ${error}`); - } - core.info(`Filtered pipeline findings: ${filteredFindingsArray.length}`); - if (filteredFindingsArray.length === 0) { - core.info('No pipeline findings after filtering, exiting and update the github check status to success'); - return; - } - else { - const repoResponse = await octokit.repos.get(ownership); - const language = repoResponse.data.language; - core.info(`Source repository language: ${language}`); - let javaMaven = false; - if (language === 'Java') { - let pomFileExists = false; - let gradleFileExists = false; - try { - await octokit.repos.getContent(Object.assign(Object.assign({}, ownership), { path: 'pom.xml' })); - pomFileExists = true; - } - catch (error) { - core.debug(`Error reading or parsing source repository:${error}`); - } - try { - await octokit.repos.getContent(Object.assign(Object.assign({}, ownership), { path: 'build.gradle' })); - gradleFileExists = true; - } - catch (error) { - core.debug(`Error reading or parsing source repository:${error}`); - } - if (pomFileExists || gradleFileExists) - javaMaven = true; - } - core.info('Pipeline findings after filtering, continue to update the github check status'); - const annotations = getAnnotations(filteredFindingsArray, javaMaven); - const maxNumberOfAnnotations = 50; - if (filteredFindingsArray.length !== policyFindings.length && inputs.fail_checks_on_policy == true) { - core.setFailed('Vulneribilities detected in the Repository'); - } - for (let index = 0; index < annotations.length / maxNumberOfAnnotations; index++) { - const annotationBatch = annotations.slice(index * maxNumberOfAnnotations, (index + 1) * maxNumberOfAnnotations); - if (annotationBatch.length > 0) { - checkStatic.status = Checks.Status.InProgress; - await (0, check_service_1.updateChecks)(octokit, checkStatic, undefined, annotationBatch, 'Here\'s the summary of the scan result.'); - } - } - } -} -function getAnnotations(pipelineFindings, javaMaven) { - const annotations = []; - pipelineFindings.forEach(function (element) { - if (javaMaven) { - element.files.source_file.file = `src/main/java/${element.files.source_file.file}`; - if (element.files.source_file.file.includes('WEB-INF')) - element.files.source_file.file = element.files.source_file.file.replace(/src\/main\/java\//, 'src/main/webapp/'); - } - const displayMessage = element.display_text - .replace(//g, '') - .replace(/<\/span> /g, '\n') - .replace(/<\/span>/g, ''); - const message = `Filename: ${element.files.source_file.file}\n` + - `Line: ${element.files.source_file.line}\n` + - `CWE: ${element.cwe_id} (${element.issue_type})\n\n${displayMessage}`; - annotations.push({ - path: `${element.files.source_file.file}`, - start_line: element.files.source_file.line, - end_line: element.files.source_file.line, - annotation_level: 'warning', - title: element.issue_type, - message: message, - }); - }); - return annotations; -} diff --git a/dist/services/policy-results-services.js b/dist/services/policy-results-services.js deleted file mode 100644 index 4047345..0000000 --- a/dist/services/policy-results-services.js +++ /dev/null @@ -1,193 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.preparePolicyResults = preparePolicyResults; -exports.postScanReport = postScanReport; -const core = __importStar(require("@actions/core")); -const rest_1 = require("@octokit/rest"); -const fs = __importStar(require("fs/promises")); -const inputs_1 = require("../inputs"); -const Checks = __importStar(require("../namespaces/Checks")); -const check_service_1 = require("./check-service"); -const app_config_1 = __importDefault(require("../app-config")); -const http = __importStar(require("../api/http-request")); -async function preparePolicyResults(inputs) { - const octokit = new rest_1.Octokit({ - auth: inputs.token, - }); - const repo = inputs.source_repository.split('/'); - const ownership = { - owner: repo[0], - repo: repo[1], - }; - const checkStatic = { - owner: ownership.owner, - repo: ownership.repo, - check_run_id: inputs.check_run_id, - status: Checks.Status.Completed, - }; - if (!(0, inputs_1.vaildateScanResultsActionInput)(inputs)) { - core.setFailed('token, check_run_id and source_repository are required.'); - await (0, check_service_1.updateChecks)(octokit, checkStatic, inputs.fail_checks_on_error ? Checks.Conclusion.Failure : Checks.Conclusion.Success, [], 'Token, check_run_id and source_repository are required.'); - return; - } - let findingsArray = []; - let resultsUrl = ''; - try { - const data = await fs.readFile('policy_flaws.json', 'utf-8'); - const parsedData = JSON.parse(data); - findingsArray = parsedData._embedded.findings; - resultsUrl = await fs.readFile('results_url.txt', 'utf-8'); - await postScanReport(inputs, findingsArray); - } - catch (error) { - core.debug(`Error reading or parsing filtered_results.json:${error}`); - core.setFailed('Error reading or parsing pipeline scan results.'); - await (0, check_service_1.updateChecks)(octokit, checkStatic, inputs.fail_checks_on_error ? Checks.Conclusion.Failure : Checks.Conclusion.Success, [], 'Error reading or parsing pipeline scan results.'); - return; - } - core.info(`Policy findings: ${findingsArray.length}`); - core.info(`Results URL: ${resultsUrl}`); - if (findingsArray.length === 0) { - core.info('No findings violates the policy, exiting and update the github check status to success'); - await (0, check_service_1.updateChecks)(octokit, checkStatic, Checks.Conclusion.Success, [], `No policy violated findings, the full report can be found [here](${resultsUrl}).`); - return; - } - else { - core.info('Findings violate the policy, exiting and update the github check status to failure'); - const repoResponse = await octokit.repos.get(ownership); - const language = repoResponse.data.language; - core.info(`Source repository language: ${language}`); - let javaMaven = false; - if (language === 'Java') { - let pomFileExists = false; - let gradleFileExists = false; - try { - await octokit.repos.getContent(Object.assign(Object.assign({}, ownership), { path: 'pom.xml' })); - pomFileExists = true; - } - catch (error) { - core.debug(`Error reading or parsing source repository:${error}`); - } - try { - await octokit.repos.getContent(Object.assign(Object.assign({}, ownership), { path: 'build.gradle' })); - gradleFileExists = true; - } - catch (error) { - core.debug(`Error reading or parsing source repository:${error}`); - } - if (pomFileExists || gradleFileExists) - javaMaven = true; - } - const annotations = getAnnotations(findingsArray, javaMaven); - const maxNumberOfAnnotations = 50; - for (let index = 0; index < annotations.length / maxNumberOfAnnotations; index++) { - const annotationBatch = annotations.slice(index * maxNumberOfAnnotations, (index + 1) * maxNumberOfAnnotations); - if (annotationBatch.length > 0) { - await (0, check_service_1.updateChecks)(octokit, checkStatic, inputs.fail_checks_on_policy ? Checks.Conclusion.Failure : Checks.Conclusion.Success, annotationBatch, `Here's the summary of the check result, the full report can be found [here](${resultsUrl}).`); - } - } - return; - } -} -function getAnnotations(policyFindings, javaMaven) { - const annotations = []; - policyFindings.forEach(function (element) { - if (javaMaven) { - element.finding_details.file_path = `src/main/java/${element.finding_details.file_path}`; - if (element.finding_details.file_path.includes('WEB-INF')) - element.finding_details.file_path = element.finding_details.file_path.replace(/src\/main\/java\//, 'src/main/webapp/'); - } - const displayMessage = element.description - .replace(//g, '') - .replace(/<\/span> /g, '\n') - .replace(/<\/span>/g, ''); - let filePath = element.finding_details.file_path; - if (filePath.startsWith('/')) - filePath = filePath.substring(1); - const message = `Filename: ${filePath}\nLine: ${element.finding_details.file_line_number}\nCWE: ${element.finding_details.cwe.id} (${element.finding_details.cwe.name})\n\n${displayMessage}`; - annotations.push({ - path: `${filePath}`, - start_line: element.finding_details.file_line_number, - end_line: element.finding_details.file_line_number, - annotation_level: 'warning', - title: element.finding_details.cwe.name, - message: message, - }); - }); - return annotations; -} -async function postScanReport(inputs, policyFindings) { - try { - if (inputs.vid.startsWith('vera01ei-')) { - return; - } - const getSelfUserDetailsResource = { - resourceUri: app_config_1.default.api.veracode.selfUserUri, - queryAttribute: '', - queryValue: '', - }; - const applicationResponse = await http.getResourceByAttribute(inputs.vid, inputs.vkey, getSelfUserDetailsResource); - const commit_sha = inputs.head_sha; - const org_id = applicationResponse.organization.org_id; - let scan_id; - const source_repository = inputs.source_repository; - const repository_Url = inputs.gitRepositoryUrl; - for (let i = 0; i < policyFindings.length; i++) { - const element = policyFindings[i]; - if (typeof element.build_id !== 'undefined') { - scan_id = '' + element.build_id; - break; - } - } - if (typeof scan_id !== 'undefined') { - const scanReport = JSON.stringify({ - scm: 'GITHUB', - commitSha: commit_sha, - organizationId: org_id, - scanId: scan_id, - repositoryName: source_repository, - repositoryUrl: repository_Url, - }); - await http.postResourceByAttribute(inputs.vid, inputs.vkey, scanReport); - } - } - catch (error) { - core.debug(`Error posting scan report: ${error}`); - } -} diff --git a/dist/services/policy-service.js b/dist/services/policy-service.js deleted file mode 100644 index d02d1e5..0000000 --- a/dist/services/policy-service.js +++ /dev/null @@ -1,51 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getPolicyNameByProfileName = getPolicyNameByProfileName; -const core = __importStar(require("@actions/core")); -const ApplicationService = __importStar(require("../services/application-service")); -async function getPolicyNameByProfileName(inputs) { - const appname = inputs.appname; - const vid = inputs.vid; - const vkey = inputs.vkey; - try { - const application = await ApplicationService.getApplicationByName(appname, vid, vkey); - core.setOutput('policy_name', application.profile.policies[0].name); - } - catch (error) { - core.info(`No application found with name ${appname}`); - core.setOutput('policy_name', ''); - } -} diff --git a/src/inputs.ts b/src/inputs.ts index b946676..0290319 100644 --- a/src/inputs.ts +++ b/src/inputs.ts @@ -42,6 +42,7 @@ export type Inputs = { gitRepositoryUrl: string; trim_to_size: number; platformType: string; + wait_for_scan_completion: boolean; }; export const parseInputs = (getInput: GetInput): Inputs => { @@ -87,6 +88,7 @@ export const parseInputs = (getInput: GetInput): Inputs => { const gitRepositoryUrl = getInput('gitRepositoryUrl'); const trim_to_size = getInput('trim_to_size'); const platformType = getInput('platformType'); + const wait_for_scan_completion = getInput('wait_for_scan_completion') === 'true'; if (source_repository && source_repository.split('/').length !== 2) { throw new Error('source_repository needs to be in the {owner}/{repo} format'); @@ -98,7 +100,7 @@ export const parseInputs = (getInput: GetInput): Inputs => { policyname, path, start_line: +start_line, end_line: +end_line, break_build_invalid_policy, filter_mitigated_flaws, check_run_name, head_sha, branch, event_type, issue_trigger_flow, workflow_app, line_number_slop: +line_number_slop, pipeline_scan_flaw_filter, filtered_results_file, - gitRepositoryUrl,trim_to_size: +trim_to_size, platformType + gitRepositoryUrl,trim_to_size: +trim_to_size, platformType, wait_for_scan_completion }; }; diff --git a/src/services/policy-results-services.ts b/src/services/policy-results-services.ts index f4278cd..bd64e7e 100644 --- a/src/services/policy-results-services.ts +++ b/src/services/policy-results-services.ts @@ -42,6 +42,39 @@ export async function preparePolicyResults(inputs: Inputs): Promise { return; } + const submittedMessage = 'Static Scan Submitted. Please check the Veracode Platform for results.'; + + if (String(inputs.wait_for_scan_completion).toLowerCase() === 'false') { + try { + core.info(submittedMessage); + + await updateChecks( + octokit, + checkStatic, + inputs.fail_checks_on_error + ? Checks.Conclusion.Failure + : Checks.Conclusion.Success, + [], + submittedMessage, + ); + } catch (error) { + core.debug(`Error while updating the checks: ${error}`); + core.setFailed('Error while updating the checks'); + + await updateChecks( + octokit, + checkStatic, + inputs.fail_checks_on_error + ? Checks.Conclusion.Failure + : Checks.Conclusion.Success, + [], + 'Error while updating the checks.', + ); + } + + return; + } + let findingsArray: VeracodePolicyResult.Finding[] = []; let resultsUrl: string = '';