From 74613a0cafe0a6d9342aca2581c9d6aa97e6aa61 Mon Sep 17 00:00:00 2001 From: Sergey Vilgelm Date: Sun, 14 Feb 2021 11:29:34 -0600 Subject: [PATCH] re-compile dist --- dist/post_run/index.js | 16848 +++++++++++++++++++++------------------ dist/run/index.js | 16848 +++++++++++++++++++++------------------ package-lock.json | 2963 ++++++- 3 files changed, 20956 insertions(+), 15703 deletions(-) diff --git a/dist/post_run/index.js b/dist/post_run/index.js index e8cfb6e4d1..4879f6304e 100644 --- a/dist/post_run/index.js +++ b/dist/post_run/index.js @@ -1405,175 +1405,175 @@ rimraf.sync = rimrafSync /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __asyncValues = (this && this.__asyncValues) || function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(__webpack_require__(470)); -const exec = __importStar(__webpack_require__(986)); -const glob = __importStar(__webpack_require__(281)); -const io = __importStar(__webpack_require__(1)); -const fs = __importStar(__webpack_require__(747)); -const path = __importStar(__webpack_require__(622)); -const semver = __importStar(__webpack_require__(864)); -const util = __importStar(__webpack_require__(669)); -const uuid_1 = __webpack_require__(930); -const constants_1 = __webpack_require__(931); -// From https://github.com/actions/toolkit/blob/main/packages/tool-cache/src/tool-cache.ts#L23 -function createTempDirectory() { - return __awaiter(this, void 0, void 0, function* () { - const IS_WINDOWS = process.platform === 'win32'; - let tempDirectory = process.env['RUNNER_TEMP'] || ''; - if (!tempDirectory) { - let baseLocation; - if (IS_WINDOWS) { - // On Windows use the USERPROFILE env variable - baseLocation = process.env['USERPROFILE'] || 'C:\\'; - } - else { - if (process.platform === 'darwin') { - baseLocation = '/Users'; - } - else { - baseLocation = '/home'; - } - } - tempDirectory = path.join(baseLocation, 'actions', 'temp'); - } - const dest = path.join(tempDirectory, uuid_1.v4()); - yield io.mkdirP(dest); - return dest; - }); -} -exports.createTempDirectory = createTempDirectory; -function getArchiveFileSizeIsBytes(filePath) { - return fs.statSync(filePath).size; -} -exports.getArchiveFileSizeIsBytes = getArchiveFileSizeIsBytes; -function resolvePaths(patterns) { - var e_1, _a; - var _b; - return __awaiter(this, void 0, void 0, function* () { - const paths = []; - const workspace = (_b = process.env['GITHUB_WORKSPACE']) !== null && _b !== void 0 ? _b : process.cwd(); - const globber = yield glob.create(patterns.join('\n'), { - implicitDescendants: false - }); - try { - for (var _c = __asyncValues(globber.globGenerator()), _d; _d = yield _c.next(), !_d.done;) { - const file = _d.value; - const relativeFile = path - .relative(workspace, file) - .replace(new RegExp(`\\${path.sep}`, 'g'), '/'); - core.debug(`Matched: ${relativeFile}`); - // Paths are made relative so the tar entries are all relative to the root of the workspace. - paths.push(`${relativeFile}`); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_d && !_d.done && (_a = _c.return)) yield _a.call(_c); - } - finally { if (e_1) throw e_1.error; } - } - return paths; - }); -} -exports.resolvePaths = resolvePaths; -function unlinkFile(filePath) { - return __awaiter(this, void 0, void 0, function* () { - return util.promisify(fs.unlink)(filePath); - }); -} -exports.unlinkFile = unlinkFile; -function getVersion(app) { - return __awaiter(this, void 0, void 0, function* () { - core.debug(`Checking ${app} --version`); - let versionOutput = ''; - try { - yield exec.exec(`${app} --version`, [], { - ignoreReturnCode: true, - silent: true, - listeners: { - stdout: (data) => (versionOutput += data.toString()), - stderr: (data) => (versionOutput += data.toString()) - } - }); - } - catch (err) { - core.debug(err.message); - } - versionOutput = versionOutput.trim(); - core.debug(versionOutput); - return versionOutput; - }); -} -// Use zstandard if possible to maximize cache performance -function getCompressionMethod() { - return __awaiter(this, void 0, void 0, function* () { - if (process.platform === 'win32' && !(yield isGnuTarInstalled())) { - // Disable zstd due to bug https://github.com/actions/cache/issues/301 - return constants_1.CompressionMethod.Gzip; - } - const versionOutput = yield getVersion('zstd'); - const version = semver.clean(versionOutput); - if (!versionOutput.toLowerCase().includes('zstd command line interface')) { - // zstd is not installed - return constants_1.CompressionMethod.Gzip; - } - else if (!version || semver.lt(version, 'v1.3.2')) { - // zstd is installed but using a version earlier than v1.3.2 - // v1.3.2 is required to use the `--long` options in zstd - return constants_1.CompressionMethod.ZstdWithoutLong; - } - else { - return constants_1.CompressionMethod.Zstd; - } - }); -} -exports.getCompressionMethod = getCompressionMethod; -function getCacheFileName(compressionMethod) { - return compressionMethod === constants_1.CompressionMethod.Gzip - ? constants_1.CacheFilename.Gzip - : constants_1.CacheFilename.Zstd; -} -exports.getCacheFileName = getCacheFileName; -function isGnuTarInstalled() { - return __awaiter(this, void 0, void 0, function* () { - const versionOutput = yield getVersion('tar'); - return versionOutput.toLowerCase().includes('gnu tar'); - }); -} -exports.isGnuTarInstalled = isGnuTarInstalled; -function assertDefined(name, value) { - if (value === undefined) { - throw Error(`Expected ${name} but value was undefiend`); - } - return value; -} -exports.assertDefined = assertDefined; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __importStar(__webpack_require__(470)); +const exec = __importStar(__webpack_require__(986)); +const glob = __importStar(__webpack_require__(281)); +const io = __importStar(__webpack_require__(1)); +const fs = __importStar(__webpack_require__(747)); +const path = __importStar(__webpack_require__(622)); +const semver = __importStar(__webpack_require__(864)); +const util = __importStar(__webpack_require__(669)); +const uuid_1 = __webpack_require__(930); +const constants_1 = __webpack_require__(931); +// From https://github.com/actions/toolkit/blob/main/packages/tool-cache/src/tool-cache.ts#L23 +function createTempDirectory() { + return __awaiter(this, void 0, void 0, function* () { + const IS_WINDOWS = process.platform === 'win32'; + let tempDirectory = process.env['RUNNER_TEMP'] || ''; + if (!tempDirectory) { + let baseLocation; + if (IS_WINDOWS) { + // On Windows use the USERPROFILE env variable + baseLocation = process.env['USERPROFILE'] || 'C:\\'; + } + else { + if (process.platform === 'darwin') { + baseLocation = '/Users'; + } + else { + baseLocation = '/home'; + } + } + tempDirectory = path.join(baseLocation, 'actions', 'temp'); + } + const dest = path.join(tempDirectory, uuid_1.v4()); + yield io.mkdirP(dest); + return dest; + }); +} +exports.createTempDirectory = createTempDirectory; +function getArchiveFileSizeIsBytes(filePath) { + return fs.statSync(filePath).size; +} +exports.getArchiveFileSizeIsBytes = getArchiveFileSizeIsBytes; +function resolvePaths(patterns) { + var e_1, _a; + var _b; + return __awaiter(this, void 0, void 0, function* () { + const paths = []; + const workspace = (_b = process.env['GITHUB_WORKSPACE']) !== null && _b !== void 0 ? _b : process.cwd(); + const globber = yield glob.create(patterns.join('\n'), { + implicitDescendants: false + }); + try { + for (var _c = __asyncValues(globber.globGenerator()), _d; _d = yield _c.next(), !_d.done;) { + const file = _d.value; + const relativeFile = path + .relative(workspace, file) + .replace(new RegExp(`\\${path.sep}`, 'g'), '/'); + core.debug(`Matched: ${relativeFile}`); + // Paths are made relative so the tar entries are all relative to the root of the workspace. + paths.push(`${relativeFile}`); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_d && !_d.done && (_a = _c.return)) yield _a.call(_c); + } + finally { if (e_1) throw e_1.error; } + } + return paths; + }); +} +exports.resolvePaths = resolvePaths; +function unlinkFile(filePath) { + return __awaiter(this, void 0, void 0, function* () { + return util.promisify(fs.unlink)(filePath); + }); +} +exports.unlinkFile = unlinkFile; +function getVersion(app) { + return __awaiter(this, void 0, void 0, function* () { + core.debug(`Checking ${app} --version`); + let versionOutput = ''; + try { + yield exec.exec(`${app} --version`, [], { + ignoreReturnCode: true, + silent: true, + listeners: { + stdout: (data) => (versionOutput += data.toString()), + stderr: (data) => (versionOutput += data.toString()) + } + }); + } + catch (err) { + core.debug(err.message); + } + versionOutput = versionOutput.trim(); + core.debug(versionOutput); + return versionOutput; + }); +} +// Use zstandard if possible to maximize cache performance +function getCompressionMethod() { + return __awaiter(this, void 0, void 0, function* () { + if (process.platform === 'win32' && !(yield isGnuTarInstalled())) { + // Disable zstd due to bug https://github.com/actions/cache/issues/301 + return constants_1.CompressionMethod.Gzip; + } + const versionOutput = yield getVersion('zstd'); + const version = semver.clean(versionOutput); + if (!versionOutput.toLowerCase().includes('zstd command line interface')) { + // zstd is not installed + return constants_1.CompressionMethod.Gzip; + } + else if (!version || semver.lt(version, 'v1.3.2')) { + // zstd is installed but using a version earlier than v1.3.2 + // v1.3.2 is required to use the `--long` options in zstd + return constants_1.CompressionMethod.ZstdWithoutLong; + } + else { + return constants_1.CompressionMethod.Zstd; + } + }); +} +exports.getCompressionMethod = getCompressionMethod; +function getCacheFileName(compressionMethod) { + return compressionMethod === constants_1.CompressionMethod.Gzip + ? constants_1.CacheFilename.Gzip + : constants_1.CacheFilename.Zstd; +} +exports.getCacheFileName = getCacheFileName; +function isGnuTarInstalled() { + return __awaiter(this, void 0, void 0, function* () { + const versionOutput = yield getVersion('tar'); + return versionOutput.toLowerCase().includes('gnu tar'); + }); +} +exports.isGnuTarInstalled = isGnuTarInstalled; +function assertDefined(name, value) { + if (value === undefined) { + throw Error(`Expected ${name} but value was undefiend`); + } + return value; +} +exports.assertDefined = assertDefined; //# sourceMappingURL=cacheUtils.js.map /***/ }), @@ -2707,7 +2707,49 @@ exports.findLintVersion = findLintVersion; /***/ }), -/* 53 */, +/* 53 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +/*! + * Copyright 2019, OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const context_1 = __webpack_require__(560); +class NoopContextManager { + active() { + return context_1.Context.ROOT_CONTEXT; + } + with(context, fn) { + return fn(); + } + bind(target, context) { + return target; + } + enable() { + return this; + } + disable() { + return this; + } +} +exports.NoopContextManager = NoopContextManager; +//# sourceMappingURL=NoopContextManager.js.map + +/***/ }), /* 54 */, /* 55 */, /* 56 */, @@ -4107,7 +4149,7 @@ module.exports = bytesToUuid; Object.defineProperty(exports, '__esModule', { value: true }); -var tslib = __webpack_require__(422); +var tslib = __webpack_require__(640); var listenersMap = new WeakMap(); var abortedMap = new WeakMap(); @@ -4405,220 +4447,221 @@ Object.defineProperty(exports, "__esModule", { value: true }); /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(__webpack_require__(470)); -const http_client_1 = __webpack_require__(22); -const auth_1 = __webpack_require__(733); -const crypto = __importStar(__webpack_require__(417)); -const fs = __importStar(__webpack_require__(747)); -const url_1 = __webpack_require__(835); -const utils = __importStar(__webpack_require__(15)); -const constants_1 = __webpack_require__(931); -const downloadUtils_1 = __webpack_require__(251); -const options_1 = __webpack_require__(538); -const requestUtils_1 = __webpack_require__(899); -const versionSalt = '1.0'; -function getCacheApiUrl(resource) { - // Ideally we just use ACTIONS_CACHE_URL - const baseUrl = (process.env['ACTIONS_CACHE_URL'] || - process.env['ACTIONS_RUNTIME_URL'] || - '').replace('pipelines', 'artifactcache'); - if (!baseUrl) { - throw new Error('Cache Service Url not found, unable to restore cache.'); - } - const url = `${baseUrl}_apis/artifactcache/${resource}`; - core.debug(`Resource Url: ${url}`); - return url; -} -function createAcceptHeader(type, apiVersion) { - return `${type};api-version=${apiVersion}`; -} -function getRequestOptions() { - const requestOptions = { - headers: { - Accept: createAcceptHeader('application/json', '6.0-preview.1') - } - }; - return requestOptions; -} -function createHttpClient() { - const token = process.env['ACTIONS_RUNTIME_TOKEN'] || ''; - const bearerCredentialHandler = new auth_1.BearerCredentialHandler(token); - return new http_client_1.HttpClient('actions/cache', [bearerCredentialHandler], getRequestOptions()); -} -function getCacheVersion(paths, compressionMethod) { - const components = paths.concat(!compressionMethod || compressionMethod === constants_1.CompressionMethod.Gzip - ? [] - : [compressionMethod]); - // Add salt to cache version to support breaking changes in cache entry - components.push(versionSalt); - return crypto - .createHash('sha256') - .update(components.join('|')) - .digest('hex'); -} -exports.getCacheVersion = getCacheVersion; -function getCacheEntry(keys, paths, options) { - return __awaiter(this, void 0, void 0, function* () { - const httpClient = createHttpClient(); - const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod); - const resource = `cache?keys=${encodeURIComponent(keys.join(','))}&version=${version}`; - const response = yield requestUtils_1.retryTypedResponse('getCacheEntry', () => __awaiter(this, void 0, void 0, function* () { return httpClient.getJson(getCacheApiUrl(resource)); })); - if (response.statusCode === 204) { - return null; - } - if (!requestUtils_1.isSuccessStatusCode(response.statusCode)) { - throw new Error(`Cache service responded with ${response.statusCode}`); - } - const cacheResult = response.result; - const cacheDownloadUrl = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.archiveLocation; - if (!cacheDownloadUrl) { - throw new Error('Cache not found.'); - } - core.setSecret(cacheDownloadUrl); - core.debug(`Cache Result:`); - core.debug(JSON.stringify(cacheResult)); - return cacheResult; - }); -} -exports.getCacheEntry = getCacheEntry; -function downloadCache(archiveLocation, archivePath, options) { - return __awaiter(this, void 0, void 0, function* () { - const archiveUrl = new url_1.URL(archiveLocation); - const downloadOptions = options_1.getDownloadOptions(options); - if (downloadOptions.useAzureSdk && - archiveUrl.hostname.endsWith('.blob.core.windows.net')) { - // Use Azure storage SDK to download caches hosted on Azure to improve speed and reliability. - yield downloadUtils_1.downloadCacheStorageSDK(archiveLocation, archivePath, downloadOptions); - } - else { - // Otherwise, download using the Actions http-client. - yield downloadUtils_1.downloadCacheHttpClient(archiveLocation, archivePath); - } - }); -} -exports.downloadCache = downloadCache; -// Reserve Cache -function reserveCache(key, paths, options) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - const httpClient = createHttpClient(); - const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod); - const reserveCacheRequest = { - key, - version - }; - const response = yield requestUtils_1.retryTypedResponse('reserveCache', () => __awaiter(this, void 0, void 0, function* () { - return httpClient.postJson(getCacheApiUrl('caches'), reserveCacheRequest); - })); - return (_b = (_a = response === null || response === void 0 ? void 0 : response.result) === null || _a === void 0 ? void 0 : _a.cacheId) !== null && _b !== void 0 ? _b : -1; - }); -} -exports.reserveCache = reserveCache; -function getContentRange(start, end) { - // Format: `bytes start-end/filesize - // start and end are inclusive - // filesize can be * - // For a 200 byte chunk starting at byte 0: - // Content-Range: bytes 0-199/* - return `bytes ${start}-${end}/*`; -} -function uploadChunk(httpClient, resourceUrl, openStream, start, end) { - return __awaiter(this, void 0, void 0, function* () { - core.debug(`Uploading chunk of size ${end - - start + - 1} bytes at offset ${start} with content range: ${getContentRange(start, end)}`); - const additionalHeaders = { - 'Content-Type': 'application/octet-stream', - 'Content-Range': getContentRange(start, end) - }; - const uploadChunkResponse = yield requestUtils_1.retryHttpClientResponse(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter(this, void 0, void 0, function* () { - return httpClient.sendStream('PATCH', resourceUrl, openStream(), additionalHeaders); - })); - if (!requestUtils_1.isSuccessStatusCode(uploadChunkResponse.message.statusCode)) { - throw new Error(`Cache service responded with ${uploadChunkResponse.message.statusCode} during upload chunk.`); - } - }); -} -function uploadFile(httpClient, cacheId, archivePath, options) { - return __awaiter(this, void 0, void 0, function* () { - // Upload Chunks - const fileSize = fs.statSync(archivePath).size; - const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`); - const fd = fs.openSync(archivePath, 'r'); - const uploadOptions = options_1.getUploadOptions(options); - const concurrency = utils.assertDefined('uploadConcurrency', uploadOptions.uploadConcurrency); - const maxChunkSize = utils.assertDefined('uploadChunkSize', uploadOptions.uploadChunkSize); - const parallelUploads = [...new Array(concurrency).keys()]; - core.debug('Awaiting all uploads'); - let offset = 0; - try { - yield Promise.all(parallelUploads.map(() => __awaiter(this, void 0, void 0, function* () { - while (offset < fileSize) { - const chunkSize = Math.min(fileSize - offset, maxChunkSize); - const start = offset; - const end = offset + chunkSize - 1; - offset += maxChunkSize; - yield uploadChunk(httpClient, resourceUrl, () => fs - .createReadStream(archivePath, { - fd, - start, - end, - autoClose: false - }) - .on('error', error => { - throw new Error(`Cache upload failed because file read failed with ${error.message}`); - }), start, end); - } - }))); - } - finally { - fs.closeSync(fd); - } - return; - }); -} -function commitCache(httpClient, cacheId, filesize) { - return __awaiter(this, void 0, void 0, function* () { - const commitCacheRequest = { size: filesize }; - return yield requestUtils_1.retryTypedResponse('commitCache', () => __awaiter(this, void 0, void 0, function* () { - return httpClient.postJson(getCacheApiUrl(`caches/${cacheId.toString()}`), commitCacheRequest); - })); - }); -} -function saveCache(cacheId, archivePath, options) { - return __awaiter(this, void 0, void 0, function* () { - const httpClient = createHttpClient(); - core.debug('Upload cache'); - yield uploadFile(httpClient, cacheId, archivePath, options); - // Commit Cache - core.debug('Commiting cache'); - const cacheSize = utils.getArchiveFileSizeIsBytes(archivePath); - const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize); - if (!requestUtils_1.isSuccessStatusCode(commitCacheResponse.statusCode)) { - throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`); - } - core.info('Cache saved successfully'); - }); -} -exports.saveCache = saveCache; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __importStar(__webpack_require__(470)); +const http_client_1 = __webpack_require__(22); +const auth_1 = __webpack_require__(733); +const crypto = __importStar(__webpack_require__(417)); +const fs = __importStar(__webpack_require__(747)); +const url_1 = __webpack_require__(835); +const utils = __importStar(__webpack_require__(15)); +const constants_1 = __webpack_require__(931); +const downloadUtils_1 = __webpack_require__(251); +const options_1 = __webpack_require__(538); +const requestUtils_1 = __webpack_require__(899); +const versionSalt = '1.0'; +function getCacheApiUrl(resource) { + // Ideally we just use ACTIONS_CACHE_URL + const baseUrl = (process.env['ACTIONS_CACHE_URL'] || + process.env['ACTIONS_RUNTIME_URL'] || + '').replace('pipelines', 'artifactcache'); + if (!baseUrl) { + throw new Error('Cache Service Url not found, unable to restore cache.'); + } + const url = `${baseUrl}_apis/artifactcache/${resource}`; + core.debug(`Resource Url: ${url}`); + return url; +} +function createAcceptHeader(type, apiVersion) { + return `${type};api-version=${apiVersion}`; +} +function getRequestOptions() { + const requestOptions = { + headers: { + Accept: createAcceptHeader('application/json', '6.0-preview.1') + } + }; + return requestOptions; +} +function createHttpClient() { + const token = process.env['ACTIONS_RUNTIME_TOKEN'] || ''; + const bearerCredentialHandler = new auth_1.BearerCredentialHandler(token); + return new http_client_1.HttpClient('actions/cache', [bearerCredentialHandler], getRequestOptions()); +} +function getCacheVersion(paths, compressionMethod) { + const components = paths.concat(!compressionMethod || compressionMethod === constants_1.CompressionMethod.Gzip + ? [] + : [compressionMethod]); + // Add salt to cache version to support breaking changes in cache entry + components.push(versionSalt); + return crypto + .createHash('sha256') + .update(components.join('|')) + .digest('hex'); +} +exports.getCacheVersion = getCacheVersion; +function getCacheEntry(keys, paths, options) { + return __awaiter(this, void 0, void 0, function* () { + const httpClient = createHttpClient(); + const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod); + const resource = `cache?keys=${encodeURIComponent(keys.join(','))}&version=${version}`; + const response = yield requestUtils_1.retryTypedResponse('getCacheEntry', () => __awaiter(this, void 0, void 0, function* () { return httpClient.getJson(getCacheApiUrl(resource)); })); + if (response.statusCode === 204) { + return null; + } + if (!requestUtils_1.isSuccessStatusCode(response.statusCode)) { + throw new Error(`Cache service responded with ${response.statusCode}`); + } + const cacheResult = response.result; + const cacheDownloadUrl = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.archiveLocation; + if (!cacheDownloadUrl) { + throw new Error('Cache not found.'); + } + core.setSecret(cacheDownloadUrl); + core.debug(`Cache Result:`); + core.debug(JSON.stringify(cacheResult)); + return cacheResult; + }); +} +exports.getCacheEntry = getCacheEntry; +function downloadCache(archiveLocation, archivePath, options) { + return __awaiter(this, void 0, void 0, function* () { + const archiveUrl = new url_1.URL(archiveLocation); + const downloadOptions = options_1.getDownloadOptions(options); + if (downloadOptions.useAzureSdk && + archiveUrl.hostname.endsWith('.blob.core.windows.net')) { + // Use Azure storage SDK to download caches hosted on Azure to improve speed and reliability. + yield downloadUtils_1.downloadCacheStorageSDK(archiveLocation, archivePath, downloadOptions); + } + else { + // Otherwise, download using the Actions http-client. + yield downloadUtils_1.downloadCacheHttpClient(archiveLocation, archivePath); + } + }); +} +exports.downloadCache = downloadCache; +// Reserve Cache +function reserveCache(key, paths, options) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + const httpClient = createHttpClient(); + const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod); + const reserveCacheRequest = { + key, + version + }; + const response = yield requestUtils_1.retryTypedResponse('reserveCache', () => __awaiter(this, void 0, void 0, function* () { + return httpClient.postJson(getCacheApiUrl('caches'), reserveCacheRequest); + })); + return (_b = (_a = response === null || response === void 0 ? void 0 : response.result) === null || _a === void 0 ? void 0 : _a.cacheId) !== null && _b !== void 0 ? _b : -1; + }); +} +exports.reserveCache = reserveCache; +function getContentRange(start, end) { + // Format: `bytes start-end/filesize + // start and end are inclusive + // filesize can be * + // For a 200 byte chunk starting at byte 0: + // Content-Range: bytes 0-199/* + return `bytes ${start}-${end}/*`; +} +function uploadChunk(httpClient, resourceUrl, openStream, start, end) { + return __awaiter(this, void 0, void 0, function* () { + core.debug(`Uploading chunk of size ${end - + start + + 1} bytes at offset ${start} with content range: ${getContentRange(start, end)}`); + const additionalHeaders = { + 'Content-Type': 'application/octet-stream', + 'Content-Range': getContentRange(start, end) + }; + const uploadChunkResponse = yield requestUtils_1.retryHttpClientResponse(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter(this, void 0, void 0, function* () { + return httpClient.sendStream('PATCH', resourceUrl, openStream(), additionalHeaders); + })); + if (!requestUtils_1.isSuccessStatusCode(uploadChunkResponse.message.statusCode)) { + throw new Error(`Cache service responded with ${uploadChunkResponse.message.statusCode} during upload chunk.`); + } + }); +} +function uploadFile(httpClient, cacheId, archivePath, options) { + return __awaiter(this, void 0, void 0, function* () { + // Upload Chunks + const fileSize = fs.statSync(archivePath).size; + const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`); + const fd = fs.openSync(archivePath, 'r'); + const uploadOptions = options_1.getUploadOptions(options); + const concurrency = utils.assertDefined('uploadConcurrency', uploadOptions.uploadConcurrency); + const maxChunkSize = utils.assertDefined('uploadChunkSize', uploadOptions.uploadChunkSize); + const parallelUploads = [...new Array(concurrency).keys()]; + core.debug('Awaiting all uploads'); + let offset = 0; + try { + yield Promise.all(parallelUploads.map(() => __awaiter(this, void 0, void 0, function* () { + while (offset < fileSize) { + const chunkSize = Math.min(fileSize - offset, maxChunkSize); + const start = offset; + const end = offset + chunkSize - 1; + offset += maxChunkSize; + yield uploadChunk(httpClient, resourceUrl, () => fs + .createReadStream(archivePath, { + fd, + start, + end, + autoClose: false + }) + .on('error', error => { + throw new Error(`Cache upload failed because file read failed with ${error.message}`); + }), start, end); + } + }))); + } + finally { + fs.closeSync(fd); + } + return; + }); +} +function commitCache(httpClient, cacheId, filesize) { + return __awaiter(this, void 0, void 0, function* () { + const commitCacheRequest = { size: filesize }; + return yield requestUtils_1.retryTypedResponse('commitCache', () => __awaiter(this, void 0, void 0, function* () { + return httpClient.postJson(getCacheApiUrl(`caches/${cacheId.toString()}`), commitCacheRequest); + })); + }); +} +function saveCache(cacheId, archivePath, options) { + return __awaiter(this, void 0, void 0, function* () { + const httpClient = createHttpClient(); + core.debug('Upload cache'); + yield uploadFile(httpClient, cacheId, archivePath, options); + // Commit Cache + core.debug('Commiting cache'); + const cacheSize = utils.getArchiveFileSizeIsBytes(archivePath); + core.info(`Cache Size: ~${Math.round(cacheSize / (1024 * 1024))} MB (${cacheSize} B)`); + const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize); + if (!requestUtils_1.isSuccessStatusCode(commitCacheResponse.statusCode)) { + throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`); + } + core.info('Cache saved successfully'); + }); +} +exports.saveCache = saveCache; //# sourceMappingURL=cacheHttpClient.js.map /***/ }), @@ -7468,43 +7511,7 @@ exports.isTokenCredential = isTokenCredential; /***/ }), /* 230 */, -/* 231 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -__exportStar(__webpack_require__(328), exports); -__exportStar(__webpack_require__(715), exports); -__exportStar(__webpack_require__(924), exports); -//# sourceMappingURL=index.js.map - -/***/ }), +/* 231 */, /* 232 */, /* 233 */, /* 234 */, @@ -8115,235 +8122,235 @@ GlobSync.prototype._makeAbs = function (f) { /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(__webpack_require__(470)); -const http_client_1 = __webpack_require__(22); -const storage_blob_1 = __webpack_require__(373); -const buffer = __importStar(__webpack_require__(293)); -const fs = __importStar(__webpack_require__(747)); -const stream = __importStar(__webpack_require__(794)); -const util = __importStar(__webpack_require__(669)); -const utils = __importStar(__webpack_require__(15)); -const constants_1 = __webpack_require__(931); -const requestUtils_1 = __webpack_require__(899); -/** - * Pipes the body of a HTTP response to a stream - * - * @param response the HTTP response - * @param output the writable stream - */ -function pipeResponseToStream(response, output) { - return __awaiter(this, void 0, void 0, function* () { - const pipeline = util.promisify(stream.pipeline); - yield pipeline(response.message, output); - }); -} -/** - * Class for tracking the download state and displaying stats. - */ -class DownloadProgress { - constructor(contentLength) { - this.contentLength = contentLength; - this.segmentIndex = 0; - this.segmentSize = 0; - this.segmentOffset = 0; - this.receivedBytes = 0; - this.displayedComplete = false; - this.startTime = Date.now(); - } - /** - * Progress to the next segment. Only call this method when the previous segment - * is complete. - * - * @param segmentSize the length of the next segment - */ - nextSegment(segmentSize) { - this.segmentOffset = this.segmentOffset + this.segmentSize; - this.segmentIndex = this.segmentIndex + 1; - this.segmentSize = segmentSize; - this.receivedBytes = 0; - core.debug(`Downloading segment at offset ${this.segmentOffset} with length ${this.segmentSize}...`); - } - /** - * Sets the number of bytes received for the current segment. - * - * @param receivedBytes the number of bytes received - */ - setReceivedBytes(receivedBytes) { - this.receivedBytes = receivedBytes; - } - /** - * Returns the total number of bytes transferred. - */ - getTransferredBytes() { - return this.segmentOffset + this.receivedBytes; - } - /** - * Returns true if the download is complete. - */ - isDone() { - return this.getTransferredBytes() === this.contentLength; - } - /** - * Prints the current download stats. Once the download completes, this will print one - * last line and then stop. - */ - display() { - if (this.displayedComplete) { - return; - } - const transferredBytes = this.segmentOffset + this.receivedBytes; - const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); - const elapsedTime = Date.now() - this.startTime; - const downloadSpeed = (transferredBytes / - (1024 * 1024) / - (elapsedTime / 1000)).toFixed(1); - core.info(`Received ${transferredBytes} of ${this.contentLength} (${percentage}%), ${downloadSpeed} MBs/sec`); - if (this.isDone()) { - this.displayedComplete = true; - } - } - /** - * Returns a function used to handle TransferProgressEvents. - */ - onProgress() { - return (progress) => { - this.setReceivedBytes(progress.loadedBytes); - }; - } - /** - * Starts the timer that displays the stats. - * - * @param delayInMs the delay between each write - */ - startDisplayTimer(delayInMs = 1000) { - const displayCallback = () => { - this.display(); - if (!this.isDone()) { - this.timeoutHandle = setTimeout(displayCallback, delayInMs); - } - }; - this.timeoutHandle = setTimeout(displayCallback, delayInMs); - } - /** - * Stops the timer that displays the stats. As this typically indicates the download - * is complete, this will display one last line, unless the last line has already - * been written. - */ - stopDisplayTimer() { - if (this.timeoutHandle) { - clearTimeout(this.timeoutHandle); - this.timeoutHandle = undefined; - } - this.display(); - } -} -exports.DownloadProgress = DownloadProgress; -/** - * Download the cache using the Actions toolkit http-client - * - * @param archiveLocation the URL for the cache - * @param archivePath the local path where the cache is saved - */ -function downloadCacheHttpClient(archiveLocation, archivePath) { - return __awaiter(this, void 0, void 0, function* () { - const writeStream = fs.createWriteStream(archivePath); - const httpClient = new http_client_1.HttpClient('actions/cache'); - const downloadResponse = yield requestUtils_1.retryHttpClientResponse('downloadCache', () => __awaiter(this, void 0, void 0, function* () { return httpClient.get(archiveLocation); })); - // Abort download if no traffic received over the socket. - downloadResponse.message.socket.setTimeout(constants_1.SocketTimeout, () => { - downloadResponse.message.destroy(); - core.debug(`Aborting download, socket timed out after ${constants_1.SocketTimeout} ms`); - }); - yield pipeResponseToStream(downloadResponse, writeStream); - // Validate download size. - const contentLengthHeader = downloadResponse.message.headers['content-length']; - if (contentLengthHeader) { - const expectedLength = parseInt(contentLengthHeader); - const actualLength = utils.getArchiveFileSizeIsBytes(archivePath); - if (actualLength !== expectedLength) { - throw new Error(`Incomplete download. Expected file size: ${expectedLength}, actual file size: ${actualLength}`); - } - } - else { - core.debug('Unable to validate download, no Content-Length header'); - } - }); -} -exports.downloadCacheHttpClient = downloadCacheHttpClient; -/** - * Download the cache using the Azure Storage SDK. Only call this method if the - * URL points to an Azure Storage endpoint. - * - * @param archiveLocation the URL for the cache - * @param archivePath the local path where the cache is saved - * @param options the download options with the defaults set - */ -function downloadCacheStorageSDK(archiveLocation, archivePath, options) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const client = new storage_blob_1.BlockBlobClient(archiveLocation, undefined, { - retryOptions: { - // Override the timeout used when downloading each 4 MB chunk - // The default is 2 min / MB, which is way too slow - tryTimeoutInMs: options.timeoutInMs - } - }); - const properties = yield client.getProperties(); - const contentLength = (_a = properties.contentLength) !== null && _a !== void 0 ? _a : -1; - if (contentLength < 0) { - // We should never hit this condition, but just in case fall back to downloading the - // file as one large stream - core.debug('Unable to determine content length, downloading file with http-client...'); - yield downloadCacheHttpClient(archiveLocation, archivePath); - } - else { - // Use downloadToBuffer for faster downloads, since internally it splits the - // file into 4 MB chunks which can then be parallelized and retried independently - // - // If the file exceeds the buffer maximum length (~1 GB on 32-bit systems and ~2 GB - // on 64-bit systems), split the download into multiple segments - const maxSegmentSize = buffer.constants.MAX_LENGTH; - const downloadProgress = new DownloadProgress(contentLength); - const fd = fs.openSync(archivePath, 'w'); - try { - downloadProgress.startDisplayTimer(); - while (!downloadProgress.isDone()) { - const segmentStart = downloadProgress.segmentOffset + downloadProgress.segmentSize; - const segmentSize = Math.min(maxSegmentSize, contentLength - segmentStart); - downloadProgress.nextSegment(segmentSize); - const result = yield client.downloadToBuffer(segmentStart, segmentSize, { - concurrency: options.downloadConcurrency, - onProgress: downloadProgress.onProgress() - }); - fs.writeFileSync(fd, result); - } - } - finally { - downloadProgress.stopDisplayTimer(); - fs.closeSync(fd); - } - } - }); -} -exports.downloadCacheStorageSDK = downloadCacheStorageSDK; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __importStar(__webpack_require__(470)); +const http_client_1 = __webpack_require__(22); +const storage_blob_1 = __webpack_require__(373); +const buffer = __importStar(__webpack_require__(293)); +const fs = __importStar(__webpack_require__(747)); +const stream = __importStar(__webpack_require__(794)); +const util = __importStar(__webpack_require__(669)); +const utils = __importStar(__webpack_require__(15)); +const constants_1 = __webpack_require__(931); +const requestUtils_1 = __webpack_require__(899); +/** + * Pipes the body of a HTTP response to a stream + * + * @param response the HTTP response + * @param output the writable stream + */ +function pipeResponseToStream(response, output) { + return __awaiter(this, void 0, void 0, function* () { + const pipeline = util.promisify(stream.pipeline); + yield pipeline(response.message, output); + }); +} +/** + * Class for tracking the download state and displaying stats. + */ +class DownloadProgress { + constructor(contentLength) { + this.contentLength = contentLength; + this.segmentIndex = 0; + this.segmentSize = 0; + this.segmentOffset = 0; + this.receivedBytes = 0; + this.displayedComplete = false; + this.startTime = Date.now(); + } + /** + * Progress to the next segment. Only call this method when the previous segment + * is complete. + * + * @param segmentSize the length of the next segment + */ + nextSegment(segmentSize) { + this.segmentOffset = this.segmentOffset + this.segmentSize; + this.segmentIndex = this.segmentIndex + 1; + this.segmentSize = segmentSize; + this.receivedBytes = 0; + core.debug(`Downloading segment at offset ${this.segmentOffset} with length ${this.segmentSize}...`); + } + /** + * Sets the number of bytes received for the current segment. + * + * @param receivedBytes the number of bytes received + */ + setReceivedBytes(receivedBytes) { + this.receivedBytes = receivedBytes; + } + /** + * Returns the total number of bytes transferred. + */ + getTransferredBytes() { + return this.segmentOffset + this.receivedBytes; + } + /** + * Returns true if the download is complete. + */ + isDone() { + return this.getTransferredBytes() === this.contentLength; + } + /** + * Prints the current download stats. Once the download completes, this will print one + * last line and then stop. + */ + display() { + if (this.displayedComplete) { + return; + } + const transferredBytes = this.segmentOffset + this.receivedBytes; + const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); + const elapsedTime = Date.now() - this.startTime; + const downloadSpeed = (transferredBytes / + (1024 * 1024) / + (elapsedTime / 1000)).toFixed(1); + core.info(`Received ${transferredBytes} of ${this.contentLength} (${percentage}%), ${downloadSpeed} MBs/sec`); + if (this.isDone()) { + this.displayedComplete = true; + } + } + /** + * Returns a function used to handle TransferProgressEvents. + */ + onProgress() { + return (progress) => { + this.setReceivedBytes(progress.loadedBytes); + }; + } + /** + * Starts the timer that displays the stats. + * + * @param delayInMs the delay between each write + */ + startDisplayTimer(delayInMs = 1000) { + const displayCallback = () => { + this.display(); + if (!this.isDone()) { + this.timeoutHandle = setTimeout(displayCallback, delayInMs); + } + }; + this.timeoutHandle = setTimeout(displayCallback, delayInMs); + } + /** + * Stops the timer that displays the stats. As this typically indicates the download + * is complete, this will display one last line, unless the last line has already + * been written. + */ + stopDisplayTimer() { + if (this.timeoutHandle) { + clearTimeout(this.timeoutHandle); + this.timeoutHandle = undefined; + } + this.display(); + } +} +exports.DownloadProgress = DownloadProgress; +/** + * Download the cache using the Actions toolkit http-client + * + * @param archiveLocation the URL for the cache + * @param archivePath the local path where the cache is saved + */ +function downloadCacheHttpClient(archiveLocation, archivePath) { + return __awaiter(this, void 0, void 0, function* () { + const writeStream = fs.createWriteStream(archivePath); + const httpClient = new http_client_1.HttpClient('actions/cache'); + const downloadResponse = yield requestUtils_1.retryHttpClientResponse('downloadCache', () => __awaiter(this, void 0, void 0, function* () { return httpClient.get(archiveLocation); })); + // Abort download if no traffic received over the socket. + downloadResponse.message.socket.setTimeout(constants_1.SocketTimeout, () => { + downloadResponse.message.destroy(); + core.debug(`Aborting download, socket timed out after ${constants_1.SocketTimeout} ms`); + }); + yield pipeResponseToStream(downloadResponse, writeStream); + // Validate download size. + const contentLengthHeader = downloadResponse.message.headers['content-length']; + if (contentLengthHeader) { + const expectedLength = parseInt(contentLengthHeader); + const actualLength = utils.getArchiveFileSizeIsBytes(archivePath); + if (actualLength !== expectedLength) { + throw new Error(`Incomplete download. Expected file size: ${expectedLength}, actual file size: ${actualLength}`); + } + } + else { + core.debug('Unable to validate download, no Content-Length header'); + } + }); +} +exports.downloadCacheHttpClient = downloadCacheHttpClient; +/** + * Download the cache using the Azure Storage SDK. Only call this method if the + * URL points to an Azure Storage endpoint. + * + * @param archiveLocation the URL for the cache + * @param archivePath the local path where the cache is saved + * @param options the download options with the defaults set + */ +function downloadCacheStorageSDK(archiveLocation, archivePath, options) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const client = new storage_blob_1.BlockBlobClient(archiveLocation, undefined, { + retryOptions: { + // Override the timeout used when downloading each 4 MB chunk + // The default is 2 min / MB, which is way too slow + tryTimeoutInMs: options.timeoutInMs + } + }); + const properties = yield client.getProperties(); + const contentLength = (_a = properties.contentLength) !== null && _a !== void 0 ? _a : -1; + if (contentLength < 0) { + // We should never hit this condition, but just in case fall back to downloading the + // file as one large stream + core.debug('Unable to determine content length, downloading file with http-client...'); + yield downloadCacheHttpClient(archiveLocation, archivePath); + } + else { + // Use downloadToBuffer for faster downloads, since internally it splits the + // file into 4 MB chunks which can then be parallelized and retried independently + // + // If the file exceeds the buffer maximum length (~1 GB on 32-bit systems and ~2 GB + // on 64-bit systems), split the download into multiple segments + const maxSegmentSize = buffer.constants.MAX_LENGTH; + const downloadProgress = new DownloadProgress(contentLength); + const fd = fs.openSync(archivePath, 'w'); + try { + downloadProgress.startDisplayTimer(); + while (!downloadProgress.isDone()) { + const segmentStart = downloadProgress.segmentOffset + downloadProgress.segmentSize; + const segmentSize = Math.min(maxSegmentSize, contentLength - segmentStart); + downloadProgress.nextSegment(segmentSize); + const result = yield client.downloadToBuffer(segmentStart, segmentSize, { + concurrency: options.downloadConcurrency, + onProgress: downloadProgress.onProgress() + }); + fs.writeFileSync(fd, result); + } + } + finally { + downloadProgress.stopDisplayTimer(); + fs.closeSync(fd); + } + } + }); +} +exports.downloadCacheStorageSDK = downloadCacheStorageSDK; //# sourceMappingURL=downloadUtils.js.map /***/ }), @@ -10882,30 +10889,7 @@ var MatchKind; //# sourceMappingURL=internal-match-kind.js.map /***/ }), -/* 328 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -//# sourceMappingURL=types.js.map - -/***/ }), +/* 328 */, /* 329 */, /* 330 */, /* 331 */, @@ -12854,12 +12838,12 @@ var FilterBlobItem = { name: "String" } }, - tagValue: { - xmlName: "TagValue", - required: true, - serializedName: "TagValue", + tags: { + xmlName: "Tags", + serializedName: "Tags", type: { - name: "String" + name: "Composite", + className: "BlobTags" } } } @@ -13636,6 +13620,12 @@ var ServiceGetAccountInfoHeaders = { ] } }, + isHierarchicalNamespaceEnabled: { + serializedName: "x-ms-is-hns-enabled", + type: { + name: "Boolean" + } + }, errorCode: { serializedName: "x-ms-error-code", type: { @@ -15634,6 +15624,87 @@ var BlockBlobUploadHeaders = { } } }; +var BlockBlobPutBlobFromUrlHeaders = { + serializedName: "blockblob-putblobfromurl-headers", + type: { + name: "Composite", + className: "BlockBlobPutBlobFromUrlHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; var BlobUndeleteHeaders = { serializedName: "blob-undelete-headers", type: { @@ -17895,6 +17966,8 @@ var Mappers = /*#__PURE__*/Object.freeze({ __proto__: null, BlobServiceProperties: BlobServiceProperties, BlobServiceStatistics: BlobServiceStatistics, + BlobTag: BlobTag, + BlobTags: BlobTags, ContainerItem: ContainerItem, ContainerProperties: ContainerProperties, CorsRule: CorsRule, @@ -18125,6 +18198,21 @@ var blobContentType = { } } }; +var blobDeleteType = { + parameterPath: [ + "options", + "blobDeleteType" + ], + mapper: { + serializedName: "deletetype", + type: { + name: "Enum", + allowedValues: [ + "Permanent" + ] + } + } +}; var blobSequenceNumber = { parameterPath: [ "options", @@ -18591,6 +18679,18 @@ var copySource = { } } }; +var copySourceBlobProperties = { + parameterPath: [ + "options", + "copySourceBlobProperties" + ], + mapper: { + serializedName: "x-ms-copy-source-blob-properties", + type: { + name: "Boolean" + } + } +}; var defaultEncryptionScope = { parameterPath: [ "options", @@ -19564,7 +19664,7 @@ var version = { required: true, isConstant: true, serializedName: "x-ms-version", - defaultValue: '2020-02-10', + defaultValue: '2020-04-08', type: { name: "String" } @@ -20845,7 +20945,8 @@ var deleteMethodOperationSpec$1 = { queryParameters: [ snapshot, versionId, - timeoutInSeconds + timeoutInSeconds, + blobDeleteType ], headerParameters: [ deleteSnapshots, @@ -21561,7 +21662,8 @@ var getTagsOperationSpec = { headerParameters: [ version, requestId, - ifTags + ifTags, + leaseId0 ], responses: { 200: { @@ -21592,7 +21694,8 @@ var setTagsOperationSpec = { transactionalContentMD5, transactionalContentCrc64, requestId, - ifTags + ifTags, + leaseId0 ], requestBody: { parameterPath: [ @@ -22345,6 +22448,7 @@ var Mappers$5 = /*#__PURE__*/Object.freeze({ Block: Block, BlockBlobCommitBlockListHeaders: BlockBlobCommitBlockListHeaders, BlockBlobGetBlockListHeaders: BlockBlobGetBlockListHeaders, + BlockBlobPutBlobFromUrlHeaders: BlockBlobPutBlobFromUrlHeaders, BlockBlobStageBlockFromURLHeaders: BlockBlobStageBlockFromURLHeaders, BlockBlobStageBlockHeaders: BlockBlobStageBlockHeaders, BlockBlobUploadHeaders: BlockBlobUploadHeaders, @@ -22378,6 +22482,13 @@ var BlockBlob = /** @class */ (function () { options: options }, uploadOperationSpec, callback); }; + BlockBlob.prototype.putBlobFromUrl = function (contentLength, copySource, options, callback) { + return this.client.sendOperationRequest({ + contentLength: contentLength, + copySource: copySource, + options: options + }, putBlobFromUrlOperationSpec, callback); + }; BlockBlob.prototype.stageBlock = function (blockId, contentLength, body, options, callback) { return this.client.sendOperationRequest({ blockId: blockId, @@ -22468,6 +22579,61 @@ var uploadOperationSpec = { isXML: true, serializer: serializer$5 }; +var putBlobFromUrlOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds + ], + headerParameters: [ + transactionalContentMD5, + contentLength, + metadata, + encryptionScope, + tier0, + version, + requestId, + sourceContentMD5, + blobTagsString, + copySource, + copySourceBlobProperties, + blobType2, + blobContentType, + blobContentEncoding, + blobContentLanguage, + blobContentMD5, + blobCacheControl, + blobContentDisposition, + leaseId0, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags, + sourceIfModifiedSince, + sourceIfUnmodifiedSince, + sourceIfMatch, + sourceIfNoneMatch, + sourceIfTags + ], + responses: { + 201: { + headersMapper: BlockBlobPutBlobFromUrlHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlockBlobPutBlobFromUrlHeaders + } + }, + isXML: true, + serializer: serializer$5 +}; var stageBlockOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", @@ -22647,8 +22813,8 @@ var logger = logger$1.createClientLogger("storage-blob"); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -var SDK_VERSION = "12.3.0"; -var SERVICE_VERSION = "2020-02-10"; +var SDK_VERSION = "12.4.1"; +var SERVICE_VERSION = "2020-04-08"; var BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES = 256 * 1024 * 1024; // 256MB var BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES = 4000 * 1024 * 1024; // 4000MB var BLOCK_BLOB_MAX_BLOCKS = 50000; @@ -23044,6 +23210,18 @@ function setURLParameter(url, name, value) { urlParsed.setQueryParameter(name, value); return urlParsed.toString(); } +/** + * Get URL parameter by name. + * + * @export + * @param {string} url + * @param {string} name + * @returns {(string | string[] | undefined)} + */ +function getURLParameter(url, name) { + var urlParsed = coreHttp.URLBuilder.parse(url); + return urlParsed.getQueryParameterValue(name); +} /** * Set URL host. * @@ -23129,6 +23307,26 @@ function getURLQueries(url) { } return queries; } +/** + * Append a string to URL query. + * + * @export + * @param {string} url Source URL string. + * @param {string} queryParts String to be appended to the URL query. + * @returns {string} An updated URL string. + */ +function appendToURLQuery(url, queryParts) { + var urlParsed = coreHttp.URLBuilder.parse(url); + var query = urlParsed.getQuery(); + if (query) { + query += "&" + queryParts; + } + else { + query = queryParts; + } + urlParsed.setQuery(query); + return urlParsed.toString(); +} /** * Rounds a date off to seconds. * @@ -23434,6 +23632,18 @@ function parseObjectReplicationRecord(objectReplicationRecord) { } return orProperties; } +/** + * Attach a TokenCredential to an object. + * + * @export + * @param {T} thing + * @param {TokenCredential} credential + * @returns {T} + */ +function attachCredential(thing, credential) { + thing.credential = credential; + return thing; +} // Copyright (c) Microsoft Corporation. All rights reserved. /** @@ -23678,11 +23888,7 @@ var StorageRetryPolicy = /** @class */ (function (_super) { var retriableError = retriableErrors_1[_i]; if (err.name.toUpperCase().includes(retriableError) || err.message.toUpperCase().includes(retriableError) || - (err.code && - err.code - .toString() - .toUpperCase() - .includes(retriableError))) { + (err.code && err.code.toString().toUpperCase() === retriableError)) { logger.info("RetryPolicy: Network error " + retriableError + " found, will retry."); return true; } @@ -23703,6 +23909,10 @@ var StorageRetryPolicy = /** @class */ (function (_super) { return true; } } + if ((err === null || err === void 0 ? void 0 : err.code) === "PARSE_ERROR" && (err === null || err === void 0 ? void 0 : err.message.startsWith("Error \"Error: Unclosed root tag"))) { + logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry."); + return true; + } return false; }; /** @@ -23962,9 +24172,7 @@ var TelemetryPolicyFactory = /** @class */ (function () { var userAgentInfo = []; { if (telemetry) { - // FIXME: replace() only replaces the first space. And we have no idea why we need to replace spaces in the first place. - // But fixing this would be a breaking change. Logged an issue here: https://github.com/Azure/azure-sdk-for-js/issues/10793 - var telemetryString = (telemetry.userAgentPrefix || "").replace(" ", ""); + var telemetryString = telemetry.userAgentPrefix || ""; if (telemetryString.length > 0 && userAgentInfo.indexOf(telemetryString) === -1) { userAgentInfo.push(telemetryString); } @@ -24067,8 +24275,11 @@ function newPipeline(credential, pipelineOptions) { telemetryPolicy, coreHttp.generateClientRequestIdPolicy(), new StorageBrowserPolicyFactory(), - coreHttp.deserializationPolicy(), new StorageRetryPolicyFactory(pipelineOptions.retryOptions), + // Default deserializationPolicy is provided by protocol layer + // Use customized XML char key of "#" so we could deserialize metadata + // with "_" key + coreHttp.deserializationPolicy(undefined, { xmlCharKey: "#" }), coreHttp.logPolicy({ logger: logger.info, allowedHeaderNames: StorageBlobLoggingAllowedHeaderNames, @@ -24081,13 +24292,12 @@ function newPipeline(credential, pipelineOptions) { factories.push(coreHttp.disableResponseDecompressionPolicy()); } factories.push(coreHttp.isTokenCredential(credential) - ? coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes) + ? attachCredential(coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes), credential) : credential); return new Pipeline(factories, pipelineOptions); } // Copyright (c) Microsoft Corporation. All rights reserved. -var ABORT_ERROR = new abortController.AbortError("The operation was aborted."); /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -24111,36 +24321,9 @@ var RetriableReadableStream = /** @class */ (function (_super) { */ function RetriableReadableStream(source, getter, offset, count, options) { if (options === void 0) { options = {}; } - var _this = _super.call(this) || this; + var _this = _super.call(this, { highWaterMark: options.highWaterMark }) || this; _this.retries = 0; - _this.abortHandler = function () { - _this.source.pause(); - _this.emit("error", ABORT_ERROR); - }; - _this.aborter = options.abortSignal || abortController.AbortSignal.none; - _this.getter = getter; - _this.source = source; - _this.start = offset; - _this.offset = offset; - _this.end = offset + count - 1; - _this.maxRetryRequests = - options.maxRetryRequests && options.maxRetryRequests >= 0 ? options.maxRetryRequests : 0; - _this.onProgress = options.onProgress; - _this.options = options; - _this.aborter.addEventListener("abort", _this.abortHandler); - _this.setSourceDataHandler(); - _this.setSourceEndHandler(); - _this.setSourceErrorHandler(); - return _this; - } - RetriableReadableStream.prototype._read = function () { - if (!this.aborter.aborted) { - this.source.resume(); - } - }; - RetriableReadableStream.prototype.setSourceDataHandler = function () { - var _this = this; - this.source.on("data", function (data) { + _this.sourceDataHandler = function (data) { if (_this.options.doInjectErrorOnce) { _this.options.doInjectErrorOnce = undefined; _this.source.pause(); @@ -24158,18 +24341,19 @@ var RetriableReadableStream = /** @class */ (function (_super) { if (!_this.push(data)) { _this.source.pause(); } - }); - }; - RetriableReadableStream.prototype.setSourceEndHandler = function () { - var _this = this; - this.source.on("end", function () { + }; + _this.sourceErrorOrEndHandler = function (err) { + if (err && err.name === "AbortError") { + _this.destroy(err); + return; + } // console.log( - // `Source stream emits end, offset: ${ + // `Source stream emits end or error, offset: ${ // this.offset // }, dest end : ${this.end}` // ); + _this.removeSourceEventHandlers(); if (_this.offset - 1 === _this.end) { - _this.aborter.removeEventListener("abort", _this.abortHandler); _this.push(null); } else if (_this.offset <= _this.end) { @@ -24181,31 +24365,53 @@ var RetriableReadableStream = /** @class */ (function (_super) { _this.getter(_this.offset) .then(function (newSource) { _this.source = newSource; - _this.setSourceDataHandler(); - _this.setSourceEndHandler(); - _this.setSourceErrorHandler(); + _this.setSourceEventHandlers(); }) .catch(function (error) { - _this.emit("error", error); + _this.destroy(error); }); } else { - _this.emit("error", new Error( + _this.destroy(new Error( // tslint:disable-next-line:max-line-length "Data corruption failure: received less data than required and reached maxRetires limitation. Received data offset: " + (_this .offset - 1) + ", data needed offset: " + _this.end + ", retries: " + _this.retries + ", max retries: " + _this.maxRetryRequests)); } } else { - _this.emit("error", new Error("Data corruption failure: Received more data than original request, data needed offset is " + _this.end + ", received offset: " + (_this.offset - 1))); + _this.destroy(new Error("Data corruption failure: Received more data than original request, data needed offset is " + _this.end + ", received offset: " + (_this.offset - 1))); } - }); + }; + _this.getter = getter; + _this.source = source; + _this.start = offset; + _this.offset = offset; + _this.end = offset + count - 1; + _this.maxRetryRequests = + options.maxRetryRequests && options.maxRetryRequests >= 0 ? options.maxRetryRequests : 0; + _this.onProgress = options.onProgress; + _this.options = options; + _this.setSourceEventHandlers(); + return _this; + } + RetriableReadableStream.prototype._read = function () { + this.source.resume(); }; - RetriableReadableStream.prototype.setSourceErrorHandler = function () { - var _this = this; - this.source.on("error", function (error) { - _this.emit("error", error); - }); + RetriableReadableStream.prototype.setSourceEventHandlers = function () { + this.source.on("data", this.sourceDataHandler); + this.source.on("end", this.sourceErrorOrEndHandler); + this.source.on("error", this.sourceErrorOrEndHandler); + }; + RetriableReadableStream.prototype.removeSourceEventHandlers = function () { + this.source.removeListener("data", this.sourceDataHandler); + this.source.removeListener("end", this.sourceErrorOrEndHandler); + this.source.removeListener("error", this.sourceErrorOrEndHandler); + }; + RetriableReadableStream.prototype._destroy = function (error, callback) { + // remove listener from source and release source + this.removeSourceEventHandlers(); + this.source.destroy(); + callback(error === null ? undefined : error); }; return RetriableReadableStream; }(stream.Readable)); @@ -25664,7 +25870,7 @@ var AvroReadable = /** @class */ (function () { }()); // Copyright (c) Microsoft Corporation. -var ABORT_ERROR$1 = new abortController.AbortError("Reading from the avro stream was aborted."); +var ABORT_ERROR = new abortController.AbortError("Reading from the avro stream was aborted."); var AvroReadableFromStream = /** @class */ (function (_super) { tslib.__extends(AvroReadableFromStream, _super); function AvroReadableFromStream(readable) { @@ -25694,7 +25900,7 @@ var AvroReadableFromStream = /** @class */ (function (_super) { var _this = this; return tslib.__generator(this, function (_b) { if ((_a = options.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { - throw ABORT_ERROR$1; + throw ABORT_ERROR; } if (size < 0) { throw new Error("size parameter should be positive: " + size); @@ -25738,7 +25944,7 @@ var AvroReadableFromStream = /** @class */ (function (_super) { }; var abortHandler = function () { cleanUp(); - reject(ABORT_ERROR$1); + reject(ABORT_ERROR); }; _this._readable.on("readable", readableCallback); _this._readable.once("error", rejectCallback); @@ -25776,6 +25982,7 @@ var BlobQuickQueryStream = /** @class */ (function (_super) { function BlobQuickQueryStream(source, options) { if (options === void 0) { options = {}; } var _this = _super.call(this) || this; + _this.avroPaused = true; _this.source = source; _this.onProgress = options.onProgress; _this.onError = options.onError; @@ -25785,29 +25992,31 @@ var BlobQuickQueryStream = /** @class */ (function (_super) { } BlobQuickQueryStream.prototype._read = function () { var _this = this; - this.readInternal().catch(function (err) { - _this.emit("error", err); - }); + if (this.avroPaused) { + this.readInternal().catch(function (err) { + _this.emit("error", err); + }); + } }; BlobQuickQueryStream.prototype.readInternal = function () { - var e_1, _a; return tslib.__awaiter(this, void 0, void 0, function () { - var _b, _c, obj, schema, exit, data, bytesScanned, totalBytes, fatal, name_1, description, position, e_1_1; - return tslib.__generator(this, function (_d) { - switch (_d.label) { + var avroNext, obj, schema, data, bytesScanned, totalBytes, fatal, name_1, description, position; + return tslib.__generator(this, function (_a) { + switch (_a.label) { case 0: - _d.trys.push([0, 5, 6, 11]); - _b = tslib.__asyncValues(this.avroIter); - _d.label = 1; - case 1: return [4 /*yield*/, _b.next()]; + this.avroPaused = false; + _a.label = 1; + case 1: return [4 /*yield*/, this.avroIter.next()]; case 2: - if (!(_c = _d.sent(), !_c.done)) return [3 /*break*/, 4]; - obj = _c.value; + avroNext = _a.sent(); + if (avroNext.done) { + return [3 /*break*/, 4]; + } + obj = avroNext.value; schema = obj.$schema; if (typeof schema !== "string") { throw Error("Missing schema in avro record."); } - exit = false; switch (schema) { case "com.microsoft.azure.storage.queryBlobContents.resultData": data = obj.data; @@ -25815,7 +26024,7 @@ var BlobQuickQueryStream = /** @class */ (function (_super) { throw Error("Invalid data in avro result record."); } if (!this.push(Buffer.from(data))) { - exit = true; + this.avroPaused = true; } break; case "com.microsoft.azure.storage.queryBlobContents.progress": @@ -25866,29 +26075,11 @@ var BlobQuickQueryStream = /** @class */ (function (_super) { default: throw Error("Unknown schema " + schema + " in avro progress record."); } - if (exit) { - return [3 /*break*/, 4]; - } - _d.label = 3; - case 3: return [3 /*break*/, 1]; - case 4: return [3 /*break*/, 11]; - case 5: - e_1_1 = _d.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 11]; - case 6: - _d.trys.push([6, , 9, 10]); - if (!(_c && !_c.done && (_a = _b.return))) return [3 /*break*/, 8]; - return [4 /*yield*/, _a.call(_b)]; - case 7: - _d.sent(); - _d.label = 8; - case 8: return [3 /*break*/, 10]; - case 9: - if (e_1) throw e_1.error; - return [7 /*endfinally*/]; - case 10: return [7 /*endfinally*/]; - case 11: return [2 /*return*/]; + _a.label = 3; + case 3: + if (!avroNext.done && !this.avroPaused) return [3 /*break*/, 1]; + _a.label = 4; + case 4: return [2 /*return*/]; } }); }); @@ -26700,7 +26891,7 @@ var StorageSharedKeyCredential = /** @class */ (function (_super) { * regenerated. */ var packageName = "azure-storage-blob"; -var packageVersion = "12.3.0"; +var packageVersion = "12.4.1"; var StorageClientContext = /** @class */ (function (_super) { tslib.__extends(StorageClientContext, _super); /** @@ -26722,7 +26913,7 @@ var StorageClientContext = /** @class */ (function (_super) { options.userAgent = packageName + "/" + packageVersion + " " + defaultUserAgent; } _this = _super.call(this, undefined, options) || this; - _this.version = "2020-02-10"; + _this.version = '2020-04-08'; _this.baseUri = "{url}"; _this.requestContentType = "application/json; charset=utf-8"; _this.url = url; @@ -26835,7 +27026,7 @@ function rangeResponseFromModel(response) { * This is the poller returned by {@link BlobClient.beginCopyFromURL}. * This can not be instantiated directly outside of this package. * - * @ignore + * @hidden */ var BlobBeginCopyFromUrlPoller = /** @class */ (function (_super) { tslib.__extends(BlobBeginCopyFromUrlPoller, _super); @@ -26865,7 +27056,7 @@ var BlobBeginCopyFromUrlPoller = /** @class */ (function (_super) { * Note: Intentionally using function expression over arrow function expression * so that the function can be invoked with a different context. * This affects what `this` refers to. - * @ignore + * @hidden */ var cancel = function cancel(options) { if (options === void 0) { options = {}; } @@ -26900,7 +27091,7 @@ var cancel = function cancel(options) { * Note: Intentionally using function expression over arrow function expression * so that the function can be invoked with a different context. * This affects what `this` refers to. - * @ignore + * @hidden */ var update = function update(options) { if (options === void 0) { options = {}; } @@ -26965,7 +27156,7 @@ var update = function update(options) { * Note: Intentionally using function expression over arrow function expression * so that the function can be invoked with a different context. * This affects what `this` refers to. - * @ignore + * @hidden */ var toString = function toString() { return JSON.stringify({ state: this.state }, function (key, value) { @@ -26978,7 +27169,7 @@ var toString = function toString() { }; /** * Creates a poll operation given the provided state. - * @ignore + * @hidden */ function makeBlobBeginCopyFromURLPollOperation(state) { return { @@ -27038,10 +27229,14 @@ var StorageClient = /** @class */ (function () { for (var _i = 0, _a = this.pipeline.factories; _i < _a.length; _i++) { var factory = _a[_i]; if ((coreHttp.isNode && factory instanceof StorageSharedKeyCredential) || - factory instanceof AnonymousCredential || - coreHttp.isTokenCredential(factory)) { + factory instanceof AnonymousCredential) { this.credential = factory; } + else if (coreHttp.isTokenCredential(factory.credential)) { + // Only works if the factory has been attached a "credential" property. + // We do that in newPipeline() when using TokenCredential. + this.credential = factory.credential; + } } // Override protocol layer's default content-type var storageClientContext = this.storageClientContext; @@ -27890,1356 +28085,1502 @@ function readStreamToLocalFile(rs, file) { var fsStat = util.promisify(fs.stat); var fsCreateReadStream = fs.createReadStream; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. /** - * A BlobClient represents a URL to an Azure Storage blob; the blob may be a block blob, - * append blob, or page blob. + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a blob. Setting + * a value to true means that any SAS which uses these permissions will grant permissions for that operation. Once all + * the values are set, this should be serialized with toString and set as the permissions field on a + * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but + * the order of the permissions is particular and this class guarantees correctness. * * @export - * @class BlobClient + * @class BlobSASPermissions */ -var BlobClient = /** @class */ (function (_super) { - tslib.__extends(BlobClient, _super); - function BlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { - var _a; - var _this = this; - options = options || {}; - var pipeline; - var url; - if (credentialOrPipelineOrContainerName instanceof Pipeline) { - // (url: string, pipeline: Pipeline) - url = urlOrConnectionString; - pipeline = credentialOrPipelineOrContainerName; - } - else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || - credentialOrPipelineOrContainerName instanceof AnonymousCredential || - coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { - // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) - url = urlOrConnectionString; - options = blobNameOrOptions; - pipeline = newPipeline(credentialOrPipelineOrContainerName, options); - } - else if (!credentialOrPipelineOrContainerName && - typeof credentialOrPipelineOrContainerName !== "string") { - // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) - // The second parameter is undefined. Use anonymous credential. - url = urlOrConnectionString; - pipeline = newPipeline(new AnonymousCredential(), options); - } - else if (credentialOrPipelineOrContainerName && - typeof credentialOrPipelineOrContainerName === "string" && - blobNameOrOptions && - typeof blobNameOrOptions === "string") { - // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) - var containerName = credentialOrPipelineOrContainerName; - var blobName = blobNameOrOptions; - var extractedCreds = extractConnectionStringParts(urlOrConnectionString); - if (extractedCreds.kind === "AccountConnString") { - { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); - options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); - pipeline = newPipeline(sharedKeyCredential, options); - } - } - else if (extractedCreds.kind === "SASConnString") { - url = - appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + - "?" + - extractedCreds.accountSas; - pipeline = newPipeline(new AnonymousCredential(), options); - } - else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); - } - } - else { - throw new Error("Expecting non-empty strings for containerName and blobName parameters"); - } - _this = _super.call(this, url, pipeline) || this; - (_a = _this.getBlobAndContainerNamesFromUrl(), _this._name = _a.blobName, _this._containerName = _a.containerName); - _this.blobContext = new Blob$1(_this.storageClientContext); - return _this; - } - Object.defineProperty(BlobClient.prototype, "name", { +var BlobSASPermissions = /** @class */ (function () { + function BlobSASPermissions() { /** - * The name of the blob. + * Specifies Read access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions */ - get: function () { - return this._name; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobClient.prototype, "containerName", { + this.read = false; /** - * The name of the storage container the blob is associated with. + * Specifies Add access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions */ - get: function () { - return this._containerName; - }, - enumerable: false, - configurable: true - }); + this.add = false; + /** + * Specifies Create access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.create = false; + /** + * Specifies Write access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.write = false; + /** + * Specifies Delete access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.delete = false; + /** + * Specifies Delete version access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.deleteVersion = false; + /** + * Specfies Tag access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.tag = false; + /** + * Specifies Move access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.move = false; + /** + * Specifies Execute access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.execute = false; + } /** - * Creates a new BlobClient object identical to the source but with the specified snapshot timestamp. - * Provide "" will remove the snapshot and return a Client to the base blob. + * Creates a {@link BlobSASPermissions} from the specified permissions string. This method will throw an + * Error if it encounters a character that does not correspond to a valid permission. * - * @param {string} snapshot The snapshot timestamp. - * @returns {BlobClient} A new BlobClient object identical to the source but with the specified snapshot timestamp - * @memberof BlobClient + * @static + * @param {string} permissions + * @returns {BlobSASPermissions} + * @memberof BlobSASPermissions */ - BlobClient.prototype.withSnapshot = function (snapshot) { - return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); + BlobSASPermissions.parse = function (permissions) { + var blobSASPermissions = new BlobSASPermissions(); + for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { + var char = permissions_1[_i]; + switch (char) { + case "r": + blobSASPermissions.read = true; + break; + case "a": + blobSASPermissions.add = true; + break; + case "c": + blobSASPermissions.create = true; + break; + case "w": + blobSASPermissions.write = true; + break; + case "d": + blobSASPermissions.delete = true; + break; + case "x": + blobSASPermissions.deleteVersion = true; + break; + case "t": + blobSASPermissions.tag = true; + break; + case "m": + blobSASPermissions.move = true; + break; + case "e": + blobSASPermissions.execute = true; + break; + default: + throw new RangeError("Invalid permission: " + char); + } + } + return blobSASPermissions; }; /** - * Creates a new BlobClient object pointing to a version of this blob. - * Provide "" will remove the versionId and return a Client to the base blob. + * Creates a {@link BlobSASPermissions} from a raw object which contains same keys as it + * and boolean values for them. * - * @param {string} versionId The versionId. - * @returns {BlobClient} A new BlobClient object pointing to the version of this blob. - * @memberof BlobClient + * @static + * @param {BlobSASPermissionsLike} permissionLike + * @returns {BlobSASPermissions} + * @memberof BlobSASPermissions */ - BlobClient.prototype.withVersion = function (versionId) { - return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.VERSIONID, versionId.length === 0 ? undefined : versionId), this.pipeline); + BlobSASPermissions.from = function (permissionLike) { + var blobSASPermissions = new BlobSASPermissions(); + if (permissionLike.read) { + blobSASPermissions.read = true; + } + if (permissionLike.add) { + blobSASPermissions.add = true; + } + if (permissionLike.create) { + blobSASPermissions.create = true; + } + if (permissionLike.write) { + blobSASPermissions.write = true; + } + if (permissionLike.delete) { + blobSASPermissions.delete = true; + } + if (permissionLike.deleteVersion) { + blobSASPermissions.deleteVersion = true; + } + if (permissionLike.tag) { + blobSASPermissions.tag = true; + } + if (permissionLike.move) { + blobSASPermissions.move = true; + } + if (permissionLike.execute) { + blobSASPermissions.execute = true; + } + return blobSASPermissions; }; /** - * Creates a AppendBlobClient object. + * Converts the given permissions to a string. Using this method will guarantee the permissions are in an + * order accepted by the service. * - * @returns {AppendBlobClient} - * @memberof BlobClient + * @returns {string} A string which represents the BlobSASPermissions + * @memberof BlobSASPermissions */ - BlobClient.prototype.getAppendBlobClient = function () { - return new AppendBlobClient(this.url, this.pipeline); + BlobSASPermissions.prototype.toString = function () { + var permissions = []; + if (this.read) { + permissions.push("r"); + } + if (this.add) { + permissions.push("a"); + } + if (this.create) { + permissions.push("c"); + } + if (this.write) { + permissions.push("w"); + } + if (this.delete) { + permissions.push("d"); + } + if (this.deleteVersion) { + permissions.push("x"); + } + if (this.tag) { + permissions.push("t"); + } + if (this.move) { + permissions.push("m"); + } + if (this.execute) { + permissions.push("e"); + } + return permissions.join(""); }; + return BlobSASPermissions; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a container. + * Setting a value to true means that any SAS which uses these permissions will grant permissions for that operation. + * Once all the values are set, this should be serialized with toString and set as the permissions field on a + * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but + * the order of the permissions is particular and this class guarantees correctness. + * + * @export + * @class ContainerSASPermissions + */ +var ContainerSASPermissions = /** @class */ (function () { + function ContainerSASPermissions() { + /** + * Specifies Read access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.read = false; + /** + * Specifies Add access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.add = false; + /** + * Specifies Create access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.create = false; + /** + * Specifies Write access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.write = false; + /** + * Specifies Delete access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.delete = false; + /** + * Specifies Delete version access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.deleteVersion = false; + /** + * Specifies List access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.list = false; + /** + * Specfies Tag access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.tag = false; + /** + * Specifies Move access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.move = false; + /** + * Specifies Execute access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.execute = false; + } /** - * Creates a BlockBlobClient object. + * Creates an {@link ContainerSASPermissions} from the specified permissions string. This method will throw an + * Error if it encounters a character that does not correspond to a valid permission. * - * @returns {BlockBlobClient} - * @memberof BlobClient + * @static + * @param {string} permissions + * @returns {ContainerSASPermissions} + * @memberof ContainerSASPermissions */ - BlobClient.prototype.getBlockBlobClient = function () { - return new BlockBlobClient(this.url, this.pipeline); + ContainerSASPermissions.parse = function (permissions) { + var containerSASPermissions = new ContainerSASPermissions(); + for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { + var char = permissions_1[_i]; + switch (char) { + case "r": + containerSASPermissions.read = true; + break; + case "a": + containerSASPermissions.add = true; + break; + case "c": + containerSASPermissions.create = true; + break; + case "w": + containerSASPermissions.write = true; + break; + case "d": + containerSASPermissions.delete = true; + break; + case "l": + containerSASPermissions.list = true; + break; + case "t": + containerSASPermissions.tag = true; + break; + case "x": + containerSASPermissions.deleteVersion = true; + break; + case "m": + containerSASPermissions.move = true; + break; + case "e": + containerSASPermissions.execute = true; + break; + default: + throw new RangeError("Invalid permission " + char); + } + } + return containerSASPermissions; }; /** - * Creates a PageBlobClient object. + * Creates a {@link ContainerSASPermissions} from a raw object which contains same keys as it + * and boolean values for them. * - * @returns {PageBlobClient} - * @memberof BlobClient + * @static + * @param {ContainerSASPermissionsLike} permissionLike + * @returns {ContainerSASPermissions} + * @memberof ContainerSASPermissions */ - BlobClient.prototype.getPageBlobClient = function () { - return new PageBlobClient(this.url, this.pipeline); + ContainerSASPermissions.from = function (permissionLike) { + var containerSASPermissions = new ContainerSASPermissions(); + if (permissionLike.read) { + containerSASPermissions.read = true; + } + if (permissionLike.add) { + containerSASPermissions.add = true; + } + if (permissionLike.create) { + containerSASPermissions.create = true; + } + if (permissionLike.write) { + containerSASPermissions.write = true; + } + if (permissionLike.delete) { + containerSASPermissions.delete = true; + } + if (permissionLike.list) { + containerSASPermissions.list = true; + } + if (permissionLike.deleteVersion) { + containerSASPermissions.deleteVersion = true; + } + if (permissionLike.tag) { + containerSASPermissions.tag = true; + } + if (permissionLike.move) { + containerSASPermissions.move = true; + } + if (permissionLike.execute) { + containerSASPermissions.execute = true; + } + return containerSASPermissions; }; /** - * Reads or downloads a blob from the system, including its metadata and properties. - * You can also call Get Blob to read a snapshot. - * - * * In Node.js, data returns in a Readable stream readableStreamBody - * * In browsers, data returns in a promise blobBody - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob - * - * @param {number} [offset] From which position of the blob to download, >= 0 - * @param {number} [count] How much data to be downloaded, > 0. Will download to the end when undefined - * @param {BlobDownloadOptions} [options] Optional options to Blob Download operation. - * @returns {Promise} - * @memberof BlobClient - * - * Example usage (Node.js): - * - * ```js - * // Download and convert a blob to a string - * const downloadBlockBlobResponse = await blobClient.download(); - * const downloaded = await streamToBuffer(downloadBlockBlobResponse.readableStreamBody); - * console.log("Downloaded blob content:", downloaded.toString()); - * - * async function streamToBuffer(readableStream) { - * return new Promise((resolve, reject) => { - * const chunks = []; - * readableStream.on("data", (data) => { - * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); - * }); - * readableStream.on("end", () => { - * resolve(Buffer.concat(chunks)); - * }); - * readableStream.on("error", reject); - * }); - * } - * ``` - * - * Example usage (browser): + * Converts the given permissions to a string. Using this method will guarantee the permissions are in an + * order accepted by the service. * - * ```js - * // Download and convert a blob to a string - * const downloadBlockBlobResponse = await blobClient.download(); - * const downloaded = await blobToString(await downloadBlockBlobResponse.blobBody); - * console.log( - * "Downloaded blob content", - * downloaded - * ); + * The order of the characters should be as specified here to ensure correctness. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * - * async function blobToString(blob: Blob): Promise { - * const fileReader = new FileReader(); - * return new Promise((resolve, reject) => { - * fileReader.onloadend = (ev: any) => { - * resolve(ev.target!.result); - * }; - * fileReader.onerror = reject; - * fileReader.readAsText(blob); - * }); - * } - * ``` + * @returns {string} + * @memberof ContainerSASPermissions */ - BlobClient.prototype.download = function (offset, count, options) { - var _a; - if (offset === void 0) { offset = 0; } - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, res_1, wrappedRes, e_1; - var _this = this; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - options.conditions = options.conditions || {}; - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - _b = createSpan("BlobClient-download", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.download({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - onDownloadProgress: coreHttp.isNode ? undefined : options.onProgress, - range: offset === 0 && !count ? undefined : rangeToString({ offset: offset, count: count }), - rangeGetContentMD5: options.rangeGetContentMD5, - rangeGetContentCRC64: options.rangeGetContentCrc64, - snapshot: options.snapshot, - cpkInfo: options.customerProvidedKey, - spanOptions: spanOptions - })]; - case 2: - res_1 = _c.sent(); - wrappedRes = tslib.__assign(tslib.__assign({}, res_1), { _response: res_1._response, objectReplicationDestinationPolicyId: res_1.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res_1.objectReplicationRules) }); - // We support retrying when download stream unexpected ends in Node.js runtime - // Following code shouldn't be bundled into browser build, however some - // bundlers may try to bundle following code and "FileReadResponse.ts". - // In this case, "FileDownloadResponse.browser.ts" will be used as a shim of "FileDownloadResponse.ts" - // The config is in package.json "browser" field - if (options.maxRetryRequests === undefined || options.maxRetryRequests < 0) { - // TODO: Default value or make it a required parameter? - options.maxRetryRequests = DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS; - } - if (res_1.contentLength === undefined) { - throw new RangeError("File download response doesn't contain valid content length header"); - } - if (!res_1.etag) { - throw new RangeError("File download response doesn't contain valid etag header"); - } - return [2 /*return*/, new BlobDownloadResponse(wrappedRes, function (start) { return tslib.__awaiter(_this, void 0, void 0, function () { - var updatedOptions; - var _a; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - updatedOptions = { - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ifMatch: options.conditions.ifMatch || res_1.etag, - ifModifiedSince: options.conditions.ifModifiedSince, - ifNoneMatch: options.conditions.ifNoneMatch, - ifUnmodifiedSince: options.conditions.ifUnmodifiedSince, - ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions - }, - range: rangeToString({ - count: offset + res_1.contentLength - start, - offset: start - }), - rangeGetContentMD5: options.rangeGetContentMD5, - rangeGetContentCRC64: options.rangeGetContentCrc64, - snapshot: options.snapshot, - cpkInfo: options.customerProvidedKey - }; - return [4 /*yield*/, this.blobContext.download(tslib.__assign({ abortSignal: options.abortSignal }, updatedOptions))]; - case 1: - // Debug purpose only - // console.log( - // `Read from internal stream, range: ${ - // updatedOptions.range - // }, options: ${JSON.stringify(updatedOptions)}` - // ); - return [2 /*return*/, (_b.sent()).readableStreamBody]; - } - }); - }); }, offset, res_1.contentLength, { - abortSignal: options.abortSignal, - maxRetryRequests: options.maxRetryRequests, - onProgress: options.onProgress - })]; - case 3: - e_1 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_1.message - }); - throw e_1; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + ContainerSASPermissions.prototype.toString = function () { + var permissions = []; + if (this.read) { + permissions.push("r"); + } + if (this.add) { + permissions.push("a"); + } + if (this.create) { + permissions.push("c"); + } + if (this.write) { + permissions.push("w"); + } + if (this.delete) { + permissions.push("d"); + } + if (this.deleteVersion) { + permissions.push("x"); + } + if (this.list) { + permissions.push("l"); + } + if (this.tag) { + permissions.push("t"); + } + if (this.move) { + permissions.push("m"); + } + if (this.execute) { + permissions.push("e"); + } + return permissions.join(""); }; + return ContainerSASPermissions; +}()); + +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * UserDelegationKeyCredential is only used for generation of user delegation SAS. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas + * + * @export + * @class UserDelegationKeyCredential + */ +var UserDelegationKeyCredential = /** @class */ (function () { /** - * Returns true if the Azure blob resource represented by this client exists; false otherwise. - * - * NOTE: use this function with care since an existing blob might be deleted by other clients or - * applications. Vice versa new blobs might be added by other clients or applications after this - * function completes. - * - * @param {BlobExistsOptions} [options] options to Exists operation. - * @returns {Promise} - * @memberof BlobClient + * Creates an instance of UserDelegationKeyCredential. + * @param {string} accountName + * @param {UserDelegationKey} userDelegationKey + * @memberof UserDelegationKeyCredential */ - BlobClient.prototype.exists = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_2; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobClient-exists", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.getProperties({ - abortSignal: options.abortSignal, - customerProvidedKey: options.customerProvidedKey, - conditions: options.conditions, - tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) - })]; - case 2: - _b.sent(); - return [2 /*return*/, true]; - case 3: - e_2 = _b.sent(); - if (e_2.statusCode === 404) { - span.setStatus({ - code: api.CanonicalCode.NOT_FOUND, - message: "Expected exception when checking blob existence" - }); - return [2 /*return*/, false]; - } - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_2.message - }); - throw e_2; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; + function UserDelegationKeyCredential(accountName, userDelegationKey) { + this.accountName = accountName; + this.userDelegationKey = userDelegationKey; + this.key = Buffer.from(userDelegationKey.value, "base64"); + } /** - * Returns all user-defined metadata, standard HTTP properties, and system properties - * for the blob. It does not return the content of the blob. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-properties - * - * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if - * they originally contained uppercase characters. This differs from the metadata keys returned by - * the methods of {@link ContainerClient} that list blobs using the `includeMetadata` option, which - * will retain their original casing. + * Generates a hash signature for an HTTP request or for a SAS. * - * @param {BlobGetPropertiesOptions} [options] Optional options to Get Properties operation. - * @returns {Promise} - * @memberof BlobClient + * @param {string} stringToSign + * @returns {string} + * @memberof UserDelegationKeyCredential */ - BlobClient.prototype.getProperties = function (options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, res, e_3; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-getProperties", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - options.conditions = options.conditions || {}; - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blobContext.getProperties({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - cpkInfo: options.customerProvidedKey, - spanOptions: spanOptions - })]; - case 2: - res = _c.sent(); - return [2 /*return*/, tslib.__assign(tslib.__assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) })]; - case 3: - e_3 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_3.message - }); - throw e_3; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + UserDelegationKeyCredential.prototype.computeHMACSHA256 = function (stringToSign) { + // console.log(`stringToSign: ${JSON.stringify(stringToSign)}`); + return crypto.createHmac("sha256", this.key) + .update(stringToSign, "utf8") + .digest("base64"); }; + return UserDelegationKeyCredential; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * Generate SasIPRange format string. For example: + * + * "8.8.8.8" or "1.1.1.1-255.255.255.255" + * + * @export + * @param {SasIPRange} ipRange + * @returns {string} + */ +function ipRangeToString(ipRange) { + return ipRange.end ? ipRange.start + "-" + ipRange.end : ipRange.start; +} + +// Copyright (c) Microsoft Corporation. All rights reserved. +(function (SASProtocol) { /** - * Marks the specified blob or snapshot for deletion. The blob is later deleted - * during garbage collection. Note that in order to delete a blob, you must delete - * all of its snapshots. You can delete both at the same time with the Delete - * Blob operation. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob - * - * @param {BlobDeleteOptions} [options] Optional options to Blob Delete operation. - * @returns {Promise} - * @memberof BlobClient + * Protocol that allows HTTPS only */ - BlobClient.prototype.delete = function (options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_4; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-delete", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.deleteMethod({ - abortSignal: options.abortSignal, - deleteSnapshots: options.deleteSnapshots, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_4 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_4.message - }); - throw e_4; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; + SASProtocol["Https"] = "https"; /** - * Marks the specified blob or snapshot for deletion if it exists. The blob is later deleted - * during garbage collection. Note that in order to delete a blob, you must delete - * all of its snapshots. You can delete both at the same time with the Delete - * Blob operation. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob - * - * @param {BlobDeleteOptions} [options] Optional options to Blob Delete operation. - * @returns {Promise} - * @memberof BlobClient + * Protocol that allows both HTTPS and HTTP */ - BlobClient.prototype.deleteIfExists = function (options) { - var _a, _b; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _c, span, spanOptions, res, e_5; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _c = createSpan("BlobClient-deleteIfExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; - _d.label = 1; - case 1: - _d.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: - res = _d.sent(); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable - })]; - case 3: - e_5 = _d.sent(); - if (((_a = e_5.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobNotFound") { - span.setStatus({ - code: api.CanonicalCode.NOT_FOUND, - message: "Expected exception when deleting a blob or snapshot only if it exists." - }); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_5.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_5.response })]; - } - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_5.message - }); - throw e_5; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - /** - * Restores the contents and metadata of soft deleted blob and any associated - * soft deleted snapshots. Undelete Blob is supported only on version 2017-07-29 - * or later. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/undelete-blob - * - * @param {BlobUndeleteOptions} [options] Optional options to Blob Undelete operation. - * @returns {Promise} - * @memberof BlobClient - */ - BlobClient.prototype.undelete = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_6; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobClient-undelete", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.undelete({ - abortSignal: options.abortSignal, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_6 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_6.message - }); - throw e_6; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; + SASProtocol["HttpsAndHttp"] = "https,http"; +})(exports.SASProtocol || (exports.SASProtocol = {})); +/** + * Represents the components that make up an Azure Storage SAS' query parameters. This type is not constructed directly + * by the user; it is only generated by the {@link AccountSASSignatureValues} and {@link BlobSASSignatureValues} + * types. Once generated, it can be encoded into a {@code String} and appended to a URL directly (though caution should + * be taken here in case there are existing query parameters, which might affect the appropriate means of appending + * these query parameters). + * + * NOTE: Instances of this class are immutable. + * + * @export + * @class SASQueryParameters + */ +var SASQueryParameters = /** @class */ (function () { + function SASQueryParameters(version, signature, permissionsOrOptions, services, resourceTypes, protocol, startsOn, expiresOn, ipRange, identifier, resource, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType, userDelegationKey, preauthorizedAgentObjectId, correlationId) { + this.version = version; + this.signature = signature; + if (permissionsOrOptions !== undefined && typeof permissionsOrOptions !== "string") { + // SASQueryParametersOptions + this.permissions = permissionsOrOptions.permissions; + this.services = permissionsOrOptions.services; + this.resourceTypes = permissionsOrOptions.resourceTypes; + this.protocol = permissionsOrOptions.protocol; + this.startsOn = permissionsOrOptions.startsOn; + this.expiresOn = permissionsOrOptions.expiresOn; + this.ipRangeInner = permissionsOrOptions.ipRange; + this.identifier = permissionsOrOptions.identifier; + this.resource = permissionsOrOptions.resource; + this.cacheControl = permissionsOrOptions.cacheControl; + this.contentDisposition = permissionsOrOptions.contentDisposition; + this.contentEncoding = permissionsOrOptions.contentEncoding; + this.contentLanguage = permissionsOrOptions.contentLanguage; + this.contentType = permissionsOrOptions.contentType; + if (permissionsOrOptions.userDelegationKey) { + this.signedOid = permissionsOrOptions.userDelegationKey.signedObjectId; + this.signedTenantId = permissionsOrOptions.userDelegationKey.signedTenantId; + this.signedStartsOn = permissionsOrOptions.userDelegationKey.signedStartsOn; + this.signedExpiresOn = permissionsOrOptions.userDelegationKey.signedExpiresOn; + this.signedService = permissionsOrOptions.userDelegationKey.signedService; + this.signedVersion = permissionsOrOptions.userDelegationKey.signedVersion; + this.preauthorizedAgentObjectId = permissionsOrOptions.preauthorizedAgentObjectId; + this.correlationId = permissionsOrOptions.correlationId; + } + } + else { + this.services = services; + this.resourceTypes = resourceTypes; + this.expiresOn = expiresOn; + this.permissions = permissionsOrOptions; + this.protocol = protocol; + this.startsOn = startsOn; + this.ipRangeInner = ipRange; + this.identifier = identifier; + this.resource = resource; + this.cacheControl = cacheControl; + this.contentDisposition = contentDisposition; + this.contentEncoding = contentEncoding; + this.contentLanguage = contentLanguage; + this.contentType = contentType; + if (userDelegationKey) { + this.signedOid = userDelegationKey.signedObjectId; + this.signedTenantId = userDelegationKey.signedTenantId; + this.signedStartsOn = userDelegationKey.signedStartsOn; + this.signedExpiresOn = userDelegationKey.signedExpiresOn; + this.signedService = userDelegationKey.signedService; + this.signedVersion = userDelegationKey.signedVersion; + this.preauthorizedAgentObjectId = preauthorizedAgentObjectId; + this.correlationId = correlationId; + } + } + } + Object.defineProperty(SASQueryParameters.prototype, "ipRange", { + /** + * Optional. IP range allowed for this SAS. + * + * @readonly + * @type {(SasIPRange | undefined)} + * @memberof SASQueryParameters + */ + get: function () { + if (this.ipRangeInner) { + return { + end: this.ipRangeInner.end, + start: this.ipRangeInner.start + }; + } + return undefined; + }, + enumerable: false, + configurable: true + }); /** - * Sets system properties on the blob. - * - * If no value provided, or no value provided for the specified blob HTTP headers, - * these blob HTTP headers without a value will be cleared. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties + * Encodes all SAS query parameters into a string that can be appended to a URL. * - * @param {BlobHTTPHeaders} [blobHTTPHeaders] If no value provided, or no value provided for - * the specified blob HTTP headers, these blob HTTP - * headers without a value will be cleared. - * @param {BlobSetHTTPHeadersOptions} [options] Optional options to Blob Set HTTP Headers operation. - * @returns {Promise} - * @memberof BlobClient + * @returns {string} + * @memberof SASQueryParameters */ - BlobClient.prototype.setHTTPHeaders = function (blobHTTPHeaders, options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_7; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-setHTTPHeaders", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blobContext.setHTTPHeaders({ - abortSignal: options.abortSignal, - blobHTTPHeaders: blobHTTPHeaders, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - cpkInfo: options.customerProvidedKey, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_7 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_7.message - }); - throw e_7; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + SASQueryParameters.prototype.toString = function () { + var params = [ + "sv", + "ss", + "srt", + "spr", + "st", + "se", + "sip", + "si", + "skoid", + "sktid", + "skt", + "ske", + "sks", + "skv", + "sr", + "sp", + "sig", + "rscc", + "rscd", + "rsce", + "rscl", + "rsct", + "saoid", + "scid" + ]; + var queries = []; + for (var _i = 0, params_1 = params; _i < params_1.length; _i++) { + var param = params_1[_i]; + switch (param) { + case "sv": + this.tryAppendQueryParameter(queries, param, this.version); + break; + case "ss": + this.tryAppendQueryParameter(queries, param, this.services); + break; + case "srt": + this.tryAppendQueryParameter(queries, param, this.resourceTypes); + break; + case "spr": + this.tryAppendQueryParameter(queries, param, this.protocol); + break; + case "st": + this.tryAppendQueryParameter(queries, param, this.startsOn ? truncatedISO8061Date(this.startsOn, false) : undefined); + break; + case "se": + this.tryAppendQueryParameter(queries, param, this.expiresOn ? truncatedISO8061Date(this.expiresOn, false) : undefined); + break; + case "sip": + this.tryAppendQueryParameter(queries, param, this.ipRange ? ipRangeToString(this.ipRange) : undefined); + break; + case "si": + this.tryAppendQueryParameter(queries, param, this.identifier); + break; + case "skoid": // Signed object ID + this.tryAppendQueryParameter(queries, param, this.signedOid); + break; + case "sktid": // Signed tenant ID + this.tryAppendQueryParameter(queries, param, this.signedTenantId); + break; + case "skt": // Signed key start time + this.tryAppendQueryParameter(queries, param, this.signedStartsOn ? truncatedISO8061Date(this.signedStartsOn, false) : undefined); + break; + case "ske": // Signed key expiry time + this.tryAppendQueryParameter(queries, param, this.signedExpiresOn ? truncatedISO8061Date(this.signedExpiresOn, false) : undefined); + break; + case "sks": // Signed key service + this.tryAppendQueryParameter(queries, param, this.signedService); + break; + case "skv": // Signed key version + this.tryAppendQueryParameter(queries, param, this.signedVersion); + break; + case "sr": + this.tryAppendQueryParameter(queries, param, this.resource); + break; + case "sp": + this.tryAppendQueryParameter(queries, param, this.permissions); + break; + case "sig": + this.tryAppendQueryParameter(queries, param, this.signature); + break; + case "rscc": + this.tryAppendQueryParameter(queries, param, this.cacheControl); + break; + case "rscd": + this.tryAppendQueryParameter(queries, param, this.contentDisposition); + break; + case "rsce": + this.tryAppendQueryParameter(queries, param, this.contentEncoding); + break; + case "rscl": + this.tryAppendQueryParameter(queries, param, this.contentLanguage); + break; + case "rsct": + this.tryAppendQueryParameter(queries, param, this.contentType); + break; + case "saoid": + this.tryAppendQueryParameter(queries, param, this.preauthorizedAgentObjectId); + break; + case "scid": + this.tryAppendQueryParameter(queries, param, this.correlationId); + break; + } + } + return queries.join("&"); }; /** - * Sets user-defined metadata for the specified blob as one or more name-value pairs. - * - * If no option provided, or no metadata defined in the parameter, the blob - * metadata will be removed. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-metadata + * A private helper method used to filter and append query key/value pairs into an array. * - * @param {Metadata} [metadata] Replace existing metadata with this value. - * If no value provided the existing metadata will be removed. - * @param {BlobSetMetadataOptions} [options] Optional options to Set Metadata operation. - * @returns {Promise} - * @memberof BlobClient + * @private + * @param {string[]} queries + * @param {string} key + * @param {string} [value] + * @returns {void} + * @memberof SASQueryParameters */ - BlobClient.prototype.setMetadata = function (metadata, options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_8; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-setMetadata", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blobContext.setMetadata({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - metadata: metadata, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_8 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_8.message - }); - throw e_8; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + SASQueryParameters.prototype.tryAppendQueryParameter = function (queries, key, value) { + if (!value) { + return; + } + key = encodeURIComponent(key); + value = encodeURIComponent(value); + if (key.length > 0 && value.length > 0) { + queries.push(key + "=" + value); + } }; - /** - * Sets tags on the underlying blob. - * A blob can have up to 10 tags. Tag keys must be between 1 and 128 characters. Tag values must be between 0 and 256 characters. - * Valid tag key and value characters include lower and upper case letters, digits (0-9), - * space (' '), plus ('+'), minus ('-'), period ('.'), foward slash ('/'), colon (':'), equals ('='), and underscore ('_'). - * - * @param {Tags} tags - * @param {BlobSetTagsOptions} [options={}] - * @returns {Promise} - * @memberof BlobClient - */ - BlobClient.prototype.setTags = function (tags, options) { + return SASQueryParameters; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +function generateBlobSASQueryParameters(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { + var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + var sharedKeyCredential = sharedKeyCredentialOrUserDelegationKey instanceof StorageSharedKeyCredential + ? sharedKeyCredentialOrUserDelegationKey + : undefined; + var userDelegationKeyCredential; + if (sharedKeyCredential === undefined && accountName !== undefined) { + userDelegationKeyCredential = new UserDelegationKeyCredential(accountName, sharedKeyCredentialOrUserDelegationKey); + } + if (sharedKeyCredential === undefined && userDelegationKeyCredential === undefined) { + throw TypeError("Invalid sharedKeyCredential, userDelegationKey or accountName."); + } + // Version 2019-12-12 adds support for the blob tags permission. + // Version 2018-11-09 adds support for the signed resource and signed blob snapshot time fields. + // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas#constructing-the-signature-string + if (version >= "2018-11-09") { + if (sharedKeyCredential !== undefined) { + return generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential); + } + else { + // Version 2020-02-10 delegation SAS signature construction includes preauthorizedAgentObjectId, agentObjectId, correlationId. + if (version >= "2020-02-10") { + return generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userDelegationKeyCredential); + } + else { + return generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential); + } + } + } + if (version >= "2015-04-05") { + if (sharedKeyCredential !== undefined) { + return generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential); + } + else { + throw new RangeError("'version' must be >= '2018-11-09' when generating user delegation SAS using user delegation key."); + } + } + throw new RangeError("'version' must be >= '2015-04-05'."); +} +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * IMPLEMENTATION FOR API VERSION FROM 2015-04-05 AND BEFORE 2018-11-09. + * + * Creates an instance of SASQueryParameters. + * + * Only accepts required settings needed to create a SAS. For optional settings please + * set corresponding properties directly, such as permissions, startsOn and identifier. + * + * WARNING: When identifier is not provided, permissions and expiresOn are required. + * You MUST assign value to identifier or expiresOn & permissions manually if you initial with + * this constructor. + * + * @param {BlobSASSignatureValues} blobSASSignatureValues + * @param {StorageSharedKeyCredential} sharedKeyCredential + * @returns {SASQueryParameters} + */ +function generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential) { + blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); + if (!blobSASSignatureValues.identifier && + !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); + } + var resource = "c"; + if (blobSASSignatureValues.blobName) { + resource = "b"; + } + // Calling parse and toString guarantees the proper ordering and throws on invalid characters. + var verifiedPermissions; + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + // Signature is generated on the un-url-encoded values. + var stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn + ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) + : "", + blobSASSignatureValues.expiresOn + ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) + : "", + getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.identifier, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + blobSASSignatureValues.version, + blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", + blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", + blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", + blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", + blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" + ].join("\n"); + var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); +} +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. + * + * Creates an instance of SASQueryParameters. + * + * Only accepts required settings needed to create a SAS. For optional settings please + * set corresponding properties directly, such as permissions, startsOn and identifier. + * + * WARNING: When identifier is not provided, permissions and expiresOn are required. + * You MUST assign value to identifier or expiresOn & permissions manually if you initial with + * this constructor. + * + * @param {BlobSASSignatureValues} blobSASSignatureValues + * @param {StorageSharedKeyCredential} sharedKeyCredential + * @returns {SASQueryParameters} + */ +function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential) { + blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); + if (!blobSASSignatureValues.identifier && + !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); + } + var resource = "c"; + var timestamp = blobSASSignatureValues.snapshotTime; + if (blobSASSignatureValues.blobName) { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } + else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } + } + // Calling parse and toString guarantees the proper ordering and throws on invalid characters. + var verifiedPermissions; + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + // Signature is generated on the un-url-encoded values. + var stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn + ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) + : "", + blobSASSignatureValues.expiresOn + ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) + : "", + getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.identifier, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + blobSASSignatureValues.version, + resource, + timestamp, + blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", + blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", + blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", + blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", + blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" + ].join("\n"); + var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); +} +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. + * + * Creates an instance of SASQueryParameters. + * + * Only accepts required settings needed to create a SAS. For optional settings please + * set corresponding properties directly, such as permissions, startsOn. + * + * WARNING: identifier will be ignored, permissions and expiresOn are required. + * + * @param {BlobSASSignatureValues} blobSASSignatureValues + * @param {UserDelegationKeyCredential} userDelegationKeyCredential + * @returns {SASQueryParameters} + */ +function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential) { + blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); + // Stored access policies are not supported for a user delegation SAS. + if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); + } + var resource = "c"; + var timestamp = blobSASSignatureValues.snapshotTime; + if (blobSASSignatureValues.blobName) { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } + else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } + } + // Calling parse and toString guarantees the proper ordering and throws on invalid characters. + var verifiedPermissions; + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + // Signature is generated on the un-url-encoded values. + var stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn + ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) + : "", + blobSASSignatureValues.expiresOn + ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) + : "", + getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + userDelegationKeyCredential.userDelegationKey.signedObjectId, + userDelegationKeyCredential.userDelegationKey.signedTenantId, + userDelegationKeyCredential.userDelegationKey.signedStartsOn + ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) + : "", + userDelegationKeyCredential.userDelegationKey.signedExpiresOn + ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) + : "", + userDelegationKeyCredential.userDelegationKey.signedService, + userDelegationKeyCredential.userDelegationKey.signedVersion, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + blobSASSignatureValues.version, + resource, + timestamp, + blobSASSignatureValues.cacheControl, + blobSASSignatureValues.contentDisposition, + blobSASSignatureValues.contentEncoding, + blobSASSignatureValues.contentLanguage, + blobSASSignatureValues.contentType + ].join("\n"); + var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey); +} +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * IMPLEMENTATION FOR API VERSION FROM 2020-02-10. + * + * Creates an instance of SASQueryParameters. + * + * Only accepts required settings needed to create a SAS. For optional settings please + * set corresponding properties directly, such as permissions, startsOn. + * + * WARNING: identifier will be ignored, permissions and expiresOn are required. + * + * @param {BlobSASSignatureValues} blobSASSignatureValues + * @param {UserDelegationKeyCredential} userDelegationKeyCredential + * @returns {SASQueryParameters} + */ +function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userDelegationKeyCredential) { + blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); + // Stored access policies are not supported for a user delegation SAS. + if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); + } + var resource = "c"; + var timestamp = blobSASSignatureValues.snapshotTime; + if (blobSASSignatureValues.blobName) { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } + else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } + } + // Calling parse and toString guarantees the proper ordering and throws on invalid characters. + var verifiedPermissions; + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + // Signature is generated on the un-url-encoded values. + var stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn + ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) + : "", + blobSASSignatureValues.expiresOn + ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) + : "", + getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + userDelegationKeyCredential.userDelegationKey.signedObjectId, + userDelegationKeyCredential.userDelegationKey.signedTenantId, + userDelegationKeyCredential.userDelegationKey.signedStartsOn + ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) + : "", + userDelegationKeyCredential.userDelegationKey.signedExpiresOn + ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) + : "", + userDelegationKeyCredential.userDelegationKey.signedService, + userDelegationKeyCredential.userDelegationKey.signedVersion, + blobSASSignatureValues.preauthorizedAgentObjectId, + undefined, + blobSASSignatureValues.correlationId, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + blobSASSignatureValues.version, + resource, + timestamp, + blobSASSignatureValues.cacheControl, + blobSASSignatureValues.contentDisposition, + blobSASSignatureValues.contentEncoding, + blobSASSignatureValues.contentLanguage, + blobSASSignatureValues.contentType + ].join("\n"); + var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId); +} +function getCanonicalName(accountName, containerName, blobName) { + // Container: "/blob/account/containerName" + // Blob: "/blob/account/containerName/blobName" + var elements = ["/blob/" + accountName + "/" + containerName]; + if (blobName) { + elements.push("/" + blobName); + } + return elements.join(""); +} +function SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues) { + var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + if (blobSASSignatureValues.snapshotTime && version < "2018-11-09") { + throw RangeError("'version' must be >= '2018-11-09' when providing 'snapshotTime'."); + } + if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.snapshotTime) { + throw RangeError("Must provide 'blobName' when providing 'snapshotTime'."); + } + if (blobSASSignatureValues.versionId && version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when providing 'versionId'."); + } + if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.versionId) { + throw RangeError("Must provide 'blobName' when providing 'versionId'."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.deleteVersion && + version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when providing 'x' permission."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.tag && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when providing 't' permission."); + } + if (version < "2020-02-10" && + blobSASSignatureValues.permissions && + (blobSASSignatureValues.permissions.move || blobSASSignatureValues.permissions.execute)) { + throw RangeError("'version' must be >= '2020-02-10' when providing the 'm' or 'e' permission."); + } + if (version < "2020-02-10" && + (blobSASSignatureValues.preauthorizedAgentObjectId || blobSASSignatureValues.correlationId)) { + throw RangeError("'version' must be >= '2020-02-10' when providing 'preauthorizedAgentObjectId' or 'correlationId'."); + } + blobSASSignatureValues.version = version; + return blobSASSignatureValues; +} + +/** + * A BlobClient represents a URL to an Azure Storage blob; the blob may be a block blob, + * append blob, or page blob. + * + * @export + * @class BlobClient + */ +var BlobClient = /** @class */ (function (_super) { + tslib.__extends(BlobClient, _super); + function BlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_9; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-setTags", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.setTags({ - abortSignal: options.abortSignal, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - spanOptions: spanOptions, - tags: toBlobTags(tags) - })]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_9 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_9.message - }); - throw e_9; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + var _this = this; + options = options || {}; + var pipeline; + var url; + if (credentialOrPipelineOrContainerName instanceof Pipeline) { + // (url: string, pipeline: Pipeline) + url = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } + else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || + credentialOrPipelineOrContainerName instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + url = urlOrConnectionString; + options = blobNameOrOptions; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } + else if (!credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName !== "string") { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + // The second parameter is undefined. Use anonymous credential. + url = urlOrConnectionString; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else if (credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName === "string" && + blobNameOrOptions && + typeof blobNameOrOptions === "string") { + // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) + var containerName = credentialOrPipelineOrContainerName; + var blobName = blobNameOrOptions; + var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + { + var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); + options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); + pipeline = newPipeline(sharedKeyCredential, options); } - }); - }); - }; + } + else if (extractedCreds.kind === "SASConnString") { + url = + appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + + "?" + + extractedCreds.accountSas; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } + else { + throw new Error("Expecting non-empty strings for containerName and blobName parameters"); + } + _this = _super.call(this, url, pipeline) || this; + (_a = _this.getBlobAndContainerNamesFromUrl(), _this._name = _a.blobName, _this._containerName = _a.containerName); + _this.blobContext = new Blob$1(_this.storageClientContext); + _this._snapshot = getURLParameter(_this.url, URLConstants.Parameters.SNAPSHOT); + _this._versionId = getURLParameter(_this.url, URLConstants.Parameters.VERSIONID); + return _this; + } + Object.defineProperty(BlobClient.prototype, "name", { + /** + * The name of the blob. + */ + get: function () { + return this._name; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobClient.prototype, "containerName", { + /** + * The name of the storage container the blob is associated with. + */ + get: function () { + return this._containerName; + }, + enumerable: false, + configurable: true + }); /** - * Gets the tags associated with the underlying blob. + * Creates a new BlobClient object identical to the source but with the specified snapshot timestamp. + * Provide "" will remove the snapshot and return a Client to the base blob. * - * @param {BlobGetTagsOptions} [options={}] - * @returns {Promise} + * @param {string} snapshot The snapshot timestamp. + * @returns {BlobClient} A new BlobClient object identical to the source but with the specified snapshot timestamp * @memberof BlobClient */ - BlobClient.prototype.getTags = function (options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, response, wrappedResponse, e_10; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-getTags", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.getTags({ - abortSignal: options.abortSignal, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - spanOptions: spanOptions - })]; - case 2: - response = _c.sent(); - wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, tags: toTags({ blobTagSet: response.blobTagSet }) || {} }); - return [2 /*return*/, wrappedResponse]; - case 3: - e_10 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_10.message - }); - throw e_10; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + BlobClient.prototype.withSnapshot = function (snapshot) { + return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); }; /** - * Get a {@link BlobLeaseClient} that manages leases on the blob. + * Creates a new BlobClient object pointing to a version of this blob. + * Provide "" will remove the versionId and return a Client to the base blob. * - * @param {string} [proposeLeaseId] Initial proposed lease Id. - * @returns {BlobLeaseClient} A new BlobLeaseClient object for managing leases on the blob. + * @param {string} versionId The versionId. + * @returns {BlobClient} A new BlobClient object pointing to the version of this blob. * @memberof BlobClient */ - BlobClient.prototype.getBlobLeaseClient = function (proposeLeaseId) { - return new BlobLeaseClient(this, proposeLeaseId); + BlobClient.prototype.withVersion = function (versionId) { + return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.VERSIONID, versionId.length === 0 ? undefined : versionId), this.pipeline); }; /** - * Creates a read-only snapshot of a blob. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/snapshot-blob + * Creates a AppendBlobClient object. * - * @param {BlobCreateSnapshotOptions} [options] Optional options to the Blob Create Snapshot operation. - * @returns {Promise} + * @returns {AppendBlobClient} * @memberof BlobClient */ - BlobClient.prototype.createSnapshot = function (options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_11; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-createSnapshot", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blobContext.createSnapshot({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - metadata: options.metadata, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_11 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_11.message - }); - throw e_11; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - /** - * Asynchronously copies a blob to a destination within the storage account. - * This method returns a long running operation poller that allows you to wait - * indefinitely until the copy is completed. - * You can also cancel a copy before it is completed by calling `cancelOperation` on the poller. - * Note that the onProgress callback will not be invoked if the operation completes in the first - * request, and attempting to cancel a completed copy will result in an error being thrown. - * - * In version 2012-02-12 and later, the source for a Copy Blob operation can be - * a committed blob in any Azure storage account. - * Beginning with version 2015-02-21, the source for a Copy Blob operation can be - * an Azure file in any Azure storage account. - * Only storage accounts created on or after June 7th, 2012 allow the Copy Blob - * operation to copy from another storage account. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob - * - * Example using automatic polling: - * - * ```js - * const copyPoller = await blobClient.beginCopyFromURL('url'); - * const result = await copyPoller.pollUntilDone(); - * ``` - * - * Example using manual polling: - * - * ```js - * const copyPoller = await blobClient.beginCopyFromURL('url'); - * while (!poller.isDone()) { - * await poller.poll(); - * } - * const result = copyPoller.getResult(); - * ``` - * - * Example using progress updates: - * - * ```js - * const copyPoller = await blobClient.beginCopyFromURL('url', { - * onProgress(state) { - * console.log(`Progress: ${state.copyProgress}`); - * } - * }); - * const result = await copyPoller.pollUntilDone(); - * ``` - * - * Example using a changing polling interval (default 15 seconds): - * - * ```js - * const copyPoller = await blobClient.beginCopyFromURL('url', { - * intervalInMs: 1000 // poll blob every 1 second for copy progress - * }); - * const result = await copyPoller.pollUntilDone(); - * ``` - * - * Example using copy cancellation: - * - * ```js - * const copyPoller = await blobClient.beginCopyFromURL('url'); - * // cancel operation after starting it. - * try { - * await copyPoller.cancelOperation(); - * // calls to get the result now throw PollerCancelledError - * await copyPoller.getResult(); - * } catch (err) { - * if (err.name === 'PollerCancelledError') { - * console.log('The copy was cancelled.'); - * } - * } - * ``` - * - * @param {string} copySource url to the source Azure Blob/File. - * @param {BlobBeginCopyFromURLOptions} [options] Optional options to the Blob Start Copy From URL operation. - */ - BlobClient.prototype.beginCopyFromURL = function (copySource, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var client, poller; - var _this = this; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - client = { - abortCopyFromURL: function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return _this.abortCopyFromURL.apply(_this, args); - }, - getProperties: function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return _this.getProperties.apply(_this, args); - }, - startCopyFromURL: function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return _this.startCopyFromURL.apply(_this, args); - } - }; - poller = new BlobBeginCopyFromUrlPoller({ - blobClient: client, - copySource: copySource, - intervalInMs: options.intervalInMs, - onProgress: options.onProgress, - resumeFrom: options.resumeFrom, - startCopyFromURLOptions: options - }); - // Trigger the startCopyFromURL call by calling poll. - // Any errors from this method should be surfaced to the user. - return [4 /*yield*/, poller.poll()]; - case 1: - // Trigger the startCopyFromURL call by calling poll. - // Any errors from this method should be surfaced to the user. - _a.sent(); - return [2 /*return*/, poller]; - } - }); - }); + BlobClient.prototype.getAppendBlobClient = function () { + return new AppendBlobClient(this.url, this.pipeline); }; /** - * Aborts a pending asynchronous Copy Blob operation, and leaves a destination blob with zero - * length and full metadata. Version 2012-02-12 and newer. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/abort-copy-blob + * Creates a BlockBlobClient object. * - * @param {string} copyId Id of the Copy From URL operation. - * @param {BlobAbortCopyFromURLOptions} [options] Optional options to the Blob Abort Copy From URL operation. - * @returns {Promise} + * @returns {BlockBlobClient} * @memberof BlobClient */ - BlobClient.prototype.abortCopyFromURL = function (copyId, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_12; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobClient-abortCopyFromURL", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.abortCopyFromURL(copyId, { - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_12 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_12.message - }); - throw e_12; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + BlobClient.prototype.getBlockBlobClient = function () { + return new BlockBlobClient(this.url, this.pipeline); }; /** - * The synchronous Copy From URL operation copies a blob or an internet resource to a new blob. It will not - * return a response until the copy is complete. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob-from-url + * Creates a PageBlobClient object. * - * @param {string} copySource The source URL to copy from, Shared Access Signature(SAS) maybe needed for authentication - * @param {BlobSyncCopyFromURLOptions} [options={}] - * @returns {Promise} + * @returns {PageBlobClient} * @memberof BlobClient */ - BlobClient.prototype.syncCopyFromURL = function (copySource, options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_13; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-syncCopyFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - options.conditions = options.conditions || {}; - options.sourceConditions = options.sourceConditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.copyFromURL(copySource, { - abortSignal: options.abortSignal, - metadata: options.metadata, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions.ifMatch, - sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince - }, - sourceContentMD5: options.sourceContentMD5, - blobTagsString: toBlobTagsString(options.tags), - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_13 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_13.message - }); - throw e_13; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + BlobClient.prototype.getPageBlobClient = function () { + return new PageBlobClient(this.url, this.pipeline); }; /** - * Sets the tier on a blob. The operation is allowed on a page blob in a premium - * storage account and on a block blob in a blob storage account (locally redundant - * storage only). A premium page blob's tier determines the allowed size, IOPS, - * and bandwidth of the blob. A block blob's tier determines Hot/Cool/Archive - * storage type. This operation does not update the blob's ETag. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-tier + * Reads or downloads a blob from the system, including its metadata and properties. + * You can also call Get Blob to read a snapshot. * - * @param {BlockBlobTier | PremiumPageBlobTier | string} tier The tier to be set on the blob. Valid values are Hot, Cool, or Archive. - * @param {BlobSetTierOptions} [options] Optional options to the Blob Set Tier operation. - * @returns {Promise} + * * In Node.js, data returns in a Readable stream readableStreamBody + * * In browsers, data returns in a promise blobBody + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob + * + * @param {number} [offset] From which position of the blob to download, >= 0 + * @param {number} [count] How much data to be downloaded, > 0. Will download to the end when undefined + * @param {BlobDownloadOptions} [options] Optional options to Blob Download operation. + * @returns {Promise} * @memberof BlobClient + * + * Example usage (Node.js): + * + * ```js + * // Download and convert a blob to a string + * const downloadBlockBlobResponse = await blobClient.download(); + * const downloaded = await streamToBuffer(downloadBlockBlobResponse.readableStreamBody); + * console.log("Downloaded blob content:", downloaded.toString()); + * + * async function streamToBuffer(readableStream) { + * return new Promise((resolve, reject) => { + * const chunks = []; + * readableStream.on("data", (data) => { + * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); + * }); + * readableStream.on("end", () => { + * resolve(Buffer.concat(chunks)); + * }); + * readableStream.on("error", reject); + * }); + * } + * ``` + * + * Example usage (browser): + * + * ```js + * // Download and convert a blob to a string + * const downloadBlockBlobResponse = await blobClient.download(); + * const downloaded = await blobToString(await downloadBlockBlobResponse.blobBody); + * console.log( + * "Downloaded blob content", + * downloaded + * ); + * + * async function blobToString(blob: Blob): Promise { + * const fileReader = new FileReader(); + * return new Promise((resolve, reject) => { + * fileReader.onloadend = (ev: any) => { + * resolve(ev.target!.result); + * }; + * fileReader.onerror = reject; + * fileReader.readAsText(blob); + * }); + * } + * ``` */ - BlobClient.prototype.setAccessTier = function (tier, options) { + BlobClient.prototype.download = function (offset, count, options) { var _a; + if (offset === void 0) { offset = 0; } if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_14; + var _b, span, spanOptions, res_1, wrappedRes, e_1; + var _this = this; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: - _b = createSpan("BlobClient-setAccessTier", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + options.conditions = options.conditions || {}; + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + _b = createSpan("BlobClient-download", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.setTier(toAccessTier(tier), { + return [4 /*yield*/, this.blobContext.download({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - rehydratePriority: options.rehydratePriority, + onDownloadProgress: coreHttp.isNode ? undefined : options.onProgress, + range: offset === 0 && !count ? undefined : rangeToString({ offset: offset, count: count }), + rangeGetContentMD5: options.rangeGetContentMD5, + rangeGetContentCRC64: options.rangeGetContentCrc64, + snapshot: options.snapshot, + cpkInfo: options.customerProvidedKey, spanOptions: spanOptions })]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_14 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_14.message - }); - throw e_14; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - BlobClient.prototype.downloadToBuffer = function (param1, param2, param3, param4) { - if (param4 === void 0) { param4 = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var buffer, offset, count, options, _a, span, spanOptions, response, transferProgress_1, batch, _loop_1, off, e_15; - var _this = this; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - offset = 0; - count = 0; - options = param4; - if (param1 instanceof Buffer) { - buffer = param1; - offset = param2 || 0; - count = typeof param3 === "number" ? param3 : 0; - } - else { - offset = typeof param1 === "number" ? param1 : 0; - count = typeof param2 === "number" ? param2 : 0; - options = param3 || {}; - } - _a = createSpan("BlobClient-downloadToBuffer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 5, 6, 7]); - if (!options.blockSize) { - options.blockSize = 0; - } - if (options.blockSize < 0) { - throw new RangeError("blockSize option must be >= 0"); - } - if (options.blockSize === 0) { - options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; - } - if (offset < 0) { - throw new RangeError("offset option must be >= 0"); - } - if (count && count <= 0) { - throw new RangeError("count option must be > 0"); - } - if (!options.conditions) { - options.conditions = {}; - } - if (!!count) return [3 /*break*/, 3]; - return [4 /*yield*/, this.getProperties(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: - response = _b.sent(); - count = response.contentLength - offset; - if (count < 0) { - throw new RangeError("offset " + offset + " shouldn't be larger than blob size " + response.contentLength); + res_1 = _c.sent(); + wrappedRes = tslib.__assign(tslib.__assign({}, res_1), { _response: res_1._response, objectReplicationDestinationPolicyId: res_1.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res_1.objectReplicationRules) }); + // We support retrying when download stream unexpected ends in Node.js runtime + // Following code shouldn't be bundled into browser build, however some + // bundlers may try to bundle following code and "FileReadResponse.ts". + // In this case, "FileDownloadResponse.browser.ts" will be used as a shim of "FileDownloadResponse.ts" + // The config is in package.json "browser" field + if (options.maxRetryRequests === undefined || options.maxRetryRequests < 0) { + // TODO: Default value or make it a required parameter? + options.maxRetryRequests = DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS; } - _b.label = 3; - case 3: - // Allocate the buffer of size = count if the buffer is not provided - if (!buffer) { - try { - buffer = Buffer.alloc(count); - } - catch (error) { - throw new Error("Unable to allocate the buffer of size: " + count + "(in bytes). Please try passing your own buffer to the \"downloadToBuffer\" method or try using other methods like \"download\" or \"downloadToFile\".\t " + error.message); - } + if (res_1.contentLength === undefined) { + throw new RangeError("File download response doesn't contain valid content length header"); } - if (buffer.length < count) { - throw new RangeError("The buffer's size should be equal to or larger than the request count of bytes: " + count); + if (!res_1.etag) { + throw new RangeError("File download response doesn't contain valid etag header"); } - transferProgress_1 = 0; - batch = new Batch(options.concurrency); - _loop_1 = function (off) { - batch.addOperation(function () { return tslib.__awaiter(_this, void 0, void 0, function () { - var chunkEnd, response, stream; - return tslib.__generator(this, function (_a) { - switch (_a.label) { + return [2 /*return*/, new BlobDownloadResponse(wrappedRes, function (start) { return tslib.__awaiter(_this, void 0, void 0, function () { + var updatedOptions; + var _a; + return tslib.__generator(this, function (_b) { + switch (_b.label) { case 0: - chunkEnd = offset + count; - if (off + options.blockSize < chunkEnd) { - chunkEnd = off + options.blockSize; - } - return [4 /*yield*/, this.download(off, chunkEnd - off, { - abortSignal: options.abortSignal, - conditions: options.conditions, - maxRetryRequests: options.maxRetryRequestsPerBlock, - customerProvidedKey: options.customerProvidedKey, - tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) - })]; - case 1: - response = _a.sent(); - stream = response.readableStreamBody; - return [4 /*yield*/, streamToBuffer(stream, buffer, off - offset, chunkEnd - offset)]; - case 2: - _a.sent(); - // Update progress after block is downloaded, in case of block trying - // Could provide finer grained progress updating inside HTTP requests, - // only if convenience layer download try is enabled - transferProgress_1 += chunkEnd - off; - if (options.onProgress) { - options.onProgress({ loadedBytes: transferProgress_1 }); - } - return [2 /*return*/]; + updatedOptions = { + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ifMatch: options.conditions.ifMatch || res_1.etag, + ifModifiedSince: options.conditions.ifModifiedSince, + ifNoneMatch: options.conditions.ifNoneMatch, + ifUnmodifiedSince: options.conditions.ifUnmodifiedSince, + ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions + }, + range: rangeToString({ + count: offset + res_1.contentLength - start, + offset: start + }), + rangeGetContentMD5: options.rangeGetContentMD5, + rangeGetContentCRC64: options.rangeGetContentCrc64, + snapshot: options.snapshot, + cpkInfo: options.customerProvidedKey + }; + return [4 /*yield*/, this.blobContext.download(tslib.__assign({ abortSignal: options.abortSignal }, updatedOptions))]; + case 1: + // Debug purpose only + // console.log( + // `Read from internal stream, range: ${ + // updatedOptions.range + // }, options: ${JSON.stringify(updatedOptions)}` + // ); + return [2 /*return*/, (_b.sent()).readableStreamBody]; } }); - }); }); - }; - for (off = offset; off < offset + count; off = off + options.blockSize) { - _loop_1(off); - } - return [4 /*yield*/, batch.do()]; - case 4: - _b.sent(); - return [2 /*return*/, buffer]; - case 5: - e_15 = _b.sent(); + }); }, offset, res_1.contentLength, { + maxRetryRequests: options.maxRetryRequests, + onProgress: options.onProgress + })]; + case 3: + e_1 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_15.message + message: e_1.message }); - throw e_15; - case 6: + throw e_1; + case 4: span.end(); return [7 /*endfinally*/]; - case 7: return [2 /*return*/]; + case 5: return [2 /*return*/]; } }); }); }; /** - * ONLY AVAILABLE IN NODE.JS RUNTIME. + * Returns true if the Azure blob resource represented by this client exists; false otherwise. * - * Downloads an Azure Blob to a local file. - * Fails if the the given file path already exits. - * Offset and count are optional, pass 0 and undefined respectively to download the entire blob. + * NOTE: use this function with care since an existing blob might be deleted by other clients or + * applications. Vice versa new blobs might be added by other clients or applications after this + * function completes. * - * @param {string} filePath - * @param {number} [offset] From which position of the block blob to download. - * @param {number} [count] How much data to be downloaded. Will download to the end when passing undefined. - * @param {BlobDownloadOptions} [options] Options to Blob download options. - * @returns {Promise} The response data for blob download operation, - * but with readableStreamBody set to undefined since its - * content is already read and written into a local file - * at the specified path. + * @param {BlobExistsOptions} [options] options to Exists operation. + * @returns {Promise} * @memberof BlobClient */ - BlobClient.prototype.downloadToFile = function (filePath, offset, count, options) { - if (offset === void 0) { offset = 0; } + BlobClient.prototype.exists = function (options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, response, e_16; + var _a, span, spanOptions, e_2; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("BlobClient-downloadToFile", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("BlobClient-exists", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: - _b.trys.push([1, 5, 6, 7]); - return [4 /*yield*/, this.download(offset, count, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + _b.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.getProperties({ + abortSignal: options.abortSignal, + customerProvidedKey: options.customerProvidedKey, + conditions: options.conditions, + tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) + })]; case 2: - response = _b.sent(); - if (!response.readableStreamBody) return [3 /*break*/, 4]; - return [4 /*yield*/, readStreamToLocalFile(response.readableStreamBody, filePath)]; - case 3: _b.sent(); - _b.label = 4; - case 4: - // The stream is no longer accessible so setting it to undefined. - response.blobDownloadStream = undefined; - return [2 /*return*/, response]; - case 5: - e_16 = _b.sent(); + return [2 /*return*/, true]; + case 3: + e_2 = _b.sent(); + if (e_2.statusCode === 404) { + span.setStatus({ + code: api.CanonicalCode.NOT_FOUND, + message: "Expected exception when checking blob existence" + }); + return [2 /*return*/, false]; + } span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_16.message + message: e_2.message }); - throw e_16; - case 6: + throw e_2; + case 4: span.end(); return [7 /*endfinally*/]; - case 7: return [2 /*return*/]; + case 5: return [2 /*return*/]; } }); }); }; - BlobClient.prototype.getBlobAndContainerNamesFromUrl = function () { - var containerName; - var blobName; - try { - // URL may look like the following - // "https://myaccount.blob.core.windows.net/mycontainer/blob?sasString"; - // "https://myaccount.blob.core.windows.net/mycontainer/blob"; - // "https://myaccount.blob.core.windows.net/mycontainer/blob/a.txt?sasString"; - // "https://myaccount.blob.core.windows.net/mycontainer/blob/a.txt"; - // IPv4/IPv6 address hosts, Endpoints - `http://127.0.0.1:10000/devstoreaccount1/containername/blob` - // http://localhost:10001/devstoreaccount1/containername/blob - var parsedUrl = coreHttp.URLBuilder.parse(this.url); - if (parsedUrl.getHost().split(".")[1] === "blob") { - // "https://myaccount.blob.core.windows.net/containername/blob". - // .getPath() -> /containername/blob - var pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); - containerName = pathComponents[1]; - blobName = pathComponents[3]; - } - else if (isIpEndpointStyle(parsedUrl)) { - // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/containername/blob - // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/containername/blob - // .getPath() -> /devstoreaccount1/containername/blob - var pathComponents = parsedUrl.getPath().match("/([^/]*)/([^/]*)(/(.*))?"); - containerName = pathComponents[2]; - blobName = pathComponents[4]; - } - else { - // "https://customdomain.com/containername/blob". - // .getPath() -> /containername/blob - var pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); - containerName = pathComponents[1]; - blobName = pathComponents[3]; - } - // decode the encoded blobName, containerName - to get all the special characters that might be present in them - containerName = decodeURIComponent(containerName); - blobName = decodeURIComponent(blobName); - // Azure Storage Server will replace "\" with "/" in the blob names - // doing the same in the SDK side so that the user doesn't have to replace "\" instances in the blobName - blobName = blobName.replace(/\\/g, "/"); - if (!blobName) { - throw new Error("Provided blobName is invalid."); - } - else if (!containerName) { - throw new Error("Provided containerName is invalid."); - } - return { blobName: blobName, containerName: containerName }; - } - catch (error) { - throw new Error("Unable to extract blobName and containerName with provided information."); - } - }; /** - * Asynchronously copies a blob to a destination within the storage account. - * In version 2012-02-12 and later, the source for a Copy Blob operation can be - * a committed blob in any Azure storage account. - * Beginning with version 2015-02-21, the source for a Copy Blob operation can be - * an Azure file in any Azure storage account. - * Only storage accounts created on or after June 7th, 2012 allow the Copy Blob - * operation to copy from another storage account. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob + * Returns all user-defined metadata, standard HTTP properties, and system properties + * for the blob. It does not return the content of the blob. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-properties * - * @param {string} copySource url to the source Azure Blob/File. - * @param {BlobStartCopyFromURLOptions} [options] Optional options to the Blob Start Copy From URL operation. - * @returns {Promise} + * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if + * they originally contained uppercase characters. This differs from the metadata keys returned by + * the methods of {@link ContainerClient} that list blobs using the `includeMetadata` option, which + * will retain their original casing. + * + * @param {BlobGetPropertiesOptions} [options] Optional options to Get Properties operation. + * @returns {Promise} * @memberof BlobClient */ - BlobClient.prototype.startCopyFromURL = function (copySource, options) { + BlobClient.prototype.getProperties = function (options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_17; + var _b, span, spanOptions, res, e_3; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: - _b = createSpan("BlobClient-startCopyFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - options.conditions = options.conditions || {}; - options.sourceConditions = options.sourceConditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.startCopyFromURL(copySource, { - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - metadata: options.metadata, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions.ifMatch, - sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince, - sourceIfTags: options.sourceConditions.tagConditions - }, - rehydratePriority: options.rehydratePriority, - tier: toAccessTier(options.tier), - blobTagsString: toBlobTagsString(options.tags), - sealBlob: options.sealBlob, + _b = createSpan("BlobClient-getProperties", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blobContext.getProperties({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, spanOptions: spanOptions })]; - case 2: return [2 /*return*/, _c.sent()]; + case 2: + res = _c.sent(); + return [2 /*return*/, tslib.__assign(tslib.__assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) })]; case 3: - e_17 = _c.sent(); + e_3 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_17.message + message: e_3.message }); - throw e_17; + throw e_3; case 4: span.end(); return [7 /*endfinally*/]; @@ -29248,138 +29589,45 @@ var BlobClient = /** @class */ (function (_super) { }); }); }; - return BlobClient; -}(StorageClient)); -/** - * AppendBlobClient defines a set of operations applicable to append blobs. - * - * @export - * @class AppendBlobClient - * @extends {BlobClient} - */ -var AppendBlobClient = /** @class */ (function (_super) { - tslib.__extends(AppendBlobClient, _super); - function AppendBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { - var _this = this; - // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. - // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); - var pipeline; - var url; - options = options || {}; - if (credentialOrPipelineOrContainerName instanceof Pipeline) { - // (url: string, pipeline: Pipeline) - url = urlOrConnectionString; - pipeline = credentialOrPipelineOrContainerName; - } - else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || - credentialOrPipelineOrContainerName instanceof AnonymousCredential || - coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { - // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) url = urlOrConnectionString; - url = urlOrConnectionString; - options = blobNameOrOptions; - pipeline = newPipeline(credentialOrPipelineOrContainerName, options); - } - else if (!credentialOrPipelineOrContainerName && - typeof credentialOrPipelineOrContainerName !== "string") { - // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) - url = urlOrConnectionString; - // The second parameter is undefined. Use anonymous credential. - pipeline = newPipeline(new AnonymousCredential(), options); - } - else if (credentialOrPipelineOrContainerName && - typeof credentialOrPipelineOrContainerName === "string" && - blobNameOrOptions && - typeof blobNameOrOptions === "string") { - // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) - var containerName = credentialOrPipelineOrContainerName; - var blobName = blobNameOrOptions; - var extractedCreds = extractConnectionStringParts(urlOrConnectionString); - if (extractedCreds.kind === "AccountConnString") { - { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); - options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); - pipeline = newPipeline(sharedKeyCredential, options); - } - } - else if (extractedCreds.kind === "SASConnString") { - url = - appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + - "?" + - extractedCreds.accountSas; - pipeline = newPipeline(new AnonymousCredential(), options); - } - else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); - } - } - else { - throw new Error("Expecting non-empty strings for containerName and blobName parameters"); - } - _this = _super.call(this, url, pipeline) || this; - _this.appendBlobContext = new AppendBlob(_this.storageClientContext); - return _this; - } - /** - * Creates a new AppendBlobClient object identical to the source but with the - * specified snapshot timestamp. - * Provide "" will remove the snapshot and return a Client to the base blob. - * - * @param {string} snapshot The snapshot timestamp. - * @returns {AppendBlobClient} A new AppendBlobClient object identical to the source but with the specified snapshot timestamp. - * @memberof AppendBlobClient - */ - AppendBlobClient.prototype.withSnapshot = function (snapshot) { - return new AppendBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); - }; /** - * Creates a 0-length append blob. Call AppendBlock to append data to an append blob. - * @see https://docs.microsoft.com/rest/api/storageservices/put-blob - * - * @param {AppendBlobCreateOptions} [options] Options to the Append Block Create operation. - * @returns {Promise} - * @memberof AppendBlobClient - * - * Example usage: + * Marks the specified blob or snapshot for deletion. The blob is later deleted + * during garbage collection. Note that in order to delete a blob, you must delete + * all of its snapshots. You can delete both at the same time with the Delete + * Blob operation. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob * - * ```js - * const appendBlobClient = containerClient.getAppendBlobClient(""); - * await appendBlobClient.create(); - * ``` + * @param {BlobDeleteOptions} [options] Optional options to Blob Delete operation. + * @returns {Promise} + * @memberof BlobClient */ - AppendBlobClient.prototype.create = function (options) { + BlobClient.prototype.delete = function (options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_18; + var _b, span, spanOptions, e_4; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: - _b = createSpan("AppendBlobClient-create", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _b = createSpan("BlobClient-delete", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; options.conditions = options.conditions || {}; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.appendBlobContext.create(0, { + return [4 /*yield*/, this.blobContext.deleteMethod({ abortSignal: options.abortSignal, - blobHTTPHeaders: options.blobHTTPHeaders, + deleteSnapshots: options.deleteSnapshots, leaseAccessConditions: options.conditions, - metadata: options.metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - blobTagsString: toBlobTagsString(options.tags), spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_18 = _c.sent(); + e_4 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_18.message + message: e_4.message }); - throw e_18; + throw e_4; case 4: span.end(); return [7 /*endfinally*/]; @@ -29389,46 +29637,47 @@ var AppendBlobClient = /** @class */ (function (_super) { }); }; /** - * Creates a 0-length append blob. Call AppendBlock to append data to an append blob. - * If the blob with the same name already exists, the content of the existing blob will remain unchanged. - * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * Marks the specified blob or snapshot for deletion if it exists. The blob is later deleted + * during garbage collection. Note that in order to delete a blob, you must delete + * all of its snapshots. You can delete both at the same time with the Delete + * Blob operation. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob * - * @param {AppendBlobCreateIfNotExistsOptions} [options] - * @returns {Promise} - * @memberof AppendBlobClient + * @param {BlobDeleteOptions} [options] Optional options to Blob Delete operation. + * @returns {Promise} + * @memberof BlobClient */ - AppendBlobClient.prototype.createIfNotExists = function (options) { + BlobClient.prototype.deleteIfExists = function (options) { var _a, _b; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _c, span, spanOptions, conditions, res, e_19; + var _c, span, spanOptions, res, e_5; return tslib.__generator(this, function (_d) { switch (_d.label) { case 0: - _c = createSpan("AppendBlobClient-createIfNotExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; - conditions = { ifNoneMatch: ETagAny }; + _c = createSpan("BlobClient-deleteIfExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; _d.label = 1; case 1: _d.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.create(tslib.__assign(tslib.__assign({}, options), { conditions: conditions, tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + return [4 /*yield*/, this.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: res = _d.sent(); return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable })]; case 3: - e_19 = _d.sent(); - if (((_a = e_19.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { + e_5 = _d.sent(); + if (((_a = e_5.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobNotFound") { span.setStatus({ - code: api.CanonicalCode.ALREADY_EXISTS, - message: "Expected exception when creating a blob only if it does not already exist." + code: api.CanonicalCode.NOT_FOUND, + message: "Expected exception when deleting a blob or snapshot only if it exists." }); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_19.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_19.response })]; + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_5.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_5.response })]; } span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_19.message + message: e_5.message }); - throw e_19; + throw e_5; case 4: span.end(); return [7 /*endfinally*/]; @@ -29438,40 +29687,90 @@ var AppendBlobClient = /** @class */ (function (_super) { }); }; /** - * Seals the append blob, making it read only. + * Restores the contents and metadata of soft deleted blob and any associated + * soft deleted snapshots. Undelete Blob is supported only on version 2017-07-29 + * or later. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/undelete-blob * - * @param {AppendBlobSealOptions} [options={}] - * @returns {Promise} - * @memberof AppendBlobClient + * @param {BlobUndeleteOptions} [options] Optional options to Blob Undelete operation. + * @returns {Promise} + * @memberof BlobClient */ - AppendBlobClient.prototype.seal = function (options) { + BlobClient.prototype.undelete = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_6; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobClient-undelete", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.blobContext.undelete({ + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_6 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_6.message + }); + throw e_6; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Sets system properties on the blob. + * + * If no value provided, or no value provided for the specified blob HTTP headers, + * these blob HTTP headers without a value will be cleared. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties + * + * @param {BlobHTTPHeaders} [blobHTTPHeaders] If no value provided, or no value provided for + * the specified blob HTTP headers, these blob HTTP + * headers without a value will be cleared. + * @param {BlobSetHTTPHeadersOptions} [options] Optional options to Blob Set HTTP Headers operation. + * @returns {Promise} + * @memberof BlobClient + */ + BlobClient.prototype.setHTTPHeaders = function (blobHTTPHeaders, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_20; + var _b, span, spanOptions, e_7; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: - _b = createSpan("AppendBlobClient-seal", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _b = createSpan("BlobClient-setHTTPHeaders", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; options.conditions = options.conditions || {}; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.appendBlobContext.seal({ + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blobContext.setHTTPHeaders({ abortSignal: options.abortSignal, - appendPositionAccessConditions: options.conditions, + blobHTTPHeaders: blobHTTPHeaders, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_20 = _c.sent(); + e_7 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_20.message + message: e_7.message }); - throw e_20; + throw e_7; case 4: span.end(); return [7 /*endfinally*/]; @@ -29481,64 +29780,49 @@ var AppendBlobClient = /** @class */ (function (_super) { }); }; /** - * Commits a new block of data to the end of the existing append blob. - * @see https://docs.microsoft.com/rest/api/storageservices/append-block - * - * @param {HttpRequestBody} body Data to be appended. - * @param {number} contentLength Length of the body in bytes. - * @param {AppendBlobAppendBlockOptions} [options] Options to the Append Block operation. - * @returns {Promise} - * @memberof AppendBlobClient - * - * Example usage: - * - * ```js - * const content = "Hello World!"; + * Sets user-defined metadata for the specified blob as one or more name-value pairs. * - * // Create a new append blob and append data to the blob. - * const newAppendBlobClient = containerClient.getAppendBlobClient(""); - * await newAppendBlobClient.create(); - * await newAppendBlobClient.appendBlock(content, content.length); + * If no option provided, or no metadata defined in the parameter, the blob + * metadata will be removed. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-metadata * - * // Append data to an existing append blob. - * const existingAppendBlobClient = containerClient.getAppendBlobClient(""); - * await existingAppendBlobClient.appendBlock(content, content.length); - * ``` + * @param {Metadata} [metadata] Replace existing metadata with this value. + * If no value provided the existing metadata will be removed. + * @param {BlobSetMetadataOptions} [options] Optional options to Set Metadata operation. + * @returns {Promise} + * @memberof BlobClient */ - AppendBlobClient.prototype.appendBlock = function (body, contentLength, options) { + BlobClient.prototype.setMetadata = function (metadata, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_21; + var _b, span, spanOptions, e_8; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: - _b = createSpan("AppendBlobClient-appendBlock", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _b = createSpan("BlobClient-setMetadata", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; options.conditions = options.conditions || {}; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.appendBlobContext.appendBlock(body, contentLength, { + return [4 /*yield*/, this.blobContext.setMetadata({ abortSignal: options.abortSignal, - appendPositionAccessConditions: options.conditions, leaseAccessConditions: options.conditions, + metadata: metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - onUploadProgress: options.onProgress, - transactionalContentMD5: options.transactionalContentMD5, - transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_21 = _c.sent(); + e_8 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_21.message + message: e_8.message }); - throw e_21; + throw e_8; case 4: span.end(); return [7 /*endfinally*/]; @@ -29548,62 +29832,43 @@ var AppendBlobClient = /** @class */ (function (_super) { }); }; /** - * The Append Block operation commits a new block of data to the end of an existing append blob - * where the contents are read from a source url. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/append-block-from-url + * Sets tags on the underlying blob. + * A blob can have up to 10 tags. Tag keys must be between 1 and 128 characters. Tag values must be between 0 and 256 characters. + * Valid tag key and value characters include lower and upper case letters, digits (0-9), + * space (' '), plus ('+'), minus ('-'), period ('.'), foward slash ('/'), colon (':'), equals ('='), and underscore ('_'). * - * @param {string} sourceURL - * The url to the blob that will be the source of the copy. A source blob in the same storage account can - * be authenticated via Shared Key. However, if the source is a blob in another account, the source blob - * must either be public or must be authenticated via a shared access signature. If the source blob is - * public, no authentication is required to perform the operation. - * @param {number} sourceOffset Offset in source to be appended - * @param {number} count Number of bytes to be appended as a block - * @param {AppendBlobAppendBlockFromURLOptions} [options={}] - * @returns {Promise} - * @memberof AppendBlobClient + * @param {Tags} tags + * @param {BlobSetTagsOptions} [options={}] + * @returns {Promise} + * @memberof BlobClient */ - AppendBlobClient.prototype.appendBlockFromURL = function (sourceURL, sourceOffset, count, options) { + BlobClient.prototype.setTags = function (tags, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_22; + var _b, span, spanOptions, e_9; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: - _b = createSpan("AppendBlobClient-appendBlockFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - options.conditions = options.conditions || {}; - options.sourceConditions = options.sourceConditions || {}; + _b = createSpan("BlobClient-setTags", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.appendBlobContext.appendBlockFromUrl(sourceURL, 0, { + return [4 /*yield*/, this.blobContext.setTags({ abortSignal: options.abortSignal, - sourceRange: rangeToString({ offset: sourceOffset, count: count }), - sourceContentMD5: options.sourceContentMD5, - sourceContentCrc64: options.sourceContentCrc64, leaseAccessConditions: options.conditions, - appendPositionAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions.ifMatch, - sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince - }, - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - spanOptions: spanOptions + spanOptions: spanOptions, + tags: toBlobTags(tags) })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_22 = _c.sent(); + e_9 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_22.message + message: e_9.message }); - throw e_22; + throw e_9; case 4: span.end(); return [7 /*endfinally*/]; @@ -29612,161 +29877,42 @@ var AppendBlobClient = /** @class */ (function (_super) { }); }); }; - return AppendBlobClient; -}(BlobClient)); -/** - * BlockBlobClient defines a set of operations applicable to block blobs. - * - * @export - * @class BlockBlobClient - * @extends {BlobClient} - */ -var BlockBlobClient = /** @class */ (function (_super) { - tslib.__extends(BlockBlobClient, _super); - function BlockBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { - var _this = this; - // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. - // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); - var pipeline; - var url; - options = options || {}; - if (credentialOrPipelineOrContainerName instanceof Pipeline) { - // (url: string, pipeline: Pipeline) - url = urlOrConnectionString; - pipeline = credentialOrPipelineOrContainerName; - } - else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || - credentialOrPipelineOrContainerName instanceof AnonymousCredential || - coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { - // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) - url = urlOrConnectionString; - options = blobNameOrOptions; - pipeline = newPipeline(credentialOrPipelineOrContainerName, options); - } - else if (!credentialOrPipelineOrContainerName && - typeof credentialOrPipelineOrContainerName !== "string") { - // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) - // The second parameter is undefined. Use anonymous credential. - url = urlOrConnectionString; - pipeline = newPipeline(new AnonymousCredential(), options); - } - else if (credentialOrPipelineOrContainerName && - typeof credentialOrPipelineOrContainerName === "string" && - blobNameOrOptions && - typeof blobNameOrOptions === "string") { - // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) - var containerName = credentialOrPipelineOrContainerName; - var blobName = blobNameOrOptions; - var extractedCreds = extractConnectionStringParts(urlOrConnectionString); - if (extractedCreds.kind === "AccountConnString") { - { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); - options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); - pipeline = newPipeline(sharedKeyCredential, options); - } - } - else if (extractedCreds.kind === "SASConnString") { - url = - appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + - "?" + - extractedCreds.accountSas; - pipeline = newPipeline(new AnonymousCredential(), options); - } - else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); - } - } - else { - throw new Error("Expecting non-empty strings for containerName and blobName parameters"); - } - _this = _super.call(this, url, pipeline) || this; - _this.blockBlobContext = new BlockBlob(_this.storageClientContext); - _this._blobContext = new Blob$1(_this.storageClientContext); - return _this; - } - /** - * Creates a new BlockBlobClient object identical to the source but with the - * specified snapshot timestamp. - * Provide "" will remove the snapshot and return a URL to the base blob. - * - * @param {string} snapshot The snapshot timestamp. - * @returns {BlockBlobClient} A new BlockBlobClient object identical to the source but with the specified snapshot timestamp. - * @memberof BlockBlobClient - */ - BlockBlobClient.prototype.withSnapshot = function (snapshot) { - return new BlockBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); - }; /** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * Quick query for a JSON or CSV formatted blob. - * - * Example usage (Node.js): - * - * ```js - * // Query and convert a blob to a string - * const queryBlockBlobResponse = await blockBlobClient.query("select * from BlobStorage"); - * const downloaded = (await streamToBuffer(queryBlockBlobResponse.readableStreamBody)).toString(); - * console.log("Query blob content:", downloaded); - * - * async function streamToBuffer(readableStream) { - * return new Promise((resolve, reject) => { - * const chunks = []; - * readableStream.on("data", (data) => { - * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); - * }); - * readableStream.on("end", () => { - * resolve(Buffer.concat(chunks)); - * }); - * readableStream.on("error", reject); - * }); - * } - * ``` + * Gets the tags associated with the underlying blob. * - * @param {string} query - * @param {BlockBlobQueryOptions} [options={}] - * @returns {Promise} - * @memberof BlockBlobClient + * @param {BlobGetTagsOptions} [options={}] + * @returns {Promise} + * @memberof BlobClient */ - BlockBlobClient.prototype.query = function (query, options) { + BlobClient.prototype.getTags = function (options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, response, e_23; + var _b, span, spanOptions, response, wrappedResponse, e_10; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - _b = createSpan("BlockBlobClient-query", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _b = createSpan("BlobClient-getTags", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this._blobContext.query({ + return [4 /*yield*/, this.blobContext.getTags({ abortSignal: options.abortSignal, - queryRequest: { - expression: query, - inputSerialization: toQuerySerialization(options.inputTextConfiguration), - outputSerialization: toQuerySerialization(options.outputTextConfiguration) - }, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), spanOptions: spanOptions })]; case 2: response = _c.sent(); - return [2 /*return*/, new BlobQueryResponse(response, { - abortSignal: options.abortSignal, - onProgress: options.onProgress, - onError: options.onError - })]; + wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, tags: toTags({ blobTagSet: response.blobTagSet }) || {} }); + return [2 /*return*/, wrappedResponse]; case 3: - e_23 = _c.sent(); + e_10 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_23.message + message: e_10.message }); - throw e_23; + throw e_10; case 4: span.end(); return [7 /*endfinally*/]; @@ -29776,68 +29922,54 @@ var BlockBlobClient = /** @class */ (function (_super) { }); }; /** - * Creates a new block blob, or updates the content of an existing block blob. - * Updating an existing block blob overwrites any existing metadata on the blob. - * Partial updates are not supported; the content of the existing blob is - * overwritten with the new content. To perform a partial update of a block blob's, - * use {@link stageBlock} and {@link commitBlockList}. - * - * This is a non-parallel uploading method, please use {@link uploadFile}, - * {@link uploadStream} or {@link uploadBrowserData} for better performance - * with concurrency uploading. - * - * @see https://docs.microsoft.com/rest/api/storageservices/put-blob - * - * @param {HttpRequestBody} body Blob, string, ArrayBuffer, ArrayBufferView or a function - * which returns a new Readable stream whose offset is from data source beginning. - * @param {number} contentLength Length of body in bytes. Use Buffer.byteLength() to calculate body length for a - * string including non non-Base64/Hex-encoded characters. - * @param {BlockBlobUploadOptions} [options] Options to the Block Blob Upload operation. - * @returns {Promise} Response data for the Block Blob Upload operation. - * @memberof BlockBlobClient - * - * Example usage: + * Get a {@link BlobLeaseClient} that manages leases on the blob. + * + * @param {string} [proposeLeaseId] Initial proposed lease Id. + * @returns {BlobLeaseClient} A new BlobLeaseClient object for managing leases on the blob. + * @memberof BlobClient + */ + BlobClient.prototype.getBlobLeaseClient = function (proposeLeaseId) { + return new BlobLeaseClient(this, proposeLeaseId); + }; + /** + * Creates a read-only snapshot of a blob. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/snapshot-blob * - * ```js - * const content = "Hello world!"; - * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); - * ``` + * @param {BlobCreateSnapshotOptions} [options] Optional options to the Blob Create Snapshot operation. + * @returns {Promise} + * @memberof BlobClient */ - BlockBlobClient.prototype.upload = function (body, contentLength, options) { + BlobClient.prototype.createSnapshot = function (options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_24; + var _b, span, spanOptions, e_11; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: + _b = createSpan("BlobClient-createSnapshot", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; options.conditions = options.conditions || {}; - _b = createSpan("BlockBlobClient-upload", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blockBlobContext.upload(body, contentLength, { + return [4 /*yield*/, this.blobContext.createSnapshot({ abortSignal: options.abortSignal, - blobHTTPHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - onUploadProgress: options.onProgress, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, - tier: toAccessTier(options.tier), - blobTagsString: toBlobTagsString(options.tags), spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_24 = _c.sent(); + e_11 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_24.message + message: e_11.message }); - throw e_24; + throw e_11; case 4: span.end(); return [7 /*endfinally*/]; @@ -29847,108 +29979,162 @@ var BlockBlobClient = /** @class */ (function (_super) { }); }; /** - * Uploads the specified block to the block blob's "staging area" to be later - * committed by a call to commitBlockList. - * @see https://docs.microsoft.com/rest/api/storageservices/put-block + * Asynchronously copies a blob to a destination within the storage account. + * This method returns a long running operation poller that allows you to wait + * indefinitely until the copy is completed. + * You can also cancel a copy before it is completed by calling `cancelOperation` on the poller. + * Note that the onProgress callback will not be invoked if the operation completes in the first + * request, and attempting to cancel a completed copy will result in an error being thrown. * - * @param {string} blockId A 64-byte value that is base64-encoded - * @param {HttpRequestBody} body Data to upload to the staging area. - * @param {number} contentLength Number of bytes to upload. - * @param {BlockBlobStageBlockOptions} [options] Options to the Block Blob Stage Block operation. - * @returns {Promise} Response data for the Block Blob Stage Block operation. - * @memberof BlockBlobClient + * In version 2012-02-12 and later, the source for a Copy Blob operation can be + * a committed blob in any Azure storage account. + * Beginning with version 2015-02-21, the source for a Copy Blob operation can be + * an Azure file in any Azure storage account. + * Only storage accounts created on or after June 7th, 2012 allow the Copy Blob + * operation to copy from another storage account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob + * + * Example using automatic polling: + * + * ```js + * const copyPoller = await blobClient.beginCopyFromURL('url'); + * const result = await copyPoller.pollUntilDone(); + * ``` + * + * Example using manual polling: + * + * ```js + * const copyPoller = await blobClient.beginCopyFromURL('url'); + * while (!poller.isDone()) { + * await poller.poll(); + * } + * const result = copyPoller.getResult(); + * ``` + * + * Example using progress updates: + * + * ```js + * const copyPoller = await blobClient.beginCopyFromURL('url', { + * onProgress(state) { + * console.log(`Progress: ${state.copyProgress}`); + * } + * }); + * const result = await copyPoller.pollUntilDone(); + * ``` + * + * Example using a changing polling interval (default 15 seconds): + * + * ```js + * const copyPoller = await blobClient.beginCopyFromURL('url', { + * intervalInMs: 1000 // poll blob every 1 second for copy progress + * }); + * const result = await copyPoller.pollUntilDone(); + * ``` + * + * Example using copy cancellation: + * + * ```js + * const copyPoller = await blobClient.beginCopyFromURL('url'); + * // cancel operation after starting it. + * try { + * await copyPoller.cancelOperation(); + * // calls to get the result now throw PollerCancelledError + * await copyPoller.getResult(); + * } catch (err) { + * if (err.name === 'PollerCancelledError') { + * console.log('The copy was cancelled.'); + * } + * } + * ``` + * + * @param {string} copySource url to the source Azure Blob/File. + * @param {BlobBeginCopyFromURLOptions} [options] Optional options to the Blob Start Copy From URL operation. */ - BlockBlobClient.prototype.stageBlock = function (blockId, body, contentLength, options) { + BlobClient.prototype.beginCopyFromURL = function (copySource, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_25; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var client, poller; + var _this = this; + return tslib.__generator(this, function (_a) { + switch (_a.label) { case 0: - _a = createSpan("BlockBlobClient-stageBlock", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blockBlobContext.stageBlock(blockId, contentLength, body, { - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - onUploadProgress: options.onProgress, - transactionalContentMD5: options.transactionalContentMD5, - transactionalContentCrc64: options.transactionalContentCrc64, - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_25 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_25.message + client = { + abortCopyFromURL: function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return _this.abortCopyFromURL.apply(_this, args); + }, + getProperties: function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return _this.getProperties.apply(_this, args); + }, + startCopyFromURL: function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return _this.startCopyFromURL.apply(_this, args); + } + }; + poller = new BlobBeginCopyFromUrlPoller({ + blobClient: client, + copySource: copySource, + intervalInMs: options.intervalInMs, + onProgress: options.onProgress, + resumeFrom: options.resumeFrom, + startCopyFromURLOptions: options }); - throw e_25; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + // Trigger the startCopyFromURL call by calling poll. + // Any errors from this method should be surfaced to the user. + return [4 /*yield*/, poller.poll()]; + case 1: + // Trigger the startCopyFromURL call by calling poll. + // Any errors from this method should be surfaced to the user. + _a.sent(); + return [2 /*return*/, poller]; } }); }); }; /** - * The Stage Block From URL operation creates a new block to be committed as part - * of a blob where the contents are read from a URL. - * This API is available starting in version 2018-03-28. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-from-url + * Aborts a pending asynchronous Copy Blob operation, and leaves a destination blob with zero + * length and full metadata. Version 2012-02-12 and newer. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/abort-copy-blob * - * @param {string} blockId A 64-byte value that is base64-encoded - * @param {string} sourceURL Specifies the URL of the blob. The value - * may be a URL of up to 2 KB in length that specifies a blob. - * The value should be URL-encoded as it would appear - * in a request URI. The source blob must either be public - * or must be authenticated via a shared access signature. - * If the source blob is public, no authentication is required - * to perform the operation. Here are some examples of source object URLs: - * - https://myaccount.blob.core.windows.net/mycontainer/myblob - * - https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= - * @param {number} [offset] From which position of the blob to download, >= 0 - * @param {number} [count] How much data to be downloaded, > 0. Will download to the end when undefined - * @param {BlockBlobStageBlockFromURLOptions} [options={}] Options to the Block Blob Stage Block From URL operation. - * @returns {Promise} Response data for the Block Blob Stage Block From URL operation. - * @memberof BlockBlobClient + * @param {string} copyId Id of the Copy From URL operation. + * @param {BlobAbortCopyFromURLOptions} [options] Optional options to the Blob Abort Copy From URL operation. + * @returns {Promise} + * @memberof BlobClient */ - BlockBlobClient.prototype.stageBlockFromURL = function (blockId, sourceURL, offset, count, options) { - if (offset === void 0) { offset = 0; } + BlobClient.prototype.abortCopyFromURL = function (copyId, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_26; + var _a, span, spanOptions, e_12; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("BlockBlobClient-stageBlockFromURL", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("BlobClient-abortCopyFromURL", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blockBlobContext.stageBlockFromURL(blockId, 0, sourceURL, { + return [4 /*yield*/, this.blobContext.abortCopyFromURL(copyId, { abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, - sourceContentMD5: options.sourceContentMD5, - sourceContentCrc64: options.sourceContentCrc64, - sourceRange: offset === 0 && !count ? undefined : rangeToString({ offset: offset, count: count }), - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _b.sent()]; case 3: - e_26 = _b.sent(); + e_12 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_26.message + message: e_12.message }); - throw e_26; + throw e_12; case 4: span.end(); return [7 /*endfinally*/]; @@ -29958,52 +30144,52 @@ var BlockBlobClient = /** @class */ (function (_super) { }); }; /** - * Writes a blob by specifying the list of block IDs that make up the blob. - * In order to be written as part of a blob, a block must have been successfully written - * to the server in a prior {@link stageBlock} operation. You can call {@link commitBlockList} to - * update a blob by uploading only those blocks that have changed, then committing the new and existing - * blocks together. Any blocks not specified in the block list and permanently deleted. - * @see https://docs.microsoft.com/rest/api/storageservices/put-block-list + * The synchronous Copy From URL operation copies a blob or an internet resource to a new blob. It will not + * return a response until the copy is complete. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob-from-url * - * @param {string[]} blocks Array of 64-byte value that is base64-encoded - * @param {BlockBlobCommitBlockListOptions} [options] Options to the Block Blob Commit Block List operation. - * @returns {Promise} Response data for the Block Blob Commit Block List operation. - * @memberof BlockBlobClient + * @param {string} copySource The source URL to copy from, Shared Access Signature(SAS) maybe needed for authentication + * @param {BlobSyncCopyFromURLOptions} [options={}] + * @returns {Promise} + * @memberof BlobClient */ - BlockBlobClient.prototype.commitBlockList = function (blocks, options) { + BlobClient.prototype.syncCopyFromURL = function (copySource, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_27; + var _b, span, spanOptions, e_13; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: + _b = createSpan("BlobClient-syncCopyFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; options.conditions = options.conditions || {}; - _b = createSpan("BlockBlobClient-commitBlockList", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + options.sourceConditions = options.sourceConditions || {}; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blockBlobContext.commitBlockList({ latest: blocks }, { + return [4 /*yield*/, this.blobContext.copyFromURL(copySource, { abortSignal: options.abortSignal, - blobHTTPHeaders: options.blobHTTPHeaders, - leaseAccessConditions: options.conditions, metadata: options.metadata, + leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - tier: toAccessTier(options.tier), + sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince + }, + sourceContentMD5: options.sourceContentMD5, blobTagsString: toBlobTagsString(options.tags), spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_27 = _c.sent(); + e_13 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_27.message + message: e_13.message }); - throw e_27; + throw e_13; case 4: span.end(); return [7 /*endfinally*/]; @@ -30013,50 +30199,45 @@ var BlockBlobClient = /** @class */ (function (_super) { }); }; /** - * Returns the list of blocks that have been uploaded as part of a block blob - * using the specified block list filter. - * @see https://docs.microsoft.com/rest/api/storageservices/get-block-list + * Sets the tier on a blob. The operation is allowed on a page blob in a premium + * storage account and on a block blob in a blob storage account (locally redundant + * storage only). A premium page blob's tier determines the allowed size, IOPS, + * and bandwidth of the blob. A block blob's tier determines Hot/Cool/Archive + * storage type. This operation does not update the blob's ETag. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-tier * - * @param {BlockListType} listType Specifies whether to return the list of committed blocks, - * the list of uncommitted blocks, or both lists together. - * @param {BlockBlobGetBlockListOptions} [options] Options to the Block Blob Get Block List operation. - * @returns {Promise} Response data for the Block Blob Get Block List operation. - * @memberof BlockBlobClient + * @param {BlockBlobTier | PremiumPageBlobTier | string} tier The tier to be set on the blob. Valid values are Hot, Cool, or Archive. + * @param {BlobSetTierOptions} [options] Optional options to the Blob Set Tier operation. + * @returns {Promise} + * @memberof BlobClient */ - BlockBlobClient.prototype.getBlockList = function (listType, options) { + BlobClient.prototype.setAccessTier = function (tier, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, res, e_28; + var _b, span, spanOptions, e_14; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: - _b = createSpan("BlockBlobClient-getBlockList", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _b = createSpan("BlobClient-setAccessTier", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blockBlobContext.getBlockList(listType, { + return [4 /*yield*/, this.blobContext.setTier(toAccessTier(tier), { abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + rehydratePriority: options.rehydratePriority, spanOptions: spanOptions })]; - case 2: - res = _c.sent(); - if (!res.committedBlocks) { - res.committedBlocks = []; - } - if (!res.uncommittedBlocks) { - res.uncommittedBlocks = []; - } - return [2 /*return*/, res]; + case 2: return [2 /*return*/, _c.sent()]; case 3: - e_28 = _c.sent(); + e_14 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_28.message + message: e_14.message }); - throw e_28; + throw e_14; case 4: span.end(); return [7 /*endfinally*/]; @@ -30065,220 +30246,122 @@ var BlockBlobClient = /** @class */ (function (_super) { }); }); }; - // High level functions - /** - * Uploads a Buffer(Node.js)/Blob(browsers)/ArrayBuffer/ArrayBufferView object to a BlockBlob. - * - * When data length is no more than the specifiled {@link BlockBlobParallelUploadOptions.maxSingleShotSize} (default is - * {@link BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}), this method will use 1 {@link upload} call to finish the upload. - * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} - * to commit the block list. - * - * @export - * @param {Buffer | Blob | ArrayBuffer | ArrayBufferView} data Buffer(Node.js), Blob, ArrayBuffer or ArrayBufferView - * @param {BlockBlobParallelUploadOptions} [options] - * @returns {Promise} - * @memberof BlockBlobClient - */ - BlockBlobClient.prototype.uploadData = function (data, options) { - if (options === void 0) { options = {}; } + BlobClient.prototype.downloadToBuffer = function (param1, param2, param3, param4) { + if (param4 === void 0) { param4 = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, buffer_1, browserBlob_1; + var buffer, offset, count, options, _a, span, spanOptions, response, transferProgress_1, batch, _loop_1, off, e_15; + var _this = this; return tslib.__generator(this, function (_b) { - _a = createSpan("BlockBlobClient-uploadData", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - try { - if (true) { - if (data instanceof Buffer) { - buffer_1 = data; - } - else if (data instanceof ArrayBuffer) { - buffer_1 = Buffer.from(data); + switch (_b.label) { + case 0: + offset = 0; + count = 0; + options = param4; + if (param1 instanceof Buffer) { + buffer = param1; + offset = param2 || 0; + count = typeof param3 === "number" ? param3 : 0; } else { - data = data; - buffer_1 = Buffer.from(data.buffer, data.byteOffset, data.byteLength); + offset = typeof param1 === "number" ? param1 : 0; + count = typeof param2 === "number" ? param2 : 0; + options = param3 || {}; } - return [2 /*return*/, this.uploadSeekableInternal(function (offset, size) { return buffer_1.slice(offset, offset + size); }, buffer_1.byteLength, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - } - else {} - } - catch (e) { - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e.message - }); - throw e; - } - finally { - span.end(); - } - return [2 /*return*/]; - }); - }); - }; - /** - * ONLY AVAILABLE IN BROWSERS. - * - * Uploads a browser Blob/File/ArrayBuffer/ArrayBufferView object to block blob. - * - * When buffer length <= 256MB, this method will use 1 upload call to finish the upload. - * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call - * {@link commitBlockList} to commit the block list. - * - * @deprecated Use {@link uploadData} instead. - * - * @export - * @param {Blob | ArrayBuffer | ArrayBufferView} browserData Blob, File, ArrayBuffer or ArrayBufferView - * @param {BlockBlobParallelUploadOptions} [options] Options to upload browser data. - * @returns {Promise} Response data for the Blob Upload operation. - * @memberof BlockBlobClient - */ - BlockBlobClient.prototype.uploadBrowserData = function (browserData, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, browserBlob_2, e_29; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlockBlobClient-uploadBrowserData", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("BlobClient-downloadToBuffer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: - _b.trys.push([1, 3, 4, 5]); - browserBlob_2 = new Blob([browserData]); - return [4 /*yield*/, this.uploadSeekableInternal(function (offset, size) { return browserBlob_2.slice(offset, offset + size); }, browserBlob_2.size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_29 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_29.message - }); - throw e_29; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - /** - * - * Uploads data to block blob. Requires a bodyFactory as the data source, - * which need to return a {@link HttpRequestBody} object with the offset and size provided. - * - * When data length is no more than the specifiled {@link BlockBlobParallelUploadOptions.maxSingleShotSize} (default is - * {@link BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}), this method will use 1 {@link upload} call to finish the upload. - * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} - * to commit the block list. - * - * @param {(offset: number, size: number) => HttpRequestBody} bodyFactory - * @param {number} size size of the data to upload. - * @param {BlockBlobParallelUploadOptions} [options] Options to Upload to Block Blob operation. - * @returns {Promise} Response data for the Blob Upload operation. - * @memberof BlockBlobClient - */ - BlockBlobClient.prototype.uploadSeekableInternal = function (bodyFactory, size, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, numBlocks_1, blockList_1, blockIDPrefix_1, transferProgress_2, batch, _loop_2, i, e_30; - var _this = this; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: + _b.trys.push([1, 5, 6, 7]); if (!options.blockSize) { options.blockSize = 0; } - if (options.blockSize < 0 || options.blockSize > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES) { - throw new RangeError("blockSize option must be >= 0 and <= " + BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES); - } - if (options.maxSingleShotSize !== 0 && !options.maxSingleShotSize) { - options.maxSingleShotSize = BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES; - } - if (options.maxSingleShotSize < 0 || - options.maxSingleShotSize > BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES) { - throw new RangeError("maxSingleShotSize option must be >= 0 and <= " + BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES); + if (options.blockSize < 0) { + throw new RangeError("blockSize option must be >= 0"); } if (options.blockSize === 0) { - if (size > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES * BLOCK_BLOB_MAX_BLOCKS) { - throw new RangeError(size + " is too larger to upload to a block blob."); - } - if (size > options.maxSingleShotSize) { - options.blockSize = Math.ceil(size / BLOCK_BLOB_MAX_BLOCKS); - if (options.blockSize < DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES) { - options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; - } - } + options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; } - if (!options.blobHTTPHeaders) { - options.blobHTTPHeaders = {}; + if (offset < 0) { + throw new RangeError("offset option must be >= 0"); + } + if (count && count <= 0) { + throw new RangeError("count option must be > 0"); } if (!options.conditions) { options.conditions = {}; } - _a = createSpan("BlockBlobClient-uploadSeekableInternal", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 5, 6, 7]); - if (!(size <= options.maxSingleShotSize)) return [3 /*break*/, 3]; - return [4 /*yield*/, this.upload(bodyFactory(0, size), size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: return [2 /*return*/, _b.sent()]; + if (!!count) return [3 /*break*/, 3]; + return [4 /*yield*/, this.getProperties(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: + response = _b.sent(); + count = response.contentLength - offset; + if (count < 0) { + throw new RangeError("offset " + offset + " shouldn't be larger than blob size " + response.contentLength); + } + _b.label = 3; case 3: - numBlocks_1 = Math.floor((size - 1) / options.blockSize) + 1; - if (numBlocks_1 > BLOCK_BLOB_MAX_BLOCKS) { - throw new RangeError("The buffer's size is too big or the BlockSize is too small;" + - ("the number of blocks must be <= " + BLOCK_BLOB_MAX_BLOCKS)); + // Allocate the buffer of size = count if the buffer is not provided + if (!buffer) { + try { + buffer = Buffer.alloc(count); + } + catch (error) { + throw new Error("Unable to allocate the buffer of size: " + count + "(in bytes). Please try passing your own buffer to the \"downloadToBuffer\" method or try using other methods like \"download\" or \"downloadToFile\".\t " + error.message); + } } - blockList_1 = []; - blockIDPrefix_1 = coreHttp.generateUuid(); - transferProgress_2 = 0; + if (buffer.length < count) { + throw new RangeError("The buffer's size should be equal to or larger than the request count of bytes: " + count); + } + transferProgress_1 = 0; batch = new Batch(options.concurrency); - _loop_2 = function (i) { + _loop_1 = function (off) { batch.addOperation(function () { return tslib.__awaiter(_this, void 0, void 0, function () { - var blockID, start, end, contentLength; + var chunkEnd, response, stream; return tslib.__generator(this, function (_a) { switch (_a.label) { case 0: - blockID = generateBlockID(blockIDPrefix_1, i); - start = options.blockSize * i; - end = i === numBlocks_1 - 1 ? size : start + options.blockSize; - contentLength = end - start; - blockList_1.push(blockID); - return [4 /*yield*/, this.stageBlock(blockID, bodyFactory(start, contentLength), contentLength, { + chunkEnd = offset + count; + if (off + options.blockSize < chunkEnd) { + chunkEnd = off + options.blockSize; + } + return [4 /*yield*/, this.download(off, chunkEnd - off, { abortSignal: options.abortSignal, conditions: options.conditions, - encryptionScope: options.encryptionScope, + maxRetryRequests: options.maxRetryRequestsPerBlock, + customerProvidedKey: options.customerProvidedKey, tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) })]; case 1: + response = _a.sent(); + stream = response.readableStreamBody; + return [4 /*yield*/, streamToBuffer(stream, buffer, off - offset, chunkEnd - offset)]; + case 2: _a.sent(); - // Update progress after block is successfully uploaded to server, in case of block trying - // TODO: Hook with convenience layer progress event in finer level - transferProgress_2 += contentLength; + // Update progress after block is downloaded, in case of block trying + // Could provide finer grained progress updating inside HTTP requests, + // only if convenience layer download try is enabled + transferProgress_1 += chunkEnd - off; if (options.onProgress) { - options.onProgress({ - loadedBytes: transferProgress_2 - }); + options.onProgress({ loadedBytes: transferProgress_1 }); } return [2 /*return*/]; } }); }); }); }; - for (i = 0; i < numBlocks_1; i++) { - _loop_2(i); + for (off = offset; off < offset + count; off = off + options.blockSize) { + _loop_1(off); } return [4 /*yield*/, batch.do()]; case 4: _b.sent(); - return [2 /*return*/, this.commitBlockList(blockList_1, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + return [2 /*return*/, buffer]; case 5: - e_30 = _b.sent(); + e_15 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_30.message + message: e_15.message }); - throw e_30; + throw e_15; case 6: span.end(); return [7 /*endfinally*/]; @@ -30290,158 +30373,205 @@ var BlockBlobClient = /** @class */ (function (_super) { /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * - * Uploads a local file in blocks to a block blob. - * - * When file size <= 256MB, this method will use 1 upload call to finish the upload. - * Otherwise, this method will call stageBlock to upload blocks, and finally call commitBlockList - * to commit the block list. + * Downloads an Azure Blob to a local file. + * Fails if the the given file path already exits. + * Offset and count are optional, pass 0 and undefined respectively to download the entire blob. * - * @param {string} filePath Full path of local file - * @param {BlockBlobParallelUploadOptions} [options] Options to Upload to Block Blob operation. - * @returns {(Promise)} Response data for the Blob Upload operation. - * @memberof BlockBlobClient + * @param {string} filePath + * @param {number} [offset] From which position of the block blob to download. + * @param {number} [count] How much data to be downloaded. Will download to the end when passing undefined. + * @param {BlobDownloadOptions} [options] Options to Blob download options. + * @returns {Promise} The response data for blob download operation, + * but with readableStreamBody set to undefined since its + * content is already read and written into a local file + * at the specified path. + * @memberof BlobClient */ - BlockBlobClient.prototype.uploadFile = function (filePath, options) { + BlobClient.prototype.downloadToFile = function (filePath, offset, count, options) { + if (offset === void 0) { offset = 0; } if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, size, e_31; + var _a, span, spanOptions, response, e_16; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("BlockBlobClient-uploadFile", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("BlobClient-downloadToFile", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: - _b.trys.push([1, 4, 5, 6]); - return [4 /*yield*/, fsStat(filePath)]; + _b.trys.push([1, 5, 6, 7]); + return [4 /*yield*/, this.download(offset, count, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: - size = (_b.sent()).size; - return [4 /*yield*/, this.uploadSeekableInternal(function (offset, count) { - return function () { - return fsCreateReadStream(filePath, { - autoClose: true, - end: count ? offset + count - 1 : Infinity, - start: offset - }); - }; - }, size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 3: return [2 /*return*/, _b.sent()]; + response = _b.sent(); + if (!response.readableStreamBody) return [3 /*break*/, 4]; + return [4 /*yield*/, readStreamToLocalFile(response.readableStreamBody, filePath)]; + case 3: + _b.sent(); + _b.label = 4; case 4: - e_31 = _b.sent(); + // The stream is no longer accessible so setting it to undefined. + response.blobDownloadStream = undefined; + return [2 /*return*/, response]; + case 5: + e_16 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_31.message + message: e_16.message }); - throw e_31; - case 5: + throw e_16; + case 6: span.end(); return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; + case 7: return [2 /*return*/]; } }); }); }; + BlobClient.prototype.getBlobAndContainerNamesFromUrl = function () { + var containerName; + var blobName; + try { + // URL may look like the following + // "https://myaccount.blob.core.windows.net/mycontainer/blob?sasString"; + // "https://myaccount.blob.core.windows.net/mycontainer/blob"; + // "https://myaccount.blob.core.windows.net/mycontainer/blob/a.txt?sasString"; + // "https://myaccount.blob.core.windows.net/mycontainer/blob/a.txt"; + // IPv4/IPv6 address hosts, Endpoints - `http://127.0.0.1:10000/devstoreaccount1/containername/blob` + // http://localhost:10001/devstoreaccount1/containername/blob + var parsedUrl = coreHttp.URLBuilder.parse(this.url); + if (parsedUrl.getHost().split(".")[1] === "blob") { + // "https://myaccount.blob.core.windows.net/containername/blob". + // .getPath() -> /containername/blob + var pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); + containerName = pathComponents[1]; + blobName = pathComponents[3]; + } + else if (isIpEndpointStyle(parsedUrl)) { + // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/containername/blob + // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/containername/blob + // .getPath() -> /devstoreaccount1/containername/blob + var pathComponents = parsedUrl.getPath().match("/([^/]*)/([^/]*)(/(.*))?"); + containerName = pathComponents[2]; + blobName = pathComponents[4]; + } + else { + // "https://customdomain.com/containername/blob". + // .getPath() -> /containername/blob + var pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); + containerName = pathComponents[1]; + blobName = pathComponents[3]; + } + // decode the encoded blobName, containerName - to get all the special characters that might be present in them + containerName = decodeURIComponent(containerName); + blobName = decodeURIComponent(blobName); + // Azure Storage Server will replace "\" with "/" in the blob names + // doing the same in the SDK side so that the user doesn't have to replace "\" instances in the blobName + blobName = blobName.replace(/\\/g, "/"); + if (!containerName) { + throw new Error("Provided containerName is invalid."); + } + return { blobName: blobName, containerName: containerName }; + } + catch (error) { + throw new Error("Unable to extract blobName and containerName with provided information."); + } + }; /** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * Uploads a Node.js Readable stream into block blob. - * - * PERFORMANCE IMPROVEMENT TIPS: - * * Input stream highWaterMark is better to set a same value with bufferSize - * parameter, which will avoid Buffer.concat() operations. + * Asynchronously copies a blob to a destination within the storage account. + * In version 2012-02-12 and later, the source for a Copy Blob operation can be + * a committed blob in any Azure storage account. + * Beginning with version 2015-02-21, the source for a Copy Blob operation can be + * an Azure file in any Azure storage account. + * Only storage accounts created on or after June 7th, 2012 allow the Copy Blob + * operation to copy from another storage account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob * - * @param {Readable} stream Node.js Readable stream - * @param {number} bufferSize Size of every buffer allocated, also the block size in the uploaded block blob. Default value is 8MB - * @param {number} maxConcurrency Max concurrency indicates the max number of buffers that can be allocated, - * positive correlation with max uploading concurrency. Default value is 5 - * @param {BlockBlobUploadStreamOptions} [options] Options to Upload Stream to Block Blob operation. - * @returns {Promise} Response data for the Blob Upload operation. - * @memberof BlockBlobClient + * @param {string} copySource url to the source Azure Blob/File. + * @param {BlobStartCopyFromURLOptions} [options] Optional options to the Blob Start Copy From URL operation. + * @returns {Promise} + * @memberof BlobClient */ - BlockBlobClient.prototype.uploadStream = function (stream, bufferSize, maxConcurrency, options) { - if (bufferSize === void 0) { bufferSize = DEFAULT_BLOCK_BUFFER_SIZE_BYTES; } - if (maxConcurrency === void 0) { maxConcurrency = 5; } + BlobClient.prototype.startCopyFromURL = function (copySource, options) { + var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, blockNum_1, blockIDPrefix_2, transferProgress_3, blockList_2, scheduler, e_32; - var _this = this; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var _b, span, spanOptions, e_17; + return tslib.__generator(this, function (_c) { + switch (_c.label) { case 0: - if (!options.blobHTTPHeaders) { - options.blobHTTPHeaders = {}; - } - if (!options.conditions) { - options.conditions = {}; - } - _a = createSpan("BlockBlobClient-uploadStream", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + _b = createSpan("BlobClient-startCopyFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + _c.label = 1; case 1: - _b.trys.push([1, 4, 5, 6]); - blockNum_1 = 0; - blockIDPrefix_2 = coreHttp.generateUuid(); - transferProgress_3 = 0; - blockList_2 = []; - scheduler = new BufferScheduler(stream, bufferSize, maxConcurrency, function (body, length) { return tslib.__awaiter(_this, void 0, void 0, function () { - var blockID; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - blockID = generateBlockID(blockIDPrefix_2, blockNum_1); - blockList_2.push(blockID); - blockNum_1++; - return [4 /*yield*/, this.stageBlock(blockID, body, length, { - conditions: options.conditions, - encryptionScope: options.encryptionScope, - tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) - })]; - case 1: - _a.sent(); - // Update progress after block is successfully uploaded to server, in case of block trying - transferProgress_3 += length; - if (options.onProgress) { - options.onProgress({ loadedBytes: transferProgress_3 }); - } - return [2 /*return*/]; - } - }); - }); }, - // concurrency should set a smaller value than maxConcurrency, which is helpful to - // reduce the possibility when a outgoing handler waits for stream data, in - // this situation, outgoing handlers are blocked. - // Outgoing queue shouldn't be empty. - Math.ceil((maxConcurrency / 4) * 3)); - return [4 /*yield*/, scheduler.do()]; - case 2: - _b.sent(); - return [4 /*yield*/, this.commitBlockList(blockList_2, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 3: return [2 /*return*/, _b.sent()]; - case 4: - e_32 = _b.sent(); + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.blobContext.startCopyFromURL(copySource, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince, + sourceIfTags: options.sourceConditions.tagConditions + }, + rehydratePriority: options.rehydratePriority, + tier: toAccessTier(options.tier), + blobTagsString: toBlobTagsString(options.tags), + sealBlob: options.sealBlob, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_17 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_32.message + message: e_17.message }); - throw e_32; - case 5: + throw e_17; + case 4: span.end(); return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; + case 5: return [2 /*return*/]; } }); }); }; - return BlockBlobClient; -}(BlobClient)); + /** + * Only available for BlobClient constructed with a shared key credential. + * + * Generates a Blob Service Shared Access Signature (SAS) URI based on the client properties + * and parameters passed in. The SAS is signed by the shared key credential of the client. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas + * + * @param {BlobGenerateSasUrlOptions} options Optional parameters. + * @returns {Promise} The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + * @memberof BlobClient + */ + BlobClient.prototype.generateSasUrl = function (options) { + var _this = this; + return new Promise(function (resolve) { + if (!(_this.credential instanceof StorageSharedKeyCredential)) { + throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); + } + var sas = generateBlobSASQueryParameters(tslib.__assign({ containerName: _this._containerName, blobName: _this._name, snapshotTime: _this._snapshot, versionId: _this._versionId }, options), _this.credential).toString(); + resolve(appendToURLQuery(_this.url, sas)); + }); + }; + return BlobClient; +}(StorageClient)); /** - * PageBlobClient defines a set of operations applicable to page blobs. + * AppendBlobClient defines a set of operations applicable to append blobs. * * @export - * @class PageBlobClient + * @class AppendBlobClient * @extends {BlobClient} */ -var PageBlobClient = /** @class */ (function (_super) { - tslib.__extends(PageBlobClient, _super); - function PageBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { +var AppendBlobClient = /** @class */ (function (_super) { + tslib.__extends(AppendBlobClient, _super); + function AppendBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { var _this = this; // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); @@ -30456,7 +30586,7 @@ var PageBlobClient = /** @class */ (function (_super) { else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { - // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) url = urlOrConnectionString; url = urlOrConnectionString; options = blobNameOrOptions; pipeline = newPipeline(credentialOrPipelineOrContainerName, options); @@ -30464,8 +30594,8 @@ var PageBlobClient = /** @class */ (function (_super) { else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) - // The second parameter is undefined. Use anonymous credential. url = urlOrConnectionString; + // The second parameter is undefined. Use anonymous credential. pipeline = newPipeline(new AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && @@ -30499,66 +30629,69 @@ var PageBlobClient = /** @class */ (function (_super) { throw new Error("Expecting non-empty strings for containerName and blobName parameters"); } _this = _super.call(this, url, pipeline) || this; - _this.pageBlobContext = new PageBlob(_this.storageClientContext); + _this.appendBlobContext = new AppendBlob(_this.storageClientContext); return _this; } /** - * Creates a new PageBlobClient object identical to the source but with the + * Creates a new AppendBlobClient object identical to the source but with the * specified snapshot timestamp. * Provide "" will remove the snapshot and return a Client to the base blob. * * @param {string} snapshot The snapshot timestamp. - * @returns {PageBlobClient} A new PageBlobClient object identical to the source but with the specified snapshot timestamp. - * @memberof PageBlobClient + * @returns {AppendBlobClient} A new AppendBlobClient object identical to the source but with the specified snapshot timestamp. + * @memberof AppendBlobClient */ - PageBlobClient.prototype.withSnapshot = function (snapshot) { - return new PageBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); + AppendBlobClient.prototype.withSnapshot = function (snapshot) { + return new AppendBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); }; /** - * Creates a page blob of the specified length. Call uploadPages to upload data - * data to a page blob. + * Creates a 0-length append blob. Call AppendBlock to append data to an append blob. * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * - * @param {number} size size of the page blob. - * @param {PageBlobCreateOptions} [options] Options to the Page Blob Create operation. - * @returns {Promise} Response data for the Page Blob Create operation. - * @memberof PageBlobClient + * @param {AppendBlobCreateOptions} [options] Options to the Append Block Create operation. + * @returns {Promise} + * @memberof AppendBlobClient + * + * Example usage: + * + * ```js + * const appendBlobClient = containerClient.getAppendBlobClient(""); + * await appendBlobClient.create(); + * ``` */ - PageBlobClient.prototype.create = function (size, options) { + AppendBlobClient.prototype.create = function (options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_33; + var _b, span, spanOptions, e_18; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: + _b = createSpan("AppendBlobClient-create", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-create", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.pageBlobContext.create(0, size, { + return [4 /*yield*/, this.appendBlobContext.create(0, { abortSignal: options.abortSignal, blobHTTPHeaders: options.blobHTTPHeaders, - blobSequenceNumber: options.blobSequenceNumber, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, - tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_33 = _c.sent(); + e_18 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_33.message + message: e_18.message }); - throw e_33; + throw e_18; case 4: span.end(); return [7 /*endfinally*/]; @@ -30568,48 +30701,46 @@ var PageBlobClient = /** @class */ (function (_super) { }); }; /** - * Creates a page blob of the specified length. Call uploadPages to upload data - * data to a page blob. If the blob with the same name already exists, the content - * of the existing blob will remain unchanged. + * Creates a 0-length append blob. Call AppendBlock to append data to an append blob. + * If the blob with the same name already exists, the content of the existing blob will remain unchanged. * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * - * @param {number} size size of the page blob. - * @param {PageBlobCreateIfNotExistsOptions} [options] - * @returns {Promise} - * @memberof PageBlobClient + * @param {AppendBlobCreateIfNotExistsOptions} [options] + * @returns {Promise} + * @memberof AppendBlobClient */ - PageBlobClient.prototype.createIfNotExists = function (size, options) { + AppendBlobClient.prototype.createIfNotExists = function (options) { var _a, _b; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _c, span, spanOptions, conditions, res, e_34; + var _c, span, spanOptions, conditions, res, e_19; return tslib.__generator(this, function (_d) { switch (_d.label) { case 0: - _c = createSpan("PageBlobClient-createIfNotExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; + _c = createSpan("AppendBlobClient-createIfNotExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; + conditions = { ifNoneMatch: ETagAny }; _d.label = 1; case 1: _d.trys.push([1, 3, 4, 5]); - conditions = { ifNoneMatch: ETagAny }; - return [4 /*yield*/, this.create(size, tslib.__assign(tslib.__assign({}, options), { conditions: conditions, tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + return [4 /*yield*/, this.create(tslib.__assign(tslib.__assign({}, options), { conditions: conditions, tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: res = _d.sent(); return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable })]; case 3: - e_34 = _d.sent(); - if (((_a = e_34.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { + e_19 = _d.sent(); + if (((_a = e_19.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { span.setStatus({ code: api.CanonicalCode.ALREADY_EXISTS, message: "Expected exception when creating a blob only if it does not already exist." }); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_34.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_34.response })]; + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_19.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_19.response })]; } span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_34.message + message: e_19.message }); - throw e_34; + throw e_19; case 4: span.end(); return [7 /*endfinally*/]; @@ -30619,51 +30750,40 @@ var PageBlobClient = /** @class */ (function (_super) { }); }; /** - * Writes 1 or more pages to the page blob. The start and end offsets must be a multiple of 512. - * @see https://docs.microsoft.com/rest/api/storageservices/put-page + * Seals the append blob, making it read only. * - * @param {HttpRequestBody} body Data to upload - * @param {number} offset Offset of destination page blob - * @param {number} count Content length of the body, also number of bytes to be uploaded - * @param {PageBlobUploadPagesOptions} [options] Options to the Page Blob Upload Pages operation. - * @returns {Promise} Response data for the Page Blob Upload Pages operation. - * @memberof PageBlobClient + * @param {AppendBlobSealOptions} [options={}] + * @returns {Promise} + * @memberof AppendBlobClient */ - PageBlobClient.prototype.uploadPages = function (body, offset, count, options) { + AppendBlobClient.prototype.seal = function (options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_35; + var _b, span, spanOptions, e_20; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: + _b = createSpan("AppendBlobClient-seal", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-uploadPages", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.pageBlobContext.uploadPages(body, count, { + return [4 /*yield*/, this.appendBlobContext.seal({ abortSignal: options.abortSignal, + appendPositionAccessConditions: options.conditions, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - onUploadProgress: options.onProgress, - range: rangeToString({ offset: offset, count: count }), - sequenceNumberAccessConditions: options.conditions, - transactionalContentMD5: options.transactionalContentMD5, - transactionalContentCrc64: options.transactionalContentCrc64, - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_35 = _c.sent(); + e_20 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_35.message + message: e_20.message }); - throw e_35; + throw e_20; case 4: span.end(); return [7 /*endfinally*/]; @@ -30673,108 +30793,64 @@ var PageBlobClient = /** @class */ (function (_super) { }); }; /** - * The Upload Pages operation writes a range of pages to a page blob where the - * contents are read from a URL. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-page-from-url + * Commits a new block of data to the end of the existing append blob. + * @see https://docs.microsoft.com/rest/api/storageservices/append-block * - * @param {string} sourceURL Specify a URL to the copy source, Shared Access Signature(SAS) maybe needed for authentication - * @param {number} sourceOffset The source offset to copy from. Pass 0 to copy from the beginning of source page blob - * @param {number} destOffset Offset of destination page blob - * @param {number} count Number of bytes to be uploaded from source page blob - * @param {PageBlobUploadPagesFromURLOptions} [options={}] - * @returns {Promise} - * @memberof PageBlobClient - */ - PageBlobClient.prototype.uploadPagesFromURL = function (sourceURL, sourceOffset, destOffset, count, options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_36; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - options.sourceConditions = options.sourceConditions || {}; - _b = createSpan("PageBlobClient-uploadPagesFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.pageBlobContext.uploadPagesFromURL(sourceURL, rangeToString({ offset: sourceOffset, count: count }), 0, rangeToString({ offset: destOffset, count: count }), { - abortSignal: options.abortSignal, - sourceContentMD5: options.sourceContentMD5, - sourceContentCrc64: options.sourceContentCrc64, - leaseAccessConditions: options.conditions, - sequenceNumberAccessConditions: options.conditions, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions.ifMatch, - sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince - }, - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_36 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_36.message - }); - throw e_36; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - /** - * Frees the specified pages from the page blob. - * @see https://docs.microsoft.com/rest/api/storageservices/put-page + * @param {HttpRequestBody} body Data to be appended. + * @param {number} contentLength Length of the body in bytes. + * @param {AppendBlobAppendBlockOptions} [options] Options to the Append Block operation. + * @returns {Promise} + * @memberof AppendBlobClient * - * @param {number} [offset] Starting byte position of the pages to clear. - * @param {number} [count] Number of bytes to clear. - * @param {PageBlobClearPagesOptions} [options] Options to the Page Blob Clear Pages operation. - * @returns {Promise} Response data for the Page Blob Clear Pages operation. - * @memberof PageBlobClient + * Example usage: + * + * ```js + * const content = "Hello World!"; + * + * // Create a new append blob and append data to the blob. + * const newAppendBlobClient = containerClient.getAppendBlobClient(""); + * await newAppendBlobClient.create(); + * await newAppendBlobClient.appendBlock(content, content.length); + * + * // Append data to an existing append blob. + * const existingAppendBlobClient = containerClient.getAppendBlobClient(""); + * await existingAppendBlobClient.appendBlock(content, content.length); + * ``` */ - PageBlobClient.prototype.clearPages = function (offset, count, options) { + AppendBlobClient.prototype.appendBlock = function (body, contentLength, options) { var _a; - if (offset === void 0) { offset = 0; } if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_37; + var _b, span, spanOptions, e_21; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: + _b = createSpan("AppendBlobClient-appendBlock", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-clearPages", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext.clearPages(0, { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.appendBlobContext.appendBlock(body, contentLength, { abortSignal: options.abortSignal, + appendPositionAccessConditions: options.conditions, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - range: rangeToString({ offset: offset, count: count }), - sequenceNumberAccessConditions: options.conditions, + onUploadProgress: options.onProgress, + transactionalContentMD5: options.transactionalContentMD5, + transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_37 = _c.sent(); + e_21 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_37.message + message: e_21.message }); - throw e_37; + throw e_21; case 4: span.end(); return [7 /*endfinally*/]; @@ -30784,46 +30860,62 @@ var PageBlobClient = /** @class */ (function (_super) { }); }; /** - * Returns the list of valid page ranges for a page blob or snapshot of a page blob. - * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * The Append Block operation commits a new block of data to the end of an existing append blob + * where the contents are read from a source url. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/append-block-from-url * - * @param {number} [offset] Starting byte position of the page ranges. - * @param {number} [count] Number of bytes to get. - * @param {PageBlobGetPageRangesOptions} [options] Options to the Page Blob Get Ranges operation. - * @returns {Promise} Response data for the Page Blob Get Ranges operation. - * @memberof PageBlobClient + * @param {string} sourceURL + * The url to the blob that will be the source of the copy. A source blob in the same storage account can + * be authenticated via Shared Key. However, if the source is a blob in another account, the source blob + * must either be public or must be authenticated via a shared access signature. If the source blob is + * public, no authentication is required to perform the operation. + * @param {number} sourceOffset Offset in source to be appended + * @param {number} count Number of bytes to be appended as a block + * @param {AppendBlobAppendBlockFromURLOptions} [options={}] + * @returns {Promise} + * @memberof AppendBlobClient */ - PageBlobClient.prototype.getPageRanges = function (offset, count, options) { + AppendBlobClient.prototype.appendBlockFromURL = function (sourceURL, sourceOffset, count, options) { var _a; - if (offset === void 0) { offset = 0; } if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_38; + var _b, span, spanOptions, e_22; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: + _b = createSpan("AppendBlobClient-appendBlockFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-getPageRanges", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + options.sourceConditions = options.sourceConditions || {}; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext - .getPageRanges({ + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.appendBlobContext.appendBlockFromUrl(sourceURL, 0, { abortSignal: options.abortSignal, + sourceRange: rangeToString({ offset: sourceOffset, count: count }), + sourceContentMD5: options.sourceContentMD5, + sourceContentCrc64: options.sourceContentCrc64, leaseAccessConditions: options.conditions, + appendPositionAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - range: rangeToString({ offset: offset, count: count }), + sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince + }, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, spanOptions: spanOptions - }) - .then(rangeResponseFromModel)]; + })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_38 = _c.sent(); + e_22 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_38.message + message: e_22.message }); - throw e_38; + throw e_22; case 4: span.end(); return [7 /*endfinally*/]; @@ -30832,48 +30924,161 @@ var PageBlobClient = /** @class */ (function (_super) { }); }); }; + return AppendBlobClient; +}(BlobClient)); +/** + * BlockBlobClient defines a set of operations applicable to block blobs. + * + * @export + * @class BlockBlobClient + * @extends {BlobClient} + */ +var BlockBlobClient = /** @class */ (function (_super) { + tslib.__extends(BlockBlobClient, _super); + function BlockBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { + var _this = this; + // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. + // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); + var pipeline; + var url; + options = options || {}; + if (credentialOrPipelineOrContainerName instanceof Pipeline) { + // (url: string, pipeline: Pipeline) + url = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } + else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || + credentialOrPipelineOrContainerName instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + url = urlOrConnectionString; + options = blobNameOrOptions; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } + else if (!credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName !== "string") { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + // The second parameter is undefined. Use anonymous credential. + url = urlOrConnectionString; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else if (credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName === "string" && + blobNameOrOptions && + typeof blobNameOrOptions === "string") { + // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) + var containerName = credentialOrPipelineOrContainerName; + var blobName = blobNameOrOptions; + var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + { + var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); + options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); + pipeline = newPipeline(sharedKeyCredential, options); + } + } + else if (extractedCreds.kind === "SASConnString") { + url = + appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + + "?" + + extractedCreds.accountSas; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } + else { + throw new Error("Expecting non-empty strings for containerName and blobName parameters"); + } + _this = _super.call(this, url, pipeline) || this; + _this.blockBlobContext = new BlockBlob(_this.storageClientContext); + _this._blobContext = new Blob$1(_this.storageClientContext); + return _this; + } + /** + * Creates a new BlockBlobClient object identical to the source but with the + * specified snapshot timestamp. + * Provide "" will remove the snapshot and return a URL to the base blob. + * + * @param {string} snapshot The snapshot timestamp. + * @returns {BlockBlobClient} A new BlockBlobClient object identical to the source but with the specified snapshot timestamp. + * @memberof BlockBlobClient + */ + BlockBlobClient.prototype.withSnapshot = function (snapshot) { + return new BlockBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); + }; /** - * Gets the collection of page ranges that differ between a specified snapshot and this page blob. - * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * ONLY AVAILABLE IN NODE.JS RUNTIME. * - * @param {number} offset Starting byte position of the page blob - * @param {number} count Number of bytes to get ranges diff. - * @param {string} prevSnapshot Timestamp of snapshot to retrieve the difference. - * @param {PageBlobGetPageRangesDiffOptions} [options] Options to the Page Blob Get Page Ranges Diff operation. - * @returns {Promise} Response data for the Page Blob Get Page Range Diff operation. - * @memberof PageBlobClient + * Quick query for a JSON or CSV formatted blob. + * + * Example usage (Node.js): + * + * ```js + * // Query and convert a blob to a string + * const queryBlockBlobResponse = await blockBlobClient.query("select * from BlobStorage"); + * const downloaded = (await streamToBuffer(queryBlockBlobResponse.readableStreamBody)).toString(); + * console.log("Query blob content:", downloaded); + * + * async function streamToBuffer(readableStream) { + * return new Promise((resolve, reject) => { + * const chunks = []; + * readableStream.on("data", (data) => { + * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); + * }); + * readableStream.on("end", () => { + * resolve(Buffer.concat(chunks)); + * }); + * readableStream.on("error", reject); + * }); + * } + * ``` + * + * @param {string} query + * @param {BlockBlobQueryOptions} [options={}] + * @returns {Promise} + * @memberof BlockBlobClient */ - PageBlobClient.prototype.getPageRangesDiff = function (offset, count, prevSnapshot, options) { + BlockBlobClient.prototype.query = function (query, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_39; + var _b, span, spanOptions, response, e_23; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: - options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-getPageRangesDiff", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + _b = createSpan("BlockBlobClient-query", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext - .getPageRangesDiff({ + return [4 /*yield*/, this._blobContext.query({ abortSignal: options.abortSignal, + queryRequest: { + expression: query, + inputSerialization: toQuerySerialization(options.inputTextConfiguration), + outputSerialization: toQuerySerialization(options.outputTextConfiguration) + }, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - prevsnapshot: prevSnapshot, - range: rangeToString({ offset: offset, count: count }), spanOptions: spanOptions - }) - .then(rangeResponseFromModel)]; - case 2: return [2 /*return*/, _c.sent()]; + })]; + case 2: + response = _c.sent(); + return [2 /*return*/, new BlobQueryResponse(response, { + abortSignal: options.abortSignal, + onProgress: options.onProgress, + onError: options.onError + })]; case 3: - e_39 = _c.sent(); + e_23 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_39.message + message: e_23.message }); - throw e_39; + throw e_23; case 4: span.end(); return [7 /*endfinally*/]; @@ -30883,47 +31088,68 @@ var PageBlobClient = /** @class */ (function (_super) { }); }; /** - * Gets the collection of page ranges that differ between a specified snapshot and this page blob for managed disks. - * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * Creates a new block blob, or updates the content of an existing block blob. + * Updating an existing block blob overwrites any existing metadata on the blob. + * Partial updates are not supported; the content of the existing blob is + * overwritten with the new content. To perform a partial update of a block blob's, + * use {@link stageBlock} and {@link commitBlockList}. * - * @param {number} offset Starting byte position of the page blob - * @param {number} count Number of bytes to get ranges diff. - * @param {string} prevSnapshotUrl URL of snapshot to retrieve the difference. - * @param {PageBlobGetPageRangesDiffOptions} [options] Options to the Page Blob Get Page Ranges Diff operation. - * @returns {Promise} Response data for the Page Blob Get Page Range Diff operation. - * @memberof PageBlobClient + * This is a non-parallel uploading method, please use {@link uploadFile}, + * {@link uploadStream} or {@link uploadBrowserData} for better performance + * with concurrency uploading. + * + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * + * @param {HttpRequestBody} body Blob, string, ArrayBuffer, ArrayBufferView or a function + * which returns a new Readable stream whose offset is from data source beginning. + * @param {number} contentLength Length of body in bytes. Use Buffer.byteLength() to calculate body length for a + * string including non non-Base64/Hex-encoded characters. + * @param {BlockBlobUploadOptions} [options] Options to the Block Blob Upload operation. + * @returns {Promise} Response data for the Block Blob Upload operation. + * @memberof BlockBlobClient + * + * Example usage: + * + * ```js + * const content = "Hello world!"; + * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); + * ``` */ - PageBlobClient.prototype.getPageRangesDiffForManagedDisks = function (offset, count, prevSnapshotUrl, options) { + BlockBlobClient.prototype.upload = function (body, contentLength, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_40; + var _b, span, spanOptions, e_24; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-GetPageRangesDiffForManagedDisks", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _b = createSpan("BlockBlobClient-upload", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext - .getPageRangesDiff({ + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blockBlobContext.upload(body, contentLength, { abortSignal: options.abortSignal, + blobHTTPHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, + metadata: options.metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - prevSnapshotUrl: prevSnapshotUrl, - range: rangeToString({ offset: offset, count: count }), + onUploadProgress: options.onProgress, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tier: toAccessTier(options.tier), + blobTagsString: toBlobTagsString(options.tags), spanOptions: spanOptions - }) - .then(rangeResponseFromModel)]; + })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_40 = _c.sent(); + e_24 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_40.message + message: e_24.message }); - throw e_40; + throw e_24; case 4: span.end(); return [7 /*endfinally*/]; @@ -30933,42 +31159,54 @@ var PageBlobClient = /** @class */ (function (_super) { }); }; /** - * Resizes the page blob to the specified size (which must be a multiple of 512). - * @see https://docs.microsoft.com/rest/api/storageservices/set-blob-properties + * Creates a new Block Blob where the contents of the blob are read from a given URL. + * This API is supported beginning with the 2020-04-08 version. Partial updates + * are not supported with Put Blob from URL; the content of an existing blob is overwritten with + * the content of the new blob. To perform partial updates to a block blob’s contents using a + * source URL, use {@link stageBlockFromURL} and {@link commitBlockList}. * - * @param {number} size Target size - * @param {PageBlobResizeOptions} [options] Options to the Page Blob Resize operation. - * @returns {Promise} Response data for the Page Blob Resize operation. - * @memberof PageBlobClient + * @param {string} sourceURL Specifies the URL of the blob. The value + * may be a URL of up to 2 KB in length that specifies a blob. + * The value should be URL-encoded as it would appear + * in a request URI. The source blob must either be public + * or must be authenticated via a shared access signature. + * If the source blob is public, no authentication is required + * to perform the operation. Here are some examples of source object URLs: + * - https://myaccount.blob.core.windows.net/mycontainer/myblob + * - https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= + * @param {BlockBlobSyncUploadFromURLOptions} [options={}] Optional parameters. + * @returns Promise + * @memberof BlockBlobClient */ - PageBlobClient.prototype.resize = function (size, options) { - var _a; + BlockBlobClient.prototype.syncUploadFromURL = function (sourceURL, options) { + var _a, _b, _c, _d, _e; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_41; - return tslib.__generator(this, function (_c) { - switch (_c.label) { + var _f, span, spanOptions, e_25; + return tslib.__generator(this, function (_g) { + switch (_g.label) { case 0: options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-resize", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - _c.label = 1; + _f = createSpan("BlockBlobClient-syncUploadFromURL", options.tracingOptions), span = _f.span, spanOptions = _f.spanOptions; + _g.label = 1; case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext.resize(size, { - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - encryptionScope: options.encryptionScope, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _c.sent()]; + _g.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blockBlobContext.putBlobFromUrl(0, sourceURL, tslib.__assign(tslib.__assign({}, options), { leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: options.conditions.tagConditions }), sourceModifiedAccessConditions: { + sourceIfMatch: (_a = options.sourceConditions) === null || _a === void 0 ? void 0 : _a.ifMatch, + sourceIfModifiedSince: (_b = options.sourceConditions) === null || _b === void 0 ? void 0 : _b.ifModifiedSince, + sourceIfNoneMatch: (_c = options.sourceConditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch, + sourceIfUnmodifiedSince: (_d = options.sourceConditions) === null || _d === void 0 ? void 0 : _d.ifUnmodifiedSince, + sourceIfTags: (_e = options.sourceConditions) === null || _e === void 0 ? void 0 : _e.tagConditions + }, cpkInfo: options.customerProvidedKey, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), spanOptions: spanOptions }))]; + case 2: return [2 /*return*/, _g.sent()]; case 3: - e_41 = _c.sent(); + e_25 = _g.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_41.message + message: e_25.message }); - throw e_41; + throw e_25; case 4: span.end(); return [7 /*endfinally*/]; @@ -30978,43 +31216,47 @@ var PageBlobClient = /** @class */ (function (_super) { }); }; /** - * Sets a page blob's sequence number. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties + * Uploads the specified block to the block blob's "staging area" to be later + * committed by a call to commitBlockList. + * @see https://docs.microsoft.com/rest/api/storageservices/put-block * - * @param {SequenceNumberActionType} sequenceNumberAction Indicates how the service should modify the blob's sequence number. - * @param {number} [sequenceNumber] Required if sequenceNumberAction is max or update - * @param {PageBlobUpdateSequenceNumberOptions} [options] Options to the Page Blob Update Sequence Number operation. - * @returns {Promise} Response data for the Page Blob Update Sequence Number operation. - * @memberof PageBlobClient + * @param {string} blockId A 64-byte value that is base64-encoded + * @param {HttpRequestBody} body Data to upload to the staging area. + * @param {number} contentLength Number of bytes to upload. + * @param {BlockBlobStageBlockOptions} [options] Options to the Block Blob Stage Block operation. + * @returns {Promise} Response data for the Block Blob Stage Block operation. + * @memberof BlockBlobClient */ - PageBlobClient.prototype.updateSequenceNumber = function (sequenceNumberAction, sequenceNumber, options) { - var _a; + BlockBlobClient.prototype.stageBlock = function (blockId, body, contentLength, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_42; - return tslib.__generator(this, function (_c) { - switch (_c.label) { + var _a, span, spanOptions, e_26; + return tslib.__generator(this, function (_b) { + switch (_b.label) { case 0: - options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-updateSequenceNumber", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - _c.label = 1; + _a = createSpan("BlockBlobClient-stageBlock", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext.updateSequenceNumber(sequenceNumberAction, { + _b.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blockBlobContext.stageBlock(blockId, contentLength, body, { abortSignal: options.abortSignal, - blobSequenceNumber: sequenceNumber, leaseAccessConditions: options.conditions, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + onUploadProgress: options.onProgress, + transactionalContentMD5: options.transactionalContentMD5, + transactionalContentCrc64: options.transactionalContentCrc64, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, spanOptions: spanOptions })]; - case 2: return [2 /*return*/, _c.sent()]; + case 2: return [2 /*return*/, _b.sent()]; case 3: - e_42 = _c.sent(); + e_26 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_42.message + message: e_26.message }); - throw e_42; + throw e_26; case 4: span.end(); return [7 /*endfinally*/]; @@ -31024,156 +31266,113 @@ var PageBlobClient = /** @class */ (function (_super) { }); }; /** - * Begins an operation to start an incremental copy from one page blob's snapshot to this page blob. - * The snapshot is copied such that only the differential changes between the previously - * copied snapshot are transferred to the destination. - * The copied snapshots are complete copies of the original snapshot and can be read or copied from as usual. - * @see https://docs.microsoft.com/rest/api/storageservices/incremental-copy-blob - * @see https://docs.microsoft.com/en-us/azure/virtual-machines/windows/incremental-snapshots + * The Stage Block From URL operation creates a new block to be committed as part + * of a blob where the contents are read from a URL. + * This API is available starting in version 2018-03-28. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-from-url * - * @param {string} copySource Specifies the name of the source page blob snapshot. For example, - * https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= - * @param {PageBlobStartCopyIncrementalOptions} [options] Options to the Page Blob Copy Incremental operation. - * @returns {Promise} Response data for the Page Blob Copy Incremental operation. - * @memberof PageBlobClient + * @param {string} blockId A 64-byte value that is base64-encoded + * @param {string} sourceURL Specifies the URL of the blob. The value + * may be a URL of up to 2 KB in length that specifies a blob. + * The value should be URL-encoded as it would appear + * in a request URI. The source blob must either be public + * or must be authenticated via a shared access signature. + * If the source blob is public, no authentication is required + * to perform the operation. Here are some examples of source object URLs: + * - https://myaccount.blob.core.windows.net/mycontainer/myblob + * - https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= + * @param {number} [offset] From which position of the blob to download, >= 0 + * @param {number} [count] How much data to be downloaded, > 0. Will download to the end when undefined + * @param {BlockBlobStageBlockFromURLOptions} [options={}] Options to the Block Blob Stage Block From URL operation. + * @returns {Promise} Response data for the Block Blob Stage Block From URL operation. + * @memberof BlockBlobClient */ - PageBlobClient.prototype.startCopyIncremental = function (copySource, options) { - var _a; + BlockBlobClient.prototype.stageBlockFromURL = function (blockId, sourceURL, offset, count, options) { + if (offset === void 0) { offset = 0; } if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_43; - return tslib.__generator(this, function (_c) { - switch (_c.label) { + var _a, span, spanOptions, e_27; + return tslib.__generator(this, function (_b) { + switch (_b.label) { case 0: - _b = createSpan("PageBlobClient-startCopyIncremental", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - _c.label = 1; + _a = createSpan("BlockBlobClient-stageBlockFromURL", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext.copyIncremental(copySource, { + _b.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blockBlobContext.stageBlockFromURL(blockId, 0, sourceURL, { abortSignal: options.abortSignal, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + leaseAccessConditions: options.conditions, + sourceContentMD5: options.sourceContentMD5, + sourceContentCrc64: options.sourceContentCrc64, + sourceRange: offset === 0 && !count ? undefined : rangeToString({ offset: offset, count: count }), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, spanOptions: spanOptions })]; - case 2: return [2 /*return*/, _c.sent()]; + case 2: return [2 /*return*/, _b.sent()]; case 3: - e_43 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_43.message - }); - throw e_43; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - return PageBlobClient; -}(BlobClient)); -/** - * A client that manages leases for a {@link ContainerClient} or a {@link BlobClient}. - * - * @export - * @class BlobLeaseClient - */ -var BlobLeaseClient = /** @class */ (function () { - /** - * Creates an instance of BlobLeaseClient. - * @param {(ContainerClient | BlobClient)} client The client to make the lease operation requests. - * @param {string} leaseId Initial proposed lease id. - * @memberof BlobLeaseClient - */ - function BlobLeaseClient(client, leaseId) { - var clientContext = new StorageClientContext(client.url, client.pipeline.toServiceClientOptions()); - this._url = client.url; - if (client instanceof ContainerClient) { - this._isContainer = true; - this._containerOrBlobOperation = new Container(clientContext); - } - else { - this._isContainer = false; - this._containerOrBlobOperation = new Blob$1(clientContext); - } - if (!leaseId) { - leaseId = coreHttp.generateUuid(); - } - this._leaseId = leaseId; - } - Object.defineProperty(BlobLeaseClient.prototype, "leaseId", { - /** - * Gets the lease Id. - * - * @readonly - * @memberof BlobLeaseClient - * @type {string} - */ - get: function () { - return this._leaseId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobLeaseClient.prototype, "url", { - /** - * Gets the url. - * - * @readonly - * @memberof BlobLeaseClient - * @type {string} - */ - get: function () { - return this._url; - }, - enumerable: false, - configurable: true - }); + e_27 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_27.message + }); + throw e_27; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; /** - * Establishes and manages a lock on a container for delete operations, or on a blob - * for write and delete operations. - * The lock duration can be 15 to 60 seconds, or can be infinite. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container - * and - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob + * Writes a blob by specifying the list of block IDs that make up the blob. + * In order to be written as part of a blob, a block must have been successfully written + * to the server in a prior {@link stageBlock} operation. You can call {@link commitBlockList} to + * update a blob by uploading only those blocks that have changed, then committing the new and existing + * blocks together. Any blocks not specified in the block list and permanently deleted. + * @see https://docs.microsoft.com/rest/api/storageservices/put-block-list * - * @param {number} duration Must be between 15 to 60 seconds, or infinite (-1) - * @param {LeaseOperationOptions} [options={}] option to configure lease management operations. - * @returns {Promise} Response data for acquire lease operation. - * @memberof BlobLeaseClient + * @param {string[]} blocks Array of 64-byte value that is base64-encoded + * @param {BlockBlobCommitBlockListOptions} [options] Options to the Block Blob Commit Block List operation. + * @returns {Promise} Response data for the Block Blob Commit Block List operation. + * @memberof BlockBlobClient */ - BlobLeaseClient.prototype.acquireLease = function (duration, options) { - var _a, _b, _c, _d, _e, _f; + BlockBlobClient.prototype.commitBlockList = function (blocks, options) { + var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _g, span, spanOptions, e_44; - return tslib.__generator(this, function (_h) { - switch (_h.label) { + var _b, span, spanOptions, e_28; + return tslib.__generator(this, function (_c) { + switch (_c.label) { case 0: - _g = createSpan("BlobLeaseClient-acquireLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; - if (this._isContainer && - ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || - (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); - } - _h.label = 1; + options.conditions = options.conditions || {}; + _b = createSpan("BlockBlobClient-commitBlockList", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; case 1: - _h.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this._containerOrBlobOperation.acquireLease({ + _c.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blockBlobContext.commitBlockList({ latest: blocks }, { abortSignal: options.abortSignal, - duration: duration, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), - proposedLeaseId: this._leaseId, + blobHTTPHeaders: options.blobHTTPHeaders, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tier: toAccessTier(options.tier), + blobTagsString: toBlobTagsString(options.tags), spanOptions: spanOptions })]; - case 2: return [2 /*return*/, _h.sent()]; + case 2: return [2 /*return*/, _c.sent()]; case 3: - e_44 = _h.sent(); + e_28 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_44.message + message: e_28.message }); - throw e_44; + throw e_28; case 4: span.end(); return [7 /*endfinally*/]; @@ -31183,49 +31382,50 @@ var BlobLeaseClient = /** @class */ (function () { }); }; /** - * To change the ID of the lease. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container - * and - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob + * Returns the list of blocks that have been uploaded as part of a block blob + * using the specified block list filter. + * @see https://docs.microsoft.com/rest/api/storageservices/get-block-list * - * @param {string} proposedLeaseId the proposed new lease Id. - * @param {LeaseOperationOptions} [options={}] option to configure lease management operations. - * @returns {Promise} Response data for change lease operation. - * @memberof BlobLeaseClient + * @param {BlockListType} listType Specifies whether to return the list of committed blocks, + * the list of uncommitted blocks, or both lists together. + * @param {BlockBlobGetBlockListOptions} [options] Options to the Block Blob Get Block List operation. + * @returns {Promise} Response data for the Block Blob Get Block List operation. + * @memberof BlockBlobClient */ - BlobLeaseClient.prototype.changeLease = function (proposedLeaseId, options) { - var _a, _b, _c, _d, _e, _f; + BlockBlobClient.prototype.getBlockList = function (listType, options) { + var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _g, span, spanOptions, response, e_45; - return tslib.__generator(this, function (_h) { - switch (_h.label) { + var _b, span, spanOptions, res, e_29; + return tslib.__generator(this, function (_c) { + switch (_c.label) { case 0: - _g = createSpan("BlobLeaseClient-changeLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; - if (this._isContainer && - ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || - (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); - } - _h.label = 1; + _b = createSpan("BlockBlobClient-getBlockList", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; case 1: - _h.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this._containerOrBlobOperation.changeLease(this._leaseId, proposedLeaseId, { + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.blockBlobContext.getBlockList(listType, { abortSignal: options.abortSignal, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), spanOptions: spanOptions })]; case 2: - response = _h.sent(); - this._leaseId = proposedLeaseId; - return [2 /*return*/, response]; + res = _c.sent(); + if (!res.committedBlocks) { + res.committedBlocks = []; + } + if (!res.uncommittedBlocks) { + res.uncommittedBlocks = []; + } + return [2 /*return*/, res]; case 3: - e_45 = _h.sent(); + e_29 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_45.message + message: e_29.message }); - throw e_45; + throw e_29; case 4: span.end(); return [7 /*endfinally*/]; @@ -31234,47 +31434,95 @@ var BlobLeaseClient = /** @class */ (function () { }); }); }; + // High level functions /** - * To free the lease if it is no longer needed so that another client may - * immediately acquire a lease against the container or the blob. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container - * and - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob + * Uploads a Buffer(Node.js)/Blob(browsers)/ArrayBuffer/ArrayBufferView object to a BlockBlob. * - * @param {LeaseOperationOptions} [options={}] option to configure lease management operations. - * @returns {Promise} Response data for release lease operation. - * @memberof BlobLeaseClient + * When data length is no more than the specifiled {@link BlockBlobParallelUploadOptions.maxSingleShotSize} (default is + * {@link BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}), this method will use 1 {@link upload} call to finish the upload. + * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} + * to commit the block list. + * + * @export + * @param {Buffer | Blob | ArrayBuffer | ArrayBufferView} data Buffer(Node.js), Blob, ArrayBuffer or ArrayBufferView + * @param {BlockBlobParallelUploadOptions} [options] + * @returns {Promise} + * @memberof BlockBlobClient */ - BlobLeaseClient.prototype.releaseLease = function (options) { - var _a, _b, _c, _d, _e, _f; + BlockBlobClient.prototype.uploadData = function (data, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _g, span, spanOptions, e_46; - return tslib.__generator(this, function (_h) { - switch (_h.label) { - case 0: - _g = createSpan("BlobLeaseClient-releaseLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; - if (this._isContainer && - ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || - (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + var _a, span, spanOptions, buffer_1, browserBlob_1; + return tslib.__generator(this, function (_b) { + _a = createSpan("BlockBlobClient-uploadData", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + try { + if (true) { + if (data instanceof Buffer) { + buffer_1 = data; } - _h.label = 1; + else if (data instanceof ArrayBuffer) { + buffer_1 = Buffer.from(data); + } + else { + data = data; + buffer_1 = Buffer.from(data.buffer, data.byteOffset, data.byteLength); + } + return [2 /*return*/, this.uploadSeekableInternal(function (offset, size) { return buffer_1.slice(offset, offset + size); }, buffer_1.byteLength, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + } + else {} + } + catch (e) { + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e.message + }); + throw e; + } + finally { + span.end(); + } + return [2 /*return*/]; + }); + }); + }; + /** + * ONLY AVAILABLE IN BROWSERS. + * + * Uploads a browser Blob/File/ArrayBuffer/ArrayBufferView object to block blob. + * + * When buffer length <= 256MB, this method will use 1 upload call to finish the upload. + * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call + * {@link commitBlockList} to commit the block list. + * + * @deprecated Use {@link uploadData} instead. + * + * @export + * @param {Blob | ArrayBuffer | ArrayBufferView} browserData Blob, File, ArrayBuffer or ArrayBufferView + * @param {BlockBlobParallelUploadOptions} [options] Options to upload browser data. + * @returns {Promise} Response data for the Blob Upload operation. + * @memberof BlockBlobClient + */ + BlockBlobClient.prototype.uploadBrowserData = function (browserData, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, browserBlob_2, e_30; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlockBlobClient-uploadBrowserData", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; case 1: - _h.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this._containerOrBlobOperation.releaseLease(this._leaseId, { - abortSignal: options.abortSignal, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _h.sent()]; + _b.trys.push([1, 3, 4, 5]); + browserBlob_2 = new Blob([browserData]); + return [4 /*yield*/, this.uploadSeekableInternal(function (offset, size) { return browserBlob_2.slice(offset, offset + size); }, browserBlob_2.size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: return [2 /*return*/, _b.sent()]; case 3: - e_46 = _h.sent(); + e_30 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_46.message + message: e_30.message }); - throw e_46; + throw e_30; case 4: span.end(); return [7 /*endfinally*/]; @@ -31284,118 +31532,288 @@ var BlobLeaseClient = /** @class */ (function () { }); }; /** - * To renew the lease. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container - * and - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * - * @param {LeaseOperationOptions} [options={}] Optional option to configure lease management operations. - * @returns {Promise} Response data for renew lease operation. - * @memberof BlobLeaseClient + * Uploads data to block blob. Requires a bodyFactory as the data source, + * which need to return a {@link HttpRequestBody} object with the offset and size provided. + * + * When data length is no more than the specifiled {@link BlockBlobParallelUploadOptions.maxSingleShotSize} (default is + * {@link BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}), this method will use 1 {@link upload} call to finish the upload. + * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} + * to commit the block list. + * + * @param {(offset: number, size: number) => HttpRequestBody} bodyFactory + * @param {number} size size of the data to upload. + * @param {BlockBlobParallelUploadOptions} [options] Options to Upload to Block Blob operation. + * @returns {Promise} Response data for the Blob Upload operation. + * @memberof BlockBlobClient */ - BlobLeaseClient.prototype.renewLease = function (options) { - var _a, _b, _c, _d, _e, _f; + BlockBlobClient.prototype.uploadSeekableInternal = function (bodyFactory, size, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _g, span, spanOptions, e_47; - return tslib.__generator(this, function (_h) { - switch (_h.label) { + var _a, span, spanOptions, numBlocks_1, blockList_1, blockIDPrefix_1, transferProgress_2, batch, _loop_2, i, e_31; + var _this = this; + return tslib.__generator(this, function (_b) { + switch (_b.label) { case 0: - _g = createSpan("BlobLeaseClient-renewLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; - if (this._isContainer && - ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || - (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + if (!options.blockSize) { + options.blockSize = 0; } - _h.label = 1; + if (options.blockSize < 0 || options.blockSize > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES) { + throw new RangeError("blockSize option must be >= 0 and <= " + BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES); + } + if (options.maxSingleShotSize !== 0 && !options.maxSingleShotSize) { + options.maxSingleShotSize = BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES; + } + if (options.maxSingleShotSize < 0 || + options.maxSingleShotSize > BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES) { + throw new RangeError("maxSingleShotSize option must be >= 0 and <= " + BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES); + } + if (options.blockSize === 0) { + if (size > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES * BLOCK_BLOB_MAX_BLOCKS) { + throw new RangeError(size + " is too larger to upload to a block blob."); + } + if (size > options.maxSingleShotSize) { + options.blockSize = Math.ceil(size / BLOCK_BLOB_MAX_BLOCKS); + if (options.blockSize < DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES) { + options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; + } + } + } + if (!options.blobHTTPHeaders) { + options.blobHTTPHeaders = {}; + } + if (!options.conditions) { + options.conditions = {}; + } + _a = createSpan("BlockBlobClient-uploadSeekableInternal", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; case 1: - _h.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this._containerOrBlobOperation.renewLease(this._leaseId, { - abortSignal: options.abortSignal, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _h.sent()]; + _b.trys.push([1, 5, 6, 7]); + if (!(size <= options.maxSingleShotSize)) return [3 /*break*/, 3]; + return [4 /*yield*/, this.upload(bodyFactory(0, size), size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: return [2 /*return*/, _b.sent()]; case 3: - e_47 = _h.sent(); + numBlocks_1 = Math.floor((size - 1) / options.blockSize) + 1; + if (numBlocks_1 > BLOCK_BLOB_MAX_BLOCKS) { + throw new RangeError("The buffer's size is too big or the BlockSize is too small;" + + ("the number of blocks must be <= " + BLOCK_BLOB_MAX_BLOCKS)); + } + blockList_1 = []; + blockIDPrefix_1 = coreHttp.generateUuid(); + transferProgress_2 = 0; + batch = new Batch(options.concurrency); + _loop_2 = function (i) { + batch.addOperation(function () { return tslib.__awaiter(_this, void 0, void 0, function () { + var blockID, start, end, contentLength; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + blockID = generateBlockID(blockIDPrefix_1, i); + start = options.blockSize * i; + end = i === numBlocks_1 - 1 ? size : start + options.blockSize; + contentLength = end - start; + blockList_1.push(blockID); + return [4 /*yield*/, this.stageBlock(blockID, bodyFactory(start, contentLength), contentLength, { + abortSignal: options.abortSignal, + conditions: options.conditions, + encryptionScope: options.encryptionScope, + tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) + })]; + case 1: + _a.sent(); + // Update progress after block is successfully uploaded to server, in case of block trying + // TODO: Hook with convenience layer progress event in finer level + transferProgress_2 += contentLength; + if (options.onProgress) { + options.onProgress({ + loadedBytes: transferProgress_2 + }); + } + return [2 /*return*/]; + } + }); + }); }); + }; + for (i = 0; i < numBlocks_1; i++) { + _loop_2(i); + } + return [4 /*yield*/, batch.do()]; + case 4: + _b.sent(); + return [2 /*return*/, this.commitBlockList(blockList_1, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 5: + e_31 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_47.message + message: e_31.message }); - throw e_47; + throw e_31; + case 6: + span.end(); + return [7 /*endfinally*/]; + case 7: return [2 /*return*/]; + } + }); + }); + }; + /** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * Uploads a local file in blocks to a block blob. + * + * When file size <= 256MB, this method will use 1 upload call to finish the upload. + * Otherwise, this method will call stageBlock to upload blocks, and finally call commitBlockList + * to commit the block list. + * + * @param {string} filePath Full path of local file + * @param {BlockBlobParallelUploadOptions} [options] Options to Upload to Block Blob operation. + * @returns {(Promise)} Response data for the Blob Upload operation. + * @memberof BlockBlobClient + */ + BlockBlobClient.prototype.uploadFile = function (filePath, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, size, e_32; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlockBlobClient-uploadFile", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 4, 5, 6]); + return [4 /*yield*/, fsStat(filePath)]; + case 2: + size = (_b.sent()).size; + return [4 /*yield*/, this.uploadSeekableInternal(function (offset, count) { + return function () { + return fsCreateReadStream(filePath, { + autoClose: true, + end: count ? offset + count - 1 : Infinity, + start: offset + }); + }; + }, size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 3: return [2 /*return*/, _b.sent()]; case 4: + e_32 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_32.message + }); + throw e_32; + case 5: span.end(); return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + case 6: return [2 /*return*/]; } }); }); }; /** - * To end the lease but ensure that another client cannot acquire a new lease - * until the current lease period has expired. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container - * and - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob + * ONLY AVAILABLE IN NODE.JS RUNTIME. * - * @static - * @param {number} breakPeriod Break period - * @param {LeaseOperationOptions} [options={}] Optional options to configure lease management operations. - * @returns {Promise} Response data for break lease operation. - * @memberof BlobLeaseClient + * Uploads a Node.js Readable stream into block blob. + * + * PERFORMANCE IMPROVEMENT TIPS: + * * Input stream highWaterMark is better to set a same value with bufferSize + * parameter, which will avoid Buffer.concat() operations. + * + * @param {Readable} stream Node.js Readable stream + * @param {number} bufferSize Size of every buffer allocated, also the block size in the uploaded block blob. Default value is 8MB + * @param {number} maxConcurrency Max concurrency indicates the max number of buffers that can be allocated, + * positive correlation with max uploading concurrency. Default value is 5 + * @param {BlockBlobUploadStreamOptions} [options] Options to Upload Stream to Block Blob operation. + * @returns {Promise} Response data for the Blob Upload operation. + * @memberof BlockBlobClient */ - BlobLeaseClient.prototype.breakLease = function (breakPeriod, options) { - var _a, _b, _c, _d, _e, _f; + BlockBlobClient.prototype.uploadStream = function (stream, bufferSize, maxConcurrency, options) { + if (bufferSize === void 0) { bufferSize = DEFAULT_BLOCK_BUFFER_SIZE_BYTES; } + if (maxConcurrency === void 0) { maxConcurrency = 5; } if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _g, span, spanOptions, operationOptions, e_48; - return tslib.__generator(this, function (_h) { - switch (_h.label) { + var _a, span, spanOptions, blockNum_1, blockIDPrefix_2, transferProgress_3, blockList_2, scheduler, e_33; + var _this = this; + return tslib.__generator(this, function (_b) { + switch (_b.label) { case 0: - _g = createSpan("BlobLeaseClient-breakLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; - if (this._isContainer && - ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || - (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + if (!options.blobHTTPHeaders) { + options.blobHTTPHeaders = {}; } - _h.label = 1; + if (!options.conditions) { + options.conditions = {}; + } + _a = createSpan("BlockBlobClient-uploadStream", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; case 1: - _h.trys.push([1, 3, 4, 5]); - operationOptions = { - abortSignal: options.abortSignal, - breakPeriod: breakPeriod, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), - spanOptions: spanOptions - }; - return [4 /*yield*/, this._containerOrBlobOperation.breakLease(operationOptions)]; - case 2: return [2 /*return*/, _h.sent()]; - case 3: - e_48 = _h.sent(); + _b.trys.push([1, 4, 5, 6]); + blockNum_1 = 0; + blockIDPrefix_2 = coreHttp.generateUuid(); + transferProgress_3 = 0; + blockList_2 = []; + scheduler = new BufferScheduler(stream, bufferSize, maxConcurrency, function (body, length) { return tslib.__awaiter(_this, void 0, void 0, function () { + var blockID; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + blockID = generateBlockID(blockIDPrefix_2, blockNum_1); + blockList_2.push(blockID); + blockNum_1++; + return [4 /*yield*/, this.stageBlock(blockID, body, length, { + conditions: options.conditions, + encryptionScope: options.encryptionScope, + tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) + })]; + case 1: + _a.sent(); + // Update progress after block is successfully uploaded to server, in case of block trying + transferProgress_3 += length; + if (options.onProgress) { + options.onProgress({ loadedBytes: transferProgress_3 }); + } + return [2 /*return*/]; + } + }); + }); }, + // concurrency should set a smaller value than maxConcurrency, which is helpful to + // reduce the possibility when a outgoing handler waits for stream data, in + // this situation, outgoing handlers are blocked. + // Outgoing queue shouldn't be empty. + Math.ceil((maxConcurrency / 4) * 3)); + return [4 /*yield*/, scheduler.do()]; + case 2: + _b.sent(); + return [4 /*yield*/, this.commitBlockList(blockList_2, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 3: return [2 /*return*/, _b.sent()]; + case 4: + e_33 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_48.message + message: e_33.message }); - throw e_48; - case 4: + throw e_33; + case 5: span.end(); return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + case 6: return [2 /*return*/]; } }); }); }; - return BlobLeaseClient; -}()); + return BlockBlobClient; +}(BlobClient)); /** - * A ContainerClient represents a URL to the Azure Storage container allowing you to manipulate its blobs. + * PageBlobClient defines a set of operations applicable to page blobs. * * @export - * @class ContainerClient + * @class PageBlobClient + * @extends {BlobClient} */ -var ContainerClient = /** @class */ (function (_super) { - tslib.__extends(ContainerClient, _super); - function ContainerClient(urlOrConnectionString, credentialOrPipelineOrContainerName, options) { +var PageBlobClient = /** @class */ (function (_super) { + tslib.__extends(PageBlobClient, _super); + function PageBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { var _this = this; + // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. + // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); var pipeline; var url; options = options || {}; @@ -31409,6 +31827,7 @@ var ContainerClient = /** @class */ (function (_super) { coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) url = urlOrConnectionString; + options = blobNameOrOptions; pipeline = newPipeline(credentialOrPipelineOrContainerName, options); } else if (!credentialOrPipelineOrContainerName && @@ -31419,21 +31838,24 @@ var ContainerClient = /** @class */ (function (_super) { pipeline = newPipeline(new AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && - typeof credentialOrPipelineOrContainerName === "string") { + typeof credentialOrPipelineOrContainerName === "string" && + blobNameOrOptions && + typeof blobNameOrOptions === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) var containerName = credentialOrPipelineOrContainerName; + var blobName = blobNameOrOptions; var extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { { var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - url = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)); + url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); pipeline = newPipeline(sharedKeyCredential, options); } } else if (extractedCreds.kind === "SASConnString") { url = - appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)) + + appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + "?" + extractedCreds.accountSas; pipeline = newPipeline(new AnonymousCredential(), options); @@ -31443,63 +31865,69 @@ var ContainerClient = /** @class */ (function (_super) { } } else { - throw new Error("Expecting non-empty strings for containerName parameter"); + throw new Error("Expecting non-empty strings for containerName and blobName parameters"); } _this = _super.call(this, url, pipeline) || this; - _this._containerName = _this.getContainerNameFromUrl(); - _this.containerContext = new Container(_this.storageClientContext); + _this.pageBlobContext = new PageBlob(_this.storageClientContext); return _this; } - Object.defineProperty(ContainerClient.prototype, "containerName", { - /** - * The name of the container. - */ - get: function () { - return this._containerName; - }, - enumerable: false, - configurable: true - }); /** - * Creates a new container under the specified account. If the container with - * the same name already exists, the operation fails. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container - * - * @param {ContainerCreateOptions} [options] Options to Container Create operation. - * @returns {Promise} - * @memberof ContainerClient + * Creates a new PageBlobClient object identical to the source but with the + * specified snapshot timestamp. + * Provide "" will remove the snapshot and return a Client to the base blob. * - * Example usage: + * @param {string} snapshot The snapshot timestamp. + * @returns {PageBlobClient} A new PageBlobClient object identical to the source but with the specified snapshot timestamp. + * @memberof PageBlobClient + */ + PageBlobClient.prototype.withSnapshot = function (snapshot) { + return new PageBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); + }; + /** + * Creates a page blob of the specified length. Call uploadPages to upload data + * data to a page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * - * ```js - * const containerClient = blobServiceClient.getContainerClient(""); - * const createContainerResponse = await containerClient.create(); - * console.log("Container was created successfully", createContainerResponse.requestId); - * ``` + * @param {number} size size of the page blob. + * @param {PageBlobCreateOptions} [options] Options to the Page Blob Create operation. + * @returns {Promise} Response data for the Page Blob Create operation. + * @memberof PageBlobClient */ - ContainerClient.prototype.create = function (options) { + PageBlobClient.prototype.create = function (size, options) { + var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_49; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var _b, span, spanOptions, e_34; + return tslib.__generator(this, function (_c) { + switch (_c.label) { case 0: - _a = createSpan("ContainerClient-create", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-create", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.create(tslib.__assign(tslib.__assign({}, options), { spanOptions: spanOptions }))]; - case 2: - // Spread operator in destructuring assignments, - // this will filter out unwanted properties from the response object into result object - return [2 /*return*/, _b.sent()]; + _c.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.pageBlobContext.create(0, size, { + abortSignal: options.abortSignal, + blobHTTPHeaders: options.blobHTTPHeaders, + blobSequenceNumber: options.blobSequenceNumber, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tier: toAccessTier(options.tier), + blobTagsString: toBlobTagsString(options.tags), + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; case 3: - e_49 = _b.sent(); + e_34 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_49.message + message: e_34.message }); - throw e_49; + throw e_34; case 4: span.end(); return [7 /*endfinally*/]; @@ -31509,45 +31937,48 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * Creates a new container under the specified account. If the container with - * the same name already exists, it is not changed. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container + * Creates a page blob of the specified length. Call uploadPages to upload data + * data to a page blob. If the blob with the same name already exists, the content + * of the existing blob will remain unchanged. + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * - * @param {ContainerCreateOptions} [options] - * @returns {Promise} - * @memberof ContainerClient + * @param {number} size size of the page blob. + * @param {PageBlobCreateIfNotExistsOptions} [options] + * @returns {Promise} + * @memberof PageBlobClient */ - ContainerClient.prototype.createIfNotExists = function (options) { + PageBlobClient.prototype.createIfNotExists = function (size, options) { var _a, _b; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _c, span, spanOptions, res, e_50; + var _c, span, spanOptions, conditions, res, e_35; return tslib.__generator(this, function (_d) { switch (_d.label) { case 0: - _c = createSpan("ContainerClient-createIfNotExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; + _c = createSpan("PageBlobClient-createIfNotExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; _d.label = 1; case 1: _d.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.create(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + conditions = { ifNoneMatch: ETagAny }; + return [4 /*yield*/, this.create(size, tslib.__assign(tslib.__assign({}, options), { conditions: conditions, tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: res = _d.sent(); return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable })]; case 3: - e_50 = _d.sent(); - if (((_a = e_50.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerAlreadyExists") { + e_35 = _d.sent(); + if (((_a = e_35.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { span.setStatus({ code: api.CanonicalCode.ALREADY_EXISTS, - message: "Expected exception when creating a container only if it does not already exist." + message: "Expected exception when creating a blob only if it does not already exist." }); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_50.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_50.response })]; + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_35.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_35.response })]; } span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_50.message + message: e_35.message }); - throw e_50; + throw e_35; case 4: span.end(); return [7 /*endfinally*/]; @@ -31557,48 +31988,51 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * Returns true if the Azure container resource represented by this client exists; false otherwise. - * - * NOTE: use this function with care since an existing container might be deleted by other clients or - * applications. Vice versa new containers with the same name might be added by other clients or - * applications after this function completes. + * Writes 1 or more pages to the page blob. The start and end offsets must be a multiple of 512. + * @see https://docs.microsoft.com/rest/api/storageservices/put-page * - * @param {ContainerExistsOptions} [options={}] - * @returns {Promise} - * @memberof ContainerClient + * @param {HttpRequestBody} body Data to upload + * @param {number} offset Offset of destination page blob + * @param {number} count Content length of the body, also number of bytes to be uploaded + * @param {PageBlobUploadPagesOptions} [options] Options to the Page Blob Upload Pages operation. + * @returns {Promise} Response data for the Page Blob Upload Pages operation. + * @memberof PageBlobClient */ - ContainerClient.prototype.exists = function (options) { + PageBlobClient.prototype.uploadPages = function (body, offset, count, options) { + var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_51; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var _b, span, spanOptions, e_36; + return tslib.__generator(this, function (_c) { + switch (_c.label) { case 0: - _a = createSpan("ContainerClient-exists", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-uploadPages", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.getProperties({ + _c.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.pageBlobContext.uploadPages(body, count, { abortSignal: options.abortSignal, - tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + onUploadProgress: options.onProgress, + range: rangeToString({ offset: offset, count: count }), + sequenceNumberAccessConditions: options.conditions, + transactionalContentMD5: options.transactionalContentMD5, + transactionalContentCrc64: options.transactionalContentCrc64, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + spanOptions: spanOptions })]; - case 2: - _b.sent(); - return [2 /*return*/, true]; + case 2: return [2 /*return*/, _c.sent()]; case 3: - e_51 = _b.sent(); - if (e_51.statusCode === 404) { - span.setStatus({ - code: api.CanonicalCode.NOT_FOUND, - message: "Expected exception when checking container existence" - }); - return [2 /*return*/, false]; - } + e_36 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_51.message + message: e_36.message }); - throw e_51; + throw e_36; case 4: span.end(); return [7 /*endfinally*/]; @@ -31608,91 +32042,302 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * Creates a {@link BlobClient} + * The Upload Pages operation writes a range of pages to a page blob where the + * contents are read from a URL. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-page-from-url * - * @param {string} blobName A blob name - * @returns {BlobClient} A new BlobClient object for the given blob name. - * @memberof ContainerClient + * @param {string} sourceURL Specify a URL to the copy source, Shared Access Signature(SAS) maybe needed for authentication + * @param {number} sourceOffset The source offset to copy from. Pass 0 to copy from the beginning of source page blob + * @param {number} destOffset Offset of destination page blob + * @param {number} count Number of bytes to be uploaded from source page blob + * @param {PageBlobUploadPagesFromURLOptions} [options={}] + * @returns {Promise} + * @memberof PageBlobClient */ - ContainerClient.prototype.getBlobClient = function (blobName) { - return new BlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); + PageBlobClient.prototype.uploadPagesFromURL = function (sourceURL, sourceOffset, destOffset, count, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_37; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + _b = createSpan("PageBlobClient-uploadPagesFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.pageBlobContext.uploadPagesFromURL(sourceURL, rangeToString({ offset: sourceOffset, count: count }), 0, rangeToString({ offset: destOffset, count: count }), { + abortSignal: options.abortSignal, + sourceContentMD5: options.sourceContentMD5, + sourceContentCrc64: options.sourceContentCrc64, + leaseAccessConditions: options.conditions, + sequenceNumberAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince + }, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_37 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_37.message + }); + throw e_37; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; /** - * Creates an {@link AppendBlobClient} + * Frees the specified pages from the page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/put-page * - * @param {string} blobName An append blob name - * @returns {AppendBlobClient} - * @memberof ContainerClient + * @param {number} [offset] Starting byte position of the pages to clear. + * @param {number} [count] Number of bytes to clear. + * @param {PageBlobClearPagesOptions} [options] Options to the Page Blob Clear Pages operation. + * @returns {Promise} Response data for the Page Blob Clear Pages operation. + * @memberof PageBlobClient */ - ContainerClient.prototype.getAppendBlobClient = function (blobName) { - return new AppendBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); + PageBlobClient.prototype.clearPages = function (offset, count, options) { + var _a; + if (offset === void 0) { offset = 0; } + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_38; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-clearPages", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext.clearPages(0, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + range: rangeToString({ offset: offset, count: count }), + sequenceNumberAccessConditions: options.conditions, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_38 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_38.message + }); + throw e_38; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; /** - * Creates a {@link BlockBlobClient} - * - * @param {string} blobName A block blob name - * @returns {BlockBlobClient} - * @memberof ContainerClient - * - * Example usage: - * - * ```js - * const content = "Hello world!"; + * Returns the list of valid page ranges for a page blob or snapshot of a page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges * - * const blockBlobClient = containerClient.getBlockBlobClient(""); - * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); - * ``` + * @param {number} [offset] Starting byte position of the page ranges. + * @param {number} [count] Number of bytes to get. + * @param {PageBlobGetPageRangesOptions} [options] Options to the Page Blob Get Ranges operation. + * @returns {Promise} Response data for the Page Blob Get Ranges operation. + * @memberof PageBlobClient */ - ContainerClient.prototype.getBlockBlobClient = function (blobName) { - return new BlockBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); + PageBlobClient.prototype.getPageRanges = function (offset, count, options) { + var _a; + if (offset === void 0) { offset = 0; } + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_39; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-getPageRanges", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext + .getPageRanges({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + range: rangeToString({ offset: offset, count: count }), + spanOptions: spanOptions + }) + .then(rangeResponseFromModel)]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_39 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_39.message + }); + throw e_39; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; /** - * Creates a {@link PageBlobClient} + * Gets the collection of page ranges that differ between a specified snapshot and this page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges * - * @param {string} blobName A page blob name - * @returns {PageBlobClient} - * @memberof ContainerClient + * @param {number} offset Starting byte position of the page blob + * @param {number} count Number of bytes to get ranges diff. + * @param {string} prevSnapshot Timestamp of snapshot to retrieve the difference. + * @param {PageBlobGetPageRangesDiffOptions} [options] Options to the Page Blob Get Page Ranges Diff operation. + * @returns {Promise} Response data for the Page Blob Get Page Range Diff operation. + * @memberof PageBlobClient */ - ContainerClient.prototype.getPageBlobClient = function (blobName) { - return new PageBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); + PageBlobClient.prototype.getPageRangesDiff = function (offset, count, prevSnapshot, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_40; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-getPageRangesDiff", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext + .getPageRangesDiff({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + prevsnapshot: prevSnapshot, + range: rangeToString({ offset: offset, count: count }), + spanOptions: spanOptions + }) + .then(rangeResponseFromModel)]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_40 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_40.message + }); + throw e_40; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; /** - * Returns all user-defined metadata and system properties for the specified - * container. The data returned does not include the container's list of blobs. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-properties - * - * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if - * they originally contained uppercase characters. This differs from the metadata keys returned by - * the `listContainers` method of {@link BlobServiceClient} using the `includeMetadata` option, which - * will retain their original casing. + * Gets the collection of page ranges that differ between a specified snapshot and this page blob for managed disks. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges * - * @param {ContainerGetPropertiesOptions} [options] Options to Container Get Properties operation. - * @returns {Promise} - * @memberof ContainerClient + * @param {number} offset Starting byte position of the page blob + * @param {number} count Number of bytes to get ranges diff. + * @param {string} prevSnapshotUrl URL of snapshot to retrieve the difference. + * @param {PageBlobGetPageRangesDiffOptions} [options] Options to the Page Blob Get Page Ranges Diff operation. + * @returns {Promise} Response data for the Page Blob Get Page Range Diff operation. + * @memberof PageBlobClient */ - ContainerClient.prototype.getProperties = function (options) { + PageBlobClient.prototype.getPageRangesDiffForManagedDisks = function (offset, count, prevSnapshotUrl, options) { + var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_52; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var _b, span, spanOptions, e_41; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-GetPageRangesDiffForManagedDisks", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext + .getPageRangesDiff({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + prevSnapshotUrl: prevSnapshotUrl, + range: rangeToString({ offset: offset, count: count }), + spanOptions: spanOptions + }) + .then(rangeResponseFromModel)]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_41 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_41.message + }); + throw e_41; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Resizes the page blob to the specified size (which must be a multiple of 512). + * @see https://docs.microsoft.com/rest/api/storageservices/set-blob-properties + * + * @param {number} size Target size + * @param {PageBlobResizeOptions} [options] Options to the Page Blob Resize operation. + * @returns {Promise} Response data for the Page Blob Resize operation. + * @memberof PageBlobClient + */ + PageBlobClient.prototype.resize = function (size, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_42; + return tslib.__generator(this, function (_c) { + switch (_c.label) { case 0: - if (!options.conditions) { - options.conditions = {}; - } - _a = createSpan("ContainerClient-getProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-resize", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.getProperties(tslib.__assign(tslib.__assign({ abortSignal: options.abortSignal }, options.conditions), { spanOptions: spanOptions }))]; - case 2: return [2 /*return*/, _b.sent()]; + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext.resize(size, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + encryptionScope: options.encryptionScope, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; case 3: - e_52 = _b.sent(); + e_42 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_52.message + message: e_42.message }); - throw e_52; + throw e_42; case 4: span.end(); return [7 /*endfinally*/]; @@ -31702,42 +32347,43 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * Marks the specified container for deletion. The container and any blobs - * contained within it are later deleted during garbage collection. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container + * Sets a page blob's sequence number. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties * - * @param {ContainerDeleteMethodOptions} [options] Options to Container Delete operation. - * @returns {Promise} - * @memberof ContainerClient + * @param {SequenceNumberActionType} sequenceNumberAction Indicates how the service should modify the blob's sequence number. + * @param {number} [sequenceNumber] Required if sequenceNumberAction is max or update + * @param {PageBlobUpdateSequenceNumberOptions} [options] Options to the Page Blob Update Sequence Number operation. + * @returns {Promise} Response data for the Page Blob Update Sequence Number operation. + * @memberof PageBlobClient */ - ContainerClient.prototype.delete = function (options) { + PageBlobClient.prototype.updateSequenceNumber = function (sequenceNumberAction, sequenceNumber, options) { + var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_53; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var _b, span, spanOptions, e_43; + return tslib.__generator(this, function (_c) { + switch (_c.label) { case 0: - if (!options.conditions) { - options.conditions = {}; - } - _a = createSpan("ContainerClient-delete", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-updateSequenceNumber", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.deleteMethod({ + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext.updateSequenceNumber(sequenceNumberAction, { abortSignal: options.abortSignal, + blobSequenceNumber: sequenceNumber, leaseAccessConditions: options.conditions, - modifiedAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), spanOptions: spanOptions })]; - case 2: return [2 /*return*/, _b.sent()]; + case 2: return [2 /*return*/, _c.sent()]; case 3: - e_53 = _b.sent(); + e_43 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_53.message + message: e_43.message }); - throw e_53; + throw e_43; case 4: span.end(); return [7 /*endfinally*/]; @@ -31747,45 +32393,44 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * Marks the specified container for deletion if it exists. The container and any blobs - * contained within it are later deleted during garbage collection. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container + * Begins an operation to start an incremental copy from one page blob's snapshot to this page blob. + * The snapshot is copied such that only the differential changes between the previously + * copied snapshot are transferred to the destination. + * The copied snapshots are complete copies of the original snapshot and can be read or copied from as usual. + * @see https://docs.microsoft.com/rest/api/storageservices/incremental-copy-blob + * @see https://docs.microsoft.com/en-us/azure/virtual-machines/windows/incremental-snapshots * - * @param {ContainerDeleteMethodOptions} [options] Options to Container Delete operation. - * @returns {Promise} - * @memberof ContainerClient + * @param {string} copySource Specifies the name of the source page blob snapshot. For example, + * https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= + * @param {PageBlobStartCopyIncrementalOptions} [options] Options to the Page Blob Copy Incremental operation. + * @returns {Promise} Response data for the Page Blob Copy Incremental operation. + * @memberof PageBlobClient */ - ContainerClient.prototype.deleteIfExists = function (options) { - var _a, _b; + PageBlobClient.prototype.startCopyIncremental = function (copySource, options) { + var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _c, span, spanOptions, res, e_54; - return tslib.__generator(this, function (_d) { - switch (_d.label) { + var _b, span, spanOptions, e_44; + return tslib.__generator(this, function (_c) { + switch (_c.label) { case 0: - _c = createSpan("ContainerClient-deleteIfExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; - _d.label = 1; + _b = createSpan("PageBlobClient-startCopyIncremental", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; case 1: - _d.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: - res = _d.sent(); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable - })]; + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext.copyIncremental(copySource, { + abortSignal: options.abortSignal, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; case 3: - e_54 = _d.sent(); - if (((_a = e_54.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerNotFound") { - span.setStatus({ - code: api.CanonicalCode.NOT_FOUND, - message: "Expected exception when deleting a container only if it exists." - }); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_54.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_54.response })]; - } + e_44 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_54.message + message: e_44.message }); - throw e_54; + throw e_44; case 4: span.end(); return [7 /*endfinally*/]; @@ -31794,52 +32439,110 @@ var ContainerClient = /** @class */ (function (_super) { }); }); }; + return PageBlobClient; +}(BlobClient)); +/** + * A client that manages leases for a {@link ContainerClient} or a {@link BlobClient}. + * + * @export + * @class BlobLeaseClient + */ +var BlobLeaseClient = /** @class */ (function () { /** - * Sets one or more user-defined name-value pairs for the specified container. - * - * If no option provided, or no metadata defined in the parameter, the container - * metadata will be removed. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-metadata + * Creates an instance of BlobLeaseClient. + * @param {(ContainerClient | BlobClient)} client The client to make the lease operation requests. + * @param {string} leaseId Initial proposed lease id. + * @memberof BlobLeaseClient + */ + function BlobLeaseClient(client, leaseId) { + var clientContext = new StorageClientContext(client.url, client.pipeline.toServiceClientOptions()); + this._url = client.url; + if (client instanceof ContainerClient) { + this._isContainer = true; + this._containerOrBlobOperation = new Container(clientContext); + } + else { + this._isContainer = false; + this._containerOrBlobOperation = new Blob$1(clientContext); + } + if (!leaseId) { + leaseId = coreHttp.generateUuid(); + } + this._leaseId = leaseId; + } + Object.defineProperty(BlobLeaseClient.prototype, "leaseId", { + /** + * Gets the lease Id. + * + * @readonly + * @memberof BlobLeaseClient + * @type {string} + */ + get: function () { + return this._leaseId; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobLeaseClient.prototype, "url", { + /** + * Gets the url. + * + * @readonly + * @memberof BlobLeaseClient + * @type {string} + */ + get: function () { + return this._url; + }, + enumerable: false, + configurable: true + }); + /** + * Establishes and manages a lock on a container for delete operations, or on a blob + * for write and delete operations. + * The lock duration can be 15 to 60 seconds, or can be infinite. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container + * and + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * - * @param {Metadata} [metadata] Replace existing metadata with this value. - * If no value provided the existing metadata will be removed. - * @param {ContainerSetMetadataOptions} [options] Options to Container Set Metadata operation. - * @returns {Promise} - * @memberof ContainerClient + * @param {number} duration Must be between 15 to 60 seconds, or infinite (-1) + * @param {LeaseOperationOptions} [options={}] option to configure lease management operations. + * @returns {Promise} Response data for acquire lease operation. + * @memberof BlobLeaseClient */ - ContainerClient.prototype.setMetadata = function (metadata, options) { + BlobLeaseClient.prototype.acquireLease = function (duration, options) { + var _a, _b, _c, _d, _e, _f; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_55; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var _g, span, spanOptions, e_45; + return tslib.__generator(this, function (_h) { + switch (_h.label) { case 0: - if (!options.conditions) { - options.conditions = {}; - } - if (options.conditions.ifUnmodifiedSince) { - throw new RangeError("the IfUnmodifiedSince must have their default values because they are ignored by the blob service"); + _g = createSpan("BlobLeaseClient-acquireLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); } - _a = createSpan("ContainerClient-setMetadata", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + _h.label = 1; case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.setMetadata({ + _h.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this._containerOrBlobOperation.acquireLease({ abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - metadata: metadata, - modifiedAccessConditions: options.conditions, + duration: duration, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), + proposedLeaseId: this._leaseId, spanOptions: spanOptions })]; - case 2: return [2 /*return*/, _b.sent()]; + case 2: return [2 /*return*/, _h.sent()]; case 3: - e_55 = _b.sent(); + e_45 = _h.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_55.message + message: e_45.message }); - throw e_55; + throw e_45; case 4: span.end(); return [7 /*endfinally*/]; @@ -31849,78 +32552,49 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * Gets the permissions for the specified container. The permissions indicate - * whether container data may be accessed publicly. - * - * WARNING: JavaScript Date will potentially lose precision when parsing startsOn and expiresOn strings. - * For example, new Date("2018-12-31T03:44:23.8827891Z").toISOString() will get "2018-12-31T03:44:23.882Z". - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-acl + * To change the ID of the lease. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container + * and + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * - * @param {ContainerGetAccessPolicyOptions} [options] Options to Container Get Access Policy operation. - * @returns {Promise} - * @memberof ContainerClient + * @param {string} proposedLeaseId the proposed new lease Id. + * @param {LeaseOperationOptions} [options={}] option to configure lease management operations. + * @returns {Promise} Response data for change lease operation. + * @memberof BlobLeaseClient */ - ContainerClient.prototype.getAccessPolicy = function (options) { + BlobLeaseClient.prototype.changeLease = function (proposedLeaseId, options) { + var _a, _b, _c, _d, _e, _f; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, response, res, _i, response_1, identifier, accessPolicy, e_56; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var _g, span, spanOptions, response, e_46; + return tslib.__generator(this, function (_h) { + switch (_h.label) { case 0: - if (!options.conditions) { - options.conditions = {}; + _g = createSpan("BlobLeaseClient-changeLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); } - _a = createSpan("ContainerClient-getAccessPolicy", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + _h.label = 1; case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.getAccessPolicy({ + _h.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this._containerOrBlobOperation.changeLease(this._leaseId, proposedLeaseId, { abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), spanOptions: spanOptions })]; case 2: - response = _b.sent(); - res = { - _response: response._response, - blobPublicAccess: response.blobPublicAccess, - date: response.date, - etag: response.etag, - errorCode: response.errorCode, - lastModified: response.lastModified, - requestId: response.requestId, - clientRequestId: response.clientRequestId, - signedIdentifiers: [], - version: response.version - }; - for (_i = 0, response_1 = response; _i < response_1.length; _i++) { - identifier = response_1[_i]; - accessPolicy = undefined; - if (identifier.accessPolicy) { - accessPolicy = { - permissions: identifier.accessPolicy.permissions - }; - if (identifier.accessPolicy.expiresOn) { - accessPolicy.expiresOn = new Date(identifier.accessPolicy.expiresOn); - } - if (identifier.accessPolicy.startsOn) { - accessPolicy.startsOn = new Date(identifier.accessPolicy.startsOn); - } - } - res.signedIdentifiers.push({ - accessPolicy: accessPolicy, - id: identifier.id - }); - } - return [2 /*return*/, res]; + response = _h.sent(); + this._leaseId = proposedLeaseId; + return [2 /*return*/, response]; case 3: - e_56 = _b.sent(); + e_46 = _h.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_56.message + message: e_46.message }); - throw e_56; + throw e_46; case 4: span.end(); return [7 /*endfinally*/]; @@ -31930,68 +32604,46 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * Sets the permissions for the specified container. The permissions indicate - * whether blobs in a container may be accessed publicly. - * - * When you set permissions for a container, the existing permissions are replaced. - * If no access or containerAcl provided, the existing container ACL will be - * removed. - * - * When you establish a stored access policy on a container, it may take up to 30 seconds to take effect. - * During this interval, a shared access signature that is associated with the stored access policy will - * fail with status code 403 (Forbidden), until the access policy becomes active. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-acl + * To free the lease if it is no longer needed so that another client may + * immediately acquire a lease against the container or the blob. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container + * and + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * - * @param {PublicAccessType} [access] The level of public access to data in the container. - * @param {SignedIdentifier[]} [containerAcl] Array of elements each having a unique Id and details of the access policy. - * @param {ContainerSetAccessPolicyOptions} [options] Options to Container Set Access Policy operation. - * @returns {Promise} - * @memberof ContainerClient + * @param {LeaseOperationOptions} [options={}] option to configure lease management operations. + * @returns {Promise} Response data for release lease operation. + * @memberof BlobLeaseClient */ - ContainerClient.prototype.setAccessPolicy = function (access, containerAcl, options) { + BlobLeaseClient.prototype.releaseLease = function (options) { + var _a, _b, _c, _d, _e, _f; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, acl, _i, _b, identifier, e_57; - return tslib.__generator(this, function (_c) { - switch (_c.label) { + var _g, span, spanOptions, e_47; + return tslib.__generator(this, function (_h) { + switch (_h.label) { case 0: - options.conditions = options.conditions || {}; - _a = createSpan("ContainerClient-setAccessPolicy", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - acl = []; - for (_i = 0, _b = containerAcl || []; _i < _b.length; _i++) { - identifier = _b[_i]; - acl.push({ - accessPolicy: { - expiresOn: identifier.accessPolicy.expiresOn - ? truncatedISO8061Date(identifier.accessPolicy.expiresOn) - : "", - permissions: identifier.accessPolicy.permissions, - startsOn: identifier.accessPolicy.startsOn - ? truncatedISO8061Date(identifier.accessPolicy.startsOn) - : "" - }, - id: identifier.id - }); + _g = createSpan("BlobLeaseClient-releaseLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); } - return [4 /*yield*/, this.containerContext.setAccessPolicy({ + _h.label = 1; + case 1: + _h.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this._containerOrBlobOperation.releaseLease(this._leaseId, { abortSignal: options.abortSignal, - access: access, - containerAcl: acl, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), spanOptions: spanOptions })]; - case 2: return [2 /*return*/, _c.sent()]; + case 2: return [2 /*return*/, _h.sent()]; case 3: - e_57 = _c.sent(); + e_47 = _h.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_57.message + message: e_47.message }); - throw e_57; + throw e_47; case 4: span.end(); return [7 /*endfinally*/]; @@ -32001,64 +32653,98 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * Get a {@link BlobLeaseClient} that manages leases on the container. + * To renew the lease. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container + * and + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * - * @param {string} [proposeLeaseId] Initial proposed lease Id. - * @returns {BlobLeaseClient} A new BlobLeaseClient object for managing leases on the container. - * @memberof ContainerClient + * @param {LeaseOperationOptions} [options={}] Optional option to configure lease management operations. + * @returns {Promise} Response data for renew lease operation. + * @memberof BlobLeaseClient */ - ContainerClient.prototype.getBlobLeaseClient = function (proposeLeaseId) { - return new BlobLeaseClient(this, proposeLeaseId); + BlobLeaseClient.prototype.renewLease = function (options) { + var _a, _b, _c, _d, _e, _f; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _g, span, spanOptions, e_48; + return tslib.__generator(this, function (_h) { + switch (_h.label) { + case 0: + _g = createSpan("BlobLeaseClient-renewLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + _h.label = 1; + case 1: + _h.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this._containerOrBlobOperation.renewLease(this._leaseId, { + abortSignal: options.abortSignal, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _h.sent()]; + case 3: + e_48 = _h.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_48.message + }); + throw e_48; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; /** - * Creates a new block blob, or updates the content of an existing block blob. - * - * Updating an existing block blob overwrites any existing metadata on the blob. - * Partial updates are not supported; the content of the existing blob is - * overwritten with the new content. To perform a partial update of a block blob's, - * use {@link BlockBlobClient.stageBlock} and {@link BlockBlobClient.commitBlockList}. - * - * This is a non-parallel uploading method, please use {@link BlockBlobClient.uploadFile}, - * {@link BlockBlobClient.uploadStream} or {@link BlockBlobClient.uploadBrowserData} for better - * performance with concurrency uploading. - * - * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * To end the lease but ensure that another client cannot acquire a new lease + * until the current lease period has expired. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container + * and + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * - * @param {string} blobName Name of the block blob to create or update. - * @param {HttpRequestBody} body Blob, string, ArrayBuffer, ArrayBufferView or a function - * which returns a new Readable stream whose offset is from data source beginning. - * @param {number} contentLength Length of body in bytes. Use Buffer.byteLength() to calculate body length for a - * string including non non-Base64/Hex-encoded characters. - * @param {BlockBlobUploadOptions} [options] Options to configure the Block Blob Upload operation. - * @returns {Promise<{ blockBlobClient: BlockBlobClient; response: BlockBlobUploadResponse }>} Block Blob upload response data and the corresponding BlockBlobClient instance. - * @memberof ContainerClient + * @static + * @param {number} breakPeriod Break period + * @param {LeaseOperationOptions} [options={}] Optional options to configure lease management operations. + * @returns {Promise} Response data for break lease operation. + * @memberof BlobLeaseClient */ - ContainerClient.prototype.uploadBlockBlob = function (blobName, body, contentLength, options) { + BlobLeaseClient.prototype.breakLease = function (breakPeriod, options) { + var _a, _b, _c, _d, _e, _f; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, blockBlobClient, response, e_58; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var _g, span, spanOptions, operationOptions, e_49; + return tslib.__generator(this, function (_h) { + switch (_h.label) { case 0: - _a = createSpan("ContainerClient-uploadBlockBlob", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + _g = createSpan("BlobLeaseClient-breakLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + _h.label = 1; case 1: - _b.trys.push([1, 3, 4, 5]); - blockBlobClient = this.getBlockBlobClient(blobName); - return [4 /*yield*/, blockBlobClient.upload(body, contentLength, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: - response = _b.sent(); - return [2 /*return*/, { - blockBlobClient: blockBlobClient, - response: response - }]; + _h.trys.push([1, 3, 4, 5]); + operationOptions = { + abortSignal: options.abortSignal, + breakPeriod: breakPeriod, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), + spanOptions: spanOptions + }; + return [4 /*yield*/, this._containerOrBlobOperation.breakLease(operationOptions)]; + case 2: return [2 /*return*/, _h.sent()]; case 3: - e_58 = _b.sent(); + e_49 = _h.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_58.message + message: e_49.message }); - throw e_58; + throw e_49; case 4: span.end(); return [7 /*endfinally*/]; @@ -32067,42 +32753,122 @@ var ContainerClient = /** @class */ (function (_super) { }); }); }; + return BlobLeaseClient; +}()); +/** + * A ContainerClient represents a URL to the Azure Storage container allowing you to manipulate its blobs. + * + * @export + * @class ContainerClient + */ +var ContainerClient = /** @class */ (function (_super) { + tslib.__extends(ContainerClient, _super); + function ContainerClient(urlOrConnectionString, credentialOrPipelineOrContainerName, options) { + var _this = this; + var pipeline; + var url; + options = options || {}; + if (credentialOrPipelineOrContainerName instanceof Pipeline) { + // (url: string, pipeline: Pipeline) + url = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } + else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || + credentialOrPipelineOrContainerName instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + url = urlOrConnectionString; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } + else if (!credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName !== "string") { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + // The second parameter is undefined. Use anonymous credential. + url = urlOrConnectionString; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else if (credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName === "string") { + // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) + var containerName = credentialOrPipelineOrContainerName; + var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + { + var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)); + options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); + pipeline = newPipeline(sharedKeyCredential, options); + } + } + else if (extractedCreds.kind === "SASConnString") { + url = + appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)) + + "?" + + extractedCreds.accountSas; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } + else { + throw new Error("Expecting non-empty strings for containerName parameter"); + } + _this = _super.call(this, url, pipeline) || this; + _this._containerName = _this.getContainerNameFromUrl(); + _this.containerContext = new Container(_this.storageClientContext); + return _this; + } + Object.defineProperty(ContainerClient.prototype, "containerName", { + /** + * The name of the container. + */ + get: function () { + return this._containerName; + }, + enumerable: false, + configurable: true + }); /** - * Marks the specified blob or snapshot for deletion. The blob is later deleted - * during garbage collection. Note that in order to delete a blob, you must delete - * all of its snapshots. You can delete both at the same time with the Delete - * Blob operation. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob + * Creates a new container under the specified account. If the container with + * the same name already exists, the operation fails. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container * - * @param {string} blobName - * @param {ContainerDeleteBlobOptions} [options] Options to Blob Delete operation. - * @returns {Promise} Block blob deletion response data. + * @param {ContainerCreateOptions} [options] Options to Container Create operation. + * @returns {Promise} * @memberof ContainerClient + * + * Example usage: + * + * ```js + * const containerClient = blobServiceClient.getContainerClient(""); + * const createContainerResponse = await containerClient.create(); + * console.log("Container was created successfully", createContainerResponse.requestId); + * ``` */ - ContainerClient.prototype.deleteBlob = function (blobName, options) { + ContainerClient.prototype.create = function (options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, blobClient, e_59; + var _a, span, spanOptions, e_50; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("ContainerClient-deleteBlob", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("ContainerClient-create", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - blobClient = this.getBlobClient(blobName); - if (options.versionId) { - blobClient = blobClient.withVersion(options.versionId); - } - return [4 /*yield*/, blobClient.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: return [2 /*return*/, _b.sent()]; + return [4 /*yield*/, this.containerContext.create(tslib.__assign(tslib.__assign({}, options), { spanOptions: spanOptions }))]; + case 2: + // Spread operator in destructuring assignments, + // this will filter out unwanted properties from the response object into result object + return [2 /*return*/, _b.sent()]; case 3: - e_59 = _b.sent(); + e_50 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_59.message + message: e_50.message }); - throw e_59; + throw e_50; case 4: span.end(); return [7 /*endfinally*/]; @@ -32112,43 +32878,45 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * listBlobFlatSegment returns a single segment of blobs starting from the - * specified Marker. Use an empty Marker to start enumeration from the beginning. - * After getting a segment, process it, and then call listBlobsFlatSegment again - * (passing the the previously-returned Marker) to get the next segment. - * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs + * Creates a new container under the specified account. If the container with + * the same name already exists, it is not changed. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container * - * @param {string} [marker] A string value that identifies the portion of the list to be returned with the next list operation. - * @param {ContainerListBlobsSegmentOptions} [options] Options to Container List Blob Flat Segment operation. - * @returns {Promise} + * @param {ContainerCreateOptions} [options] + * @returns {Promise} * @memberof ContainerClient */ - ContainerClient.prototype.listBlobFlatSegment = function (marker, options) { + ContainerClient.prototype.createIfNotExists = function (options) { + var _a, _b; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, response, wrappedResponse, e_60; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var _c, span, spanOptions, res, e_51; + return tslib.__generator(this, function (_d) { + switch (_d.label) { case 0: - _a = createSpan("ContainerClient-listBlobFlatSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + _c = createSpan("ContainerClient-createIfNotExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; + _d.label = 1; case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.listBlobFlatSegment(tslib.__assign(tslib.__assign({ marker: marker }, options), { spanOptions: spanOptions }))]; + _d.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.create(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: - response = _b.sent(); - wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, segment: tslib.__assign(tslib.__assign({}, response.segment), { blobItems: response.segment.blobItems.map(function (blobItemInteral) { - var blobItem = tslib.__assign(tslib.__assign({}, blobItemInteral), { tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); - return blobItem; - }) }) }); - return [2 /*return*/, wrappedResponse]; + res = _d.sent(); + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable + })]; case 3: - e_60 = _b.sent(); + e_51 = _d.sent(); + if (((_a = e_51.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerAlreadyExists") { + span.setStatus({ + code: api.CanonicalCode.ALREADY_EXISTS, + message: "Expected exception when creating a container only if it does not already exist." + }); + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_51.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_51.response })]; + } span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_60.message + message: e_51.message }); - throw e_60; + throw e_51; case 4: span.end(); return [7 /*endfinally*/]; @@ -32158,44 +32926,48 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * listBlobHierarchySegment returns a single segment of blobs starting from - * the specified Marker. Use an empty Marker to start enumeration from the - * beginning. After getting a segment, process it, and then call listBlobsHierarchicalSegment - * again (passing the the previously-returned Marker) to get the next segment. - * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs + * Returns true if the Azure container resource represented by this client exists; false otherwise. * - * @param {string} delimiter The character or string used to define the virtual hierarchy - * @param {string} [marker] A string value that identifies the portion of the list to be returned with the next list operation. - * @param {ContainerListBlobsSegmentOptions} [options] Options to Container List Blob Hierarchy Segment operation. - * @returns {Promise} + * NOTE: use this function with care since an existing container might be deleted by other clients or + * applications. Vice versa new containers with the same name might be added by other clients or + * applications after this function completes. + * + * @param {ContainerExistsOptions} [options={}] + * @returns {Promise} * @memberof ContainerClient */ - ContainerClient.prototype.listBlobHierarchySegment = function (delimiter, marker, options) { + ContainerClient.prototype.exists = function (options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, response, wrappedResponse, e_61; + var _a, span, spanOptions, e_52; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("ContainerClient-listBlobHierarchySegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("ContainerClient-exists", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.listBlobHierarchySegment(delimiter, tslib.__assign(tslib.__assign({ marker: marker }, options), { spanOptions: spanOptions }))]; + return [4 /*yield*/, this.getProperties({ + abortSignal: options.abortSignal, + tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) + })]; case 2: - response = _b.sent(); - wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, segment: tslib.__assign(tslib.__assign({}, response.segment), { blobItems: response.segment.blobItems.map(function (blobItemInteral) { - var blobItem = tslib.__assign(tslib.__assign({}, blobItemInteral), { tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); - return blobItem; - }) }) }); - return [2 /*return*/, wrappedResponse]; + _b.sent(); + return [2 /*return*/, true]; case 3: - e_61 = _b.sent(); + e_52 = _b.sent(); + if (e_52.statusCode === 404) { + span.setStatus({ + code: api.CanonicalCode.NOT_FOUND, + message: "Expected exception when checking container existence" + }); + return [2 /*return*/, false]; + } span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_61.message + message: e_52.message }); - throw e_61; + throw e_52; case 4: span.end(); return [7 /*endfinally*/]; @@ -32205,883 +32977,501 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * Returns an AsyncIterableIterator for ContainerListBlobFlatSegmentResponse + * Creates a {@link BlobClient} * - * @private - * @param {string} [marker] A string value that identifies the portion of - * the list of blobs to be returned with the next listing operation. The - * operation returns the ContinuationToken value within the response body if the - * listing operation did not return all blobs remaining to be listed - * with the current page. The ContinuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. - * @returns {AsyncIterableIterator} + * @param {string} blobName A blob name + * @returns {BlobClient} A new BlobClient object for the given blob name. * @memberof ContainerClient */ - ContainerClient.prototype.listSegments = function (marker, options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listSegments_1() { - var listBlobsFlatSegmentResponse; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!(!!marker || marker === undefined)) return [3 /*break*/, 7]; - _a.label = 1; - case 1: return [4 /*yield*/, tslib.__await(this.listBlobFlatSegment(marker, options))]; - case 2: - listBlobsFlatSegmentResponse = _a.sent(); - marker = listBlobsFlatSegmentResponse.continuationToken; - return [4 /*yield*/, tslib.__await(listBlobsFlatSegmentResponse)]; - case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_a.sent()])]; - case 4: return [4 /*yield*/, _a.sent()]; - case 5: - _a.sent(); - _a.label = 6; - case 6: - if (marker) return [3 /*break*/, 1]; - _a.label = 7; - case 7: return [2 /*return*/]; - } - }); - }); + ContainerClient.prototype.getBlobClient = function (blobName) { + return new BlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); }; /** - * Returns an AsyncIterableIterator of {@link BlobItem} objects + * Creates an {@link AppendBlobClient} * - * @private - * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. - * @returns {AsyncIterableIterator} + * @param {string} blobName An append blob name + * @returns {AppendBlobClient} * @memberof ContainerClient */ - ContainerClient.prototype.listItems = function (options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listItems_1() { - var marker, _a, _b, listBlobsFlatSegmentResponse, e_62_1; - var e_62, _c; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _d.trys.push([0, 7, 8, 13]); - _a = tslib.__asyncValues(this.listSegments(marker, options)); - _d.label = 1; - case 1: return [4 /*yield*/, tslib.__await(_a.next())]; - case 2: - if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; - listBlobsFlatSegmentResponse = _b.value; - return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(listBlobsFlatSegmentResponse.segment.blobItems)))]; - case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; - case 4: - _d.sent(); - _d.label = 5; - case 5: return [3 /*break*/, 1]; - case 6: return [3 /*break*/, 13]; - case 7: - e_62_1 = _d.sent(); - e_62 = { error: e_62_1 }; - return [3 /*break*/, 13]; - case 8: - _d.trys.push([8, , 11, 12]); - if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; - return [4 /*yield*/, tslib.__await(_c.call(_a))]; - case 9: - _d.sent(); - _d.label = 10; - case 10: return [3 /*break*/, 12]; - case 11: - if (e_62) throw e_62.error; - return [7 /*endfinally*/]; - case 12: return [7 /*endfinally*/]; - case 13: return [2 /*return*/]; - } - }); - }); + ContainerClient.prototype.getAppendBlobClient = function (blobName) { + return new AppendBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); }; /** - * Returns an async iterable iterator to list all the blobs - * under the specified account. - * - * .byPage() returns an async iterable iterator to list the blobs in pages. - * - * Example using `for await` syntax: + * Creates a {@link BlockBlobClient} * - * ```js - * // Get the containerClient before you run these snippets, - * // Can be obtained from `blobServiceClient.getContainerClient("");` - * let i = 1; - * for await (const blob of containerClient.listBlobsFlat()) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * ``` + * @param {string} blobName A block blob name + * @returns {BlockBlobClient} + * @memberof ContainerClient * - * Example using `iter.next()`: + * Example usage: * * ```js - * let i = 1; - * let iter = containerClient.listBlobsFlat(); - * let blobItem = await iter.next(); - * while (!blobItem.done) { - * console.log(`Blob ${i++}: ${blobItem.value.name}`); - * blobItem = await iter.next(); - * } - * ``` - * - * Example using `byPage()`: + * const content = "Hello world!"; * - * ```js - * // passing optional maxPageSize in the page settings - * let i = 1; - * for await (const response of containerClient.listBlobsFlat().byPage({ maxPageSize: 20 })) { - * for (const blob of response.segment.blobItems) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } + * const blockBlobClient = containerClient.getBlockBlobClient(""); + * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); * ``` + */ + ContainerClient.prototype.getBlockBlobClient = function (blobName) { + return new BlockBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); + }; + /** + * Creates a {@link PageBlobClient} * - * Example using paging with a marker: - * - * ```js - * let i = 1; - * let iterator = containerClient.listBlobsFlat().byPage({ maxPageSize: 2 }); - * let response = (await iterator.next()).value; - * - * // Prints 2 blob names - * for (const blob of response.segment.blobItems) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * - * // Gets next marker - * let marker = response.continuationToken; - * - * // Passing next marker as continuationToken - * - * iterator = containerClient.listBlobsFlat().byPage({ continuationToken: marker, maxPageSize: 10 }); - * response = (await iterator.next()).value; + * @param {string} blobName A page blob name + * @returns {PageBlobClient} + * @memberof ContainerClient + */ + ContainerClient.prototype.getPageBlobClient = function (blobName) { + return new PageBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); + }; + /** + * Returns all user-defined metadata and system properties for the specified + * container. The data returned does not include the container's list of blobs. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-properties * - * // Prints 10 blob names - * for (const blob of response.segment.blobItems) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * ``` + * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if + * they originally contained uppercase characters. This differs from the metadata keys returned by + * the `listContainers` method of {@link BlobServiceClient} using the `includeMetadata` option, which + * will retain their original casing. * - * @param {ContainerListBlobsOptions} [options={}] Options to list blobs. - * @returns {PagedAsyncIterableIterator} An asyncIterableIterator that supports paging. + * @param {ContainerGetPropertiesOptions} [options] Options to Container Get Properties operation. + * @returns {Promise} * @memberof ContainerClient */ - ContainerClient.prototype.listBlobsFlat = function (options) { - var _a; - var _this = this; + ContainerClient.prototype.getProperties = function (options) { if (options === void 0) { options = {}; } - var include = []; - if (options.includeCopy) { - include.push("copy"); - } - if (options.includeDeleted) { - include.push("deleted"); - } - if (options.includeMetadata) { - include.push("metadata"); - } - if (options.includeSnapshots) { - include.push("snapshots"); - } - if (options.includeVersions) { - include.push("versions"); - } - if (options.includeUncommitedBlobs) { - include.push("uncommittedblobs"); - } - if (options.includeTags) { - include.push("tags"); - } - if (options.prefix === "") { - options.prefix = undefined; - } - var updatedOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); - // AsyncIterableIterator to iterate over blobs - var iter = this.listItems(updatedOptions); - return _a = { - /** - * @member {Promise} [next] The next method, part of the iteration protocol - */ - next: function () { - return iter.next(); + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_53; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!options.conditions) { + options.conditions = {}; + } + _a = createSpan("ContainerClient-getProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.containerContext.getProperties(tslib.__assign(tslib.__assign({ abortSignal: options.abortSignal }, options.conditions), { spanOptions: spanOptions }))]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_53 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_53.message + }); + throw e_53; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; } - }, - /** - * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol - */ - _a[Symbol.asyncIterator] = function () { - return this; - }, - /** - * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time - */ - _a.byPage = function (settings) { - if (settings === void 0) { settings = {}; } - return _this.listSegments(settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); - }, - _a; + }); + }); + }; + /** + * Marks the specified container for deletion. The container and any blobs + * contained within it are later deleted during garbage collection. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container + * + * @param {ContainerDeleteMethodOptions} [options] Options to Container Delete operation. + * @returns {Promise} + * @memberof ContainerClient + */ + ContainerClient.prototype.delete = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_54; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!options.conditions) { + options.conditions = {}; + } + _a = createSpan("ContainerClient-delete", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.containerContext.deleteMethod({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: options.conditions, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_54 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_54.message + }); + throw e_54; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; /** - * Returns an AsyncIterableIterator for ContainerListBlobHierarchySegmentResponse + * Marks the specified container for deletion if it exists. The container and any blobs + * contained within it are later deleted during garbage collection. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container * - * @private - * @param {string} delimiter The character or string used to define the virtual hierarchy - * @param {string} [marker] A string value that identifies the portion of - * the list of blobs to be returned with the next listing operation. The - * operation returns the ContinuationToken value within the response body if the - * listing operation did not return all blobs remaining to be listed - * with the current page. The ContinuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. - * @returns {AsyncIterableIterator} + * @param {ContainerDeleteMethodOptions} [options] Options to Container Delete operation. + * @returns {Promise} * @memberof ContainerClient */ - ContainerClient.prototype.listHierarchySegments = function (delimiter, marker, options) { + ContainerClient.prototype.deleteIfExists = function (options) { + var _a, _b; if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listHierarchySegments_1() { - var listBlobsHierarchySegmentResponse; - return tslib.__generator(this, function (_a) { - switch (_a.label) { + return tslib.__awaiter(this, void 0, void 0, function () { + var _c, span, spanOptions, res, e_55; + return tslib.__generator(this, function (_d) { + switch (_d.label) { case 0: - if (!(!!marker || marker === undefined)) return [3 /*break*/, 7]; - _a.label = 1; - case 1: return [4 /*yield*/, tslib.__await(this.listBlobHierarchySegment(delimiter, marker, options))]; + _c = createSpan("ContainerClient-deleteIfExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; + _d.label = 1; + case 1: + _d.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: - listBlobsHierarchySegmentResponse = _a.sent(); - marker = listBlobsHierarchySegmentResponse.continuationToken; - return [4 /*yield*/, tslib.__await(listBlobsHierarchySegmentResponse)]; - case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_a.sent()])]; - case 4: return [4 /*yield*/, _a.sent()]; - case 5: - _a.sent(); - _a.label = 6; - case 6: - if (marker) return [3 /*break*/, 1]; - _a.label = 7; - case 7: return [2 /*return*/]; + res = _d.sent(); + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable + })]; + case 3: + e_55 = _d.sent(); + if (((_a = e_55.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerNotFound") { + span.setStatus({ + code: api.CanonicalCode.NOT_FOUND, + message: "Expected exception when deleting a container only if it exists." + }); + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_55.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_55.response })]; + } + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_55.message + }); + throw e_55; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; } }); }); }; /** - * Returns an AsyncIterableIterator for {@link BlobPrefix} and {@link BlobItem} objects. + * Sets one or more user-defined name-value pairs for the specified container. * - * @private - * @param {string} delimiter The character or string used to define the virtual hierarchy - * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. - * @returns {AsyncIterableIterator<{ kind: "prefix" } & BlobPrefix | { kind: "blob" } & BlobItem>} + * If no option provided, or no metadata defined in the parameter, the container + * metadata will be removed. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-metadata + * + * @param {Metadata} [metadata] Replace existing metadata with this value. + * If no value provided the existing metadata will be removed. + * @param {ContainerSetMetadataOptions} [options] Options to Container Set Metadata operation. + * @returns {Promise} * @memberof ContainerClient */ - ContainerClient.prototype.listItemsByHierarchy = function (delimiter, options) { + ContainerClient.prototype.setMetadata = function (metadata, options) { if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listItemsByHierarchy_1() { - var marker, _a, _b, listBlobsHierarchySegmentResponse, segment, _i, _c, prefix, _d, _e, blob, e_63_1; - var e_63, _f; - return tslib.__generator(this, function (_g) { - switch (_g.label) { + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_56; + return tslib.__generator(this, function (_b) { + switch (_b.label) { case 0: - _g.trys.push([0, 14, 15, 20]); - _a = tslib.__asyncValues(this.listHierarchySegments(delimiter, marker, options)); - _g.label = 1; - case 1: return [4 /*yield*/, tslib.__await(_a.next())]; - case 2: - if (!(_b = _g.sent(), !_b.done)) return [3 /*break*/, 13]; - listBlobsHierarchySegmentResponse = _b.value; - segment = listBlobsHierarchySegmentResponse.segment; - if (!segment.blobPrefixes) return [3 /*break*/, 7]; - _i = 0, _c = segment.blobPrefixes; - _g.label = 3; + if (!options.conditions) { + options.conditions = {}; + } + if (options.conditions.ifUnmodifiedSince) { + throw new RangeError("the IfUnmodifiedSince must have their default values because they are ignored by the blob service"); + } + _a = createSpan("ContainerClient-setMetadata", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.containerContext.setMetadata({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + metadata: metadata, + modifiedAccessConditions: options.conditions, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; case 3: - if (!(_i < _c.length)) return [3 /*break*/, 7]; - prefix = _c[_i]; - return [4 /*yield*/, tslib.__await(tslib.__assign({ kind: "prefix" }, prefix))]; - case 4: return [4 /*yield*/, _g.sent()]; - case 5: - _g.sent(); - _g.label = 6; - case 6: - _i++; - return [3 /*break*/, 3]; - case 7: - _d = 0, _e = segment.blobItems; - _g.label = 8; - case 8: - if (!(_d < _e.length)) return [3 /*break*/, 12]; - blob = _e[_d]; - return [4 /*yield*/, tslib.__await(tslib.__assign({ kind: "blob" }, blob))]; - case 9: return [4 /*yield*/, _g.sent()]; - case 10: - _g.sent(); - _g.label = 11; - case 11: - _d++; - return [3 /*break*/, 8]; - case 12: return [3 /*break*/, 1]; - case 13: return [3 /*break*/, 20]; - case 14: - e_63_1 = _g.sent(); - e_63 = { error: e_63_1 }; - return [3 /*break*/, 20]; - case 15: - _g.trys.push([15, , 18, 19]); - if (!(_b && !_b.done && (_f = _a.return))) return [3 /*break*/, 17]; - return [4 /*yield*/, tslib.__await(_f.call(_a))]; - case 16: - _g.sent(); - _g.label = 17; - case 17: return [3 /*break*/, 19]; - case 18: - if (e_63) throw e_63.error; + e_56 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_56.message + }); + throw e_56; + case 4: + span.end(); return [7 /*endfinally*/]; - case 19: return [7 /*endfinally*/]; - case 20: return [2 /*return*/]; + case 5: return [2 /*return*/]; } }); }); }; /** - * Returns an async iterable iterator to list all the blobs by hierarchy. - * under the specified account. - * - * .byPage() returns an async iterable iterator to list the blobs by hierarchy in pages. - * - * Example using `for await` syntax: - * - * ```js - * for await (const item of containerClient.listBlobsByHierarchy("/")) { - * if (item.kind === "prefix") { - * console.log(`\tBlobPrefix: ${item.name}`); - * } else { - * console.log(`\tBlobItem: name - ${item.name}, last modified - ${item.properties.lastModified}`); - * } - * } - * ``` - * - * Example using `iter.next()`: - * - * ```js - * let iter = containerClient.listBlobsByHierarchy("/", { prefix: "prefix1/" }); - * let entity = await iter.next(); - * while (!entity.done) { - * let item = entity.value; - * if (item.kind === "prefix") { - * console.log(`\tBlobPrefix: ${item.name}`); - * } else { - * console.log(`\tBlobItem: name - ${item.name}, last modified - ${item.properties.lastModified}`); - * } - * entity = await iter.next(); - * } - * ```js - * - * Example using `byPage()`: - * - * ```js - * console.log("Listing blobs by hierarchy by page"); - * for await (const response of containerClient.listBlobsByHierarchy("/").byPage()) { - * const segment = response.segment; - * if (segment.blobPrefixes) { - * for (const prefix of segment.blobPrefixes) { - * console.log(`\tBlobPrefix: ${prefix.name}`); - * } - * } - * for (const blob of response.segment.blobItems) { - * console.log(`\tBlobItem: name - ${blob.name}, last modified - ${blob.properties.lastModified}`); - * } - * } - * ``` - * - * Example using paging with a max page size: - * - * ```js - * console.log("Listing blobs by hierarchy by page, specifying a prefix and a max page size"); - * - * let i = 1; - * for await (const response of containerClient.listBlobsByHierarchy("/", { prefix: "prefix2/sub1/"}).byPage({ maxPageSize: 2 })) { - * console.log(`Page ${i++}`); - * const segment = response.segment; + * Gets the permissions for the specified container. The permissions indicate + * whether container data may be accessed publicly. * - * if (segment.blobPrefixes) { - * for (const prefix of segment.blobPrefixes) { - * console.log(`\tBlobPrefix: ${prefix.name}`); - * } - * } + * WARNING: JavaScript Date will potentially lose precision when parsing startsOn and expiresOn strings. + * For example, new Date("2018-12-31T03:44:23.8827891Z").toISOString() will get "2018-12-31T03:44:23.882Z". * - * for (const blob of response.segment.blobItems) { - * console.log(`\tBlobItem: name - ${blob.name}, last modified - ${blob.properties.lastModified}`); - * } - * } - * ``` + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-acl * - * @param {string} delimiter The character or string used to define the virtual hierarchy - * @param {ContainerListBlobsOptions} [options={}] Options to list blobs operation. - * @returns {(PagedAsyncIterableIterator< - * { kind: "prefix" } & BlobPrefix | { kind: "blob" } & BlobItem, - * ContainerListBlobHierarchySegmentResponse - * >)} + * @param {ContainerGetAccessPolicyOptions} [options] Options to Container Get Access Policy operation. + * @returns {Promise} * @memberof ContainerClient */ - ContainerClient.prototype.listBlobsByHierarchy = function (delimiter, options) { - var _a; - var _this = this; + ContainerClient.prototype.getAccessPolicy = function (options) { if (options === void 0) { options = {}; } - if (delimiter === "") { - throw new RangeError("delimiter should contain one or more characters"); - } - var include = []; - if (options.includeCopy) { - include.push("copy"); - } - if (options.includeDeleted) { - include.push("deleted"); - } - if (options.includeMetadata) { - include.push("metadata"); - } - if (options.includeSnapshots) { - include.push("snapshots"); - } - if (options.includeVersions) { - include.push("versions"); - } - if (options.includeUncommitedBlobs) { - include.push("uncommittedblobs"); - } - if (options.includeTags) { - include.push("tags"); - } - if (options.prefix === "") { - options.prefix = undefined; - } - var updatedOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); - // AsyncIterableIterator to iterate over blob prefixes and blobs - var iter = this.listItemsByHierarchy(delimiter, updatedOptions); - return _a = { - /** - * @member {Promise} [next] The next method, part of the iteration protocol - */ - next: function () { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - return [2 /*return*/, iter.next()]; - }); - }); - } - }, - /** - * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol - */ - _a[Symbol.asyncIterator] = function () { - return this; - }, - /** - * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time - */ - _a.byPage = function (settings) { - if (settings === void 0) { settings = {}; } - return _this.listHierarchySegments(delimiter, settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); - }, - _a; - }; - ContainerClient.prototype.getContainerNameFromUrl = function () { - var containerName; - try { - // URL may look like the following - // "https://myaccount.blob.core.windows.net/mycontainer?sasString"; - // "https://myaccount.blob.core.windows.net/mycontainer"; - // IPv4/IPv6 address hosts, Endpoints - `http://127.0.0.1:10000/devstoreaccount1/containername` - // http://localhost:10001/devstoreaccount1/containername - var parsedUrl = coreHttp.URLBuilder.parse(this.url); - if (parsedUrl.getHost().split(".")[1] === "blob") { - // "https://myaccount.blob.core.windows.net/containername". - // "https://customdomain.com/containername". - // .getPath() -> /containername - containerName = parsedUrl.getPath().split("/")[1]; - } - else if (isIpEndpointStyle(parsedUrl)) { - // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/containername - // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/containername - // .getPath() -> /devstoreaccount1/containername - containerName = parsedUrl.getPath().split("/")[2]; - } - else { - // "https://customdomain.com/containername". - // .getPath() -> /containername - containerName = parsedUrl.getPath().split("/")[1]; - } - // decode the encoded containerName - to get all the special characters that might be present in it - containerName = decodeURIComponent(containerName); - if (!containerName) { - throw new Error("Provided containerName is invalid."); - } - return containerName; - } - catch (error) { - throw new Error("Unable to extract containerName with provided information."); - } - }; - return ContainerClient; -}(StorageClient)); - -function getBodyAsText(batchResponse) { - return tslib.__awaiter(this, void 0, void 0, function () { - var buffer, responseLength; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - buffer = Buffer.alloc(BATCH_MAX_PAYLOAD_IN_BYTES); - return [4 /*yield*/, streamToBuffer2(batchResponse.readableStreamBody, buffer)]; - case 1: - responseLength = _a.sent(); - // Slice the buffer to trim the empty ending. - buffer = buffer.slice(0, responseLength); - return [2 /*return*/, buffer.toString()]; - } - }); - }); -} -function utf8ByteLength(str) { - return Buffer.byteLength(str); -} - -var HTTP_HEADER_DELIMITER = ": "; -var SPACE_DELIMITER = " "; -var NOT_FOUND = -1; -/** - * Util class for parsing batch response. - */ -var BatchResponseParser = /** @class */ (function () { - function BatchResponseParser(batchResponse, subRequests) { - if (!batchResponse || !batchResponse.contentType) { - // In special case(reported), server may return invalid content-type which could not be parsed. - throw new RangeError("batchResponse is malformed or doesn't contain valid content-type."); - } - if (!subRequests || subRequests.size === 0) { - // This should be prevent during coding. - throw new RangeError("Invalid state: subRequests is not provided or size is 0."); - } - this.batchResponse = batchResponse; - this.subRequests = subRequests; - this.responseBatchBoundary = this.batchResponse.contentType.split("=")[1]; - this.perResponsePrefix = "--" + this.responseBatchBoundary + HTTP_LINE_ENDING; - this.batchResponseEnding = "--" + this.responseBatchBoundary + "--"; - } - // For example of response, please refer to https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#response - BatchResponseParser.prototype.parseBatchResponse = function () { return tslib.__awaiter(this, void 0, void 0, function () { - var responseBodyAsText, subResponses, subResponseCount, deserializedSubResponses, subResponsesSucceededCount, subResponsesFailedCount, index, subResponse, deserializedSubResponse, responseLines, subRespHeaderStartFound, subRespHeaderEndFound, subRespFailed, contentId, _i, responseLines_1, responseLine, tokens, tokens; - return tslib.__generator(this, function (_a) { - switch (_a.label) { + var _a, span, spanOptions, response, res, _i, response_1, identifier, accessPolicy, e_57; + return tslib.__generator(this, function (_b) { + switch (_b.label) { case 0: - // When logic reach here, suppose batch request has already succeeded with 202, so we can further parse - // sub request's response. - if (this.batchResponse._response.status != HTTPURLConnection.HTTP_ACCEPTED) { - throw new Error("Invalid state: batch request failed with status: '" + this.batchResponse._response.status + "'."); + if (!options.conditions) { + options.conditions = {}; } - return [4 /*yield*/, getBodyAsText(this.batchResponse)]; + _a = createSpan("ContainerClient-getAccessPolicy", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; case 1: - responseBodyAsText = _a.sent(); - subResponses = responseBodyAsText - .split(this.batchResponseEnding)[0] // string after ending is useless - .split(this.perResponsePrefix) - .slice(1); - subResponseCount = subResponses.length; - // Defensive coding in case of potential error parsing. - // Note: subResponseCount == 1 is special case where sub request is invalid. - // We try to prevent such cases through early validation, e.g. validate sub request count >= 1. - // While in unexpected sub request invalid case, we allow sub response to be parsed and return to user. - if (subResponseCount != this.subRequests.size && subResponseCount != 1) { - throw new Error("Invalid state: sub responses' count is not equal to sub requests' count."); - } - deserializedSubResponses = new Array(subResponseCount); - subResponsesSucceededCount = 0; - subResponsesFailedCount = 0; - // Parse sub subResponses. - for (index = 0; index < subResponseCount; index++) { - subResponse = subResponses[index]; - deserializedSubResponses[index] = {}; - deserializedSubResponse = deserializedSubResponses[index]; - deserializedSubResponse.headers = new coreHttp.HttpHeaders(); - responseLines = subResponse.split("" + HTTP_LINE_ENDING); - subRespHeaderStartFound = false; - subRespHeaderEndFound = false; - subRespFailed = false; - contentId = NOT_FOUND; - for (_i = 0, responseLines_1 = responseLines; _i < responseLines_1.length; _i++) { - responseLine = responseLines_1[_i]; - if (!subRespHeaderStartFound) { - // Convention line to indicate content ID - if (responseLine.startsWith(HeaderConstants.CONTENT_ID)) { - contentId = parseInt(responseLine.split(HTTP_HEADER_DELIMITER)[1]); - } - // Http version line with status code indicates the start of sub request's response. - // Example: HTTP/1.1 202 Accepted - if (responseLine.startsWith(HTTP_VERSION_1_1)) { - subRespHeaderStartFound = true; - tokens = responseLine.split(SPACE_DELIMITER); - deserializedSubResponse.status = parseInt(tokens[1]); - deserializedSubResponse.statusMessage = tokens.slice(2).join(SPACE_DELIMITER); - } - continue; // Skip convention headers not specifically for sub request i.e. Content-Type: application/http and Content-ID: * - } - if (responseLine.trim() === "") { - // Sub response's header start line already found, and the first empty line indicates header end line found. - if (!subRespHeaderEndFound) { - subRespHeaderEndFound = true; - } - continue; // Skip empty line - } - // Note: when code reach here, it indicates subRespHeaderStartFound == true - if (!subRespHeaderEndFound) { - if (responseLine.indexOf(HTTP_HEADER_DELIMITER) === -1) { - // Defensive coding to prevent from missing valuable lines. - throw new Error("Invalid state: find non-empty line '" + responseLine + "' without HTTP header delimiter '" + HTTP_HEADER_DELIMITER + "'."); - } - tokens = responseLine.split(HTTP_HEADER_DELIMITER); - deserializedSubResponse.headers.set(tokens[0], tokens[1]); - if (tokens[0] === HeaderConstants.X_MS_ERROR_CODE) { - deserializedSubResponse.errorCode = tokens[1]; - subRespFailed = true; - } + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.containerContext.getAccessPolicy({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + spanOptions: spanOptions + })]; + case 2: + response = _b.sent(); + res = { + _response: response._response, + blobPublicAccess: response.blobPublicAccess, + date: response.date, + etag: response.etag, + errorCode: response.errorCode, + lastModified: response.lastModified, + requestId: response.requestId, + clientRequestId: response.clientRequestId, + signedIdentifiers: [], + version: response.version + }; + for (_i = 0, response_1 = response; _i < response_1.length; _i++) { + identifier = response_1[_i]; + accessPolicy = undefined; + if (identifier.accessPolicy) { + accessPolicy = { + permissions: identifier.accessPolicy.permissions + }; + if (identifier.accessPolicy.expiresOn) { + accessPolicy.expiresOn = new Date(identifier.accessPolicy.expiresOn); } - else { - // Assemble body of sub response. - if (!deserializedSubResponse.bodyAsText) { - deserializedSubResponse.bodyAsText = ""; - } - deserializedSubResponse.bodyAsText += responseLine; + if (identifier.accessPolicy.startsOn) { + accessPolicy.startsOn = new Date(identifier.accessPolicy.startsOn); } - } // Inner for end - if (contentId != NOT_FOUND) { - deserializedSubResponse._request = this.subRequests.get(contentId); - } - if (subRespFailed) { - subResponsesFailedCount++; - } - else { - subResponsesSucceededCount++; } + res.signedIdentifiers.push({ + accessPolicy: accessPolicy, + id: identifier.id + }); } - return [2 /*return*/, { - subResponses: deserializedSubResponses, - subResponsesSucceededCount: subResponsesSucceededCount, - subResponsesFailedCount: subResponsesFailedCount - }]; + return [2 /*return*/, res]; + case 3: + e_57 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_57.message + }); + throw e_57; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; } }); }); }; - return BatchResponseParser; -}()); - -var MutexLockStatus; -(function (MutexLockStatus) { - MutexLockStatus[MutexLockStatus["LOCKED"] = 0] = "LOCKED"; - MutexLockStatus[MutexLockStatus["UNLOCKED"] = 1] = "UNLOCKED"; -})(MutexLockStatus || (MutexLockStatus = {})); -/** - * An async mutex lock. - * - * @export - * @class Mutex - */ -var Mutex = /** @class */ (function () { - function Mutex() { - } /** - * Lock for a specific key. If the lock has been acquired by another customer, then - * will wait until getting the lock. + * Sets the permissions for the specified container. The permissions indicate + * whether blobs in a container may be accessed publicly. * - * @static - * @param {string} key lock key - * @returns {Promise} - * @memberof Mutex + * When you set permissions for a container, the existing permissions are replaced. + * If no access or containerAcl provided, the existing container ACL will be + * removed. + * + * When you establish a stored access policy on a container, it may take up to 30 seconds to take effect. + * During this interval, a shared access signature that is associated with the stored access policy will + * fail with status code 403 (Forbidden), until the access policy becomes active. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-acl + * + * @param {PublicAccessType} [access] The level of public access to data in the container. + * @param {SignedIdentifier[]} [containerAcl] Array of elements each having a unique Id and details of the access policy. + * @param {ContainerSetAccessPolicyOptions} [options] Options to Container Set Access Policy operation. + * @returns {Promise} + * @memberof ContainerClient */ - Mutex.lock = function (key) { + ContainerClient.prototype.setAccessPolicy = function (access, containerAcl, options) { + if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _this = this; - return tslib.__generator(this, function (_a) { - return [2 /*return*/, new Promise(function (resolve) { - if (_this.keys[key] === undefined || _this.keys[key] === MutexLockStatus.UNLOCKED) { - _this.keys[key] = MutexLockStatus.LOCKED; - resolve(); - } - else { - _this.onUnlockEvent(key, function () { - _this.keys[key] = MutexLockStatus.LOCKED; - resolve(); + var _a, span, spanOptions, acl, _i, _b, identifier, e_58; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _a = createSpan("ContainerClient-setAccessPolicy", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + acl = []; + for (_i = 0, _b = containerAcl || []; _i < _b.length; _i++) { + identifier = _b[_i]; + acl.push({ + accessPolicy: { + expiresOn: identifier.accessPolicy.expiresOn + ? truncatedISO8061Date(identifier.accessPolicy.expiresOn) + : "", + permissions: identifier.accessPolicy.permissions, + startsOn: identifier.accessPolicy.startsOn + ? truncatedISO8061Date(identifier.accessPolicy.startsOn) + : "" + }, + id: identifier.id }); } - })]; + return [4 /*yield*/, this.containerContext.setAccessPolicy({ + abortSignal: options.abortSignal, + access: access, + containerAcl: acl, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: options.conditions, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_58 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_58.message + }); + throw e_58; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } }); }); }; /** - * Unlock a key. + * Get a {@link BlobLeaseClient} that manages leases on the container. * - * @static - * @param {string} key - * @returns {Promise} - * @memberof Mutex - */ - Mutex.unlock = function (key) { - return tslib.__awaiter(this, void 0, void 0, function () { - var _this = this; - return tslib.__generator(this, function (_a) { - return [2 /*return*/, new Promise(function (resolve) { - if (_this.keys[key] === MutexLockStatus.LOCKED) { - _this.emitUnlockEvent(key); - } - delete _this.keys[key]; - resolve(); - })]; - }); - }); - }; - Mutex.onUnlockEvent = function (key, handler) { - if (this.listeners[key] === undefined) { - this.listeners[key] = [handler]; - } - else { - this.listeners[key].push(handler); - } - }; - Mutex.emitUnlockEvent = function (key) { - var _this = this; - if (this.listeners[key] !== undefined && this.listeners[key].length > 0) { - var handler_1 = this.listeners[key].shift(); - setImmediate(function () { - handler_1.call(_this); - }); - } - }; - Mutex.keys = {}; - Mutex.listeners = {}; - return Mutex; -}()); - -/** - * A BlobBatch represents an aggregated set of operations on blobs. - * Currently, only `delete` and `setAccessTier` are supported. - * - * @export - * @class BlobBatch - */ -var BlobBatch = /** @class */ (function () { - function BlobBatch() { - this.batch = "batch"; - this.batchRequest = new InnerBatchRequest(); - } - /** - * Get the value of Content-Type for a batch request. - * The value must be multipart/mixed with a batch boundary. - * Example: multipart/mixed; boundary=batch_a81786c8-e301-4e42-a729-a32ca24ae252 - */ - BlobBatch.prototype.getMultiPartContentType = function () { - return this.batchRequest.getMultipartContentType(); - }; - /** - * Get assembled HTTP request body for sub requests. + * @param {string} [proposeLeaseId] Initial proposed lease Id. + * @returns {BlobLeaseClient} A new BlobLeaseClient object for managing leases on the container. + * @memberof ContainerClient */ - BlobBatch.prototype.getHttpRequestBody = function () { - return this.batchRequest.getHttpRequestBody(); + ContainerClient.prototype.getBlobLeaseClient = function (proposeLeaseId) { + return new BlobLeaseClient(this, proposeLeaseId); }; /** - * Get sub requests that are added into the batch request. + * Creates a new block blob, or updates the content of an existing block blob. + * + * Updating an existing block blob overwrites any existing metadata on the blob. + * Partial updates are not supported; the content of the existing blob is + * overwritten with the new content. To perform a partial update of a block blob's, + * use {@link BlockBlobClient.stageBlock} and {@link BlockBlobClient.commitBlockList}. + * + * This is a non-parallel uploading method, please use {@link BlockBlobClient.uploadFile}, + * {@link BlockBlobClient.uploadStream} or {@link BlockBlobClient.uploadBrowserData} for better + * performance with concurrency uploading. + * + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * + * @param {string} blobName Name of the block blob to create or update. + * @param {HttpRequestBody} body Blob, string, ArrayBuffer, ArrayBufferView or a function + * which returns a new Readable stream whose offset is from data source beginning. + * @param {number} contentLength Length of body in bytes. Use Buffer.byteLength() to calculate body length for a + * string including non non-Base64/Hex-encoded characters. + * @param {BlockBlobUploadOptions} [options] Options to configure the Block Blob Upload operation. + * @returns {Promise<{ blockBlobClient: BlockBlobClient; response: BlockBlobUploadResponse }>} Block Blob upload response data and the corresponding BlockBlobClient instance. + * @memberof ContainerClient */ - BlobBatch.prototype.getSubRequests = function () { - return this.batchRequest.getSubRequests(); - }; - BlobBatch.prototype.addSubRequestInternal = function (subRequest, assembleSubRequestFunc) { + ContainerClient.prototype.uploadBlockBlob = function (blobName, body, contentLength, options) { + if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, Mutex.lock(this.batch)]; + var _a, span, spanOptions, blockBlobClient, response, e_59; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("ContainerClient-uploadBlockBlob", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; case 1: - _a.sent(); - _a.label = 2; + _b.trys.push([1, 3, 4, 5]); + blockBlobClient = this.getBlockBlobClient(blobName); + return [4 /*yield*/, blockBlobClient.upload(body, contentLength, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: - _a.trys.push([2, , 4, 6]); - this.batchRequest.preAddSubRequest(subRequest); - return [4 /*yield*/, assembleSubRequestFunc()]; + response = _b.sent(); + return [2 /*return*/, { + blockBlobClient: blockBlobClient, + response: response + }]; case 3: - _a.sent(); - this.batchRequest.postAddSubRequest(subRequest); - return [3 /*break*/, 6]; - case 4: return [4 /*yield*/, Mutex.unlock(this.batch)]; - case 5: - _a.sent(); + e_59 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_59.message + }); + throw e_59; + case 4: + span.end(); return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; + case 5: return [2 /*return*/]; } }); }); }; - BlobBatch.prototype.setBatchType = function (batchType) { - if (!this.batchType) { - this.batchType = batchType; - } - if (this.batchType !== batchType) { - throw new RangeError("BlobBatch only supports one operation type per batch and it already is being used for " + this.batchType + " operations."); - } - }; - BlobBatch.prototype.deleteBlob = function (urlOrBlobClient, credentialOrOptions, options) { + /** + * Marks the specified blob or snapshot for deletion. The blob is later deleted + * during garbage collection. Note that in order to delete a blob, you must delete + * all of its snapshots. You can delete both at the same time with the Delete + * Blob operation. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob + * + * @param {string} blobName + * @param {ContainerDeleteBlobOptions} [options] Options to Blob Delete operation. + * @returns {Promise} Block blob deletion response data. + * @memberof ContainerClient + */ + ContainerClient.prototype.deleteBlob = function (blobName, options) { + if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var url, credential, _a, span, spanOptions, e_1; - var _this = this; + var _a, span, spanOptions, blobClient, e_60; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - if (typeof urlOrBlobClient === "string" && - ((coreHttp.isNode && credentialOrOptions instanceof StorageSharedKeyCredential) || - credentialOrOptions instanceof AnonymousCredential || - coreHttp.isTokenCredential(credentialOrOptions))) { - // First overload - url = urlOrBlobClient; - credential = credentialOrOptions; - } - else if (urlOrBlobClient instanceof BlobClient) { - // Second overload - url = urlOrBlobClient.url; - credential = urlOrBlobClient.credential; - options = credentialOrOptions; - } - else { - throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); - } - if (!options) { - options = {}; - } - _a = createSpan("BatchDeleteRequest-addSubRequest", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("ContainerClient-deleteBlob", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - this.setBatchType("delete"); - return [4 /*yield*/, this.addSubRequestInternal({ - url: url, - credential: credential - }, function () { return tslib.__awaiter(_this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, new BlobClient(url, this.batchRequest.createPipeline(credential)).delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); })]; - case 2: - _b.sent(); - return [3 /*break*/, 5]; + blobClient = this.getBlobClient(blobName); + if (options.versionId) { + blobClient = blobClient.withVersion(options.versionId); + } + return [4 /*yield*/, blobClient.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: return [2 /*return*/, _b.sent()]; case 3: - e_1 = _b.sent(); + e_60 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_1.message + message: e_60.message }); - throw e_1; + throw e_60; case 4: span.end(); return [7 /*endfinally*/]; @@ -33090,63 +33480,44 @@ var BlobBatch = /** @class */ (function () { }); }); }; - BlobBatch.prototype.setBlobAccessTier = function (urlOrBlobClient, credentialOrTier, tierOrOptions, options) { + /** + * listBlobFlatSegment returns a single segment of blobs starting from the + * specified Marker. Use an empty Marker to start enumeration from the beginning. + * After getting a segment, process it, and then call listBlobsFlatSegment again + * (passing the the previously-returned Marker) to get the next segment. + * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs + * + * @param {string} [marker] A string value that identifies the portion of the list to be returned with the next list operation. + * @param {ContainerListBlobsSegmentOptions} [options] Options to Container List Blob Flat Segment operation. + * @returns {Promise} + * @memberof ContainerClient + */ + ContainerClient.prototype.listBlobFlatSegment = function (marker, options) { + if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var url, credential, tier, _a, span, spanOptions, e_2; - var _this = this; + var _a, span, spanOptions, response, wrappedResponse, e_61; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - if (typeof urlOrBlobClient === "string" && - ((coreHttp.isNode && credentialOrTier instanceof StorageSharedKeyCredential) || - credentialOrTier instanceof AnonymousCredential || - coreHttp.isTokenCredential(credentialOrTier))) { - // First overload - url = urlOrBlobClient; - credential = credentialOrTier; - tier = tierOrOptions; - } - else if (urlOrBlobClient instanceof BlobClient) { - // Second overload - url = urlOrBlobClient.url; - credential = urlOrBlobClient.credential; - tier = credentialOrTier; - options = tierOrOptions; - } - else { - throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); - } - if (!options) { - options = {}; - } - _a = createSpan("BatchSetTierRequest-addSubRequest", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("ContainerClient-listBlobFlatSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - this.setBatchType("setAccessTier"); - return [4 /*yield*/, this.addSubRequestInternal({ - url: url, - credential: credential - }, function () { return tslib.__awaiter(_this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, new BlobClient(url, this.batchRequest.createPipeline(credential)).setAccessTier(tier, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); })]; + return [4 /*yield*/, this.containerContext.listBlobFlatSegment(tslib.__assign(tslib.__assign({ marker: marker }, options), { spanOptions: spanOptions }))]; case 2: - _b.sent(); - return [3 /*break*/, 5]; + response = _b.sent(); + wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, segment: tslib.__assign(tslib.__assign({}, response.segment), { blobItems: response.segment.blobItems.map(function (blobItemInteral) { + var blobItem = tslib.__assign(tslib.__assign({}, blobItemInteral), { tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); + return blobItem; + }) }) }); + return [2 /*return*/, wrappedResponse]; case 3: - e_2 = _b.sent(); + e_61 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_2.message + message: e_61.message }); - throw e_2; + throw e_61; case 4: span.end(); return [7 /*endfinally*/]; @@ -33155,648 +33526,963 @@ var BlobBatch = /** @class */ (function () { }); }); }; - return BlobBatch; -}()); -/** - * Inner batch request class which is responsible for assembling and serializing sub requests. - * See https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#request-body for how requests are assembled. - */ -var InnerBatchRequest = /** @class */ (function () { - function InnerBatchRequest() { - this.operationCount = 0; - this.body = ""; - var tempGuid = coreHttp.generateUuid(); - // batch_{batchid} - this.boundary = "batch_" + tempGuid; - // --batch_{batchid} - // Content-Type: application/http - // Content-Transfer-Encoding: binary - this.subRequestPrefix = "--" + this.boundary + HTTP_LINE_ENDING + HeaderConstants.CONTENT_TYPE + ": application/http" + HTTP_LINE_ENDING + HeaderConstants.CONTENT_TRANSFER_ENCODING + ": binary"; - // multipart/mixed; boundary=batch_{batchid} - this.multipartContentType = "multipart/mixed; boundary=" + this.boundary; - // --batch_{batchid}-- - this.batchRequestEnding = "--" + this.boundary + "--"; - this.subRequests = new Map(); - } /** - * Create pipeline to assemble sub requests. The idea here is to use existing - * credential and serialization/deserialization components, with additional policies to - * filter unnecessary headers, assemble sub requests into request's body - * and intercept request from going to wire. - * @param {StorageSharedKeyCredential | AnonymousCredential | TokenCredential} credential Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the @azure/identity package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used. - */ - InnerBatchRequest.prototype.createPipeline = function (credential) { - var isAnonymousCreds = credential instanceof AnonymousCredential; - var policyFactoryLength = 3 + (isAnonymousCreds ? 0 : 1); // [deserializationPolicy, BatchHeaderFilterPolicyFactory, (Optional)Credential, BatchRequestAssemblePolicyFactory] - var factories = new Array(policyFactoryLength); - factories[0] = coreHttp.deserializationPolicy(); // Default deserializationPolicy is provided by protocol layer - factories[1] = new BatchHeaderFilterPolicyFactory(); // Use batch header filter policy to exclude unnecessary headers - if (!isAnonymousCreds) { - factories[2] = coreHttp.isTokenCredential(credential) - ? coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes) - : credential; - } - factories[policyFactoryLength - 1] = new BatchRequestAssemblePolicyFactory(this); // Use batch assemble policy to assemble request and intercept request from going to wire - return new Pipeline(factories, {}); - }; - InnerBatchRequest.prototype.appendSubRequestToBody = function (request) { - // Start to assemble sub request - this.body += [ - this.subRequestPrefix, - HeaderConstants.CONTENT_ID + ": " + this.operationCount, - "", - request.method.toString() + " " + getURLPathAndQuery(request.url) + " " + HTTP_VERSION_1_1 + HTTP_LINE_ENDING // sub request start line with method - ].join(HTTP_LINE_ENDING); - for (var _i = 0, _a = request.headers.headersArray(); _i < _a.length; _i++) { - var header = _a[_i]; - this.body += header.name + ": " + header.value + HTTP_LINE_ENDING; - } - this.body += HTTP_LINE_ENDING; // sub request's headers need be ending with an empty line - // No body to assemble for current batch request support - // End to assemble sub request - }; - InnerBatchRequest.prototype.preAddSubRequest = function (subRequest) { - if (this.operationCount >= BATCH_MAX_REQUEST) { - throw new RangeError("Cannot exceed " + BATCH_MAX_REQUEST + " sub requests in a single batch"); - } - // Fast fail if url for sub request is invalid - var path = getURLPath(subRequest.url); - if (!path || path == "") { - throw new RangeError("Invalid url for sub request: '" + subRequest.url + "'"); - } - }; - InnerBatchRequest.prototype.postAddSubRequest = function (subRequest) { - this.subRequests.set(this.operationCount, subRequest); - this.operationCount++; - }; - // Return the http request body with assembling the ending line to the sub request body. - InnerBatchRequest.prototype.getHttpRequestBody = function () { - return "" + this.body + this.batchRequestEnding + HTTP_LINE_ENDING; - }; - InnerBatchRequest.prototype.getMultipartContentType = function () { - return this.multipartContentType; - }; - InnerBatchRequest.prototype.getSubRequests = function () { - return this.subRequests; - }; - return InnerBatchRequest; -}()); -var BatchRequestAssemblePolicy = /** @class */ (function (_super) { - tslib.__extends(BatchRequestAssemblePolicy, _super); - function BatchRequestAssemblePolicy(batchRequest, nextPolicy, options) { - var _this = _super.call(this, nextPolicy, options) || this; - _this.dummyResponse = { - request: new coreHttp.WebResource(), - status: 200, - headers: new coreHttp.HttpHeaders() - }; - _this.batchRequest = batchRequest; - return _this; - } - BatchRequestAssemblePolicy.prototype.sendRequest = function (request) { + * listBlobHierarchySegment returns a single segment of blobs starting from + * the specified Marker. Use an empty Marker to start enumeration from the + * beginning. After getting a segment, process it, and then call listBlobsHierarchicalSegment + * again (passing the the previously-returned Marker) to get the next segment. + * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs + * + * @param {string} delimiter The character or string used to define the virtual hierarchy + * @param {string} [marker] A string value that identifies the portion of the list to be returned with the next list operation. + * @param {ContainerListBlobsSegmentOptions} [options] Options to Container List Blob Hierarchy Segment operation. + * @returns {Promise} + * @memberof ContainerClient + */ + ContainerClient.prototype.listBlobHierarchySegment = function (delimiter, marker, options) { + if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, response, wrappedResponse, e_62; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("ContainerClient-listBlobHierarchySegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.containerContext.listBlobHierarchySegment(delimiter, tslib.__assign(tslib.__assign({ marker: marker }, options), { spanOptions: spanOptions }))]; + case 2: + response = _b.sent(); + wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, segment: tslib.__assign(tslib.__assign({}, response.segment), { blobItems: response.segment.blobItems.map(function (blobItemInteral) { + var blobItem = tslib.__assign(tslib.__assign({}, blobItemInteral), { tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); + return blobItem; + }) }) }); + return [2 /*return*/, wrappedResponse]; + case 3: + e_62 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_62.message + }); + throw e_62; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an AsyncIterableIterator for ContainerListBlobFlatSegmentResponse + * + * @private + * @param {string} [marker] A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the ContinuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The ContinuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. + * @returns {AsyncIterableIterator} + * @memberof ContainerClient + */ + ContainerClient.prototype.listSegments = function (marker, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listSegments_1() { + var listBlobsFlatSegmentResponse; return tslib.__generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, this.batchRequest.appendSubRequestToBody(request)]; - case 1: + case 0: + if (!(!!marker || marker === undefined)) return [3 /*break*/, 7]; + _a.label = 1; + case 1: return [4 /*yield*/, tslib.__await(this.listBlobFlatSegment(marker, options))]; + case 2: + listBlobsFlatSegmentResponse = _a.sent(); + marker = listBlobsFlatSegmentResponse.continuationToken; + return [4 /*yield*/, tslib.__await(listBlobsFlatSegmentResponse)]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_a.sent()])]; + case 4: return [4 /*yield*/, _a.sent()]; + case 5: _a.sent(); - return [2 /*return*/, this.dummyResponse]; // Intercept request from going to wire + _a.label = 6; + case 6: + if (marker) return [3 /*break*/, 1]; + _a.label = 7; + case 7: return [2 /*return*/]; } }); }); }; - return BatchRequestAssemblePolicy; -}(coreHttp.BaseRequestPolicy)); -var BatchRequestAssemblePolicyFactory = /** @class */ (function () { - function BatchRequestAssemblePolicyFactory(batchRequest) { - this.batchRequest = batchRequest; - } - BatchRequestAssemblePolicyFactory.prototype.create = function (nextPolicy, options) { - return new BatchRequestAssemblePolicy(this.batchRequest, nextPolicy, options); - }; - return BatchRequestAssemblePolicyFactory; -}()); -var BatchHeaderFilterPolicy = /** @class */ (function (_super) { - tslib.__extends(BatchHeaderFilterPolicy, _super); - function BatchHeaderFilterPolicy(nextPolicy, options) { - return _super.call(this, nextPolicy, options) || this; - } - BatchHeaderFilterPolicy.prototype.sendRequest = function (request) { - return tslib.__awaiter(this, void 0, void 0, function () { - var xMsHeaderName, _i, _a, header; - return tslib.__generator(this, function (_b) { - xMsHeaderName = ""; - for (_i = 0, _a = request.headers.headersArray(); _i < _a.length; _i++) { - header = _a[_i]; - if (iEqual(header.name, HeaderConstants.X_MS_VERSION)) { - xMsHeaderName = header.name; - } - } - if (xMsHeaderName !== "") { - request.headers.remove(xMsHeaderName); // The subrequests should not have the x-ms-version header. + /** + * Returns an AsyncIterableIterator of {@link BlobItem} objects + * + * @private + * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. + * @returns {AsyncIterableIterator} + * @memberof ContainerClient + */ + ContainerClient.prototype.listItems = function (options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listItems_1() { + var marker, _a, _b, listBlobsFlatSegmentResponse, e_63_1; + var e_63, _c; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _d.trys.push([0, 7, 8, 13]); + _a = tslib.__asyncValues(this.listSegments(marker, options)); + _d.label = 1; + case 1: return [4 /*yield*/, tslib.__await(_a.next())]; + case 2: + if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; + listBlobsFlatSegmentResponse = _b.value; + return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(listBlobsFlatSegmentResponse.segment.blobItems)))]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; + case 4: + _d.sent(); + _d.label = 5; + case 5: return [3 /*break*/, 1]; + case 6: return [3 /*break*/, 13]; + case 7: + e_63_1 = _d.sent(); + e_63 = { error: e_63_1 }; + return [3 /*break*/, 13]; + case 8: + _d.trys.push([8, , 11, 12]); + if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; + return [4 /*yield*/, tslib.__await(_c.call(_a))]; + case 9: + _d.sent(); + _d.label = 10; + case 10: return [3 /*break*/, 12]; + case 11: + if (e_63) throw e_63.error; + return [7 /*endfinally*/]; + case 12: return [7 /*endfinally*/]; + case 13: return [2 /*return*/]; } - return [2 /*return*/, this._nextPolicy.sendRequest(request)]; }); }); }; - return BatchHeaderFilterPolicy; -}(coreHttp.BaseRequestPolicy)); -var BatchHeaderFilterPolicyFactory = /** @class */ (function () { - function BatchHeaderFilterPolicyFactory() { - } - BatchHeaderFilterPolicyFactory.prototype.create = function (nextPolicy, options) { - return new BatchHeaderFilterPolicy(nextPolicy, options); - }; - return BatchHeaderFilterPolicyFactory; -}()); - -// Copyright (c) Microsoft Corporation. All rights reserved. -/** - * A BlobBatchClient allows you to make batched requests to the Azure Storage Blob service. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch - */ -var BlobBatchClient = /** @class */ (function () { - function BlobBatchClient(url, credentialOrPipeline, options) { - var pipeline; - if (credentialOrPipeline instanceof Pipeline) { - pipeline = credentialOrPipeline; + /** + * Returns an async iterable iterator to list all the blobs + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the blobs in pages. + * + * Example using `for await` syntax: + * + * ```js + * // Get the containerClient before you run these snippets, + * // Can be obtained from `blobServiceClient.getContainerClient("");` + * let i = 1; + * for await (const blob of containerClient.listBlobsFlat()) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * let iter = containerClient.listBlobsFlat(); + * let blobItem = await iter.next(); + * while (!blobItem.done) { + * console.log(`Blob ${i++}: ${blobItem.value.name}`); + * blobItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of containerClient.listBlobsFlat().byPage({ maxPageSize: 20 })) { + * for (const blob of response.segment.blobItems) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = containerClient.listBlobsFlat().byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 blob names + * for (const blob of response.segment.blobItems) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * + * // Passing next marker as continuationToken + * + * iterator = containerClient.listBlobsFlat().byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints 10 blob names + * for (const blob of response.segment.blobItems) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * ``` + * + * @param {ContainerListBlobsOptions} [options={}] Options to list blobs. + * @returns {PagedAsyncIterableIterator} An asyncIterableIterator that supports paging. + * @memberof ContainerClient + */ + ContainerClient.prototype.listBlobsFlat = function (options) { + var _a; + var _this = this; + if (options === void 0) { options = {}; } + var include = []; + if (options.includeCopy) { + include.push("copy"); } - else if (!credentialOrPipeline) { - // no credential provided - pipeline = newPipeline(new AnonymousCredential(), options); + if (options.includeDeleted) { + include.push("deleted"); } - else { - pipeline = newPipeline(credentialOrPipeline, options); + if (options.includeMetadata) { + include.push("metadata"); } - var storageClientContext = new StorageClientContext(url, pipeline.toServiceClientOptions()); - this._serviceContext = new Service(storageClientContext); - } + if (options.includeSnapshots) { + include.push("snapshots"); + } + if (options.includeVersions) { + include.push("versions"); + } + if (options.includeUncommitedBlobs) { + include.push("uncommittedblobs"); + } + if (options.includeTags) { + include.push("tags"); + } + if (options.prefix === "") { + options.prefix = undefined; + } + var updatedOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); + // AsyncIterableIterator to iterate over blobs + var iter = this.listItems(updatedOptions); + return _a = { + /** + * @member {Promise} [next] The next method, part of the iteration protocol + */ + next: function () { + return iter.next(); + } + }, + /** + * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol + */ + _a[Symbol.asyncIterator] = function () { + return this; + }, + /** + * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time + */ + _a.byPage = function (settings) { + if (settings === void 0) { settings = {}; } + return _this.listSegments(settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); + }, + _a; + }; /** - * Creates a {@link BlobBatch}. - * A BlobBatch represents an aggregated set of operations on blobs. + * Returns an AsyncIterableIterator for ContainerListBlobHierarchySegmentResponse + * + * @private + * @param {string} delimiter The character or string used to define the virtual hierarchy + * @param {string} [marker] A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the ContinuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The ContinuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. + * @returns {AsyncIterableIterator} + * @memberof ContainerClient */ - BlobBatchClient.prototype.createBatch = function () { - return new BlobBatch(); - }; - BlobBatchClient.prototype.deleteBlobs = function (urlsOrBlobClients, credentialOrOptions, options) { - return tslib.__awaiter(this, void 0, void 0, function () { - var batch, _i, urlsOrBlobClients_1, urlOrBlobClient; + ContainerClient.prototype.listHierarchySegments = function (delimiter, marker, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listHierarchySegments_1() { + var listBlobsHierarchySegmentResponse; return tslib.__generator(this, function (_a) { switch (_a.label) { case 0: - batch = new BlobBatch(); - _i = 0, urlsOrBlobClients_1 = urlsOrBlobClients; + if (!(!!marker || marker === undefined)) return [3 /*break*/, 7]; _a.label = 1; - case 1: - if (!(_i < urlsOrBlobClients_1.length)) return [3 /*break*/, 6]; - urlOrBlobClient = urlsOrBlobClients_1[_i]; - if (!(typeof urlOrBlobClient === "string")) return [3 /*break*/, 3]; - return [4 /*yield*/, batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options)]; + case 1: return [4 /*yield*/, tslib.__await(this.listBlobHierarchySegment(delimiter, marker, options))]; case 2: - _a.sent(); - return [3 /*break*/, 5]; - case 3: return [4 /*yield*/, batch.deleteBlob(urlOrBlobClient, credentialOrOptions)]; - case 4: - _a.sent(); - _a.label = 5; + listBlobsHierarchySegmentResponse = _a.sent(); + marker = listBlobsHierarchySegmentResponse.continuationToken; + return [4 /*yield*/, tslib.__await(listBlobsHierarchySegmentResponse)]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_a.sent()])]; + case 4: return [4 /*yield*/, _a.sent()]; case 5: - _i++; - return [3 /*break*/, 1]; - case 6: return [2 /*return*/, this.submitBatch(batch)]; + _a.sent(); + _a.label = 6; + case 6: + if (marker) return [3 /*break*/, 1]; + _a.label = 7; + case 7: return [2 /*return*/]; } }); }); }; - BlobBatchClient.prototype.setBlobsAccessTier = function (urlsOrBlobClients, credentialOrTier, tierOrOptions, options) { - return tslib.__awaiter(this, void 0, void 0, function () { - var batch, _i, urlsOrBlobClients_2, urlOrBlobClient; - return tslib.__generator(this, function (_a) { - switch (_a.label) { + /** + * Returns an AsyncIterableIterator for {@link BlobPrefix} and {@link BlobItem} objects. + * + * @private + * @param {string} delimiter The character or string used to define the virtual hierarchy + * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. + * @returns {AsyncIterableIterator<{ kind: "prefix" } & BlobPrefix | { kind: "blob" } & BlobItem>} + * @memberof ContainerClient + */ + ContainerClient.prototype.listItemsByHierarchy = function (delimiter, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listItemsByHierarchy_1() { + var marker, _a, _b, listBlobsHierarchySegmentResponse, segment, _i, _c, prefix, _d, _e, blob, e_64_1; + var e_64, _f; + return tslib.__generator(this, function (_g) { + switch (_g.label) { case 0: - batch = new BlobBatch(); - _i = 0, urlsOrBlobClients_2 = urlsOrBlobClients; - _a.label = 1; - case 1: - if (!(_i < urlsOrBlobClients_2.length)) return [3 /*break*/, 6]; - urlOrBlobClient = urlsOrBlobClients_2[_i]; - if (!(typeof urlOrBlobClient === "string")) return [3 /*break*/, 3]; - return [4 /*yield*/, batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options)]; + _g.trys.push([0, 14, 15, 20]); + _a = tslib.__asyncValues(this.listHierarchySegments(delimiter, marker, options)); + _g.label = 1; + case 1: return [4 /*yield*/, tslib.__await(_a.next())]; case 2: - _a.sent(); - return [3 /*break*/, 5]; - case 3: return [4 /*yield*/, batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions)]; - case 4: - _a.sent(); - _a.label = 5; + if (!(_b = _g.sent(), !_b.done)) return [3 /*break*/, 13]; + listBlobsHierarchySegmentResponse = _b.value; + segment = listBlobsHierarchySegmentResponse.segment; + if (!segment.blobPrefixes) return [3 /*break*/, 7]; + _i = 0, _c = segment.blobPrefixes; + _g.label = 3; + case 3: + if (!(_i < _c.length)) return [3 /*break*/, 7]; + prefix = _c[_i]; + return [4 /*yield*/, tslib.__await(tslib.__assign({ kind: "prefix" }, prefix))]; + case 4: return [4 /*yield*/, _g.sent()]; case 5: + _g.sent(); + _g.label = 6; + case 6: _i++; - return [3 /*break*/, 1]; - case 6: return [2 /*return*/, this.submitBatch(batch)]; + return [3 /*break*/, 3]; + case 7: + _d = 0, _e = segment.blobItems; + _g.label = 8; + case 8: + if (!(_d < _e.length)) return [3 /*break*/, 12]; + blob = _e[_d]; + return [4 /*yield*/, tslib.__await(tslib.__assign({ kind: "blob" }, blob))]; + case 9: return [4 /*yield*/, _g.sent()]; + case 10: + _g.sent(); + _g.label = 11; + case 11: + _d++; + return [3 /*break*/, 8]; + case 12: return [3 /*break*/, 1]; + case 13: return [3 /*break*/, 20]; + case 14: + e_64_1 = _g.sent(); + e_64 = { error: e_64_1 }; + return [3 /*break*/, 20]; + case 15: + _g.trys.push([15, , 18, 19]); + if (!(_b && !_b.done && (_f = _a.return))) return [3 /*break*/, 17]; + return [4 /*yield*/, tslib.__await(_f.call(_a))]; + case 16: + _g.sent(); + _g.label = 17; + case 17: return [3 /*break*/, 19]; + case 18: + if (e_64) throw e_64.error; + return [7 /*endfinally*/]; + case 19: return [7 /*endfinally*/]; + case 20: return [2 /*return*/]; } }); }); }; /** - * Submit batch request which consists of multiple subrequests. + * Returns an async iterable iterator to list all the blobs by hierarchy. + * under the specified account. * - * Get `blobBatchClient` and other details before running the snippets. - * `blobServiceClient.getBlobBatchClient()` gives the `blobBatchClient` + * .byPage() returns an async iterable iterator to list the blobs by hierarchy in pages. * - * Example usage: + * Example using `for await` syntax: * * ```js - * let batchRequest = new BlobBatch(); - * await batchRequest.deleteBlob(urlInString0, credential0); - * await batchRequest.deleteBlob(urlInString1, credential1, { - * deleteSnapshots: "include" - * }); - * const batchResp = await blobBatchClient.submitBatch(batchRequest); - * console.log(batchResp.subResponsesSucceededCount); + * for await (const item of containerClient.listBlobsByHierarchy("/")) { + * if (item.kind === "prefix") { + * console.log(`\tBlobPrefix: ${item.name}`); + * } else { + * console.log(`\tBlobItem: name - ${item.name}, last modified - ${item.properties.lastModified}`); + * } + * } * ``` * - * Example using a lease: + * Example using `iter.next()`: * * ```js - * let batchRequest = new BlobBatch(); - * await batchRequest.setBlobAccessTier(blockBlobClient0, "Cool"); - * await batchRequest.setBlobAccessTier(blockBlobClient1, "Cool", { - * conditions: { leaseId: leaseId } - * }); - * const batchResp = await blobBatchClient.submitBatch(batchRequest); - * console.log(batchResp.subResponsesSucceededCount); + * let iter = containerClient.listBlobsByHierarchy("/", { prefix: "prefix1/" }); + * let entity = await iter.next(); + * while (!entity.done) { + * let item = entity.value; + * if (item.kind === "prefix") { + * console.log(`\tBlobPrefix: ${item.name}`); + * } else { + * console.log(`\tBlobItem: name - ${item.name}, last modified - ${item.properties.lastModified}`); + * } + * entity = await iter.next(); + * } * ``` * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch + * Example using `byPage()`: + * + * ```js + * console.log("Listing blobs by hierarchy by page"); + * for await (const response of containerClient.listBlobsByHierarchy("/").byPage()) { + * const segment = response.segment; + * if (segment.blobPrefixes) { + * for (const prefix of segment.blobPrefixes) { + * console.log(`\tBlobPrefix: ${prefix.name}`); + * } + * } + * for (const blob of response.segment.blobItems) { + * console.log(`\tBlobItem: name - ${blob.name}, last modified - ${blob.properties.lastModified}`); + * } + * } + * ``` + * + * Example using paging with a max page size: + * + * ```js + * console.log("Listing blobs by hierarchy by page, specifying a prefix and a max page size"); + * + * let i = 1; + * for await (const response of containerClient.listBlobsByHierarchy("/", { prefix: "prefix2/sub1/"}).byPage({ maxPageSize: 2 })) { + * console.log(`Page ${i++}`); + * const segment = response.segment; + * + * if (segment.blobPrefixes) { + * for (const prefix of segment.blobPrefixes) { + * console.log(`\tBlobPrefix: ${prefix.name}`); + * } + * } + * + * for (const blob of response.segment.blobItems) { + * console.log(`\tBlobItem: name - ${blob.name}, last modified - ${blob.properties.lastModified}`); + * } + * } + * ``` * - * @param {BlobBatch} batchRequest A set of Delete or SetTier operations. - * @param {BlobBatchSubmitBatchOptionalParams} [options] - * @returns {Promise} - * @memberof BlobBatchClient + * @param {string} delimiter The character or string used to define the virtual hierarchy + * @param {ContainerListBlobsOptions} [options={}] Options to list blobs operation. + * @returns {(PagedAsyncIterableIterator< + * { kind: "prefix" } & BlobPrefix | { kind: "blob" } & BlobItem, + * ContainerListBlobHierarchySegmentResponse>)} + * @memberof ContainerClient */ - BlobBatchClient.prototype.submitBatch = function (batchRequest, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, batchRequestBody, rawBatchResponse, batchResponseParser, responseSummary, res, e_1; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!batchRequest || batchRequest.getSubRequests().size == 0) { - throw new RangeError("Batch request should contain one or more sub requests."); - } - _a = createSpan("BlobBatchClient-submitBatch", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 4, 5, 6]); - batchRequestBody = batchRequest.getHttpRequestBody(); - return [4 /*yield*/, this._serviceContext.submitBatch(batchRequestBody, utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), tslib.__assign(tslib.__assign({}, options), { spanOptions: spanOptions }))]; - case 2: - rawBatchResponse = _b.sent(); - batchResponseParser = new BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests()); - return [4 /*yield*/, batchResponseParser.parseBatchResponse()]; - case 3: - responseSummary = _b.sent(); - res = { - _response: rawBatchResponse._response, - contentType: rawBatchResponse.contentType, - errorCode: rawBatchResponse.errorCode, - requestId: rawBatchResponse.requestId, - clientRequestId: rawBatchResponse.clientRequestId, - version: rawBatchResponse.version, - subResponses: responseSummary.subResponses, - subResponsesSucceededCount: responseSummary.subResponsesSucceededCount, - subResponsesFailedCount: responseSummary.subResponsesFailedCount - }; - return [2 /*return*/, res]; - case 4: - e_1 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_1.message - }); - throw e_1; - case 5: - span.end(); - return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; - } - }); - }); - }; - return BlobBatchClient; -}()); - -/** - * A BlobServiceClient represents a Client to the Azure Storage Blob service allowing you - * to manipulate blob containers. - * - * @export - * @class BlobServiceClient - */ -var BlobServiceClient = /** @class */ (function (_super) { - tslib.__extends(BlobServiceClient, _super); - function BlobServiceClient(url, credentialOrPipeline, options) { + ContainerClient.prototype.listBlobsByHierarchy = function (delimiter, options) { + var _a; var _this = this; - var pipeline; - if (credentialOrPipeline instanceof Pipeline) { - pipeline = credentialOrPipeline; + if (options === void 0) { options = {}; } + if (delimiter === "") { + throw new RangeError("delimiter should contain one or more characters"); } - else if ((coreHttp.isNode && credentialOrPipeline instanceof StorageSharedKeyCredential) || - credentialOrPipeline instanceof AnonymousCredential || - coreHttp.isTokenCredential(credentialOrPipeline)) { - pipeline = newPipeline(credentialOrPipeline, options); + var include = []; + if (options.includeCopy) { + include.push("copy"); } - else { - // The second parameter is undefined. Use anonymous credential - pipeline = newPipeline(new AnonymousCredential(), options); + if (options.includeDeleted) { + include.push("deleted"); } - _this = _super.call(this, url, pipeline) || this; - _this.serviceContext = new Service(_this.storageClientContext); - return _this; - } - /** - * - * Creates an instance of BlobServiceClient from connection string. - * - * @param {string} connectionString Account connection string or a SAS connection string of an Azure storage account. - * [ Note - Account connection string can only be used in NODE.JS runtime. ] - * Account connection string example - - * `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net` - * SAS connection string example - - * `BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString` - * @param {StoragePipelineOptions} [options] Optional. Options to configure the HTTP pipeline. - * @memberof BlobServiceClient - */ - BlobServiceClient.fromConnectionString = function (connectionString, options) { - options = options || {}; - var extractedCreds = extractConnectionStringParts(connectionString); - if (extractedCreds.kind === "AccountConnString") { - { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); - var pipeline = newPipeline(sharedKeyCredential, options); - return new BlobServiceClient(extractedCreds.url, pipeline); - } + if (options.includeMetadata) { + include.push("metadata"); } - else if (extractedCreds.kind === "SASConnString") { - var pipeline = newPipeline(new AnonymousCredential(), options); - return new BlobServiceClient(extractedCreds.url + "?" + extractedCreds.accountSas, pipeline); + if (options.includeSnapshots) { + include.push("snapshots"); } - else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + if (options.includeVersions) { + include.push("versions"); + } + if (options.includeUncommitedBlobs) { + include.push("uncommittedblobs"); + } + if (options.includeTags) { + include.push("tags"); + } + if (options.prefix === "") { + options.prefix = undefined; + } + var updatedOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); + // AsyncIterableIterator to iterate over blob prefixes and blobs + var iter = this.listItemsByHierarchy(delimiter, updatedOptions); + return _a = { + /** + * @member {Promise} [next] The next method, part of the iteration protocol + */ + next: function () { + return tslib.__awaiter(this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + return [2 /*return*/, iter.next()]; + }); + }); + } + }, + /** + * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol + */ + _a[Symbol.asyncIterator] = function () { + return this; + }, + /** + * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time + */ + _a.byPage = function (settings) { + if (settings === void 0) { settings = {}; } + return _this.listHierarchySegments(delimiter, settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); + }, + _a; + }; + ContainerClient.prototype.getContainerNameFromUrl = function () { + var containerName; + try { + // URL may look like the following + // "https://myaccount.blob.core.windows.net/mycontainer?sasString"; + // "https://myaccount.blob.core.windows.net/mycontainer"; + // IPv4/IPv6 address hosts, Endpoints - `http://127.0.0.1:10000/devstoreaccount1/containername` + // http://localhost:10001/devstoreaccount1/containername + var parsedUrl = coreHttp.URLBuilder.parse(this.url); + if (parsedUrl.getHost().split(".")[1] === "blob") { + // "https://myaccount.blob.core.windows.net/containername". + // "https://customdomain.com/containername". + // .getPath() -> /containername + containerName = parsedUrl.getPath().split("/")[1]; + } + else if (isIpEndpointStyle(parsedUrl)) { + // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/containername + // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/containername + // .getPath() -> /devstoreaccount1/containername + containerName = parsedUrl.getPath().split("/")[2]; + } + else { + // "https://customdomain.com/containername". + // .getPath() -> /containername + containerName = parsedUrl.getPath().split("/")[1]; + } + // decode the encoded containerName - to get all the special characters that might be present in it + containerName = decodeURIComponent(containerName); + if (!containerName) { + throw new Error("Provided containerName is invalid."); + } + return containerName; + } + catch (error) { + throw new Error("Unable to extract containerName with provided information."); } }; /** - * Creates a {@link ContainerClient} object + * Only available for ContainerClient constructed with a shared key credential. * - * @param {string} containerName A container name - * @returns {ContainerClient} A new ContainerClient object for the given container name. - * @memberof BlobServiceClient + * Generates a Blob Container Service Shared Access Signature (SAS) URI based on the client properties + * and parameters passed in. The SAS is signed by the shared key credential of the client. * - * Example usage: + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * - * ```js - * const containerClient = blobServiceClient.getContainerClient(""); - * ``` + * @param {ContainerGenerateSasUrlOptions} options Optional parameters. + * @returns {Promise} The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + * @memberof ContainerClient */ - BlobServiceClient.prototype.getContainerClient = function (containerName) { - return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline); + ContainerClient.prototype.generateSasUrl = function (options) { + var _this = this; + return new Promise(function (resolve) { + if (!(_this.credential instanceof StorageSharedKeyCredential)) { + throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); + } + var sas = generateBlobSASQueryParameters(tslib.__assign({ containerName: _this._containerName }, options), _this.credential).toString(); + resolve(appendToURLQuery(_this.url, sas)); + }); }; - /** - * Create a Blob container. - * - * @param {string} containerName Name of the container to create. - * @param {ContainerCreateOptions} [options] Options to configure Container Create operation. - * @returns {Promise<{ containerClient: ContainerClient; containerCreateResponse: ContainerCreateResponse }>} Container creation response and the corresponding container client. - * @memberof BlobServiceClient - */ - BlobServiceClient.prototype.createContainer = function (containerName, options) { - if (options === void 0) { options = {}; } + return ContainerClient; +}(StorageClient)); + +function getBodyAsText(batchResponse) { + return tslib.__awaiter(this, void 0, void 0, function () { + var buffer, responseLength; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + buffer = Buffer.alloc(BATCH_MAX_PAYLOAD_IN_BYTES); + return [4 /*yield*/, streamToBuffer2(batchResponse.readableStreamBody, buffer)]; + case 1: + responseLength = _a.sent(); + // Slice the buffer to trim the empty ending. + buffer = buffer.slice(0, responseLength); + return [2 /*return*/, buffer.toString()]; + } + }); + }); +} +function utf8ByteLength(str) { + return Buffer.byteLength(str); +} + +var HTTP_HEADER_DELIMITER = ": "; +var SPACE_DELIMITER = " "; +var NOT_FOUND = -1; +/** + * Util class for parsing batch response. + */ +var BatchResponseParser = /** @class */ (function () { + function BatchResponseParser(batchResponse, subRequests) { + if (!batchResponse || !batchResponse.contentType) { + // In special case(reported), server may return invalid content-type which could not be parsed. + throw new RangeError("batchResponse is malformed or doesn't contain valid content-type."); + } + if (!subRequests || subRequests.size === 0) { + // This should be prevent during coding. + throw new RangeError("Invalid state: subRequests is not provided or size is 0."); + } + this.batchResponse = batchResponse; + this.subRequests = subRequests; + this.responseBatchBoundary = this.batchResponse.contentType.split("=")[1]; + this.perResponsePrefix = "--" + this.responseBatchBoundary + HTTP_LINE_ENDING; + this.batchResponseEnding = "--" + this.responseBatchBoundary + "--"; + } + // For example of response, please refer to https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#response + BatchResponseParser.prototype.parseBatchResponse = function () { return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, containerClient, containerCreateResponse, e_1; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var responseBodyAsText, subResponses, subResponseCount, deserializedSubResponses, subResponsesSucceededCount, subResponsesFailedCount, index, subResponse, deserializedSubResponse, responseLines, subRespHeaderStartFound, subRespHeaderEndFound, subRespFailed, contentId, _i, responseLines_1, responseLine, tokens, tokens; + return tslib.__generator(this, function (_a) { + switch (_a.label) { case 0: - _a = createSpan("BlobServiceClient-createContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + // When logic reach here, suppose batch request has already succeeded with 202, so we can further parse + // sub request's response. + if (this.batchResponse._response.status != HTTPURLConnection.HTTP_ACCEPTED) { + throw new Error("Invalid state: batch request failed with status: '" + this.batchResponse._response.status + "'."); + } + return [4 /*yield*/, getBodyAsText(this.batchResponse)]; case 1: - _b.trys.push([1, 3, 4, 5]); - containerClient = this.getContainerClient(containerName); - return [4 /*yield*/, containerClient.create(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: - containerCreateResponse = _b.sent(); + responseBodyAsText = _a.sent(); + subResponses = responseBodyAsText + .split(this.batchResponseEnding)[0] // string after ending is useless + .split(this.perResponsePrefix) + .slice(1); + subResponseCount = subResponses.length; + // Defensive coding in case of potential error parsing. + // Note: subResponseCount == 1 is special case where sub request is invalid. + // We try to prevent such cases through early validation, e.g. validate sub request count >= 1. + // While in unexpected sub request invalid case, we allow sub response to be parsed and return to user. + if (subResponseCount != this.subRequests.size && subResponseCount != 1) { + throw new Error("Invalid state: sub responses' count is not equal to sub requests' count."); + } + deserializedSubResponses = new Array(subResponseCount); + subResponsesSucceededCount = 0; + subResponsesFailedCount = 0; + // Parse sub subResponses. + for (index = 0; index < subResponseCount; index++) { + subResponse = subResponses[index]; + deserializedSubResponse = {}; + deserializedSubResponse.headers = new coreHttp.HttpHeaders(); + responseLines = subResponse.split("" + HTTP_LINE_ENDING); + subRespHeaderStartFound = false; + subRespHeaderEndFound = false; + subRespFailed = false; + contentId = NOT_FOUND; + for (_i = 0, responseLines_1 = responseLines; _i < responseLines_1.length; _i++) { + responseLine = responseLines_1[_i]; + if (!subRespHeaderStartFound) { + // Convention line to indicate content ID + if (responseLine.startsWith(HeaderConstants.CONTENT_ID)) { + contentId = parseInt(responseLine.split(HTTP_HEADER_DELIMITER)[1]); + } + // Http version line with status code indicates the start of sub request's response. + // Example: HTTP/1.1 202 Accepted + if (responseLine.startsWith(HTTP_VERSION_1_1)) { + subRespHeaderStartFound = true; + tokens = responseLine.split(SPACE_DELIMITER); + deserializedSubResponse.status = parseInt(tokens[1]); + deserializedSubResponse.statusMessage = tokens.slice(2).join(SPACE_DELIMITER); + } + continue; // Skip convention headers not specifically for sub request i.e. Content-Type: application/http and Content-ID: * + } + if (responseLine.trim() === "") { + // Sub response's header start line already found, and the first empty line indicates header end line found. + if (!subRespHeaderEndFound) { + subRespHeaderEndFound = true; + } + continue; // Skip empty line + } + // Note: when code reach here, it indicates subRespHeaderStartFound == true + if (!subRespHeaderEndFound) { + if (responseLine.indexOf(HTTP_HEADER_DELIMITER) === -1) { + // Defensive coding to prevent from missing valuable lines. + throw new Error("Invalid state: find non-empty line '" + responseLine + "' without HTTP header delimiter '" + HTTP_HEADER_DELIMITER + "'."); + } + tokens = responseLine.split(HTTP_HEADER_DELIMITER); + deserializedSubResponse.headers.set(tokens[0], tokens[1]); + if (tokens[0] === HeaderConstants.X_MS_ERROR_CODE) { + deserializedSubResponse.errorCode = tokens[1]; + subRespFailed = true; + } + } + else { + // Assemble body of sub response. + if (!deserializedSubResponse.bodyAsText) { + deserializedSubResponse.bodyAsText = ""; + } + deserializedSubResponse.bodyAsText += responseLine; + } + } // Inner for end + // The response will contain the Content-ID header for each corresponding subrequest response to use for tracking. + // The Content-IDs are set to a valid index in the subrequests we sent. In the status code 202 path, we could expect it + // to be 1-1 mapping from the [0, subRequests.size) to the Content-IDs returned. If not, we simply don't return that + // unexpected subResponse in the parsed reponse and we can always look it up in the raw response for debugging purpose. + if (contentId != NOT_FOUND && + Number.isInteger(contentId) && + contentId >= 0 && + contentId < this.subRequests.size && + deserializedSubResponses[contentId] === undefined) { + deserializedSubResponse._request = this.subRequests.get(contentId); + deserializedSubResponses[contentId] = deserializedSubResponse; + } + else { + logger.error("subResponses[" + index + "] is dropped as the Content-ID is not found or invalid, Content-ID: " + contentId); + } + if (subRespFailed) { + subResponsesFailedCount++; + } + else { + subResponsesSucceededCount++; + } + } return [2 /*return*/, { - containerClient: containerClient, - containerCreateResponse: containerCreateResponse + subResponses: deserializedSubResponses, + subResponsesSucceededCount: subResponsesSucceededCount, + subResponsesFailedCount: subResponsesFailedCount }]; - case 3: - e_1 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_1.message - }); - throw e_1; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; } }); }); }; + return BatchResponseParser; +}()); + +var MutexLockStatus; +(function (MutexLockStatus) { + MutexLockStatus[MutexLockStatus["LOCKED"] = 0] = "LOCKED"; + MutexLockStatus[MutexLockStatus["UNLOCKED"] = 1] = "UNLOCKED"; +})(MutexLockStatus || (MutexLockStatus = {})); +/** + * An async mutex lock. + * + * @export + * @class Mutex + */ +var Mutex = /** @class */ (function () { + function Mutex() { + } /** - * Deletes a Blob container. + * Lock for a specific key. If the lock has been acquired by another customer, then + * will wait until getting the lock. * - * @param {string} containerName Name of the container to delete. - * @param {ContainerDeleteMethodOptions} [options] Options to configure Container Delete operation. - * @returns {Promise} Container deletion response. - * @memberof BlobServiceClient + * @static + * @param {string} key lock key + * @returns {Promise} + * @memberof Mutex */ - BlobServiceClient.prototype.deleteContainer = function (containerName, options) { - if (options === void 0) { options = {}; } + Mutex.lock = function (key) { return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, containerClient, e_2; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-deleteContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - containerClient = this.getContainerClient(containerName); - return [4 /*yield*/, containerClient.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_2 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_2.message - }); - throw e_2; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + var _this = this; + return tslib.__generator(this, function (_a) { + return [2 /*return*/, new Promise(function (resolve) { + if (_this.keys[key] === undefined || _this.keys[key] === MutexLockStatus.UNLOCKED) { + _this.keys[key] = MutexLockStatus.LOCKED; + resolve(); + } + else { + _this.onUnlockEvent(key, function () { + _this.keys[key] = MutexLockStatus.LOCKED; + resolve(); + }); + } + })]; }); }); }; /** - * Restore a previously deleted Blob container. - * This API is only functional if Container Soft Delete is enabled for the storage account associated with the container. + * Unlock a key. * - * @param {string} deletedContainerName Name of the previously deleted container. - * @param {string} deletedContainerVersion Version of the previously deleted container, used to uniquely identify the deleted container. - * @returns {Promise} Container deletion response. - * @memberof BlobServiceClient + * @static + * @param {string} key + * @returns {Promise} + * @memberof Mutex */ - BlobServiceClient.prototype.undeleteContainer = function (deletedContainerName, deletedContainerVersion, options) { - if (options === void 0) { options = {}; } + Mutex.unlock = function (key) { return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, containerClient, containerContext, containerUndeleteResponse, e_3; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-undeleteContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - containerClient = this.getContainerClient(options.destinationContainerName || deletedContainerName); - containerContext = new Container(containerClient["storageClientContext"]); - return [4 /*yield*/, containerContext.restore(tslib.__assign(tslib.__assign({ deletedContainerName: deletedContainerName, - deletedContainerVersion: deletedContainerVersion }, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: - containerUndeleteResponse = _b.sent(); - return [2 /*return*/, { containerClient: containerClient, containerUndeleteResponse: containerUndeleteResponse }]; - case 3: - e_3 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_3.message - }); - throw e_3; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + var _this = this; + return tslib.__generator(this, function (_a) { + return [2 /*return*/, new Promise(function (resolve) { + if (_this.keys[key] === MutexLockStatus.LOCKED) { + _this.emitUnlockEvent(key); + } + delete _this.keys[key]; + resolve(); + })]; }); }); }; + Mutex.onUnlockEvent = function (key, handler) { + if (this.listeners[key] === undefined) { + this.listeners[key] = [handler]; + } + else { + this.listeners[key].push(handler); + } + }; + Mutex.emitUnlockEvent = function (key) { + var _this = this; + if (this.listeners[key] !== undefined && this.listeners[key].length > 0) { + var handler_1 = this.listeners[key].shift(); + setImmediate(function () { + handler_1.call(_this); + }); + } + }; + Mutex.keys = {}; + Mutex.listeners = {}; + return Mutex; +}()); + +/** + * A BlobBatch represents an aggregated set of operations on blobs. + * Currently, only `delete` and `setAccessTier` are supported. + * + * @export + * @class BlobBatch + */ +var BlobBatch = /** @class */ (function () { + function BlobBatch() { + this.batch = "batch"; + this.batchRequest = new InnerBatchRequest(); + } /** - * Gets the properties of a storage account’s Blob service, including properties - * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties - * - * @param {ServiceGetPropertiesOptions} [options] Options to the Service Get Properties operation. - * @returns {Promise} Response data for the Service Get Properties operation. - * @memberof BlobServiceClient + * Get the value of Content-Type for a batch request. + * The value must be multipart/mixed with a batch boundary. + * Example: multipart/mixed; boundary=batch_a81786c8-e301-4e42-a729-a32ca24ae252 */ - BlobServiceClient.prototype.getProperties = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_4; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-getProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getProperties({ - abortSignal: options.abortSignal, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_4 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_4.message - }); - throw e_4; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + BlobBatch.prototype.getMultiPartContentType = function () { + return this.batchRequest.getMultipartContentType(); }; /** - * Sets properties for a storage account’s Blob service endpoint, including properties - * for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules and soft delete settings. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties} - * - * @param {BlobServiceProperties} properties - * @param {ServiceSetPropertiesOptions} [options] Options to the Service Set Properties operation. - * @returns {Promise} Response data for the Service Set Properties operation. - * @memberof BlobServiceClient + * Get assembled HTTP request body for sub requests. */ - BlobServiceClient.prototype.setProperties = function (properties, options) { - if (options === void 0) { options = {}; } + BlobBatch.prototype.getHttpRequestBody = function () { + return this.batchRequest.getHttpRequestBody(); + }; + /** + * Get sub requests that are added into the batch request. + */ + BlobBatch.prototype.getSubRequests = function () { + return this.batchRequest.getSubRequests(); + }; + BlobBatch.prototype.addSubRequestInternal = function (subRequest, assembleSubRequestFunc) { return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_5; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-setProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Mutex.lock(this.batch)]; case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.setProperties(properties, { - abortSignal: options.abortSignal, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; + _a.sent(); + _a.label = 2; + case 2: + _a.trys.push([2, , 4, 6]); + this.batchRequest.preAddSubRequest(subRequest); + return [4 /*yield*/, assembleSubRequestFunc()]; case 3: - e_5 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_5.message - }); - throw e_5; - case 4: - span.end(); + _a.sent(); + this.batchRequest.postAddSubRequest(subRequest); + return [3 /*break*/, 6]; + case 4: return [4 /*yield*/, Mutex.unlock(this.batch)]; + case 5: + _a.sent(); return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + case 6: return [2 /*return*/]; } }); }); }; - /** - * Retrieves statistics related to replication for the Blob service. It is only - * available on the secondary location endpoint when read-access geo-redundant - * replication is enabled for the storage account. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-stats} - * - * @param {ServiceGetStatisticsOptions} [options] Options to the Service Get Statistics operation. - * @returns {Promise} Response data for the Service Get Statistics operation. - * @memberof BlobServiceClient - */ - BlobServiceClient.prototype.getStatistics = function (options) { - if (options === void 0) { options = {}; } + BlobBatch.prototype.setBatchType = function (batchType) { + if (!this.batchType) { + this.batchType = batchType; + } + if (this.batchType !== batchType) { + throw new RangeError("BlobBatch only supports one operation type per batch and it already is being used for " + this.batchType + " operations."); + } + }; + BlobBatch.prototype.deleteBlob = function (urlOrBlobClient, credentialOrOptions, options) { return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_6; + var url, credential, _a, span, spanOptions, e_1; + var _this = this; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("BlobServiceClient-getStatistics", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + if (typeof urlOrBlobClient === "string" && + ((coreHttp.isNode && credentialOrOptions instanceof StorageSharedKeyCredential) || + credentialOrOptions instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrOptions))) { + // First overload + url = urlOrBlobClient; + credential = credentialOrOptions; + } + else if (urlOrBlobClient instanceof BlobClient) { + // Second overload + url = urlOrBlobClient.url; + credential = urlOrBlobClient.credential; + options = credentialOrOptions; + } + else { + throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + } + if (!options) { + options = {}; + } + _a = createSpan("BatchDeleteRequest-addSubRequest", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getStatistics({ - abortSignal: options.abortSignal, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; + this.setBatchType("delete"); + return [4 /*yield*/, this.addSubRequestInternal({ + url: url, + credential: credential + }, function () { return tslib.__awaiter(_this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, new BlobClient(url, this.batchRequest.createPipeline(credential)).delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); })]; + case 2: + _b.sent(); + return [3 /*break*/, 5]; case 3: - e_6 = _b.sent(); + e_1 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_6.message + message: e_1.message }); - throw e_6; + throw e_1; case 4: span.end(); return [7 /*endfinally*/]; @@ -33805,40 +34491,63 @@ var BlobServiceClient = /** @class */ (function (_super) { }); }); }; - /** - * The Get Account Information operation returns the sku name and account kind - * for the specified account. - * The Get Account Information operation is available on service versions beginning - * with version 2018-03-28. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information - * - * @param {ServiceGetAccountInfoOptions} [options] Options to the Service Get Account Info operation. - * @returns {Promise} Response data for the Service Get Account Info operation. - * @memberof BlobServiceClient - */ - BlobServiceClient.prototype.getAccountInfo = function (options) { - if (options === void 0) { options = {}; } + BlobBatch.prototype.setBlobAccessTier = function (urlOrBlobClient, credentialOrTier, tierOrOptions, options) { return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_7; + var url, credential, tier, _a, span, spanOptions, e_2; + var _this = this; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("BlobServiceClient-getAccountInfo", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + if (typeof urlOrBlobClient === "string" && + ((coreHttp.isNode && credentialOrTier instanceof StorageSharedKeyCredential) || + credentialOrTier instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrTier))) { + // First overload + url = urlOrBlobClient; + credential = credentialOrTier; + tier = tierOrOptions; + } + else if (urlOrBlobClient instanceof BlobClient) { + // Second overload + url = urlOrBlobClient.url; + credential = urlOrBlobClient.credential; + tier = credentialOrTier; + options = tierOrOptions; + } + else { + throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + } + if (!options) { + options = {}; + } + _a = createSpan("BatchSetTierRequest-addSubRequest", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getAccountInfo({ - abortSignal: options.abortSignal, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; + this.setBatchType("setAccessTier"); + return [4 /*yield*/, this.addSubRequestInternal({ + url: url, + credential: credential + }, function () { return tslib.__awaiter(_this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, new BlobClient(url, this.batchRequest.createPipeline(credential)).setAccessTier(tier, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); })]; + case 2: + _b.sent(); + return [3 /*break*/, 5]; case 3: - e_7 = _b.sent(); + e_2 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_7.message + message: e_2.message }); - throw e_7; + throw e_2; case 4: span.end(); return [7 /*endfinally*/]; @@ -33847,598 +34556,336 @@ var BlobServiceClient = /** @class */ (function (_super) { }); }); }; + return BlobBatch; +}()); +/** + * Inner batch request class which is responsible for assembling and serializing sub requests. + * See https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#request-body for how requests are assembled. + */ +var InnerBatchRequest = /** @class */ (function () { + function InnerBatchRequest() { + this.operationCount = 0; + this.body = ""; + var tempGuid = coreHttp.generateUuid(); + // batch_{batchid} + this.boundary = "batch_" + tempGuid; + // --batch_{batchid} + // Content-Type: application/http + // Content-Transfer-Encoding: binary + this.subRequestPrefix = "--" + this.boundary + HTTP_LINE_ENDING + HeaderConstants.CONTENT_TYPE + ": application/http" + HTTP_LINE_ENDING + HeaderConstants.CONTENT_TRANSFER_ENCODING + ": binary"; + // multipart/mixed; boundary=batch_{batchid} + this.multipartContentType = "multipart/mixed; boundary=" + this.boundary; + // --batch_{batchid}-- + this.batchRequestEnding = "--" + this.boundary + "--"; + this.subRequests = new Map(); + } /** - * Returns a list of the containers under the specified account. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/list-containers2 - * - * @param {string} [marker] A string value that identifies the portion of - * the list of containers to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all containers remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param {ServiceListContainersSegmentOptions} [options] Options to the Service List Container Segment operation. - * @returns {Promise} Response data for the Service List Container Segment operation. - * @memberof BlobServiceClient + * Create pipeline to assemble sub requests. The idea here is to use existing + * credential and serialization/deserialization components, with additional policies to + * filter unnecessary headers, assemble sub requests into request's body + * and intercept request from going to wire. + * @param {StorageSharedKeyCredential | AnonymousCredential | TokenCredential} credential Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the @azure/identity package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used. */ - BlobServiceClient.prototype.listContainersSegment = function (marker, options) { - if (options === void 0) { options = {}; } + InnerBatchRequest.prototype.createPipeline = function (credential) { + var isAnonymousCreds = credential instanceof AnonymousCredential; + var policyFactoryLength = 3 + (isAnonymousCreds ? 0 : 1); // [deserializationPolicy, BatchHeaderFilterPolicyFactory, (Optional)Credential, BatchRequestAssemblePolicyFactory] + var factories = new Array(policyFactoryLength); + factories[0] = coreHttp.deserializationPolicy(); // Default deserializationPolicy is provided by protocol layer + factories[1] = new BatchHeaderFilterPolicyFactory(); // Use batch header filter policy to exclude unnecessary headers + if (!isAnonymousCreds) { + factories[2] = coreHttp.isTokenCredential(credential) + ? attachCredential(coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes), credential) + : credential; + } + factories[policyFactoryLength - 1] = new BatchRequestAssemblePolicyFactory(this); // Use batch assemble policy to assemble request and intercept request from going to wire + return new Pipeline(factories, {}); + }; + InnerBatchRequest.prototype.appendSubRequestToBody = function (request) { + // Start to assemble sub request + this.body += [ + this.subRequestPrefix, + HeaderConstants.CONTENT_ID + ": " + this.operationCount, + "", + request.method.toString() + " " + getURLPathAndQuery(request.url) + " " + HTTP_VERSION_1_1 + HTTP_LINE_ENDING // sub request start line with method + ].join(HTTP_LINE_ENDING); + for (var _i = 0, _a = request.headers.headersArray(); _i < _a.length; _i++) { + var header = _a[_i]; + this.body += header.name + ": " + header.value + HTTP_LINE_ENDING; + } + this.body += HTTP_LINE_ENDING; // sub request's headers need be ending with an empty line + // No body to assemble for current batch request support + // End to assemble sub request + }; + InnerBatchRequest.prototype.preAddSubRequest = function (subRequest) { + if (this.operationCount >= BATCH_MAX_REQUEST) { + throw new RangeError("Cannot exceed " + BATCH_MAX_REQUEST + " sub requests in a single batch"); + } + // Fast fail if url for sub request is invalid + var path = getURLPath(subRequest.url); + if (!path || path == "") { + throw new RangeError("Invalid url for sub request: '" + subRequest.url + "'"); + } + }; + InnerBatchRequest.prototype.postAddSubRequest = function (subRequest) { + this.subRequests.set(this.operationCount, subRequest); + this.operationCount++; + }; + // Return the http request body with assembling the ending line to the sub request body. + InnerBatchRequest.prototype.getHttpRequestBody = function () { + return "" + this.body + this.batchRequestEnding + HTTP_LINE_ENDING; + }; + InnerBatchRequest.prototype.getMultipartContentType = function () { + return this.multipartContentType; + }; + InnerBatchRequest.prototype.getSubRequests = function () { + return this.subRequests; + }; + return InnerBatchRequest; +}()); +var BatchRequestAssemblePolicy = /** @class */ (function (_super) { + tslib.__extends(BatchRequestAssemblePolicy, _super); + function BatchRequestAssemblePolicy(batchRequest, nextPolicy, options) { + var _this = _super.call(this, nextPolicy, options) || this; + _this.dummyResponse = { + request: new coreHttp.WebResource(), + status: 200, + headers: new coreHttp.HttpHeaders() + }; + _this.batchRequest = batchRequest; + return _this; + } + BatchRequestAssemblePolicy.prototype.sendRequest = function (request) { return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_8; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-listContainersSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.batchRequest.appendSubRequestToBody(request)]; case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.listContainersSegment(tslib.__assign(tslib.__assign({ abortSignal: options.abortSignal, marker: marker }, options), { include: typeof options.include === "string" ? [options.include] : options.include, spanOptions: spanOptions }))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_8 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_8.message - }); - throw e_8; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + _a.sent(); + return [2 /*return*/, this.dummyResponse]; // Intercept request from going to wire } }); }); }; - /** - * The Filter Blobs operation enables callers to list blobs across all containers whose tags - * match a given search expression. Filter blobs searches across all containers within a - * storage account but can be scoped within the expression to a single container. - * - * @private - * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param {string} [marker] A string value that identifies the portion of - * the list of blobs to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all blobs remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to find blobs by tags. - * @returns {Promise} - * @memberof BlobServiceClient - */ - BlobServiceClient.prototype.findBlobsByTagsSegment = function (tagFilterSqlExpression, marker, options) { - if (options === void 0) { options = {}; } + return BatchRequestAssemblePolicy; +}(coreHttp.BaseRequestPolicy)); +var BatchRequestAssemblePolicyFactory = /** @class */ (function () { + function BatchRequestAssemblePolicyFactory(batchRequest) { + this.batchRequest = batchRequest; + } + BatchRequestAssemblePolicyFactory.prototype.create = function (nextPolicy, options) { + return new BatchRequestAssemblePolicy(this.batchRequest, nextPolicy, options); + }; + return BatchRequestAssemblePolicyFactory; +}()); +var BatchHeaderFilterPolicy = /** @class */ (function (_super) { + tslib.__extends(BatchHeaderFilterPolicy, _super); + function BatchHeaderFilterPolicy(nextPolicy, options) { + return _super.call(this, nextPolicy, options) || this; + } + BatchHeaderFilterPolicy.prototype.sendRequest = function (request) { return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_9; + var xMsHeaderName, _i, _a, header; return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-findBlobsByTagsSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.filterBlobs({ - abortSignal: options.abortSignal, - where: tagFilterSqlExpression, - marker: marker, - maxPageSize: options.maxPageSize, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_9 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_9.message - }); - throw e_9; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + xMsHeaderName = ""; + for (_i = 0, _a = request.headers.headersArray(); _i < _a.length; _i++) { + header = _a[_i]; + if (iEqual(header.name, HeaderConstants.X_MS_VERSION)) { + xMsHeaderName = header.name; + } + } + if (xMsHeaderName !== "") { + request.headers.remove(xMsHeaderName); // The subrequests should not have the x-ms-version header. } + return [2 /*return*/, this._nextPolicy.sendRequest(request)]; }); }); }; + return BatchHeaderFilterPolicy; +}(coreHttp.BaseRequestPolicy)); +var BatchHeaderFilterPolicyFactory = /** @class */ (function () { + function BatchHeaderFilterPolicyFactory() { + } + BatchHeaderFilterPolicyFactory.prototype.create = function (nextPolicy, options) { + return new BatchHeaderFilterPolicy(nextPolicy, options); + }; + return BatchHeaderFilterPolicyFactory; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * A BlobBatchClient allows you to make batched requests to the Azure Storage Blob service. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch + */ +var BlobBatchClient = /** @class */ (function () { + function BlobBatchClient(url, credentialOrPipeline, options) { + var pipeline; + if (credentialOrPipeline instanceof Pipeline) { + pipeline = credentialOrPipeline; + } + else if (!credentialOrPipeline) { + // no credential provided + pipeline = newPipeline(new AnonymousCredential(), options); + } + else { + pipeline = newPipeline(credentialOrPipeline, options); + } + var storageClientContext = new StorageClientContext(url, pipeline.toServiceClientOptions()); + this._serviceContext = new Service(storageClientContext); + } /** - * Returns an AsyncIterableIterator for ServiceFindBlobsByTagsSegmentResponse. - * - * @private - * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param {string} [marker] A string value that identifies the portion of - * the list of blobs to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all blobs remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to find blobs by tags. - * @returns {AsyncIterableIterator} - * @memberof BlobServiceClient + * Creates a {@link BlobBatch}. + * A BlobBatch represents an aggregated set of operations on blobs. */ - BlobServiceClient.prototype.findBlobsByTagsSegments = function (tagFilterSqlExpression, marker, options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function findBlobsByTagsSegments_1() { - var response; + BlobBatchClient.prototype.createBatch = function () { + return new BlobBatch(); + }; + BlobBatchClient.prototype.deleteBlobs = function (urlsOrBlobClients, credentialOrOptions, options) { + return tslib.__awaiter(this, void 0, void 0, function () { + var batch, _i, urlsOrBlobClients_1, urlOrBlobClient; return tslib.__generator(this, function (_a) { switch (_a.label) { case 0: - if (!(!!marker || marker === undefined)) return [3 /*break*/, 6]; + batch = new BlobBatch(); + _i = 0, urlsOrBlobClients_1 = urlsOrBlobClients; _a.label = 1; - case 1: return [4 /*yield*/, tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker, options))]; + case 1: + if (!(_i < urlsOrBlobClients_1.length)) return [3 /*break*/, 6]; + urlOrBlobClient = urlsOrBlobClients_1[_i]; + if (!(typeof urlOrBlobClient === "string")) return [3 /*break*/, 3]; + return [4 /*yield*/, batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options)]; case 2: - response = _a.sent(); - response.blobs = response.blobs || []; - marker = response.continuationToken; - return [4 /*yield*/, tslib.__await(response)]; - case 3: return [4 /*yield*/, _a.sent()]; + _a.sent(); + return [3 /*break*/, 5]; + case 3: return [4 /*yield*/, batch.deleteBlob(urlOrBlobClient, credentialOrOptions)]; case 4: _a.sent(); _a.label = 5; case 5: - if (marker) return [3 /*break*/, 1]; - _a.label = 6; - case 6: return [2 /*return*/]; - } - }); - }); - }; - /** - * Returns an AsyncIterableIterator for blobs. - * - * @private - * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to findBlobsByTagsItems. - * @returns {AsyncIterableIterator} - * @memberof BlobServiceClient - */ - BlobServiceClient.prototype.findBlobsByTagsItems = function (tagFilterSqlExpression, options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function findBlobsByTagsItems_1() { - var marker, _a, _b, segment, e_10_1; - var e_10, _c; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _d.trys.push([0, 7, 8, 13]); - _a = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker, options)); - _d.label = 1; - case 1: return [4 /*yield*/, tslib.__await(_a.next())]; - case 2: - if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; - segment = _b.value; - return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs)))]; - case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; - case 4: - _d.sent(); - _d.label = 5; - case 5: return [3 /*break*/, 1]; - case 6: return [3 /*break*/, 13]; - case 7: - e_10_1 = _d.sent(); - e_10 = { error: e_10_1 }; - return [3 /*break*/, 13]; - case 8: - _d.trys.push([8, , 11, 12]); - if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; - return [4 /*yield*/, tslib.__await(_c.call(_a))]; - case 9: - _d.sent(); - _d.label = 10; - case 10: return [3 /*break*/, 12]; - case 11: - if (e_10) throw e_10.error; - return [7 /*endfinally*/]; - case 12: return [7 /*endfinally*/]; - case 13: return [2 /*return*/]; + _i++; + return [3 /*break*/, 1]; + case 6: return [2 /*return*/, this.submitBatch(batch)]; } }); }); }; - /** - * Returns an async iterable iterator to find all blobs with specified tag - * under the specified account. - * - * .byPage() returns an async iterable iterator to list the blobs in pages. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties - * - * Example using `for await` syntax: - * - * ```js - * let i = 1; - * for await (const blob of blobServiceClient.findBlobsByTags("tagkey='tagvalue'")) { - * console.log(`Blob ${i++}: ${container.name}`); - * } - * ``` - * - * Example using `iter.next()`: - * - * ```js - * let i = 1; - * const iter = blobServiceClient.findBlobsByTags("tagkey='tagvalue'"); - * let blobItem = await iter.next(); - * while (!blobItem.done) { - * console.log(`Blob ${i++}: ${blobItem.value.name}`); - * blobItem = await iter.next(); - * } - * ``` - * - * Example using `byPage()`: - * - * ```js - * // passing optional maxPageSize in the page settings - * let i = 1; - * for await (const response of blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { - * if (response.blobs) { - * for (const blob of response.blobs) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } - * } - * ``` - * - * Example using paging with a marker: - * - * ```js - * let i = 1; - * let iterator = blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); - * let response = (await iterator.next()).value; - * - * // Prints 2 blob names - * if (response.blobs) { - * for (const blob of response.blobs) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } - * - * // Gets next marker - * let marker = response.continuationToken; - * // Passing next marker as continuationToken - * iterator = blobServiceClient - * .findBlobsByTags("tagkey='tagvalue'") - * .byPage({ continuationToken: marker, maxPageSize: 10 }); - * response = (await iterator.next()).value; - * - * // Prints blob names - * if (response.blobs) { - * for (const blob of response.blobs) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } - * ``` - * - * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param {ServiceFindBlobByTagsOptions} [options={}] Options to find blobs by tags. - * @returns {PagedAsyncIterableIterator} - * @memberof BlobServiceClient - */ - BlobServiceClient.prototype.findBlobsByTags = function (tagFilterSqlExpression, options) { - var _a; - var _this = this; - if (options === void 0) { options = {}; } - // AsyncIterableIterator to iterate over blobs - var listSegmentOptions = tslib.__assign({}, options); - var iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); - return _a = { - /** - * @member {Promise} [next] The next method, part of the iteration protocol - */ - next: function () { - return iter.next(); - } - }, - /** - * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol - */ - _a[Symbol.asyncIterator] = function () { - return this; - }, - /** - * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time - */ - _a.byPage = function (settings) { - if (settings === void 0) { settings = {}; } - return _this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); - }, - _a; - }; - /** - * Returns an AsyncIterableIterator for ServiceListContainersSegmentResponses - * - * @private - * @param {string} [marker] A string value that identifies the portion of - * the list of containers to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all containers remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param {ServiceListContainersSegmentOptions} [options] Options to list containers operation. - * @returns {AsyncIterableIterator} - * @memberof BlobServiceClient - */ - BlobServiceClient.prototype.listSegments = function (marker, options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listSegments_1() { - var listContainersSegmentResponse; + BlobBatchClient.prototype.setBlobsAccessTier = function (urlsOrBlobClients, credentialOrTier, tierOrOptions, options) { + return tslib.__awaiter(this, void 0, void 0, function () { + var batch, _i, urlsOrBlobClients_2, urlOrBlobClient; return tslib.__generator(this, function (_a) { switch (_a.label) { case 0: - if (!(!!marker || marker === undefined)) return [3 /*break*/, 7]; + batch = new BlobBatch(); + _i = 0, urlsOrBlobClients_2 = urlsOrBlobClients; _a.label = 1; - case 1: return [4 /*yield*/, tslib.__await(this.listContainersSegment(marker, options))]; + case 1: + if (!(_i < urlsOrBlobClients_2.length)) return [3 /*break*/, 6]; + urlOrBlobClient = urlsOrBlobClients_2[_i]; + if (!(typeof urlOrBlobClient === "string")) return [3 /*break*/, 3]; + return [4 /*yield*/, batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options)]; case 2: - listContainersSegmentResponse = _a.sent(); - listContainersSegmentResponse.containerItems = - listContainersSegmentResponse.containerItems || []; - marker = listContainersSegmentResponse.continuationToken; - return [4 /*yield*/, tslib.__await(listContainersSegmentResponse)]; - case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_a.sent()])]; - case 4: return [4 /*yield*/, _a.sent()]; - case 5: _a.sent(); - _a.label = 6; - case 6: - if (marker) return [3 /*break*/, 1]; - _a.label = 7; - case 7: return [2 /*return*/]; - } - }); - }); - }; - /** - * Returns an AsyncIterableIterator for Container Items - * - * @private - * @param {ServiceListContainersSegmentOptions} [options] Options to list containers operation. - * @returns {AsyncIterableIterator} - * @memberof BlobServiceClient - */ - BlobServiceClient.prototype.listItems = function (options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listItems_1() { - var marker, _a, _b, segment, e_11_1; - var e_11, _c; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _d.trys.push([0, 7, 8, 13]); - _a = tslib.__asyncValues(this.listSegments(marker, options)); - _d.label = 1; - case 1: return [4 /*yield*/, tslib.__await(_a.next())]; - case 2: - if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; - segment = _b.value; - return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(segment.containerItems)))]; - case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; + return [3 /*break*/, 5]; + case 3: return [4 /*yield*/, batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions)]; case 4: - _d.sent(); - _d.label = 5; - case 5: return [3 /*break*/, 1]; - case 6: return [3 /*break*/, 13]; - case 7: - e_11_1 = _d.sent(); - e_11 = { error: e_11_1 }; - return [3 /*break*/, 13]; - case 8: - _d.trys.push([8, , 11, 12]); - if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; - return [4 /*yield*/, tslib.__await(_c.call(_a))]; - case 9: - _d.sent(); - _d.label = 10; - case 10: return [3 /*break*/, 12]; - case 11: - if (e_11) throw e_11.error; - return [7 /*endfinally*/]; - case 12: return [7 /*endfinally*/]; - case 13: return [2 /*return*/]; + _a.sent(); + _a.label = 5; + case 5: + _i++; + return [3 /*break*/, 1]; + case 6: return [2 /*return*/, this.submitBatch(batch)]; } }); }); }; /** - * Returns an async iterable iterator to list all the containers - * under the specified account. - * - * .byPage() returns an async iterable iterator to list the containers in pages. - * - * Example using `for await` syntax: - * - * ```js - * let i = 1; - * for await (const container of blobServiceClient.listContainers()) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * ``` - * - * Example using `iter.next()`: + * Submit batch request which consists of multiple subrequests. * - * ```js - * let i = 1; - * const iter = blobServiceClient.listContainers(); - * let containerItem = await iter.next(); - * while (!containerItem.done) { - * console.log(`Container ${i++}: ${containerItem.value.name}`); - * containerItem = await iter.next(); - * } - * ``` + * Get `blobBatchClient` and other details before running the snippets. + * `blobServiceClient.getBlobBatchClient()` gives the `blobBatchClient` * - * Example using `byPage()`: + * Example usage: * * ```js - * // passing optional maxPageSize in the page settings - * let i = 1; - * for await (const response of blobServiceClient.listContainers().byPage({ maxPageSize: 20 })) { - * if (response.containerItems) { - * for (const container of response.containerItems) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * } - * } + * let batchRequest = new BlobBatch(); + * await batchRequest.deleteBlob(urlInString0, credential0); + * await batchRequest.deleteBlob(urlInString1, credential1, { + * deleteSnapshots: "include" + * }); + * const batchResp = await blobBatchClient.submitBatch(batchRequest); + * console.log(batchResp.subResponsesSucceededCount); * ``` * - * Example using paging with a marker: + * Example using a lease: * * ```js - * let i = 1; - * let iterator = blobServiceClient.listContainers().byPage({ maxPageSize: 2 }); - * let response = (await iterator.next()).value; - * - * // Prints 2 container names - * if (response.containerItems) { - * for (const container of response.containerItems) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * } - * - * // Gets next marker - * let marker = response.continuationToken; - * // Passing next marker as continuationToken - * iterator = blobServiceClient - * .listContainers() - * .byPage({ continuationToken: marker, maxPageSize: 10 }); - * response = (await iterator.next()).value; - * - * // Prints 10 container names - * if (response.containerItems) { - * for (const container of response.containerItems) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * } + * let batchRequest = new BlobBatch(); + * await batchRequest.setBlobAccessTier(blockBlobClient0, "Cool"); + * await batchRequest.setBlobAccessTier(blockBlobClient1, "Cool", { + * conditions: { leaseId: leaseId } + * }); + * const batchResp = await blobBatchClient.submitBatch(batchRequest); + * console.log(batchResp.subResponsesSucceededCount); * ``` * - * @param {ServiceListContainersOptions} [options={}] Options to list containers. - * @returns {PagedAsyncIterableIterator} An asyncIterableIterator that supports paging. - * @memberof BlobServiceClient - */ - BlobServiceClient.prototype.listContainers = function (options) { - var _a; - var _this = this; - if (options === void 0) { options = {}; } - if (options.prefix === "") { - options.prefix = undefined; - } - var include = []; - if (options.includeDeleted) { - include.push("deleted"); - } - if (options.includeMetadata) { - include.push("metadata"); - } - // AsyncIterableIterator to iterate over containers - var listSegmentOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); - var iter = this.listItems(listSegmentOptions); - return _a = { - /** - * @member {Promise} [next] The next method, part of the iteration protocol - */ - next: function () { - return iter.next(); - } - }, - /** - * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol - */ - _a[Symbol.asyncIterator] = function () { - return this; - }, - /** - * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time - */ - _a.byPage = function (settings) { - if (settings === void 0) { settings = {}; } - return _this.listSegments(settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); - }, - _a; - }; - /** - * ONLY AVAILABLE WHEN USING BEARER TOKEN AUTHENTICATION (TokenCredential). - * - * Retrieves a user delegation key for the Blob service. This is only a valid operation when using - * bearer token authentication. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-user-delegation-key + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch * - * @param {Date} startsOn The start time for the user delegation SAS. Must be within 7 days of the current time - * @param {Date} expiresOn The end time for the user delegation SAS. Must be within 7 days of the current time - * @returns {Promise} - * @memberof BlobServiceClient + * @param {BlobBatch} batchRequest A set of Delete or SetTier operations. + * @param {BlobBatchSubmitBatchOptionalParams} [options] + * @returns {Promise} + * @memberof BlobBatchClient */ - BlobServiceClient.prototype.getUserDelegationKey = function (startsOn, expiresOn, options) { + BlobBatchClient.prototype.submitBatch = function (batchRequest, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, response, userDelegationKey, res, e_12; + var _a, span, spanOptions, batchRequestBody, rawBatchResponse, batchResponseParser, responseSummary, res, e_1; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("BlobServiceClient-getUserDelegationKey", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + if (!batchRequest || batchRequest.getSubRequests().size == 0) { + throw new RangeError("Batch request should contain one or more sub requests."); + } + _a = createSpan("BlobBatchClient-submitBatch", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getUserDelegationKey({ - startsOn: truncatedISO8061Date(startsOn, false), - expiresOn: truncatedISO8061Date(expiresOn, false) - }, { - abortSignal: options.abortSignal, - spanOptions: spanOptions - })]; + _b.trys.push([1, 4, 5, 6]); + batchRequestBody = batchRequest.getHttpRequestBody(); + return [4 /*yield*/, this._serviceContext.submitBatch(batchRequestBody, utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), tslib.__assign(tslib.__assign({}, options), { spanOptions: spanOptions }))]; case 2: - response = _b.sent(); - userDelegationKey = { - signedObjectId: response.signedObjectId, - signedTenantId: response.signedTenantId, - signedStartsOn: new Date(response.signedStartsOn), - signedExpiresOn: new Date(response.signedExpiresOn), - signedService: response.signedService, - signedVersion: response.signedVersion, - value: response.value + rawBatchResponse = _b.sent(); + batchResponseParser = new BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests()); + return [4 /*yield*/, batchResponseParser.parseBatchResponse()]; + case 3: + responseSummary = _b.sent(); + res = { + _response: rawBatchResponse._response, + contentType: rawBatchResponse.contentType, + errorCode: rawBatchResponse.errorCode, + requestId: rawBatchResponse.requestId, + clientRequestId: rawBatchResponse.clientRequestId, + version: rawBatchResponse.version, + subResponses: responseSummary.subResponses, + subResponsesSucceededCount: responseSummary.subResponsesSucceededCount, + subResponsesFailedCount: responseSummary.subResponsesFailedCount }; - res = tslib.__assign({ _response: response._response, requestId: response.requestId, clientRequestId: response.clientRequestId, version: response.version, date: response.date, errorCode: response.errorCode }, userDelegationKey); return [2 /*return*/, res]; - case 3: - e_12 = _b.sent(); + case 4: + e_1 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_12.message + message: e_1.message }); - throw e_12; - case 4: + throw e_1; + case 5: span.end(); return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + case 6: return [2 /*return*/]; } }); }); }; - /** - * Creates a BlobBatchClient object to conduct batch operations. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch - * - * @returns {BlobBatchClient} A new BlobBatchClient object for this service. - * @memberof BlobServiceClient - */ - BlobServiceClient.prototype.getBlobBatchClient = function () { - return new BlobBatchClient(this.url, this.pipeline); - }; - return BlobServiceClient; -}(StorageClient)); + return BlobBatchClient; +}()); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. @@ -34586,6 +35033,52 @@ var AccountSASPermissions = /** @class */ (function () { } return accountSASPermissions; }; + /** + * Creates a {@link AccountSASPermissions} from a raw object which contains same keys as it + * and boolean values for them. + * + * @static + * @param {AccountSASPermissionsLike} permissionLike + * @returns {AccountSASPermissions} + * @memberof AccountSASPermissions + */ + AccountSASPermissions.from = function (permissionLike) { + var accountSASPermissions = new AccountSASPermissions(); + if (permissionLike.read) { + accountSASPermissions.read = true; + } + if (permissionLike.write) { + accountSASPermissions.write = true; + } + if (permissionLike.delete) { + accountSASPermissions.delete = true; + } + if (permissionLike.deleteVersion) { + accountSASPermissions.deleteVersion = true; + } + if (permissionLike.filter) { + accountSASPermissions.filter = true; + } + if (permissionLike.tag) { + accountSASPermissions.tag = true; + } + if (permissionLike.list) { + accountSASPermissions.list = true; + } + if (permissionLike.add) { + accountSASPermissions.add = true; + } + if (permissionLike.create) { + accountSASPermissions.create = true; + } + if (permissionLike.update) { + accountSASPermissions.update = true; + } + if (permissionLike.process) { + accountSASPermissions.process = true; + } + return accountSASPermissions; + }; /** * Produces the SAS permissions string for an Azure Storage account. * Call this method to set AccountSASSignatureValues Permissions field. @@ -34835,1072 +35328,1053 @@ var AccountSASServices = /** @class */ (function () { }()); // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. /** - * Generate SasIPRange format string. For example: + * ONLY AVAILABLE IN NODE.JS RUNTIME. * - * "8.8.8.8" or "1.1.1.1-255.255.255.255" + * Generates a {@link SASQueryParameters} object which contains all SAS query parameters needed to make an actual + * REST request. * - * @export - * @param {SasIPRange} ipRange - * @returns {string} + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas + * + * @param {AccountSASSignatureValues} accountSASSignatureValues + * @param {StorageSharedKeyCredential} sharedKeyCredential + * @returns {SASQueryParameters} + * @memberof AccountSASSignatureValues */ -function ipRangeToString(ipRange) { - return ipRange.end ? ipRange.start + "-" + ipRange.end : ipRange.start; +function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { + var version = accountSASSignatureValues.version + ? accountSASSignatureValues.version + : SERVICE_VERSION; + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.deleteVersion && + version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); + } + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.tag && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); + } + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.filter && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 'f' permission."); + } + var parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); + var parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); + var parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); + var stringToSign = [ + sharedKeyCredential.accountName, + parsedPermissions, + parsedServices, + parsedResourceTypes, + accountSASSignatureValues.startsOn + ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) + : "", + truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), + accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", + accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", + version, + "" // Account SAS requires an additional newline character + ].join("\n"); + var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(version, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange); } -// Copyright (c) Microsoft Corporation. All rights reserved. -(function (SASProtocol) { +/** + * A BlobServiceClient represents a Client to the Azure Storage Blob service allowing you + * to manipulate blob containers. + * + * @export + * @class BlobServiceClient + */ +var BlobServiceClient = /** @class */ (function (_super) { + tslib.__extends(BlobServiceClient, _super); + function BlobServiceClient(url, credentialOrPipeline, options) { + var _this = this; + var pipeline; + if (credentialOrPipeline instanceof Pipeline) { + pipeline = credentialOrPipeline; + } + else if ((coreHttp.isNode && credentialOrPipeline instanceof StorageSharedKeyCredential) || + credentialOrPipeline instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrPipeline)) { + pipeline = newPipeline(credentialOrPipeline, options); + } + else { + // The second parameter is undefined. Use anonymous credential + pipeline = newPipeline(new AnonymousCredential(), options); + } + _this = _super.call(this, url, pipeline) || this; + _this.serviceContext = new Service(_this.storageClientContext); + return _this; + } /** - * Protocol that allows HTTPS only + * + * Creates an instance of BlobServiceClient from connection string. + * + * @param {string} connectionString Account connection string or a SAS connection string of an Azure storage account. + * [ Note - Account connection string can only be used in NODE.JS runtime. ] + * Account connection string example - + * `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net` + * SAS connection string example - + * `BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString` + * @param {StoragePipelineOptions} [options] Optional. Options to configure the HTTP pipeline. + * @memberof BlobServiceClient */ - SASProtocol["Https"] = "https"; + BlobServiceClient.fromConnectionString = function (connectionString, options) { + options = options || {}; + var extractedCreds = extractConnectionStringParts(connectionString); + if (extractedCreds.kind === "AccountConnString") { + { + var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); + var pipeline = newPipeline(sharedKeyCredential, options); + return new BlobServiceClient(extractedCreds.url, pipeline); + } + } + else if (extractedCreds.kind === "SASConnString") { + var pipeline = newPipeline(new AnonymousCredential(), options); + return new BlobServiceClient(extractedCreds.url + "?" + extractedCreds.accountSas, pipeline); + } + else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + }; + /** + * Creates a {@link ContainerClient} object + * + * @param {string} containerName A container name + * @returns {ContainerClient} A new ContainerClient object for the given container name. + * @memberof BlobServiceClient + * + * Example usage: + * + * ```js + * const containerClient = blobServiceClient.getContainerClient(""); + * ``` + */ + BlobServiceClient.prototype.getContainerClient = function (containerName) { + return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline); + }; + /** + * Create a Blob container. + * + * @param {string} containerName Name of the container to create. + * @param {ContainerCreateOptions} [options] Options to configure Container Create operation. + * @returns {Promise<{ containerClient: ContainerClient; containerCreateResponse: ContainerCreateResponse }>} Container creation response and the corresponding container client. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.createContainer = function (containerName, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, containerClient, containerCreateResponse, e_1; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-createContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + containerClient = this.getContainerClient(containerName); + return [4 /*yield*/, containerClient.create(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: + containerCreateResponse = _b.sent(); + return [2 /*return*/, { + containerClient: containerClient, + containerCreateResponse: containerCreateResponse + }]; + case 3: + e_1 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_1.message + }); + throw e_1; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Deletes a Blob container. + * + * @param {string} containerName Name of the container to delete. + * @param {ContainerDeleteMethodOptions} [options] Options to configure Container Delete operation. + * @returns {Promise} Container deletion response. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.deleteContainer = function (containerName, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, containerClient, e_2; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-deleteContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + containerClient = this.getContainerClient(containerName); + return [4 /*yield*/, containerClient.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_2 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_2.message + }); + throw e_2; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Restore a previously deleted Blob container. + * This API is only functional if Container Soft Delete is enabled for the storage account associated with the container. + * + * @param {string} deletedContainerName Name of the previously deleted container. + * @param {string} deletedContainerVersion Version of the previously deleted container, used to uniquely identify the deleted container. + * @returns {Promise} Container deletion response. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.undeleteContainer = function (deletedContainerName, deletedContainerVersion, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, containerClient, containerContext, containerUndeleteResponse, e_3; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-undeleteContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + containerClient = this.getContainerClient(options.destinationContainerName || deletedContainerName); + containerContext = new Container(containerClient["storageClientContext"]); + return [4 /*yield*/, containerContext.restore(tslib.__assign(tslib.__assign({ deletedContainerName: deletedContainerName, + deletedContainerVersion: deletedContainerVersion }, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: + containerUndeleteResponse = _b.sent(); + return [2 /*return*/, { containerClient: containerClient, containerUndeleteResponse: containerUndeleteResponse }]; + case 3: + e_3 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_3.message + }); + throw e_3; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Gets the properties of a storage account’s Blob service, including properties + * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties + * + * @param {ServiceGetPropertiesOptions} [options] Options to the Service Get Properties operation. + * @returns {Promise} Response data for the Service Get Properties operation. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.getProperties = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_4; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-getProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.getProperties({ + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_4 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_4.message + }); + throw e_4; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Sets properties for a storage account’s Blob service endpoint, including properties + * for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules and soft delete settings. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties} + * + * @param {BlobServiceProperties} properties + * @param {ServiceSetPropertiesOptions} [options] Options to the Service Set Properties operation. + * @returns {Promise} Response data for the Service Set Properties operation. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.setProperties = function (properties, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_5; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-setProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.setProperties(properties, { + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_5 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_5.message + }); + throw e_5; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Retrieves statistics related to replication for the Blob service. It is only + * available on the secondary location endpoint when read-access geo-redundant + * replication is enabled for the storage account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-stats} + * + * @param {ServiceGetStatisticsOptions} [options] Options to the Service Get Statistics operation. + * @returns {Promise} Response data for the Service Get Statistics operation. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.getStatistics = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_6; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-getStatistics", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.getStatistics({ + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_6 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_6.message + }); + throw e_6; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * The Get Account Information operation returns the sku name and account kind + * for the specified account. + * The Get Account Information operation is available on service versions beginning + * with version 2018-03-28. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information + * + * @param {ServiceGetAccountInfoOptions} [options] Options to the Service Get Account Info operation. + * @returns {Promise} Response data for the Service Get Account Info operation. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.getAccountInfo = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_7; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-getAccountInfo", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.getAccountInfo({ + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_7 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_7.message + }); + throw e_7; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns a list of the containers under the specified account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/list-containers2 + * + * @param {string} [marker] A string value that identifies the portion of + * the list of containers to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all containers remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ServiceListContainersSegmentOptions} [options] Options to the Service List Container Segment operation. + * @returns {Promise} Response data for the Service List Container Segment operation. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.listContainersSegment = function (marker, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_8; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-listContainersSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.listContainersSegment(tslib.__assign(tslib.__assign({ abortSignal: options.abortSignal, marker: marker }, options), { include: typeof options.include === "string" ? [options.include] : options.include, spanOptions: spanOptions }))]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_8 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_8.message + }); + throw e_8; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; /** - * Protocol that allows both HTTPS and HTTP + * The Filter Blobs operation enables callers to list blobs across all containers whose tags + * match a given search expression. Filter blobs searches across all containers within a + * storage account but can be scoped within the expression to a single container. + * + * @private + * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param {string} [marker] A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to find blobs by tags. + * @returns {Promise} + * @memberof BlobServiceClient */ - SASProtocol["HttpsAndHttp"] = "https,http"; -})(exports.SASProtocol || (exports.SASProtocol = {})); -/** - * Represents the components that make up an Azure Storage SAS' query parameters. This type is not constructed directly - * by the user; it is only generated by the {@link AccountSASSignatureValues} and {@link BlobSASSignatureValues} - * types. Once generated, it can be encoded into a {@code String} and appended to a URL directly (though caution should - * be taken here in case there are existing query parameters, which might affect the appropriate means of appending - * these query parameters). - * - * NOTE: Instances of this class are immutable. - * - * @export - * @class SASQueryParameters - */ -var SASQueryParameters = /** @class */ (function () { - function SASQueryParameters(version, signature, permissionsOrOptions, services, resourceTypes, protocol, startsOn, expiresOn, ipRange, identifier, resource, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType, userDelegationKey, preauthorizedAgentObjectId, correlationId) { - this.version = version; - this.signature = signature; - if (permissionsOrOptions !== undefined && typeof permissionsOrOptions !== "string") { - // SASQueryParametersOptions - this.permissions = permissionsOrOptions.permissions; - this.services = permissionsOrOptions.services; - this.resourceTypes = permissionsOrOptions.resourceTypes; - this.protocol = permissionsOrOptions.protocol; - this.startsOn = permissionsOrOptions.startsOn; - this.expiresOn = permissionsOrOptions.expiresOn; - this.ipRangeInner = permissionsOrOptions.ipRange; - this.identifier = permissionsOrOptions.identifier; - this.resource = permissionsOrOptions.resource; - this.cacheControl = permissionsOrOptions.cacheControl; - this.contentDisposition = permissionsOrOptions.contentDisposition; - this.contentEncoding = permissionsOrOptions.contentEncoding; - this.contentLanguage = permissionsOrOptions.contentLanguage; - this.contentType = permissionsOrOptions.contentType; - if (permissionsOrOptions.userDelegationKey) { - this.signedOid = permissionsOrOptions.userDelegationKey.signedObjectId; - this.signedTenantId = permissionsOrOptions.userDelegationKey.signedTenantId; - this.signedStartsOn = permissionsOrOptions.userDelegationKey.signedStartsOn; - this.signedExpiresOn = permissionsOrOptions.userDelegationKey.signedExpiresOn; - this.signedService = permissionsOrOptions.userDelegationKey.signedService; - this.signedVersion = permissionsOrOptions.userDelegationKey.signedVersion; - this.preauthorizedAgentObjectId = permissionsOrOptions.preauthorizedAgentObjectId; - this.correlationId = permissionsOrOptions.correlationId; - } - } - else { - this.services = services; - this.resourceTypes = resourceTypes; - this.expiresOn = expiresOn; - this.permissions = permissionsOrOptions; - this.protocol = protocol; - this.startsOn = startsOn; - this.ipRangeInner = ipRange; - this.identifier = identifier; - this.resource = resource; - this.cacheControl = cacheControl; - this.contentDisposition = contentDisposition; - this.contentEncoding = contentEncoding; - this.contentLanguage = contentLanguage; - this.contentType = contentType; - if (userDelegationKey) { - this.signedOid = userDelegationKey.signedObjectId; - this.signedTenantId = userDelegationKey.signedTenantId; - this.signedStartsOn = userDelegationKey.signedStartsOn; - this.signedExpiresOn = userDelegationKey.signedExpiresOn; - this.signedService = userDelegationKey.signedService; - this.signedVersion = userDelegationKey.signedVersion; - this.preauthorizedAgentObjectId = preauthorizedAgentObjectId; - this.correlationId = correlationId; - } - } - } - Object.defineProperty(SASQueryParameters.prototype, "ipRange", { - /** - * Optional. IP range allowed for this SAS. - * - * @readonly - * @type {(SasIPRange | undefined)} - * @memberof SASQueryParameters - */ - get: function () { - if (this.ipRangeInner) { - return { - end: this.ipRangeInner.end, - start: this.ipRangeInner.start - }; - } - return undefined; - }, - enumerable: false, - configurable: true - }); + BlobServiceClient.prototype.findBlobsByTagsSegment = function (tagFilterSqlExpression, marker, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, response, wrappedResponse, e_9; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-findBlobsByTagsSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.filterBlobs({ + abortSignal: options.abortSignal, + where: tagFilterSqlExpression, + marker: marker, + maxPageSize: options.maxPageSize, + spanOptions: spanOptions + })]; + case 2: + response = _b.sent(); + wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, blobs: response.blobs.map(function (blob) { + var _a; + var tagValue = ""; + if (((_a = blob.tags) === null || _a === void 0 ? void 0 : _a.blobTagSet.length) === 1) { + tagValue = blob.tags.blobTagSet[0].value; + } + return tslib.__assign(tslib.__assign({}, blob), { tags: toTags(blob.tags), tagValue: tagValue }); + }) }); + return [2 /*return*/, wrappedResponse]; + case 3: + e_9 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_9.message + }); + throw e_9; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; /** - * Encodes all SAS query parameters into a string that can be appended to a URL. + * Returns an AsyncIterableIterator for ServiceFindBlobsByTagsSegmentResponse. * - * @returns {string} - * @memberof SASQueryParameters + * @private + * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param {string} [marker] A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to find blobs by tags. + * @returns {AsyncIterableIterator} + * @memberof BlobServiceClient */ - SASQueryParameters.prototype.toString = function () { - var params = [ - "sv", - "ss", - "srt", - "spr", - "st", - "se", - "sip", - "si", - "skoid", - "sktid", - "skt", - "ske", - "sks", - "skv", - "sr", - "sp", - "sig", - "rscc", - "rscd", - "rsce", - "rscl", - "rsct", - "saoid", - "scid" - ]; - var queries = []; - for (var _i = 0, params_1 = params; _i < params_1.length; _i++) { - var param = params_1[_i]; - switch (param) { - case "sv": - this.tryAppendQueryParameter(queries, param, this.version); - break; - case "ss": - this.tryAppendQueryParameter(queries, param, this.services); - break; - case "srt": - this.tryAppendQueryParameter(queries, param, this.resourceTypes); - break; - case "spr": - this.tryAppendQueryParameter(queries, param, this.protocol); - break; - case "st": - this.tryAppendQueryParameter(queries, param, this.startsOn ? truncatedISO8061Date(this.startsOn, false) : undefined); - break; - case "se": - this.tryAppendQueryParameter(queries, param, this.expiresOn ? truncatedISO8061Date(this.expiresOn, false) : undefined); - break; - case "sip": - this.tryAppendQueryParameter(queries, param, this.ipRange ? ipRangeToString(this.ipRange) : undefined); - break; - case "si": - this.tryAppendQueryParameter(queries, param, this.identifier); - break; - case "skoid": // Signed object ID - this.tryAppendQueryParameter(queries, param, this.signedOid); - break; - case "sktid": // Signed tenant ID - this.tryAppendQueryParameter(queries, param, this.signedTenantId); - break; - case "skt": // Signed key start time - this.tryAppendQueryParameter(queries, param, this.signedStartsOn ? truncatedISO8061Date(this.signedStartsOn, false) : undefined); - break; - case "ske": // Signed key expiry time - this.tryAppendQueryParameter(queries, param, this.signedExpiresOn ? truncatedISO8061Date(this.signedExpiresOn, false) : undefined); - break; - case "sks": // Signed key service - this.tryAppendQueryParameter(queries, param, this.signedService); - break; - case "skv": // Signed key version - this.tryAppendQueryParameter(queries, param, this.signedVersion); - break; - case "sr": - this.tryAppendQueryParameter(queries, param, this.resource); - break; - case "sp": - this.tryAppendQueryParameter(queries, param, this.permissions); - break; - case "sig": - this.tryAppendQueryParameter(queries, param, this.signature); - break; - case "rscc": - this.tryAppendQueryParameter(queries, param, this.cacheControl); - break; - case "rscd": - this.tryAppendQueryParameter(queries, param, this.contentDisposition); - break; - case "rsce": - this.tryAppendQueryParameter(queries, param, this.contentEncoding); - break; - case "rscl": - this.tryAppendQueryParameter(queries, param, this.contentLanguage); - break; - case "rsct": - this.tryAppendQueryParameter(queries, param, this.contentType); - break; - case "saoid": - this.tryAppendQueryParameter(queries, param, this.preauthorizedAgentObjectId); - break; - case "scid": - this.tryAppendQueryParameter(queries, param, this.correlationId); - break; - } - } - return queries.join("&"); + BlobServiceClient.prototype.findBlobsByTagsSegments = function (tagFilterSqlExpression, marker, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function findBlobsByTagsSegments_1() { + var response; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!(!!marker || marker === undefined)) return [3 /*break*/, 6]; + _a.label = 1; + case 1: return [4 /*yield*/, tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker, options))]; + case 2: + response = _a.sent(); + response.blobs = response.blobs || []; + marker = response.continuationToken; + return [4 /*yield*/, tslib.__await(response)]; + case 3: return [4 /*yield*/, _a.sent()]; + case 4: + _a.sent(); + _a.label = 5; + case 5: + if (marker) return [3 /*break*/, 1]; + _a.label = 6; + case 6: return [2 /*return*/]; + } + }); + }); }; /** - * A private helper method used to filter and append query key/value pairs into an array. + * Returns an AsyncIterableIterator for blobs. * * @private - * @param {string[]} queries - * @param {string} key - * @param {string} [value] - * @returns {void} - * @memberof SASQueryParameters + * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to findBlobsByTagsItems. + * @returns {AsyncIterableIterator} + * @memberof BlobServiceClient */ - SASQueryParameters.prototype.tryAppendQueryParameter = function (queries, key, value) { - if (!value) { - return; - } - key = encodeURIComponent(key); - value = encodeURIComponent(value); - if (key.length > 0 && value.length > 0) { - queries.push(key + "=" + value); - } + BlobServiceClient.prototype.findBlobsByTagsItems = function (tagFilterSqlExpression, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function findBlobsByTagsItems_1() { + var marker, _a, _b, segment, e_10_1; + var e_10, _c; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _d.trys.push([0, 7, 8, 13]); + _a = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker, options)); + _d.label = 1; + case 1: return [4 /*yield*/, tslib.__await(_a.next())]; + case 2: + if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; + segment = _b.value; + return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs)))]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; + case 4: + _d.sent(); + _d.label = 5; + case 5: return [3 /*break*/, 1]; + case 6: return [3 /*break*/, 13]; + case 7: + e_10_1 = _d.sent(); + e_10 = { error: e_10_1 }; + return [3 /*break*/, 13]; + case 8: + _d.trys.push([8, , 11, 12]); + if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; + return [4 /*yield*/, tslib.__await(_c.call(_a))]; + case 9: + _d.sent(); + _d.label = 10; + case 10: return [3 /*break*/, 12]; + case 11: + if (e_10) throw e_10.error; + return [7 /*endfinally*/]; + case 12: return [7 /*endfinally*/]; + case 13: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an async iterable iterator to find all blobs with specified tag + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the blobs in pages. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties + * + * Example using `for await` syntax: + * + * ```js + * let i = 1; + * for await (const blob of blobServiceClient.findBlobsByTags("tagkey='tagvalue'")) { + * console.log(`Blob ${i++}: ${container.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * const iter = blobServiceClient.findBlobsByTags("tagkey='tagvalue'"); + * let blobItem = await iter.next(); + * while (!blobItem.done) { + * console.log(`Blob ${i++}: ${blobItem.value.name}`); + * blobItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 blob names + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * // Passing next marker as continuationToken + * iterator = blobServiceClient + * .findBlobsByTags("tagkey='tagvalue'") + * .byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints blob names + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * ``` + * + * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param {ServiceFindBlobByTagsOptions} [options={}] Options to find blobs by tags. + * @returns {PagedAsyncIterableIterator} + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.findBlobsByTags = function (tagFilterSqlExpression, options) { + var _a; + var _this = this; + if (options === void 0) { options = {}; } + // AsyncIterableIterator to iterate over blobs + var listSegmentOptions = tslib.__assign({}, options); + var iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); + return _a = { + /** + * @member {Promise} [next] The next method, part of the iteration protocol + */ + next: function () { + return iter.next(); + } + }, + /** + * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol + */ + _a[Symbol.asyncIterator] = function () { + return this; + }, + /** + * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time + */ + _a.byPage = function (settings) { + if (settings === void 0) { settings = {}; } + return _this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + }, + _a; }; - return SASQueryParameters; -}()); - -// Copyright (c) Microsoft Corporation. All rights reserved. -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * Generates a {@link SASQueryParameters} object which contains all SAS query parameters needed to make an actual - * REST request. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas - * - * @param {AccountSASSignatureValues} accountSASSignatureValues - * @param {StorageSharedKeyCredential} sharedKeyCredential - * @returns {SASQueryParameters} - * @memberof AccountSASSignatureValues - */ -function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { - var version = accountSASSignatureValues.version - ? accountSASSignatureValues.version - : SERVICE_VERSION; - if (accountSASSignatureValues.permissions && - accountSASSignatureValues.permissions.deleteVersion && - version < "2019-10-10") { - throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); - } - if (accountSASSignatureValues.permissions && - accountSASSignatureValues.permissions.tag && - version < "2019-12-12") { - throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); - } - if (accountSASSignatureValues.permissions && - accountSASSignatureValues.permissions.filter && - version < "2019-12-12") { - throw RangeError("'version' must be >= '2019-12-12' when provided 'f' permission."); - } - var parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); - var parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); - var parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); - var stringToSign = [ - sharedKeyCredential.accountName, - parsedPermissions, - parsedServices, - parsedResourceTypes, - accountSASSignatureValues.startsOn - ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) - : "", - truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), - accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", - accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", - version, - "" // Account SAS requires an additional newline character - ].join("\n"); - var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(version, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange); -} - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a blob. Setting - * a value to true means that any SAS which uses these permissions will grant permissions for that operation. Once all - * the values are set, this should be serialized with toString and set as the permissions field on a - * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but - * the order of the permissions is particular and this class guarantees correctness. - * - * @export - * @class BlobSASPermissions - */ -var BlobSASPermissions = /** @class */ (function () { - function BlobSASPermissions() { - /** - * Specifies Read access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.read = false; - /** - * Specifies Add access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.add = false; - /** - * Specifies Create access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.create = false; - /** - * Specifies Write access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.write = false; - /** - * Specifies Delete access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.delete = false; - /** - * Specifies Delete version access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.deleteVersion = false; - /** - * Specfies Tag access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.tag = false; - /** - * Specifies Move access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.move = false; - /** - * Specifies Execute access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.execute = false; - } /** - * Creates a {@link BlobSASPermissions} from the specified permissions string. This method will throw an - * Error if it encounters a character that does not correspond to a valid permission. + * Returns an AsyncIterableIterator for ServiceListContainersSegmentResponses * - * @static - * @param {string} permissions - * @returns {BlobSASPermissions} - * @memberof BlobSASPermissions + * @private + * @param {string} [marker] A string value that identifies the portion of + * the list of containers to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all containers remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ServiceListContainersSegmentOptions} [options] Options to list containers operation. + * @returns {AsyncIterableIterator} + * @memberof BlobServiceClient */ - BlobSASPermissions.parse = function (permissions) { - var blobSASPermissions = new BlobSASPermissions(); - for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { - var char = permissions_1[_i]; - switch (char) { - case "r": - blobSASPermissions.read = true; - break; - case "a": - blobSASPermissions.add = true; - break; - case "c": - blobSASPermissions.create = true; - break; - case "w": - blobSASPermissions.write = true; - break; - case "d": - blobSASPermissions.delete = true; - break; - case "x": - blobSASPermissions.deleteVersion = true; - break; - case "t": - blobSASPermissions.tag = true; - break; - case "m": - blobSASPermissions.move = true; - break; - case "e": - blobSASPermissions.execute = true; - break; - default: - throw new RangeError("Invalid permission: " + char); - } - } - return blobSASPermissions; + BlobServiceClient.prototype.listSegments = function (marker, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listSegments_1() { + var listContainersSegmentResponse; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!(!!marker || marker === undefined)) return [3 /*break*/, 7]; + _a.label = 1; + case 1: return [4 /*yield*/, tslib.__await(this.listContainersSegment(marker, options))]; + case 2: + listContainersSegmentResponse = _a.sent(); + listContainersSegmentResponse.containerItems = + listContainersSegmentResponse.containerItems || []; + marker = listContainersSegmentResponse.continuationToken; + return [4 /*yield*/, tslib.__await(listContainersSegmentResponse)]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_a.sent()])]; + case 4: return [4 /*yield*/, _a.sent()]; + case 5: + _a.sent(); + _a.label = 6; + case 6: + if (marker) return [3 /*break*/, 1]; + _a.label = 7; + case 7: return [2 /*return*/]; + } + }); + }); }; /** - * Converts the given permissions to a string. Using this method will guarantee the permissions are in an - * order accepted by the service. + * Returns an AsyncIterableIterator for Container Items * - * @returns {string} A string which represents the BlobSASPermissions - * @memberof BlobSASPermissions + * @private + * @param {ServiceListContainersSegmentOptions} [options] Options to list containers operation. + * @returns {AsyncIterableIterator} + * @memberof BlobServiceClient */ - BlobSASPermissions.prototype.toString = function () { - var permissions = []; - if (this.read) { - permissions.push("r"); - } - if (this.add) { - permissions.push("a"); - } - if (this.create) { - permissions.push("c"); - } - if (this.write) { - permissions.push("w"); - } - if (this.delete) { - permissions.push("d"); - } - if (this.deleteVersion) { - permissions.push("x"); - } - if (this.tag) { - permissions.push("t"); - } - if (this.move) { - permissions.push("m"); - } - if (this.execute) { - permissions.push("e"); - } - return permissions.join(""); + BlobServiceClient.prototype.listItems = function (options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listItems_1() { + var marker, _a, _b, segment, e_11_1; + var e_11, _c; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _d.trys.push([0, 7, 8, 13]); + _a = tslib.__asyncValues(this.listSegments(marker, options)); + _d.label = 1; + case 1: return [4 /*yield*/, tslib.__await(_a.next())]; + case 2: + if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; + segment = _b.value; + return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(segment.containerItems)))]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; + case 4: + _d.sent(); + _d.label = 5; + case 5: return [3 /*break*/, 1]; + case 6: return [3 /*break*/, 13]; + case 7: + e_11_1 = _d.sent(); + e_11 = { error: e_11_1 }; + return [3 /*break*/, 13]; + case 8: + _d.trys.push([8, , 11, 12]); + if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; + return [4 /*yield*/, tslib.__await(_c.call(_a))]; + case 9: + _d.sent(); + _d.label = 10; + case 10: return [3 /*break*/, 12]; + case 11: + if (e_11) throw e_11.error; + return [7 /*endfinally*/]; + case 12: return [7 /*endfinally*/]; + case 13: return [2 /*return*/]; + } + }); + }); }; - return BlobSASPermissions; -}()); - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -/** - * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a container. - * Setting a value to true means that any SAS which uses these permissions will grant permissions for that operation. - * Once all the values are set, this should be serialized with toString and set as the permissions field on a - * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but - * the order of the permissions is particular and this class guarantees correctness. - * - * @export - * @class ContainerSASPermissions - */ -var ContainerSASPermissions = /** @class */ (function () { - function ContainerSASPermissions() { - /** - * Specifies Read access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.read = false; - /** - * Specifies Add access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.add = false; - /** - * Specifies Create access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.create = false; - /** - * Specifies Write access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.write = false; - /** - * Specifies Delete access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.delete = false; - /** - * Specifies Delete version access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.deleteVersion = false; - /** - * Specifies List access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.list = false; - /** - * Specfies Tag access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.tag = false; - /** - * Specifies Move access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.move = false; - /** - * Specifies Execute access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.execute = false; - } /** - * Creates an {@link ContainerSASPermissions} from the specified permissions string. This method will throw an - * Error if it encounters a character that does not correspond to a valid permission. + * Returns an async iterable iterator to list all the containers + * under the specified account. * - * @static - * @param {string} permissions - * @returns {ContainerSASPermissions} - * @memberof ContainerSASPermissions + * .byPage() returns an async iterable iterator to list the containers in pages. + * + * Example using `for await` syntax: + * + * ```js + * let i = 1; + * for await (const container of blobServiceClient.listContainers()) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * const iter = blobServiceClient.listContainers(); + * let containerItem = await iter.next(); + * while (!containerItem.done) { + * console.log(`Container ${i++}: ${containerItem.value.name}`); + * containerItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of blobServiceClient.listContainers().byPage({ maxPageSize: 20 })) { + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = blobServiceClient.listContainers().byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 container names + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * // Passing next marker as continuationToken + * iterator = blobServiceClient + * .listContainers() + * .byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints 10 container names + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * ``` + * + * @param {ServiceListContainersOptions} [options={}] Options to list containers. + * @returns {PagedAsyncIterableIterator} An asyncIterableIterator that supports paging. + * @memberof BlobServiceClient */ - ContainerSASPermissions.parse = function (permissions) { - var containerSASPermissions = new ContainerSASPermissions(); - for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { - var char = permissions_1[_i]; - switch (char) { - case "r": - containerSASPermissions.read = true; - break; - case "a": - containerSASPermissions.add = true; - break; - case "c": - containerSASPermissions.create = true; - break; - case "w": - containerSASPermissions.write = true; - break; - case "d": - containerSASPermissions.delete = true; - break; - case "l": - containerSASPermissions.list = true; - break; - case "t": - containerSASPermissions.tag = true; - break; - case "x": - containerSASPermissions.deleteVersion = true; - break; - case "m": - containerSASPermissions.move = true; - break; - case "e": - containerSASPermissions.execute = true; - break; - default: - throw new RangeError("Invalid permission " + char); - } + BlobServiceClient.prototype.listContainers = function (options) { + var _a; + var _this = this; + if (options === void 0) { options = {}; } + if (options.prefix === "") { + options.prefix = undefined; } - return containerSASPermissions; + var include = []; + if (options.includeDeleted) { + include.push("deleted"); + } + if (options.includeMetadata) { + include.push("metadata"); + } + // AsyncIterableIterator to iterate over containers + var listSegmentOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); + var iter = this.listItems(listSegmentOptions); + return _a = { + /** + * @member {Promise} [next] The next method, part of the iteration protocol + */ + next: function () { + return iter.next(); + } + }, + /** + * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol + */ + _a[Symbol.asyncIterator] = function () { + return this; + }, + /** + * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time + */ + _a.byPage = function (settings) { + if (settings === void 0) { settings = {}; } + return _this.listSegments(settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + }, + _a; }; /** - * Converts the given permissions to a string. Using this method will guarantee the permissions are in an - * order accepted by the service. + * ONLY AVAILABLE WHEN USING BEARER TOKEN AUTHENTICATION (TokenCredential). * - * The order of the characters should be as specified here to ensure correctness. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas + * Retrieves a user delegation key for the Blob service. This is only a valid operation when using + * bearer token authentication. * - * @returns {string} - * @memberof ContainerSASPermissions + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-user-delegation-key + * + * @param {Date} startsOn The start time for the user delegation SAS. Must be within 7 days of the current time + * @param {Date} expiresOn The end time for the user delegation SAS. Must be within 7 days of the current time + * @returns {Promise} + * @memberof BlobServiceClient */ - ContainerSASPermissions.prototype.toString = function () { - var permissions = []; - if (this.read) { - permissions.push("r"); - } - if (this.add) { - permissions.push("a"); - } - if (this.create) { - permissions.push("c"); - } - if (this.write) { - permissions.push("w"); - } - if (this.delete) { - permissions.push("d"); - } - if (this.deleteVersion) { - permissions.push("x"); - } - if (this.list) { - permissions.push("l"); - } - if (this.tag) { - permissions.push("t"); - } - if (this.move) { - permissions.push("m"); - } - if (this.execute) { - permissions.push("e"); - } - return permissions.join(""); + BlobServiceClient.prototype.getUserDelegationKey = function (startsOn, expiresOn, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, response, userDelegationKey, res, e_12; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-getUserDelegationKey", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.getUserDelegationKey({ + startsOn: truncatedISO8061Date(startsOn, false), + expiresOn: truncatedISO8061Date(expiresOn, false) + }, { + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: + response = _b.sent(); + userDelegationKey = { + signedObjectId: response.signedObjectId, + signedTenantId: response.signedTenantId, + signedStartsOn: new Date(response.signedStartsOn), + signedExpiresOn: new Date(response.signedExpiresOn), + signedService: response.signedService, + signedVersion: response.signedVersion, + value: response.value + }; + res = tslib.__assign({ _response: response._response, requestId: response.requestId, clientRequestId: response.clientRequestId, version: response.version, date: response.date, errorCode: response.errorCode }, userDelegationKey); + return [2 /*return*/, res]; + case 3: + e_12 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_12.message + }); + throw e_12; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; - return ContainerSASPermissions; -}()); - -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * UserDelegationKeyCredential is only used for generation of user delegation SAS. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas - * - * @export - * @class UserDelegationKeyCredential - */ -var UserDelegationKeyCredential = /** @class */ (function () { /** - * Creates an instance of UserDelegationKeyCredential. - * @param {string} accountName - * @param {UserDelegationKey} userDelegationKey - * @memberof UserDelegationKeyCredential + * Creates a BlobBatchClient object to conduct batch operations. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch + * + * @returns {BlobBatchClient} A new BlobBatchClient object for this service. + * @memberof BlobServiceClient */ - function UserDelegationKeyCredential(accountName, userDelegationKey) { - this.accountName = accountName; - this.userDelegationKey = userDelegationKey; - this.key = Buffer.from(userDelegationKey.value, "base64"); - } + BlobServiceClient.prototype.getBlobBatchClient = function () { + return new BlobBatchClient(this.url, this.pipeline); + }; /** - * Generates a hash signature for an HTTP request or for a SAS. + * Only available for BlobServiceClient constructed with a shared key credential. * - * @param {string} stringToSign - * @returns {string} - * @memberof UserDelegationKeyCredential + * Generates a Blob account Shared Access Signature (SAS) URI based on the client properties + * and parameters passed in. The SAS is signed by the shared key credential of the client. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-account-sas + * + * @param {Date} expiresOn Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not provided. + * @param {AccountSASPermissions} [permissions=AccountSASPermissions.parse("r")] Specifies the list of permissions to be associated with the SAS. + * @param {string} [resourceTypes="sco"] Specifies the resource types associated with the shared access signature. + * @param {ServiceGenerateAccountSasUrlOptions} [options={}] Optional parameters. + * @returns {string} An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + * @memberof BlobServiceClient */ - UserDelegationKeyCredential.prototype.computeHMACSHA256 = function (stringToSign) { - // console.log(`stringToSign: ${JSON.stringify(stringToSign)}`); - return crypto.createHmac("sha256", this.key) - .update(stringToSign, "utf8") - .digest("base64"); - }; - return UserDelegationKeyCredential; -}()); - -// Copyright (c) Microsoft Corporation. All rights reserved. -function generateBlobSASQueryParameters(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { - var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; - var sharedKeyCredential = sharedKeyCredentialOrUserDelegationKey instanceof StorageSharedKeyCredential - ? sharedKeyCredentialOrUserDelegationKey - : undefined; - var userDelegationKeyCredential; - if (sharedKeyCredential === undefined && accountName !== undefined) { - userDelegationKeyCredential = new UserDelegationKeyCredential(accountName, sharedKeyCredentialOrUserDelegationKey); - } - if (sharedKeyCredential === undefined && userDelegationKeyCredential === undefined) { - throw TypeError("Invalid sharedKeyCredential, userDelegationKey or accountName."); - } - // Version 2019-12-12 adds support for the blob tags permission. - // Version 2018-11-09 adds support for the signed resource and signed blob snapshot time fields. - // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas#constructing-the-signature-string - if (version >= "2018-11-09") { - if (sharedKeyCredential !== undefined) { - return generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential); - } - else { - // Version 2020-02-10 delegation SAS signature construction includes preauthorizedAgentObjectId, agentObjectId, correlationId. - if (version >= "2020-02-10") { - return generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userDelegationKeyCredential); - } - else { - return generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential); - } - } - } - if (version >= "2015-04-05") { - if (sharedKeyCredential !== undefined) { - return generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential); - } - else { - throw new RangeError("'version' must be >= '2018-11-09' when generating user delegation SAS using user delegation key."); - } - } - throw new RangeError("'version' must be >= '2015-04-05'."); -} -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * IMPLEMENTATION FOR API VERSION FROM 2015-04-05 AND BEFORE 2018-11-09. - * - * Creates an instance of SASQueryParameters. - * - * Only accepts required settings needed to create a SAS. For optional settings please - * set corresponding properties directly, such as permissions, startsOn and identifier. - * - * WARNING: When identifier is not provided, permissions and expiresOn are required. - * You MUST assign value to identifier or expiresOn & permissions manually if you initial with - * this constructor. - * - * @param {BlobSASSignatureValues} blobSASSignatureValues - * @param {StorageSharedKeyCredential} sharedKeyCredential - * @returns {SASQueryParameters} - */ -function generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential) { - blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); - if (!blobSASSignatureValues.identifier && - !blobSASSignatureValues.permissions && - !blobSASSignatureValues.expiresOn) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); - } - var resource = "c"; - if (blobSASSignatureValues.blobName) { - resource = "b"; - } - // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; - if (blobSASSignatureValues.permissions) { - if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - else { - verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - } - // Signature is generated on the un-url-encoded values. - var stringToSign = [ - verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn - ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) - : "", - blobSASSignatureValues.expiresOn - ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) - : "", - getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), - blobSASSignatureValues.identifier, - blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", - blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", - blobSASSignatureValues.version, - blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", - blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", - blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", - blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", - blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" - ].join("\n"); - var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); -} -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. - * - * Creates an instance of SASQueryParameters. - * - * Only accepts required settings needed to create a SAS. For optional settings please - * set corresponding properties directly, such as permissions, startsOn and identifier. - * - * WARNING: When identifier is not provided, permissions and expiresOn are required. - * You MUST assign value to identifier or expiresOn & permissions manually if you initial with - * this constructor. - * - * @param {BlobSASSignatureValues} blobSASSignatureValues - * @param {StorageSharedKeyCredential} sharedKeyCredential - * @returns {SASQueryParameters} - */ -function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential) { - blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); - if (!blobSASSignatureValues.identifier && - !blobSASSignatureValues.permissions && - !blobSASSignatureValues.expiresOn) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); - } - var resource = "c"; - var timestamp = blobSASSignatureValues.snapshotTime; - if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; - } - else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; - } - } - // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; - if (blobSASSignatureValues.permissions) { - if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - else { - verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - } - // Signature is generated on the un-url-encoded values. - var stringToSign = [ - verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn - ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) - : "", - blobSASSignatureValues.expiresOn - ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) - : "", - getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), - blobSASSignatureValues.identifier, - blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", - blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", - blobSASSignatureValues.version, - resource, - timestamp, - blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", - blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", - blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", - blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", - blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" - ].join("\n"); - var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); -} -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. - * - * Creates an instance of SASQueryParameters. - * - * Only accepts required settings needed to create a SAS. For optional settings please - * set corresponding properties directly, such as permissions, startsOn. - * - * WARNING: identifier will be ignored, permissions and expiresOn are required. - * - * @param {BlobSASSignatureValues} blobSASSignatureValues - * @param {UserDelegationKeyCredential} userDelegationKeyCredential - * @returns {SASQueryParameters} - */ -function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential) { - blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); - // Stored access policies are not supported for a user delegation SAS. - if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); - } - var resource = "c"; - var timestamp = blobSASSignatureValues.snapshotTime; - if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; - } - else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; - } - } - // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; - if (blobSASSignatureValues.permissions) { - if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - else { - verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - } - // Signature is generated on the un-url-encoded values. - var stringToSign = [ - verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn - ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) - : "", - blobSASSignatureValues.expiresOn - ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) - : "", - getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), - userDelegationKeyCredential.userDelegationKey.signedObjectId, - userDelegationKeyCredential.userDelegationKey.signedTenantId, - userDelegationKeyCredential.userDelegationKey.signedStartsOn - ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) - : "", - userDelegationKeyCredential.userDelegationKey.signedExpiresOn - ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) - : "", - userDelegationKeyCredential.userDelegationKey.signedService, - userDelegationKeyCredential.userDelegationKey.signedVersion, - blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", - blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", - blobSASSignatureValues.version, - resource, - timestamp, - blobSASSignatureValues.cacheControl, - blobSASSignatureValues.contentDisposition, - blobSASSignatureValues.contentEncoding, - blobSASSignatureValues.contentLanguage, - blobSASSignatureValues.contentType - ].join("\n"); - var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey); -} -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * IMPLEMENTATION FOR API VERSION FROM 2020-02-10. - * - * Creates an instance of SASQueryParameters. - * - * Only accepts required settings needed to create a SAS. For optional settings please - * set corresponding properties directly, such as permissions, startsOn. - * - * WARNING: identifier will be ignored, permissions and expiresOn are required. - * - * @param {BlobSASSignatureValues} blobSASSignatureValues - * @param {UserDelegationKeyCredential} userDelegationKeyCredential - * @returns {SASQueryParameters} - */ -function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userDelegationKeyCredential) { - blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); - // Stored access policies are not supported for a user delegation SAS. - if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); - } - var resource = "c"; - var timestamp = blobSASSignatureValues.snapshotTime; - if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; - } - else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; - } - } - // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; - if (blobSASSignatureValues.permissions) { - if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + BlobServiceClient.prototype.generateAccountSasUrl = function (expiresOn, permissions, resourceTypes, options) { + if (permissions === void 0) { permissions = AccountSASPermissions.parse("r"); } + if (resourceTypes === void 0) { resourceTypes = "sco"; } + if (options === void 0) { options = {}; } + if (!(this.credential instanceof StorageSharedKeyCredential)) { + throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); } - else { - verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + if (expiresOn === undefined) { + var now = new Date(); + expiresOn = new Date(now.getTime() + 3600 * 1000); } - } - // Signature is generated on the un-url-encoded values. - var stringToSign = [ - verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn - ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) - : "", - blobSASSignatureValues.expiresOn - ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) - : "", - getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), - userDelegationKeyCredential.userDelegationKey.signedObjectId, - userDelegationKeyCredential.userDelegationKey.signedTenantId, - userDelegationKeyCredential.userDelegationKey.signedStartsOn - ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) - : "", - userDelegationKeyCredential.userDelegationKey.signedExpiresOn - ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) - : "", - userDelegationKeyCredential.userDelegationKey.signedService, - userDelegationKeyCredential.userDelegationKey.signedVersion, - blobSASSignatureValues.preauthorizedAgentObjectId, - undefined, - blobSASSignatureValues.correlationId, - blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", - blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", - blobSASSignatureValues.version, - resource, - timestamp, - blobSASSignatureValues.cacheControl, - blobSASSignatureValues.contentDisposition, - blobSASSignatureValues.contentEncoding, - blobSASSignatureValues.contentLanguage, - blobSASSignatureValues.contentType - ].join("\n"); - var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId); -} -function getCanonicalName(accountName, containerName, blobName) { - // Container: "/blob/account/containerName" - // Blob: "/blob/account/containerName/blobName" - var elements = ["/blob/" + accountName + "/" + containerName]; - if (blobName) { - elements.push("/" + blobName); - } - return elements.join(""); -} -function SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues) { - var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; - if (blobSASSignatureValues.snapshotTime && version < "2018-11-09") { - throw RangeError("'version' must be >= '2018-11-09' when providing 'snapshotTime'."); - } - if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.snapshotTime) { - throw RangeError("Must provide 'blobName' when providing 'snapshotTime'."); - } - if (blobSASSignatureValues.versionId && version < "2019-10-10") { - throw RangeError("'version' must be >= '2019-10-10' when providing 'versionId'."); - } - if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.versionId) { - throw RangeError("Must provide 'blobName' when providing 'versionId'."); - } - if (blobSASSignatureValues.permissions && - blobSASSignatureValues.permissions.deleteVersion && - version < "2019-10-10") { - throw RangeError("'version' must be >= '2019-10-10' when providing 'x' permission."); - } - if (blobSASSignatureValues.permissions && - blobSASSignatureValues.permissions.tag && - version < "2019-12-12") { - throw RangeError("'version' must be >= '2019-12-12' when providing 't' permission."); - } - if (version < "2020-02-10" && - blobSASSignatureValues.permissions && - (blobSASSignatureValues.permissions.move || blobSASSignatureValues.permissions.execute)) { - throw RangeError("'version' must be >= '2020-02-10' when providing the 'm' or 'e' permission."); - } - if (version < "2020-02-10" && - (blobSASSignatureValues.preauthorizedAgentObjectId || blobSASSignatureValues.correlationId)) { - throw RangeError("'version' must be >= '2020-02-10' when providing 'preauthorizedAgentObjectId' or 'correlationId'."); - } - blobSASSignatureValues.version = version; - return blobSASSignatureValues; -} + var sas = generateAccountSASQueryParameters(tslib.__assign({ permissions: permissions, + expiresOn: expiresOn, + resourceTypes: resourceTypes, services: AccountSASServices.parse("b").toString() }, options), this.credential).toString(); + return appendToURLQuery(this.url, sas); + }; + return BlobServiceClient; +}(StorageClient)); Object.defineProperty(exports, 'BaseRequestPolicy', { enumerable: true, @@ -38994,288 +39468,7 @@ module.exports = require("crypto"); /* 419 */, /* 420 */, /* 421 */, -/* 422 */ -/***/ (function(module) { - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ -/* global global, define, System, Reflect, Promise */ -var __extends; -var __assign; -var __rest; -var __decorate; -var __param; -var __metadata; -var __awaiter; -var __generator; -var __exportStar; -var __values; -var __read; -var __spread; -var __spreadArrays; -var __await; -var __asyncGenerator; -var __asyncDelegator; -var __asyncValues; -var __makeTemplateObject; -var __importStar; -var __importDefault; -var __classPrivateFieldGet; -var __classPrivateFieldSet; -(function (factory) { - var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; - if (typeof define === "function" && define.amd) { - define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); - } - else if ( true && typeof module.exports === "object") { - factory(createExporter(root, createExporter(module.exports))); - } - else { - factory(createExporter(root)); - } - function createExporter(exports, previous) { - if (exports !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports, "__esModule", { value: true }); - } - else { - exports.__esModule = true; - } - } - return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; - } -}) -(function (exporter) { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - - __extends = function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - - __assign = Object.assign || function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - - __rest = function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; - - __decorate = function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - - __param = function (paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - }; - - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - }; - - __awaiter = function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - - __generator = function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - - __exportStar = function (m, exports) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; - }; - - __values = function (o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - - __read = function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - - __spread = function () { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - }; - - __spreadArrays = function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; - }; - - __await = function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - - __asyncGenerator = function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - }; - - __asyncDelegator = function (o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } - }; - - __asyncValues = function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } - }; - - __makeTemplateObject = function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - }; - - __importStar = function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; - }; - - __importDefault = function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - - __classPrivateFieldGet = function (receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - return privateMap.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - privateMap.set(receiver, value); - return value; - } - - exporter("__extends", __extends); - exporter("__assign", __assign); - exporter("__rest", __rest); - exporter("__decorate", __decorate); - exporter("__param", __param); - exporter("__metadata", __metadata); - exporter("__awaiter", __awaiter); - exporter("__generator", __generator); - exporter("__exportStar", __exportStar); - exporter("__values", __values); - exporter("__read", __read); - exporter("__spread", __spread); - exporter("__spreadArrays", __spreadArrays); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); - exporter("__asyncDelegator", __asyncDelegator); - exporter("__asyncValues", __asyncValues); - exporter("__makeTemplateObject", __makeTemplateObject); - exporter("__importStar", __importStar); - exporter("__importDefault", __importDefault); - exporter("__classPrivateFieldGet", __classPrivateFieldGet); - exporter("__classPrivateFieldSet", __classPrivateFieldSet); -}); - - -/***/ }), +/* 422 */, /* 423 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -39856,130 +40049,167 @@ function escapeProperty(s) { /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const exec_1 = __webpack_require__(986); -const io = __importStar(__webpack_require__(1)); -const fs_1 = __webpack_require__(747); -const path = __importStar(__webpack_require__(622)); -const utils = __importStar(__webpack_require__(15)); -const constants_1 = __webpack_require__(931); -function getTarPath(args, compressionMethod) { - return __awaiter(this, void 0, void 0, function* () { - const IS_WINDOWS = process.platform === 'win32'; - if (IS_WINDOWS) { - const systemTar = `${process.env['windir']}\\System32\\tar.exe`; - if (compressionMethod !== constants_1.CompressionMethod.Gzip) { - // We only use zstandard compression on windows when gnu tar is installed due to - // a bug with compressing large files with bsdtar + zstd - args.push('--force-local'); - } - else if (fs_1.existsSync(systemTar)) { - return systemTar; - } - else if (yield utils.isGnuTarInstalled()) { - args.push('--force-local'); - } - } - return yield io.which('tar', true); - }); -} -function execTar(args, compressionMethod, cwd) { - return __awaiter(this, void 0, void 0, function* () { - try { - yield exec_1.exec(`"${yield getTarPath(args, compressionMethod)}"`, args, { cwd }); - } - catch (error) { - throw new Error(`Tar failed with error: ${error === null || error === void 0 ? void 0 : error.message}`); - } - }); -} -function getWorkingDirectory() { - var _a; - return (_a = process.env['GITHUB_WORKSPACE']) !== null && _a !== void 0 ? _a : process.cwd(); -} -function extractTar(archivePath, compressionMethod) { - return __awaiter(this, void 0, void 0, function* () { - // Create directory to extract tar into - const workingDirectory = getWorkingDirectory(); - yield io.mkdirP(workingDirectory); - // --d: Decompress. - // --long=#: Enables long distance matching with # bits. Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit. - // Using 30 here because we also support 32-bit self-hosted runners. - function getCompressionProgram() { - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return ['--use-compress-program', 'zstd -d --long=30']; - case constants_1.CompressionMethod.ZstdWithoutLong: - return ['--use-compress-program', 'zstd -d']; - default: - return ['-z']; - } - } - const args = [ - ...getCompressionProgram(), - '-xf', - archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), - '-P', - '-C', - workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/') - ]; - yield execTar(args, compressionMethod); - }); -} -exports.extractTar = extractTar; -function createTar(archiveFolder, sourceDirectories, compressionMethod) { - return __awaiter(this, void 0, void 0, function* () { - // Write source directories to manifest.txt to avoid command length limits - const manifestFilename = 'manifest.txt'; - const cacheFileName = utils.getCacheFileName(compressionMethod); - fs_1.writeFileSync(path.join(archiveFolder, manifestFilename), sourceDirectories.join('\n')); - const workingDirectory = getWorkingDirectory(); - // -T#: Compress using # working thread. If # is 0, attempt to detect and use the number of physical CPU cores. - // --long=#: Enables long distance matching with # bits. Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit. - // Using 30 here because we also support 32-bit self-hosted runners. - // Long range mode is added to zstd in v1.3.2 release, so we will not use --long in older version of zstd. - function getCompressionProgram() { - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return ['--use-compress-program', 'zstd -T0 --long=30']; - case constants_1.CompressionMethod.ZstdWithoutLong: - return ['--use-compress-program', 'zstd -T0']; - default: - return ['-z']; - } - } - const args = [ - '--posix', - ...getCompressionProgram(), - '-cf', - cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), - '-P', - '-C', - workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), - '--files-from', - manifestFilename - ]; - yield execTar(args, compressionMethod, archiveFolder); - }); -} -exports.createTar = createTar; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const exec_1 = __webpack_require__(986); +const io = __importStar(__webpack_require__(1)); +const fs_1 = __webpack_require__(747); +const path = __importStar(__webpack_require__(622)); +const utils = __importStar(__webpack_require__(15)); +const constants_1 = __webpack_require__(931); +function getTarPath(args, compressionMethod) { + return __awaiter(this, void 0, void 0, function* () { + switch (process.platform) { + case 'win32': { + const systemTar = `${process.env['windir']}\\System32\\tar.exe`; + if (compressionMethod !== constants_1.CompressionMethod.Gzip) { + // We only use zstandard compression on windows when gnu tar is installed due to + // a bug with compressing large files with bsdtar + zstd + args.push('--force-local'); + } + else if (fs_1.existsSync(systemTar)) { + return systemTar; + } + else if (yield utils.isGnuTarInstalled()) { + args.push('--force-local'); + } + break; + } + case 'darwin': { + const gnuTar = yield io.which('gtar', false); + if (gnuTar) { + return gnuTar; + } + break; + } + default: + break; + } + return yield io.which('tar', true); + }); +} +function execTar(args, compressionMethod, cwd) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield exec_1.exec(`"${yield getTarPath(args, compressionMethod)}"`, args, { cwd }); + } + catch (error) { + throw new Error(`Tar failed with error: ${error === null || error === void 0 ? void 0 : error.message}`); + } + }); +} +function getWorkingDirectory() { + var _a; + return (_a = process.env['GITHUB_WORKSPACE']) !== null && _a !== void 0 ? _a : process.cwd(); +} +function extractTar(archivePath, compressionMethod) { + return __awaiter(this, void 0, void 0, function* () { + // Create directory to extract tar into + const workingDirectory = getWorkingDirectory(); + yield io.mkdirP(workingDirectory); + // --d: Decompress. + // --long=#: Enables long distance matching with # bits. Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit. + // Using 30 here because we also support 32-bit self-hosted runners. + function getCompressionProgram() { + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return ['--use-compress-program', 'zstd -d --long=30']; + case constants_1.CompressionMethod.ZstdWithoutLong: + return ['--use-compress-program', 'zstd -d']; + default: + return ['-z']; + } + } + const args = [ + ...getCompressionProgram(), + '-xf', + archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), + '-P', + '-C', + workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/') + ]; + yield execTar(args, compressionMethod); + }); +} +exports.extractTar = extractTar; +function createTar(archiveFolder, sourceDirectories, compressionMethod) { + return __awaiter(this, void 0, void 0, function* () { + // Write source directories to manifest.txt to avoid command length limits + const manifestFilename = 'manifest.txt'; + const cacheFileName = utils.getCacheFileName(compressionMethod); + fs_1.writeFileSync(path.join(archiveFolder, manifestFilename), sourceDirectories.join('\n')); + const workingDirectory = getWorkingDirectory(); + // -T#: Compress using # working thread. If # is 0, attempt to detect and use the number of physical CPU cores. + // --long=#: Enables long distance matching with # bits. Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit. + // Using 30 here because we also support 32-bit self-hosted runners. + // Long range mode is added to zstd in v1.3.2 release, so we will not use --long in older version of zstd. + function getCompressionProgram() { + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return ['--use-compress-program', 'zstd -T0 --long=30']; + case constants_1.CompressionMethod.ZstdWithoutLong: + return ['--use-compress-program', 'zstd -T0']; + default: + return ['-z']; + } + } + const args = [ + '--posix', + ...getCompressionProgram(), + '-cf', + cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), + '-P', + '-C', + workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), + '--files-from', + manifestFilename + ]; + yield execTar(args, compressionMethod, archiveFolder); + }); +} +exports.createTar = createTar; +function listTar(archivePath, compressionMethod) { + return __awaiter(this, void 0, void 0, function* () { + // --d: Decompress. + // --long=#: Enables long distance matching with # bits. + // Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit. + // Using 30 here because we also support 32-bit self-hosted runners. + function getCompressionProgram() { + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return ['--use-compress-program', 'zstd -d --long=30']; + case constants_1.CompressionMethod.ZstdWithoutLong: + return ['--use-compress-program', 'zstd -d']; + default: + return ['-z']; + } + } + const args = [ + ...getCompressionProgram(), + '-tf', + archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), + '-P' + ]; + yield execTar(args, compressionMethod); + }); +} +exports.listTar = listTar; //# sourceMappingURL=tar.js.map /***/ }), @@ -40057,7 +40287,7 @@ __exportStar(__webpack_require__(975), exports); __exportStar(__webpack_require__(70), exports); __exportStar(__webpack_require__(694), exports); __exportStar(__webpack_require__(695), exports); -var context_base_1 = __webpack_require__(231); +var context_base_1 = __webpack_require__(459); Object.defineProperty(exports, "Context", { enumerable: true, get: function () { return context_base_1.Context; } }); var context_1 = __webpack_require__(492); /** Entrypoint for context API */ @@ -42279,7 +42509,35 @@ exports.FetchError = FetchError; /***/ }), -/* 459 */, +/* 459 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +/*! + * Copyright 2019, OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(__webpack_require__(560)); +__export(__webpack_require__(53)); +//# sourceMappingURL=index.js.map + +/***/ }), /* 460 */ /***/ (function(module) { @@ -42872,7 +43130,7 @@ exports.getState = getState; */ Object.defineProperty(exports, "__esModule", { value: true }); exports.ContextAPI = void 0; -var context_base_1 = __webpack_require__(231); +var context_base_1 = __webpack_require__(459); var global_utils_1 = __webpack_require__(976); var NOOP_CONTEXT_MANAGER = new context_base_1.NoopContextManager(); /** @@ -44036,67 +44294,67 @@ function _unique(values) { /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(__webpack_require__(470)); -/** - * Returns a copy of the upload options with defaults filled in. - * - * @param copy the original upload options - */ -function getUploadOptions(copy) { - const result = { - uploadConcurrency: 4, - uploadChunkSize: 32 * 1024 * 1024 - }; - if (copy) { - if (typeof copy.uploadConcurrency === 'number') { - result.uploadConcurrency = copy.uploadConcurrency; - } - if (typeof copy.uploadChunkSize === 'number') { - result.uploadChunkSize = copy.uploadChunkSize; - } - } - core.debug(`Upload concurrency: ${result.uploadConcurrency}`); - core.debug(`Upload chunk size: ${result.uploadChunkSize}`); - return result; -} -exports.getUploadOptions = getUploadOptions; -/** - * Returns a copy of the download options with defaults filled in. - * - * @param copy the original download options - */ -function getDownloadOptions(copy) { - const result = { - useAzureSdk: true, - downloadConcurrency: 8, - timeoutInMs: 30000 - }; - if (copy) { - if (typeof copy.useAzureSdk === 'boolean') { - result.useAzureSdk = copy.useAzureSdk; - } - if (typeof copy.downloadConcurrency === 'number') { - result.downloadConcurrency = copy.downloadConcurrency; - } - if (typeof copy.timeoutInMs === 'number') { - result.timeoutInMs = copy.timeoutInMs; - } - } - core.debug(`Use Azure SDK: ${result.useAzureSdk}`); - core.debug(`Download concurrency: ${result.downloadConcurrency}`); - core.debug(`Request timeout (ms): ${result.timeoutInMs}`); - return result; -} -exports.getDownloadOptions = getDownloadOptions; + +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __importStar(__webpack_require__(470)); +/** + * Returns a copy of the upload options with defaults filled in. + * + * @param copy the original upload options + */ +function getUploadOptions(copy) { + const result = { + uploadConcurrency: 4, + uploadChunkSize: 32 * 1024 * 1024 + }; + if (copy) { + if (typeof copy.uploadConcurrency === 'number') { + result.uploadConcurrency = copy.uploadConcurrency; + } + if (typeof copy.uploadChunkSize === 'number') { + result.uploadChunkSize = copy.uploadChunkSize; + } + } + core.debug(`Upload concurrency: ${result.uploadConcurrency}`); + core.debug(`Upload chunk size: ${result.uploadChunkSize}`); + return result; +} +exports.getUploadOptions = getUploadOptions; +/** + * Returns a copy of the download options with defaults filled in. + * + * @param copy the original download options + */ +function getDownloadOptions(copy) { + const result = { + useAzureSdk: true, + downloadConcurrency: 8, + timeoutInMs: 30000 + }; + if (copy) { + if (typeof copy.useAzureSdk === 'boolean') { + result.useAzureSdk = copy.useAzureSdk; + } + if (typeof copy.downloadConcurrency === 'number') { + result.downloadConcurrency = copy.downloadConcurrency; + } + if (typeof copy.timeoutInMs === 'number') { + result.timeoutInMs = copy.timeoutInMs; + } + } + core.debug(`Use Azure SDK: ${result.useAzureSdk}`); + core.debug(`Download concurrency: ${result.downloadConcurrency}`); + core.debug(`Request timeout (ms): ${result.timeoutInMs}`); + return result; +} +exports.getDownloadOptions = getDownloadOptions; //# sourceMappingURL=options.js.map /***/ }), @@ -45223,7 +45481,90 @@ exports.defaultSetter = defaultSetter; /***/ }), -/* 560 */, +/* 560 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +/*! + * Copyright 2020, OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Class which stores and manages current context values. All methods which + * update context such as get and delete do not modify an existing context, + * but create a new one with updated values. + */ +class Context { + /** + * Construct a new context which inherits values from an optional parent context. + * + * @param parentContext a context from which to inherit values + */ + constructor(parentContext) { + this._currentContext = parentContext ? new Map(parentContext) : new Map(); + } + /** Get a key to uniquely identify a context value */ + static createKey(description) { + return Symbol(description); + } + /** + * Get a value from the context. + * + * @param key key which identifies a context value + */ + getValue(key) { + return this._currentContext.get(key); + } + /** + * Create a new context which inherits from this context and has + * the given key set to the given value. + * + * @param key context key for which to set the value + * @param value value to set for the given key + */ + setValue(key, value) { + const context = new Context(this._currentContext); + context._currentContext.set(key, value); + return context; + } + /** + * Return a new context which inherits from this context but does + * not contain a value for the given key. + * + * @param key context key for which to clear a value + */ + deleteValue(key) { + const context = new Context(this._currentContext); + context._currentContext.delete(key); + return context; + } +} +exports.Context = Context; +/** The root context is used as the default parent context when there is no active context */ +Context.ROOT_CONTEXT = new Context(); +/** + * This is another identifier to the root context which allows developers to easily search the + * codebase for direct uses of context which need to be removed in later PRs. + * + * It's existence is temporary and it should be removed when all references are fixed. + */ +Context.TODO = Context.ROOT_CONTEXT; +//# sourceMappingURL=context.js.map + +/***/ }), /* 561 */, /* 562 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { @@ -46639,152 +46980,159 @@ exports.makeSemver = makeSemver; /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(__webpack_require__(470)); -const path = __importStar(__webpack_require__(622)); -const utils = __importStar(__webpack_require__(15)); -const cacheHttpClient = __importStar(__webpack_require__(114)); -const tar_1 = __webpack_require__(434); -class ValidationError extends Error { - constructor(message) { - super(message); - this.name = 'ValidationError'; - Object.setPrototypeOf(this, ValidationError.prototype); - } -} -exports.ValidationError = ValidationError; -class ReserveCacheError extends Error { - constructor(message) { - super(message); - this.name = 'ReserveCacheError'; - Object.setPrototypeOf(this, ReserveCacheError.prototype); - } -} -exports.ReserveCacheError = ReserveCacheError; -function checkPaths(paths) { - if (!paths || paths.length === 0) { - throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); - } -} -function checkKey(key) { - if (key.length > 512) { - throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); - } - const regex = /^[^,]*$/; - if (!regex.test(key)) { - throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); - } -} -/** - * Restores cache from keys - * - * @param paths a list of file paths to restore from the cache - * @param primaryKey an explicit key for restoring the cache - * @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for key - * @param downloadOptions cache download options - * @returns string returns the key for the cache hit, otherwise returns undefined - */ -function restoreCache(paths, primaryKey, restoreKeys, options) { - return __awaiter(this, void 0, void 0, function* () { - checkPaths(paths); - restoreKeys = restoreKeys || []; - const keys = [primaryKey, ...restoreKeys]; - core.debug('Resolved Keys:'); - core.debug(JSON.stringify(keys)); - if (keys.length > 10) { - throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); - } - for (const key of keys) { - checkKey(key); - } - const compressionMethod = yield utils.getCompressionMethod(); - // path are needed to compute version - const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { - compressionMethod - }); - if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { - // Cache not found - return undefined; - } - const archivePath = path.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); - core.debug(`Archive Path: ${archivePath}`); - try { - // Download the cache from the cache entry - yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); - const archiveFileSize = utils.getArchiveFileSizeIsBytes(archivePath); - core.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); - yield tar_1.extractTar(archivePath, compressionMethod); - } - finally { - // Try to delete the archive to save space - try { - yield utils.unlinkFile(archivePath); - } - catch (error) { - core.debug(`Failed to delete archive: ${error}`); - } - } - return cacheEntry.cacheKey; - }); -} -exports.restoreCache = restoreCache; -/** - * Saves a list of files with the specified key - * - * @param paths a list of file paths to be cached - * @param key an explicit key for restoring the cache - * @param options cache upload options - * @returns number returns cacheId if the cache was saved successfully and throws an error if save fails - */ -function saveCache(paths, key, options) { - return __awaiter(this, void 0, void 0, function* () { - checkPaths(paths); - checkKey(key); - const compressionMethod = yield utils.getCompressionMethod(); - core.debug('Reserving Cache'); - const cacheId = yield cacheHttpClient.reserveCache(key, paths, { - compressionMethod - }); - if (cacheId === -1) { - throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); - } - core.debug(`Cache ID: ${cacheId}`); - const cachePaths = yield utils.resolvePaths(paths); - core.debug('Cache Paths:'); - core.debug(`${JSON.stringify(cachePaths)}`); - const archiveFolder = yield utils.createTempDirectory(); - const archivePath = path.join(archiveFolder, utils.getCacheFileName(compressionMethod)); - core.debug(`Archive Path: ${archivePath}`); - yield tar_1.createTar(archiveFolder, cachePaths, compressionMethod); - const fileSizeLimit = 5 * 1024 * 1024 * 1024; // 5GB per repo limit - const archiveFileSize = utils.getArchiveFileSizeIsBytes(archivePath); - core.debug(`File Size: ${archiveFileSize}`); - if (archiveFileSize > fileSizeLimit) { - throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 5GB limit, not saving cache.`); - } - core.debug(`Saving Cache (ID: ${cacheId})`); - yield cacheHttpClient.saveCache(cacheId, archivePath, options); - return cacheId; - }); -} -exports.saveCache = saveCache; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __importStar(__webpack_require__(470)); +const path = __importStar(__webpack_require__(622)); +const utils = __importStar(__webpack_require__(15)); +const cacheHttpClient = __importStar(__webpack_require__(114)); +const tar_1 = __webpack_require__(434); +class ValidationError extends Error { + constructor(message) { + super(message); + this.name = 'ValidationError'; + Object.setPrototypeOf(this, ValidationError.prototype); + } +} +exports.ValidationError = ValidationError; +class ReserveCacheError extends Error { + constructor(message) { + super(message); + this.name = 'ReserveCacheError'; + Object.setPrototypeOf(this, ReserveCacheError.prototype); + } +} +exports.ReserveCacheError = ReserveCacheError; +function checkPaths(paths) { + if (!paths || paths.length === 0) { + throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); + } +} +function checkKey(key) { + if (key.length > 512) { + throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); + } + const regex = /^[^,]*$/; + if (!regex.test(key)) { + throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); + } +} +/** + * Restores cache from keys + * + * @param paths a list of file paths to restore from the cache + * @param primaryKey an explicit key for restoring the cache + * @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for key + * @param downloadOptions cache download options + * @returns string returns the key for the cache hit, otherwise returns undefined + */ +function restoreCache(paths, primaryKey, restoreKeys, options) { + return __awaiter(this, void 0, void 0, function* () { + checkPaths(paths); + restoreKeys = restoreKeys || []; + const keys = [primaryKey, ...restoreKeys]; + core.debug('Resolved Keys:'); + core.debug(JSON.stringify(keys)); + if (keys.length > 10) { + throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + } + for (const key of keys) { + checkKey(key); + } + const compressionMethod = yield utils.getCompressionMethod(); + // path are needed to compute version + const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { + compressionMethod + }); + if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { + // Cache not found + return undefined; + } + const archivePath = path.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + core.debug(`Archive Path: ${archivePath}`); + try { + // Download the cache from the cache entry + yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); + if (core.isDebug()) { + yield tar_1.listTar(archivePath, compressionMethod); + } + const archiveFileSize = utils.getArchiveFileSizeIsBytes(archivePath); + core.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + yield tar_1.extractTar(archivePath, compressionMethod); + core.info('Cache restored successfully'); + } + finally { + // Try to delete the archive to save space + try { + yield utils.unlinkFile(archivePath); + } + catch (error) { + core.debug(`Failed to delete archive: ${error}`); + } + } + return cacheEntry.cacheKey; + }); +} +exports.restoreCache = restoreCache; +/** + * Saves a list of files with the specified key + * + * @param paths a list of file paths to be cached + * @param key an explicit key for restoring the cache + * @param options cache upload options + * @returns number returns cacheId if the cache was saved successfully and throws an error if save fails + */ +function saveCache(paths, key, options) { + return __awaiter(this, void 0, void 0, function* () { + checkPaths(paths); + checkKey(key); + const compressionMethod = yield utils.getCompressionMethod(); + core.debug('Reserving Cache'); + const cacheId = yield cacheHttpClient.reserveCache(key, paths, { + compressionMethod + }); + if (cacheId === -1) { + throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); + } + core.debug(`Cache ID: ${cacheId}`); + const cachePaths = yield utils.resolvePaths(paths); + core.debug('Cache Paths:'); + core.debug(`${JSON.stringify(cachePaths)}`); + const archiveFolder = yield utils.createTempDirectory(); + const archivePath = path.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + core.debug(`Archive Path: ${archivePath}`); + yield tar_1.createTar(archiveFolder, cachePaths, compressionMethod); + if (core.isDebug()) { + yield tar_1.listTar(archivePath, compressionMethod); + } + const fileSizeLimit = 5 * 1024 * 1024 * 1024; // 5GB per repo limit + const archiveFileSize = utils.getArchiveFileSizeIsBytes(archivePath); + core.debug(`File Size: ${archiveFileSize}`); + if (archiveFileSize > fileSizeLimit) { + throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 5GB limit, not saving cache.`); + } + core.debug(`Saving Cache (ID: ${cacheId})`); + yield cacheHttpClient.saveCache(cacheId, archivePath, options); + return cacheId; + }); +} +exports.saveCache = saveCache; //# sourceMappingURL=cache.js.map /***/ }), @@ -46873,7 +47221,316 @@ exports.saveCache = saveCache; /***/ }), -/* 640 */, +/* 640 */ +/***/ (function(module) { + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global global, define, System, Reflect, Promise */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __spreadArray; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __createBinding; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if ( true && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + + __extends = function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __exportStar = function(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); + }; + + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + }) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + /** @deprecated */ + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + /** @deprecated */ + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __spreadArray = function (to, from) { + for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) + to[j] = from[i]; + return to; + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, privateMap) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return privateMap.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, privateMap, value) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to set private field on non-instance"); + } + privateMap.set(receiver, value); + return value; + }; + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__spreadArray", __spreadArray); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); +}); + + +/***/ }), /* 641 */, /* 642 */, /* 643 */, @@ -49845,87 +50502,7 @@ __webpack_require__(71); /***/ }), /* 713 */, /* 714 */, -/* 715 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Context = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var Context = /** @class */ (function () { - /** - * Construct a new context which inherits values from an optional parent context. - * - * @param parentContext a context from which to inherit values - */ - function Context(parentContext) { - this._currentContext = parentContext ? new Map(parentContext) : new Map(); - } - /** Get a key to uniquely identify a context value */ - Context.createKey = function (description) { - return Symbol(description); - }; - /** - * Get a value from the context. - * - * @param key key which identifies a context value - */ - Context.prototype.getValue = function (key) { - return this._currentContext.get(key); - }; - /** - * Create a new context which inherits from this context and has - * the given key set to the given value. - * - * @param key context key for which to set the value - * @param value value to set for the given key - */ - Context.prototype.setValue = function (key, value) { - var context = new Context(this._currentContext); - context._currentContext.set(key, value); - return context; - }; - /** - * Return a new context which inherits from this context but does - * not contain a value for the given key. - * - * @param key context key for which to clear a value - */ - Context.prototype.deleteValue = function (key) { - var context = new Context(this._currentContext); - context._currentContext.delete(key); - return context; - }; - /** The root context is used as the default parent context when there is no active context */ - Context.ROOT_CONTEXT = new Context(); - /** - * This is another identifier to the root context which allows developers to easily search the - * codebase for direct uses of context which need to be removed in later PRs. - * - * It's existence is temporary and it should be removed when all references are fixed. - */ - Context.TODO = Context.ROOT_CONTEXT; - return Context; -}()); -exports.Context = Context; -//# sourceMappingURL=context.js.map - -/***/ }), +/* 715 */, /* 716 */, /* 717 */, /* 718 */, @@ -50136,7 +50713,316 @@ exports.saveCache = saveCache; /***/ }), -/* 725 */, +/* 725 */ +/***/ (function(module) { + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global global, define, System, Reflect, Promise */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __spreadArray; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __createBinding; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if ( true && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + + __extends = function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __exportStar = function(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); + }; + + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + }) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + /** @deprecated */ + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + /** @deprecated */ + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __spreadArray = function (to, from) { + for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) + to[j] = from[i]; + return to; + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, privateMap) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return privateMap.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, privateMap, value) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to set private field on non-instance"); + } + privateMap.set(receiver, value); + return value; + }; + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__spreadArray", __spreadArray); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); +}); + + +/***/ }), /* 726 */, /* 727 */ /***/ (function(__unusedmodule, exports) { @@ -57187,7 +58073,7 @@ exports.TraceAPI = TraceAPI; Object.defineProperty(exports, '__esModule', { value: true }); -var tslib = __webpack_require__(422); +var tslib = __webpack_require__(725); // Copyright (c) Microsoft Corporation. /** @@ -57857,124 +58743,124 @@ exports.withCustomRequest = withCustomRequest; /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(__webpack_require__(470)); -const http_client_1 = __webpack_require__(22); -const constants_1 = __webpack_require__(931); -function isSuccessStatusCode(statusCode) { - if (!statusCode) { - return false; - } - return statusCode >= 200 && statusCode < 300; -} -exports.isSuccessStatusCode = isSuccessStatusCode; -function isServerErrorStatusCode(statusCode) { - if (!statusCode) { - return true; - } - return statusCode >= 500; -} -exports.isServerErrorStatusCode = isServerErrorStatusCode; -function isRetryableStatusCode(statusCode) { - if (!statusCode) { - return false; - } - const retryableStatusCodes = [ - http_client_1.HttpCodes.BadGateway, - http_client_1.HttpCodes.ServiceUnavailable, - http_client_1.HttpCodes.GatewayTimeout - ]; - return retryableStatusCodes.includes(statusCode); -} -exports.isRetryableStatusCode = isRetryableStatusCode; -function sleep(milliseconds) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise(resolve => setTimeout(resolve, milliseconds)); - }); -} -function retry(name, method, getStatusCode, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay, onError = undefined) { - return __awaiter(this, void 0, void 0, function* () { - let errorMessage = ''; - let attempt = 1; - while (attempt <= maxAttempts) { - let response = undefined; - let statusCode = undefined; - let isRetryable = false; - try { - response = yield method(); - } - catch (error) { - if (onError) { - response = onError(error); - } - isRetryable = true; - errorMessage = error.message; - } - if (response) { - statusCode = getStatusCode(response); - if (!isServerErrorStatusCode(statusCode)) { - return response; - } - } - if (statusCode) { - isRetryable = isRetryableStatusCode(statusCode); - errorMessage = `Cache service responded with ${statusCode}`; - } - core.debug(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`); - if (!isRetryable) { - core.debug(`${name} - Error is not retryable`); - break; - } - yield sleep(delay); - attempt++; - } - throw Error(`${name} failed: ${errorMessage}`); - }); -} -exports.retry = retry; -function retryTypedResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) { - return __awaiter(this, void 0, void 0, function* () { - return yield retry(name, method, (response) => response.statusCode, maxAttempts, delay, - // If the error object contains the statusCode property, extract it and return - // an ITypedResponse so it can be processed by the retry logic. - (error) => { - if (error instanceof http_client_1.HttpClientError) { - return { - statusCode: error.statusCode, - result: null, - headers: {} - }; - } - else { - return undefined; - } - }); - }); -} -exports.retryTypedResponse = retryTypedResponse; -function retryHttpClientResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) { - return __awaiter(this, void 0, void 0, function* () { - return yield retry(name, method, (response) => response.message.statusCode, maxAttempts, delay); - }); -} -exports.retryHttpClientResponse = retryHttpClientResponse; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __importStar(__webpack_require__(470)); +const http_client_1 = __webpack_require__(22); +const constants_1 = __webpack_require__(931); +function isSuccessStatusCode(statusCode) { + if (!statusCode) { + return false; + } + return statusCode >= 200 && statusCode < 300; +} +exports.isSuccessStatusCode = isSuccessStatusCode; +function isServerErrorStatusCode(statusCode) { + if (!statusCode) { + return true; + } + return statusCode >= 500; +} +exports.isServerErrorStatusCode = isServerErrorStatusCode; +function isRetryableStatusCode(statusCode) { + if (!statusCode) { + return false; + } + const retryableStatusCodes = [ + http_client_1.HttpCodes.BadGateway, + http_client_1.HttpCodes.ServiceUnavailable, + http_client_1.HttpCodes.GatewayTimeout + ]; + return retryableStatusCodes.includes(statusCode); +} +exports.isRetryableStatusCode = isRetryableStatusCode; +function sleep(milliseconds) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise(resolve => setTimeout(resolve, milliseconds)); + }); +} +function retry(name, method, getStatusCode, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay, onError = undefined) { + return __awaiter(this, void 0, void 0, function* () { + let errorMessage = ''; + let attempt = 1; + while (attempt <= maxAttempts) { + let response = undefined; + let statusCode = undefined; + let isRetryable = false; + try { + response = yield method(); + } + catch (error) { + if (onError) { + response = onError(error); + } + isRetryable = true; + errorMessage = error.message; + } + if (response) { + statusCode = getStatusCode(response); + if (!isServerErrorStatusCode(statusCode)) { + return response; + } + } + if (statusCode) { + isRetryable = isRetryableStatusCode(statusCode); + errorMessage = `Cache service responded with ${statusCode}`; + } + core.debug(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`); + if (!isRetryable) { + core.debug(`${name} - Error is not retryable`); + break; + } + yield sleep(delay); + attempt++; + } + throw Error(`${name} failed: ${errorMessage}`); + }); +} +exports.retry = retry; +function retryTypedResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) { + return __awaiter(this, void 0, void 0, function* () { + return yield retry(name, method, (response) => response.statusCode, maxAttempts, delay, + // If the error object contains the statusCode property, extract it and return + // an ITypedResponse so it can be processed by the retry logic. + (error) => { + if (error instanceof http_client_1.HttpClientError) { + return { + statusCode: error.statusCode, + result: null, + headers: {} + }; + } + else { + return undefined; + } + }); + }); +} +exports.retryTypedResponse = retryTypedResponse; +function retryHttpClientResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) { + return __awaiter(this, void 0, void 0, function* () { + return yield retry(name, method, (response) => response.message.statusCode, maxAttempts, delay); + }); +} +exports.retryHttpClientResponse = retryHttpClientResponse; //# sourceMappingURL=requestUtils.js.map /***/ }), @@ -58383,53 +59269,7 @@ exports.Pattern = Pattern; //# sourceMappingURL=internal-pattern.js.map /***/ }), -/* 924 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.NoopContextManager = void 0; -var context_1 = __webpack_require__(715); -var NoopContextManager = /** @class */ (function () { - function NoopContextManager() { - } - NoopContextManager.prototype.active = function () { - return context_1.Context.ROOT_CONTEXT; - }; - NoopContextManager.prototype.with = function (context, fn) { - return fn(); - }; - NoopContextManager.prototype.bind = function (target, context) { - return target; - }; - NoopContextManager.prototype.enable = function () { - return this; - }; - NoopContextManager.prototype.disable = function () { - return this; - }; - return NoopContextManager; -}()); -exports.NoopContextManager = NoopContextManager; -//# sourceMappingURL=NoopContextManager.js.map - -/***/ }), +/* 924 */, /* 925 */, /* 926 */, /* 927 */, @@ -58443,7 +59283,7 @@ Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var tslib = __webpack_require__(422); +var tslib = __webpack_require__(966); var util = _interopDefault(__webpack_require__(669)); var os = __webpack_require__(87); @@ -58739,29 +59579,29 @@ module.exports = uuid; /***/ (function(__unusedmodule, exports) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var CacheFilename; -(function (CacheFilename) { - CacheFilename["Gzip"] = "cache.tgz"; - CacheFilename["Zstd"] = "cache.tzst"; -})(CacheFilename = exports.CacheFilename || (exports.CacheFilename = {})); -var CompressionMethod; -(function (CompressionMethod) { - CompressionMethod["Gzip"] = "gzip"; - // Long range mode was added to zstd in v1.3.2. - // This enum is for earlier version of zstd that does not have --long support - CompressionMethod["ZstdWithoutLong"] = "zstd-without-long"; - CompressionMethod["Zstd"] = "zstd"; -})(CompressionMethod = exports.CompressionMethod || (exports.CompressionMethod = {})); -// The default number of retry attempts. -exports.DefaultRetryAttempts = 2; -// The default delay in milliseconds between retry attempts. -exports.DefaultRetryDelay = 5000; -// Socket timeout in milliseconds during download. If no traffic is received -// over the socket during this period, the socket is destroyed and the download -// is aborted. -exports.SocketTimeout = 5000; + +Object.defineProperty(exports, "__esModule", { value: true }); +var CacheFilename; +(function (CacheFilename) { + CacheFilename["Gzip"] = "cache.tgz"; + CacheFilename["Zstd"] = "cache.tzst"; +})(CacheFilename = exports.CacheFilename || (exports.CacheFilename = {})); +var CompressionMethod; +(function (CompressionMethod) { + CompressionMethod["Gzip"] = "gzip"; + // Long range mode was added to zstd in v1.3.2. + // This enum is for earlier version of zstd that does not have --long support + CompressionMethod["ZstdWithoutLong"] = "zstd-without-long"; + CompressionMethod["Zstd"] = "zstd"; +})(CompressionMethod = exports.CompressionMethod || (exports.CompressionMethod = {})); +// The default number of retry attempts. +exports.DefaultRetryAttempts = 2; +// The default delay in milliseconds between retry attempts. +exports.DefaultRetryDelay = 5000; +// Socket timeout in milliseconds during download. If no traffic is received +// over the socket during this period, the socket is destroyed and the download +// is aborted. +exports.SocketTimeout = 5000; //# sourceMappingURL=constants.js.map /***/ }), @@ -59108,7 +59948,316 @@ exports.checkBypass = checkBypass; /* 963 */, /* 964 */, /* 965 */, -/* 966 */, +/* 966 */ +/***/ (function(module) { + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global global, define, System, Reflect, Promise */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __spreadArray; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __createBinding; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if ( true && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + + __extends = function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __exportStar = function(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); + }; + + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + }) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + /** @deprecated */ + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + /** @deprecated */ + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __spreadArray = function (to, from) { + for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) + to[j] = from[i]; + return to; + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, privateMap) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return privateMap.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, privateMap, value) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to set private field on non-instance"); + } + privateMap.set(receiver, value); + return value; + }; + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__spreadArray", __spreadArray); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); +}); + + +/***/ }), /* 967 */, /* 968 */, /* 969 */, @@ -59603,9 +60752,9 @@ var FormData = _interopDefault(__webpack_require__(790)); var util = __webpack_require__(669); var url = __webpack_require__(835); var stream = __webpack_require__(794); +var logger$1 = __webpack_require__(928); var tunnel = __webpack_require__(413); var coreAuth = __webpack_require__(229); -var logger$1 = __webpack_require__(928); var xml2js = __webpack_require__(992); var os = __webpack_require__(87); var coreTracing = __webpack_require__(263); @@ -59620,20 +60769,20 @@ function getHeaderKey(headerName) { return headerName.toLowerCase(); } function isHttpHeadersLike(object) { - if (!object || typeof object !== "object") { - return false; - } - if (typeof object.rawHeaders === "function" && - typeof object.clone === "function" && - typeof object.get === "function" && - typeof object.set === "function" && - typeof object.contains === "function" && - typeof object.remove === "function" && - typeof object.headersArray === "function" && - typeof object.headerValues === "function" && - typeof object.headerNames === "function" && - typeof object.toJson === "function") { - return true; + if (object && typeof object === "object") { + var castObject = object; + if (typeof castObject.rawHeaders === "function" && + typeof castObject.clone === "function" && + typeof castObject.get === "function" && + typeof castObject.set === "function" && + typeof castObject.contains === "function" && + typeof castObject.remove === "function" && + typeof castObject.headersArray === "function" && + typeof castObject.headerValues === "function" && + typeof castObject.headerNames === "function" && + typeof castObject.toJson === "function") { + return true; + } } return false; } @@ -59652,8 +60801,8 @@ var HttpHeaders = /** @class */ (function () { /** * Set a header in this collection with the provided name and value. The name is * case-insensitive. - * @param headerName The name of the header to set. This value is case-insensitive. - * @param headerValue The value of the header to set. + * @param headerName - The name of the header to set. This value is case-insensitive. + * @param headerValue - The value of the header to set. */ HttpHeaders.prototype.set = function (headerName, headerValue) { this._headersMap[getHeaderKey(headerName)] = { @@ -59664,7 +60813,7 @@ var HttpHeaders = /** @class */ (function () { /** * Get the header value for the provided header name, or undefined if no header exists in this * collection with the provided name. - * @param headerName The name of the header. + * @param headerName - The name of the header. */ HttpHeaders.prototype.get = function (headerName) { var header = this._headersMap[getHeaderKey(headerName)]; @@ -59679,7 +60828,7 @@ var HttpHeaders = /** @class */ (function () { /** * Remove the header with the provided headerName. Return whether or not the header existed and * was removed. - * @param headerName The name of the header to remove. + * @param headerName - The name of the header to remove. */ HttpHeaders.prototype.remove = function (headerName) { var result = this.contains(headerName); @@ -59754,14 +60903,14 @@ var HttpHeaders = /** @class */ (function () { // Licensed under the MIT license. /** * Encodes a string in base64 format. - * @param value the string to encode + * @param value - The string to encode */ function encodeString(value) { return Buffer.from(value).toString("base64"); } /** * Encodes a byte array in base64 format. - * @param value the Uint8Aray to encode + * @param value - The Uint8Aray to encode */ function encodeByteArray(value) { // Buffer.from accepts | -- the TypeScript definition is off here @@ -59771,7 +60920,7 @@ function encodeByteArray(value) { } /** * Decodes a base64 string into a byte array. - * @param value the base64 string to decode + * @param value - The base64 string to decode */ function decodeString(value) { return Buffer.from(value, "base64"); @@ -59782,58 +60931,35 @@ function decodeString(value) { var Constants = { /** * The core-http version - * @const - * @type {string} */ - coreHttpVersion: "1.2.1", + coreHttpVersion: "1.2.3", /** * Specifies HTTP. - * - * @const - * @type {string} */ HTTP: "http:", /** * Specifies HTTPS. - * - * @const - * @type {string} */ HTTPS: "https:", /** * Specifies HTTP Proxy. - * - * @const - * @type {string} */ HTTP_PROXY: "HTTP_PROXY", /** * Specifies HTTPS Proxy. - * - * @const - * @type {string} */ HTTPS_PROXY: "HTTPS_PROXY", /** * Specifies NO Proxy. - * - * @const - * @type {string} */ NO_PROXY: "NO_PROXY", /** * Specifies ALL Proxy. - * - * @const - * @type {string} */ ALL_PROXY: "ALL_PROXY", HttpConstants: { /** * Http Verbs - * - * @const - * @enum {string} */ HttpVerbs: { PUT: "PUT", @@ -59854,9 +60980,6 @@ var Constants = { HeaderConstants: { /** * The Authorization header. - * - * @const - * @type {string} */ AUTHORIZATION: "authorization", AUTHORIZATION_SCHEME: "Bearer", @@ -59864,16 +60987,10 @@ var Constants = { * The Retry-After response-header field can be used with a 503 (Service * Unavailable) or 349 (Too Many Requests) responses to indicate how long * the service is expected to be unavailable to the requesting client. - * - * @const - * @type {string} */ RETRY_AFTER: "Retry-After", /** * The UserAgent header. - * - * @const - * @type {string} */ USER_AGENT: "User-Agent" } @@ -59902,8 +61019,8 @@ var isNode = typeof process !== "undefined" && /** * Encodes an URI. * - * @param {string} uri The URI to be encoded. - * @return {string} The encoded URI. + * @param uri - The URI to be encoded. + * @returns The encoded URI. */ function encodeUri(uri) { return encodeURIComponent(uri) @@ -59917,9 +61034,8 @@ function encodeUri(uri) { * Returns a stripped version of the Http Response which only contains body, * headers and the status. * - * @param {HttpOperationResponse} response The Http Response - * - * @return {object} The stripped version of Http Response. + * @param response - The Http Response + * @returns The stripped version of Http Response. */ function stripResponse(response) { var strippedResponse = {}; @@ -59932,9 +61048,8 @@ function stripResponse(response) { * Returns a stripped version of the Http Request that does not contain the * Authorization header. * - * @param {WebResourceLike} request The Http Request object - * - * @return {WebResourceLike} The stripped version of Http Request. + * @param request - The Http Request object + * @returns The stripped version of Http Request. */ function stripRequest(request) { var strippedRequest = request.clone(); @@ -59946,9 +61061,8 @@ function stripRequest(request) { /** * Validates the given uuid as a string * - * @param {string} uuid The uuid as a string that needs to be validated - * - * @return {boolean} True if the uuid is valid; false otherwise. + * @param uuid - The uuid as a string that needs to be validated + * @returns True if the uuid is valid; false otherwise. */ function isValidUuid(uuid) { return validUuidRegex.test(uuid); @@ -59956,7 +61070,7 @@ function isValidUuid(uuid) { /** * Generated UUID * - * @return {string} RFC4122 v4 UUID. + * @returns RFC4122 v4 UUID. */ function generateUuid() { return uuid.v4(); @@ -59965,12 +61079,10 @@ function generateUuid() { * Executes an array of promises sequentially. Inspiration of this method is here: * https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html. An awesome blog on promises! * - * @param {Array} promiseFactories An array of promise factories(A function that return a promise) - * - * @param {any} [kickstart] Input to the first promise that is used to kickstart the promise chain. + * @param promiseFactories - An array of promise factories(A function that return a promise) + * @param kickstart - Input to the first promise that is used to kickstart the promise chain. * If not provided then the promise chain starts with undefined. - * - * @return A chain of resolved or rejected promises + * @returns A chain of resolved or rejected promises */ function executePromisesSequentially(promiseFactories, kickstart) { var result = Promise.resolve(kickstart); @@ -59981,23 +61093,25 @@ function executePromisesSequentially(promiseFactories, kickstart) { } /** * A wrapper for setTimeout that resolves a promise after t milliseconds. - * @param {number} t The number of milliseconds to be delayed. - * @param {T} value The value to be resolved with after a timeout of t milliseconds. - * @returns {Promise} Resolved promise + * @param t - The number of milliseconds to be delayed. + * @param value - The value to be resolved with after a timeout of t milliseconds. + * @returns Resolved promise */ function delay(t, value) { return new Promise(function (resolve) { return setTimeout(function () { return resolve(value); }, t); }); } /** * Converts a Promise to a callback. - * @param {Promise} promise The Promise to be converted to a callback - * @returns {Function} A function that takes the callback (cb: Function): void + * @param promise - The Promise to be converted to a callback + * @returns A function that takes the callback `(cb: Function) => void` * @deprecated generated code should instead depend on responseToBody */ +// eslint-disable-next-line @typescript-eslint/ban-types function promiseToCallback(promise) { if (typeof promise.then !== "function") { throw new Error("The provided input is not a Promise."); } + // eslint-disable-next-line @typescript-eslint/ban-types return function (cb) { promise .then(function (data) { @@ -60012,8 +61126,8 @@ function promiseToCallback(promise) { } /** * Converts a Promise to a service callback. - * @param {Promise} promise - The Promise of HttpOperationResponse to be converted to a service callback - * @returns {Function} A function that takes the service callback (cb: ServiceCallback): void + * @param promise - The Promise of HttpOperationResponse to be converted to a service callback + * @returns A function that takes the service callback (cb: ServiceCallback): void */ function promiseToServiceCallback(promise) { if (typeof promise.then !== "function") { @@ -60043,31 +61157,32 @@ function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) { } /** * Applies the properties on the prototype of sourceCtors to the prototype of targetCtor - * @param {object} targetCtor The target object on which the properties need to be applied. - * @param {Array} sourceCtors An array of source objects from which the properties need to be taken. + * @param targetCtor - The target object on which the properties need to be applied. + * @param sourceCtors - An array of source objects from which the properties need to be taken. */ -function applyMixins(targetCtor, sourceCtors) { - sourceCtors.forEach(function (sourceCtors) { - Object.getOwnPropertyNames(sourceCtors.prototype).forEach(function (name) { - targetCtor.prototype[name] = sourceCtors.prototype[name]; +function applyMixins(targetCtorParam, sourceCtors) { + var castTargetCtorParam = targetCtorParam; + sourceCtors.forEach(function (sourceCtor) { + Object.getOwnPropertyNames(sourceCtor.prototype).forEach(function (name) { + castTargetCtorParam.prototype[name] = sourceCtor.prototype[name]; }); }); } var validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; /** * Indicates whether the given string is in ISO 8601 format. - * @param {string} value The value to be validated for ISO 8601 duration format. - * @return {boolean} `true` if valid, `false` otherwise. + * @param value - The value to be validated for ISO 8601 duration format. + * @returns `true` if valid, `false` otherwise. */ function isDuration(value) { return validateISODuration.test(value); } /** * Replace all of the instances of searchValue in value with the provided replaceValue. - * @param {string | undefined} value The value to search and replace in. - * @param {string} searchValue The value to search for in the value argument. - * @param {string} replaceValue The value to replace searchValue with in the value argument. - * @returns {string | undefined} The value where each instance of searchValue was replaced with replacedValue. + * @param value - The value to search and replace in. + * @param searchValue - The value to search for in the value argument. + * @param replaceValue - The value to replace searchValue with in the value argument. + * @returns The value where each instance of searchValue was replaced with replacedValue. */ function replaceAll(value, searchValue, replaceValue) { return !value || !searchValue ? value : value.split(searchValue).join(replaceValue || ""); @@ -60075,8 +61190,8 @@ function replaceAll(value, searchValue, replaceValue) { /** * Determines whether the given entity is a basic/primitive type * (string, number, boolean, null, undefined). - * @param {any} value Any entity - * @return {boolean} - true is it is primitive type, false otherwise. + * @param value - Any entity + * @returns true is it is primitive type, false otherwise. */ function isPrimitiveType(value) { return (typeof value !== "object" && typeof value !== "function") || value === null; @@ -60103,32 +61218,34 @@ var Serializer = /** @class */ (function () { throw new Error("\"" + objectName + "\" with value \"" + value + "\" should satisfy the constraint \"" + constraintName + "\": " + constraintValue + "."); }; if (mapper.constraints && value != undefined) { + var valueAsNumber = value; var _a = mapper.constraints, ExclusiveMaximum = _a.ExclusiveMaximum, ExclusiveMinimum = _a.ExclusiveMinimum, InclusiveMaximum = _a.InclusiveMaximum, InclusiveMinimum = _a.InclusiveMinimum, MaxItems = _a.MaxItems, MaxLength = _a.MaxLength, MinItems = _a.MinItems, MinLength = _a.MinLength, MultipleOf = _a.MultipleOf, Pattern = _a.Pattern, UniqueItems = _a.UniqueItems; - if (ExclusiveMaximum != undefined && value >= ExclusiveMaximum) { + if (ExclusiveMaximum != undefined && valueAsNumber >= ExclusiveMaximum) { failValidation("ExclusiveMaximum", ExclusiveMaximum); } - if (ExclusiveMinimum != undefined && value <= ExclusiveMinimum) { + if (ExclusiveMinimum != undefined && valueAsNumber <= ExclusiveMinimum) { failValidation("ExclusiveMinimum", ExclusiveMinimum); } - if (InclusiveMaximum != undefined && value > InclusiveMaximum) { + if (InclusiveMaximum != undefined && valueAsNumber > InclusiveMaximum) { failValidation("InclusiveMaximum", InclusiveMaximum); } - if (InclusiveMinimum != undefined && value < InclusiveMinimum) { + if (InclusiveMinimum != undefined && valueAsNumber < InclusiveMinimum) { failValidation("InclusiveMinimum", InclusiveMinimum); } - if (MaxItems != undefined && value.length > MaxItems) { + var valueAsArray = value; + if (MaxItems != undefined && valueAsArray.length > MaxItems) { failValidation("MaxItems", MaxItems); } - if (MaxLength != undefined && value.length > MaxLength) { + if (MaxLength != undefined && valueAsArray.length > MaxLength) { failValidation("MaxLength", MaxLength); } - if (MinItems != undefined && value.length < MinItems) { + if (MinItems != undefined && valueAsArray.length < MinItems) { failValidation("MinItems", MinItems); } - if (MinLength != undefined && value.length < MinLength) { + if (MinLength != undefined && valueAsArray.length < MinLength) { failValidation("MinLength", MinLength); } - if (MultipleOf != undefined && value % MultipleOf !== 0) { + if (MultipleOf != undefined && valueAsNumber % MultipleOf !== 0) { failValidation("MultipleOf", MultipleOf); } if (Pattern) { @@ -60138,7 +61255,7 @@ var Serializer = /** @class */ (function () { } } if (UniqueItems && - value.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) { + valueAsArray.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) { failValidation("UniqueItems", UniqueItems); } } @@ -60146,15 +61263,11 @@ var Serializer = /** @class */ (function () { /** * Serialize the given object based on its metadata defined in the mapper * - * @param {Mapper} mapper The mapper which defines the metadata of the serializable object - * - * @param {object|string|Array|number|boolean|Date|stream} object A valid Javascript object to be serialized - * - * @param {string} objectName Name of the serialized object - * - * @param {options} options additional options to deserialization - * - * @returns {object|string|Array|number|boolean|Date|stream} A valid serialized Javascript object + * @param mapper - The mapper which defines the metadata of the serializable object + * @param object - A valid Javascript object to be serialized + * @param objectName - Name of the serialized object + * @param options - additional options to deserialization + * @returns A valid serialized Javascript object */ Serializer.prototype.serialize = function (mapper, object, objectName, options) { var _a, _b, _c; @@ -60234,15 +61347,11 @@ var Serializer = /** @class */ (function () { /** * Deserialize the given object based on its metadata defined in the mapper * - * @param {object} mapper The mapper which defines the metadata of the serializable object - * - * @param {object|string|Array|number|boolean|Date|stream} responseBody A valid Javascript entity to be deserialized - * - * @param {string} objectName Name of the deserialized object - * - * @param options Controls behavior of XML parser and builder. - * - * @returns {object|string|Array|number|boolean|Date|stream} A valid deserialized Javascript object + * @param mapper - The mapper which defines the metadata of the serializable object + * @param responseBody - A valid Javascript entity to be deserialized + * @param objectName - Name of the deserialized object + * @param options - Controls behavior of XML parser and builder. + * @returns A valid deserialized Javascript object */ Serializer.prototype.deserialize = function (mapper, responseBody, objectName, options) { var _a, _b, _c; @@ -60276,13 +61385,15 @@ var Serializer = /** @class */ (function () { else { if (this.isXML) { var xmlCharKey = updatedOptions.xmlCharKey; + var castResponseBody = responseBody; /** * If the mapper specifies this as a non-composite type value but the responseBody contains * both header ("$" i.e., XML_ATTRKEY) and body ("#" i.e., XML_CHARKEY) properties, * then just reduce the responseBody value to the body ("#" i.e., XML_CHARKEY) property. */ - if (responseBody[XML_ATTRKEY] != undefined && responseBody[xmlCharKey] != undefined) { - responseBody = responseBody[xmlCharKey]; + if (castResponseBody[XML_ATTRKEY] != undefined && + castResponseBody[xmlCharKey] != undefined) { + responseBody = castResponseBody[xmlCharKey]; } } if (mapperType.match(/^Number$/i) !== null) { @@ -60571,9 +61682,9 @@ function serializeDictionaryType(serializer, mapper, object, objectName, isXml, } /** * Resolves the additionalProperties property from a referenced mapper - * @param serializer the serializer containing the entire set of mappers - * @param mapper the composite mapper to resolve - * @param objectName name of the object being serialized + * @param serializer - The serializer containing the entire set of mappers + * @param mapper - The composite mapper to resolve + * @param objectName - Name of the object being serialized */ function resolveAdditionalProperties(serializer, mapper, objectName) { var additionalProperties = mapper.type.additionalProperties; @@ -60585,9 +61696,9 @@ function resolveAdditionalProperties(serializer, mapper, objectName) { } /** * Finds the mapper referenced by className - * @param serializer the serializer containing the entire set of mappers - * @param mapper the composite mapper to resolve - * @param objectName name of the object being serialized + * @param serializer - The serializer containing the entire set of mappers + * @param mapper - The composite mapper to resolve + * @param objectName - Name of the object being serialized */ function resolveReferencedMapper(serializer, mapper, objectName) { var className = mapper.type.className; @@ -60598,8 +61709,8 @@ function resolveReferencedMapper(serializer, mapper, objectName) { } /** * Resolves a composite mapper's modelProperties. - * @param serializer the serializer containing the entire set of mappers - * @param mapper the composite mapper to resolve + * @param serializer - The serializer containing the entire set of mappers + * @param mapper - The composite mapper to resolve */ function resolveModelProperties(serializer, mapper, objectName) { var modelProps = mapper.type.modelProperties; @@ -60929,6 +62040,7 @@ function getPolymorphicDiscriminatorSafely(serializer, typeName) { } // TODO: why is this here? function serializeObject(toSerialize) { + var castToSerialize = toSerialize; if (toSerialize == undefined) return undefined; if (toSerialize instanceof Uint8Array) { @@ -60948,7 +62060,7 @@ function serializeObject(toSerialize) { else if (typeof toSerialize === "object") { var dictionary = {}; for (var property in toSerialize) { - dictionary[property] = serializeObject(toSerialize[property]); + dictionary[property] = serializeObject(castToSerialize[property]); } return dictionary; } @@ -60965,6 +62077,7 @@ function strEnum(o) { } return result; } +// eslint-disable-next-line @typescript-eslint/no-redeclare var MapperType = strEnum([ "Base64Url", "Boolean", @@ -60986,17 +62099,17 @@ var MapperType = strEnum([ // Copyright (c) Microsoft Corporation. function isWebResourceLike(object) { - if (typeof object !== "object") { - return false; - } - if (typeof object.url === "string" && - typeof object.method === "string" && - typeof object.headers === "object" && - isHttpHeadersLike(object.headers) && - typeof object.validateRequestProperties === "function" && - typeof object.prepare === "function" && - typeof object.clone === "function") { - return true; + if (object && typeof object === "object") { + var castObject = object; + if (typeof castObject.url === "string" && + typeof castObject.method === "string" && + typeof castObject.headers === "object" && + isHttpHeadersLike(castObject.headers) && + typeof castObject.validateRequestProperties === "function" && + typeof castObject.prepare === "function" && + typeof castObject.clone === "function") { + return true; + } } return false; } @@ -61005,12 +62118,11 @@ function isWebResourceLike(object) { * * This class provides an abstraction over a REST call by being library / implementation agnostic and wrapping the necessary * properties to initiate a request. - * - * @constructor */ var WebResource = /** @class */ (function () { - function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, decompressResponse) { + function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, decompressResponse, streamResponseStatusCodes) { this.streamResponseBody = streamResponseBody; + this.streamResponseStatusCodes = streamResponseStatusCodes; this.url = url || ""; this.method = method || "GET"; this.headers = isHttpHeadersLike(headers) ? headers : new HttpHeaders(headers); @@ -61042,8 +62154,8 @@ var WebResource = /** @class */ (function () { }; /** * Prepares the request. - * @param {RequestPrepareOptions} options Options to provide for preparing the request. - * @returns {WebResource} Returns the prepared WebResource (HTTP Request) object that needs to be given to the request pipeline. + * @param options - Options to provide for preparing the request. + * @returns Returns the prepared WebResource (HTTP Request) object that needs to be given to the request pipeline. */ WebResource.prototype.prepare = function (options) { if (!options) { @@ -61223,10 +62335,10 @@ var WebResource = /** @class */ (function () { }; /** * Clone this WebResource HTTP request object. - * @returns {WebResource} The clone of this WebResource HTTP request object. + * @returns The clone of this WebResource HTTP request object. */ WebResource.prototype.clone = function () { - var result = new WebResource(this.url, this.method, this.body, this.query, this.headers && this.headers.clone(), this.streamResponseBody, this.withCredentials, this.abortSignal, this.timeout, this.onUploadProgress, this.onDownloadProgress, this.proxySettings, this.keepAlive, this.decompressResponse); + var result = new WebResource(this.url, this.method, this.body, this.query, this.headers && this.headers.clone(), this.streamResponseBody, this.withCredentials, this.abortSignal, this.timeout, this.onUploadProgress, this.onDownloadProgress, this.proxySettings, this.keepAlive, this.decompressResponse, this.streamResponseStatusCodes); if (this.formData) { result.formData = this.formData; } @@ -61273,9 +62385,12 @@ var URLQuery = /** @class */ (function () { * parameterName. */ URLQuery.prototype.set = function (parameterName, parameterValue) { + var caseParameterValue = parameterValue; if (parameterName) { - if (parameterValue !== undefined && parameterValue !== null) { - var newValue = Array.isArray(parameterValue) ? parameterValue : parameterValue.toString(); + if (caseParameterValue !== undefined && caseParameterValue !== null) { + var newValue = Array.isArray(caseParameterValue) + ? caseParameterValue + : caseParameterValue.toString(); this._rawQuery[parameterName] = newValue; } else { @@ -61852,6 +62967,7 @@ var defaultAllowedHeaderNames = [ "x-ms-correlation-request-id", "x-ms-request-id", "client-request-id", + "ms-cv", "return-client-request-id", "traceparent", "Access-Control-Allow-Credentials", @@ -61997,6 +63113,9 @@ var RestError = /** @class */ (function (_super) { return RestError; }(Error)); +// Copyright (c) Microsoft Corporation. +var logger = logger$1.createClientLogger("core-http"); + // Copyright (c) Microsoft Corporation. var ReportTransform = /** @class */ (function (_super) { tslib.__extends(ReportTransform, _super); @@ -62018,10 +63137,12 @@ var FetchHttpClient = /** @class */ (function () { function FetchHttpClient() { } FetchHttpClient.prototype.sendRequest = function (httpRequest) { + var _a; return tslib.__awaiter(this, void 0, void 0, function () { - var abortController$1, abortListener, formData, requestForm_1, appendFormValue, _i, _a, formKey, formValue, j, contentType, body, onUploadProgress, uploadReportStream, platformSpecificRequestInit, requestInit, response, headers, operationResponse, _b, _c, onDownloadProgress, responseBody, downloadReportStream, length_1, error_1, fetchError; - return tslib.__generator(this, function (_d) { - switch (_d.label) { + var abortController$1, abortListener, formData, requestForm_1, appendFormValue, _i, _b, formKey, formValue, j, contentType, body, onUploadProgress, uploadReportStream, platformSpecificRequestInit, requestInit, operationResponse, response, headers, streaming, _c, onDownloadProgress, responseBody, downloadReportStream, length_1, error_1, fetchError, uploadStreamDone, downloadStreamDone; + var _d; + return tslib.__generator(this, function (_e) { + switch (_e.label) { case 0: if (!httpRequest && typeof httpRequest !== "object") { throw new Error("'httpRequest' (WebResourceLike) cannot be null or undefined and must be of type object."); @@ -62060,8 +63181,8 @@ var FetchHttpClient = /** @class */ (function () { requestForm_1.append(key, value); } }; - for (_i = 0, _a = Object.keys(formData); _i < _a.length; _i++) { - formKey = _a[_i]; + for (_i = 0, _b = Object.keys(formData); _i < _b.length; _i++) { + formKey = _b[_i]; formValue = formData[formKey]; if (Array.isArray(formValue)) { for (j = 0; j < formValue.length; j++) { @@ -62103,34 +63224,36 @@ var FetchHttpClient = /** @class */ (function () { } return [4 /*yield*/, this.prepareRequest(httpRequest)]; case 1: - platformSpecificRequestInit = _d.sent(); + platformSpecificRequestInit = _e.sent(); requestInit = tslib.__assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, signal: abortController$1.signal, redirect: "manual" }, platformSpecificRequestInit); - _d.label = 2; + _e.label = 2; case 2: - _d.trys.push([2, 8, 9, 10]); + _e.trys.push([2, 8, 9, 10]); return [4 /*yield*/, this.fetch(httpRequest.url, requestInit)]; case 3: - response = _d.sent(); + response = _e.sent(); headers = parseHeaders(response.headers); - _b = { + streaming = ((_a = httpRequest.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(response.status)) || + httpRequest.streamResponseBody; + _d = { headers: headers, request: httpRequest, status: response.status, - readableStreamBody: httpRequest.streamResponseBody + readableStreamBody: streaming ? response.body : undefined }; - if (!!httpRequest.streamResponseBody) return [3 /*break*/, 5]; + if (!!streaming) return [3 /*break*/, 5]; return [4 /*yield*/, response.text()]; case 4: - _c = _d.sent(); + _c = _e.sent(); return [3 /*break*/, 6]; case 5: _c = undefined; - _d.label = 6; + _e.label = 6; case 6: - operationResponse = (_b.bodyAsText = _c, - _b); + operationResponse = (_d.bodyAsText = _c, + _d); onDownloadProgress = httpRequest.onDownloadProgress; if (onDownloadProgress) { responseBody = response.body || undefined; @@ -62149,10 +63272,10 @@ var FetchHttpClient = /** @class */ (function () { } return [4 /*yield*/, this.processRequest(operationResponse)]; case 7: - _d.sent(); + _e.sent(); return [2 /*return*/, operationResponse]; case 8: - error_1 = _d.sent(); + error_1 = _e.sent(); fetchError = error_1; if (fetchError.code === "ENOTFOUND") { throw new RestError(fetchError.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest); @@ -62164,7 +63287,23 @@ var FetchHttpClient = /** @class */ (function () { case 9: // clean up event listener if (httpRequest.abortSignal && abortListener) { - httpRequest.abortSignal.removeEventListener("abort", abortListener); + uploadStreamDone = Promise.resolve(); + if (isReadableStream(body)) { + uploadStreamDone = isStreamComplete(body); + } + downloadStreamDone = Promise.resolve(); + if (isReadableStream(operationResponse === null || operationResponse === void 0 ? void 0 : operationResponse.readableStreamBody)) { + downloadStreamDone = isStreamComplete(operationResponse.readableStreamBody); + } + Promise.all([uploadStreamDone, downloadStreamDone]) + .then(function () { + var _a; + (_a = httpRequest.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener); + return; + }) + .catch(function (e) { + logger.warning("Error when cleaning up abortListener on httpRequest", e); + }); } return [7 /*endfinally*/]; case 10: return [2 /*return*/]; @@ -62177,6 +63316,13 @@ var FetchHttpClient = /** @class */ (function () { function isReadableStream(body) { return body && typeof body.pipe === "function"; } +function isStreamComplete(stream) { + return new Promise(function (resolve) { + stream.on("close", resolve); + stream.on("end", resolve); + stream.on("error", resolve); + }); +} function parseHeaders(headers) { var httpHeaders = new HttpHeaders(); headers.forEach(function (value, key) { @@ -62383,7 +63529,7 @@ var NodeFetchHttpClient = /** @class */ (function (_super) { /** * Converts an OperationOptions to a RequestOptionsBase * - * @param opts OperationOptions object to convert to RequestOptionsBase + * @param opts - OperationOptions object to convert to RequestOptionsBase */ function operationOptionsToRequestOptionsBase(opts) { var requestOptions = opts.requestOptions, tracingOptions = opts.tracingOptions, additionalOptions = tslib.__rest(opts, ["requestOptions", "tracingOptions"]); @@ -62405,7 +63551,7 @@ var BaseRequestPolicy = /** @class */ (function () { } /** * Get whether or not a log with the provided log level should be logged. - * @param logLevel The log level of the log that will be logged. + * @param logLevel - The log level of the log that will be logged. * @returns Whether or not a log with the provided log level should be logged. */ BaseRequestPolicy.prototype.shouldLog = function (logLevel) { @@ -62414,8 +63560,8 @@ var BaseRequestPolicy = /** @class */ (function () { /** * Attempt to log the provided message to the provided logger. If no logger was provided or if * the log level does not meat the logger's threshold, then nothing will be logged. - * @param logLevel The log level of this log. - * @param message The message of this log. + * @param logLevel - The log level of this log. + * @param message - The message of this log. */ BaseRequestPolicy.prototype.log = function (logLevel, message) { this._options.log(logLevel, message); @@ -62431,7 +63577,7 @@ var RequestPolicyOptions = /** @class */ (function () { } /** * Get whether or not a log with the provided log level should be logged. - * @param logLevel The log level of the log that will be logged. + * @param logLevel - The log level of the log that will be logged. * @returns Whether or not a log with the provided log level should be logged. */ RequestPolicyOptions.prototype.shouldLog = function (logLevel) { @@ -62442,8 +63588,8 @@ var RequestPolicyOptions = /** @class */ (function () { /** * Attempt to log the provided message to the provided logger. If no logger was provided or if * the log level does not meet the logger's threshold, then nothing will be logged. - * @param logLevel The log level of this log. - * @param message The message of this log. + * @param logLevel - The log level of this log. + * @param message - The message of this log. */ RequestPolicyOptions.prototype.log = function (logLevel, message) { if (this._logger && this.shouldLog(logLevel)) { @@ -62453,9 +63599,6 @@ var RequestPolicyOptions = /** @class */ (function () { return RequestPolicyOptions; }()); -// Copyright (c) Microsoft Corporation. -var logger = logger$1.createClientLogger("core-http"); - // Copyright (c) Microsoft Corporation. function logPolicy(loggingOptions) { if (loggingOptions === void 0) { loggingOptions = {}; } @@ -62540,7 +63683,7 @@ var LogPolicy = /** @class */ (function (_super) { // Licensed under the MIT license. /** * Get the path to this parameter's value as a dotted string (a.b.c). - * @param parameter The parameter to get the path string for. + * @param parameter - The parameter to get the path string for. * @returns The path to this parameter's value as a dotted string. */ function getPathStringFromParameter(parameter) { @@ -62561,14 +63704,17 @@ function getPathStringFromParameterPath(parameterPath, mapper) { } // Copyright (c) Microsoft Corporation. -function isStreamOperation(operationSpec) { - var result = false; +/** + * Gets the list of status codes for streaming responses. + * @internal @hidden + */ +function getStreamResponseStatusCodes(operationSpec) { + var result = new Set(); for (var statusCode in operationSpec.responses) { var operationResponse = operationSpec.responses[statusCode]; if (operationResponse.bodyMapper && operationResponse.bodyMapper.type.name === MapperType.Stream) { - result = true; - break; + result.add(Number(statusCode)); } } return result; @@ -62630,9 +63776,8 @@ xml2jsBuilderSettings.renderOpts = { }; /** * Converts given JSON object to XML string - * @param obj JSON object to be converted into XML string - * @param opts Options that govern the parsing of given JSON object - * `rootName` indicates the name of the root element in the resulting XML + * @param obj - JSON object to be converted into XML string + * @param opts - Options that govern the parsing of given JSON object */ function stringifyXML(obj, opts) { var _a; @@ -62644,9 +63789,8 @@ function stringifyXML(obj, opts) { } /** * Converts given XML string into JSON - * @param str String containing the XML content to be parsed into JSON - * @param opts Options that govern the parsing of given xml string - * `includeRoot` indicates whether the root element is to be included or not in the output + * @param str - String containing the XML content to be parsed into JSON + * @param opts - Options that govern the parsing of given xml string */ function parseXML(str, opts) { var _a; @@ -62789,8 +63933,8 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, op try { parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options); } - catch (error) { - var restError = new RestError("Error " + error + " occurred in deserializing the responseBody - " + parsedResponse.bodyAsText, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); + catch (innerError) { + var restError = new RestError("Error " + innerError + " occurred in deserializing the responseBody - " + parsedResponse.bodyAsText, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); throw restError; } } @@ -62811,6 +63955,7 @@ function isOperationSpecEmpty(operationSpec) { (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default")); } function handleErrorResponse(parsedResponse, operationSpec, responseSpec) { + var _a; var isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300; var isExpectedStatusCode = isOperationSpecEmpty(operationSpec) ? isSuccessByStatus @@ -62826,7 +63971,9 @@ function handleErrorResponse(parsedResponse, operationSpec, responseSpec) { } } var errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default; - var initialErrorMessage = isStreamOperation(operationSpec) + var streaming = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status)) || + parsedResponse.request.streamResponseBody; + var initialErrorMessage = streaming ? "Unexpected status code: " + parsedResponse.status : parsedResponse.bodyAsText; var error = new RestError(initialErrorMessage, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); @@ -62871,13 +64018,16 @@ function handleErrorResponse(parsedResponse, operationSpec, responseSpec) { return { error: error, shouldReturnResponse: false }; } function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts) { + var _a; var errorHandler = function (err) { var msg = "Error \"" + err + "\" occurred while parsing the response body - " + operationResponse.bodyAsText + "."; var errCode = err.code || RestError.PARSE_ERROR; var e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse); return Promise.reject(e); }; - if (!operationResponse.request.streamResponseBody && operationResponse.bodyAsText) { + var streaming = ((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) || + operationResponse.request.streamResponseBody; + if (!streaming && operationResponse.bodyAsText) { var text_1 = operationResponse.bodyAsText; var contentType = operationResponse.headers.get("Content-Type") || ""; var contentComponents = !contentType @@ -62916,10 +64066,10 @@ function isNumber(n) { * @internal * Determines if the operation should be retried. * - * @param {number} retryLimit Specifies the max number of retries. - * @param {(response?: HttpOperationResponse, error?: RetryError) => boolean} predicate Initial chekck on whether to retry based on given responses or errors - * @param {RetryData} retryData The retry data. - * @return {boolean} True if the operation qualifies for a retry; false otherwise. + * @param retryLimit - Specifies the max number of retries. + * @param predicate - Initial chekck on whether to retry based on given responses or errors + * @param retryData - The retry data. + * @returns True if the operation qualifies for a retry; false otherwise. */ function shouldRetry(retryLimit, predicate, retryData, response, error) { if (!predicate(response, error)) { @@ -62931,9 +64081,9 @@ function shouldRetry(retryLimit, predicate, retryData, response, error) { * @internal * Updates the retry data for the next attempt. * - * @param {RetryPolicyOptions} retryOptions specifies retry interval, and its lower bound and upper bound. - * @param {RetryData} [retryData] The retry data. - * @param {RetryError} [err] The operation"s error, if any. + * @param retryOptions - specifies retry interval, and its lower bound and upper bound. + * @param retryData - The retry data. + * @param err - The operation"s error, if any. */ function updateRetryData(retryOptions, retryData, err) { if (retryData === void 0) { retryData = { retryCount: 0, retryInterval: 0 }; } @@ -62971,19 +64121,17 @@ var DefaultRetryOptions = { maxRetryDelayInMs: DEFAULT_CLIENT_MAX_RETRY_INTERVAL }; /** - * @class * Instantiates a new "ExponentialRetryPolicyFilter" instance. */ var ExponentialRetryPolicy = /** @class */ (function (_super) { tslib.__extends(ExponentialRetryPolicy, _super); /** - * @constructor - * @param {RequestPolicy} nextPolicy The next RequestPolicy in the pipeline chain. - * @param {RequestPolicyOptions} options The options for this RequestPolicy. - * @param {number} [retryCount] The client retry count. - * @param {number} [retryInterval] The client retry interval, in milliseconds. - * @param {number} [minRetryInterval] The minimum retry interval, in milliseconds. - * @param {number} [maxRetryInterval] The maximum retry interval, in milliseconds. + * @param nextPolicy - The next RequestPolicy in the pipeline chain. + * @param options - The options for this RequestPolicy. + * @param retryCount - The client retry count. + * @param retryInterval - The client retry interval, in milliseconds. + * @param minRetryInterval - The minimum retry interval, in milliseconds. + * @param maxRetryInterval - The maximum retry interval, in milliseconds. */ function ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, maxRetryInterval) { var _this = _super.call(this, nextPolicy, options) || this; @@ -63005,8 +64153,8 @@ var ExponentialRetryPolicy = /** @class */ (function (_super) { }(BaseRequestPolicy)); function retry(policy, request, response, retryData, requestError) { return tslib.__awaiter(this, void 0, void 0, function () { - function shouldPolicyRetry(response) { - var statusCode = response === null || response === void 0 ? void 0 : response.status; + function shouldPolicyRetry(responseParam) { + var statusCode = responseParam === null || responseParam === void 0 ? void 0 : responseParam.status; if (statusCode === undefined || (statusCode < 500 && statusCode !== 408) || statusCode === 501 || @@ -63269,9 +64417,9 @@ function registerIfNeeded(policy, request, response) { } /** * Reuses the headers of the original request and url (if specified). - * @param {WebResourceLike} originalRequest The original request - * @param {boolean} reuseUrlToo Should the url from the original request be reused as well. Default false. - * @returns {object} A new request object with desired headers. + * @param originalRequest - The original request + * @param reuseUrlToo - Should the url from the original request be reused as well. Default false. + * @returns A new request object with desired headers. */ function getRequestEssentials(originalRequest, reuseUrlToo) { if (reuseUrlToo === void 0) { reuseUrlToo = false; } @@ -63289,8 +64437,8 @@ function getRequestEssentials(originalRequest, reuseUrlToo) { /** * Validates the error code and message associated with 409 response status code. If it matches to that of * RP not registered then it returns the name of the RP else returns undefined. - * @param {string} body The response body received after making the original request. - * @returns {string} The name of the RP if condition is satisfied else undefined. + * @param body - The response body received after making the original request. + * @returns The name of the RP if condition is satisfied else undefined. */ function checkRPNotRegisteredError(body) { var result, responseBody; @@ -63317,8 +64465,8 @@ function checkRPNotRegisteredError(body) { /** * Extracts the first part of the URL, just after subscription: * https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ - * @param {string} url The original request url - * @returns {string} The url prefix as explained above. + * @param url - The original request url + * @returns The url prefix as explained above. */ function extractSubscriptionUrl(url) { var result; @@ -63333,12 +64481,12 @@ function extractSubscriptionUrl(url) { } /** * Registers the given provider. - * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against. - * @param {string} urlPrefix https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ - * @param {string} provider The provider name to be registered. - * @param {WebResourceLike} originalRequest The original request sent by the user that returned a 409 response + * @param policy - The RPRegistrationPolicy this function is being called against. + * @param urlPrefix - https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ + * @param provider - The provider name to be registered. + * @param originalRequest - The original request sent by the user that returned a 409 response * with a message that the provider is not registered. - * @param {registrationCallback} callback The callback that handles the RP registration + * @param callback - The callback that handles the RP registration */ function registerRP(policy, urlPrefix, provider, originalRequest) { var postUrl = urlPrefix + "providers/" + provider + "/register?api-version=2016-02-01"; @@ -63356,11 +64504,11 @@ function registerRP(policy, urlPrefix, provider, originalRequest) { /** * Polls the registration status of the provider that was registered. Polling happens at an interval of 30 seconds. * Polling will happen till the registrationState property of the response body is "Registered". - * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against. - * @param {string} url The request url for polling - * @param {WebResourceLike} originalRequest The original request sent by the user that returned a 409 response + * @param policy - The RPRegistrationPolicy this function is being called against. + * @param url - The request url for polling + * @param originalRequest - The original request sent by the user that returned a 409 response * with a message that the provider is not registered. - * @returns {Promise} True if RP Registration is successful. + * @returns True if RP Registration is successful. */ function getRegistrationStatus(policy, url, originalRequest) { var reqOptions = getRequestEssentials(originalRequest); @@ -63427,8 +64575,6 @@ var AccessTokenRefresher = /** @class */ (function () { /** * Returns true if the required milliseconds(defaulted to 30000) have been passed signifying * that we are ready for a new refresh. - * - * @returns {boolean} */ AccessTokenRefresher.prototype.isReady = function () { // We're only ready for a new refresh if the required milliseconds have passed. @@ -63439,7 +64585,6 @@ var AccessTokenRefresher = /** @class */ (function () { * then requests a new token, * then sets this.promise to undefined, * then returns the token. - * @param options getToken options */ AccessTokenRefresher.prototype.getToken = function (options) { return tslib.__awaiter(this, void 0, void 0, function () { @@ -63460,7 +64605,6 @@ var AccessTokenRefresher = /** @class */ (function () { /** * Requests a new token if we're not currently waiting for a new token. * Returns null if the required time between each call hasn't been reached. - * @param options getToken options */ AccessTokenRefresher.prototype.refresh = function (options) { if (!this.promise) { @@ -63481,8 +64625,8 @@ var timeBetweenRefreshAttemptsInMs = 30000; /** * Creates a new BearerTokenAuthenticationPolicy factory. * - * @param credential The TokenCredential implementation that can supply the bearer token. - * @param scopes The scopes for which the bearer token applies. + * @param credential - The TokenCredential implementation that can supply the bearer token. + * @param scopes - The scopes for which the bearer token applies. */ function bearerTokenAuthenticationPolicy(credential, scopes) { var tokenCache = new ExpiringAccessTokenCache(); @@ -63505,11 +64649,11 @@ var BearerTokenAuthenticationPolicy = /** @class */ (function (_super) { /** * Creates a new BearerTokenAuthenticationPolicy object. * - * @param nextPolicy The next RequestPolicy in the request pipeline. - * @param options Options for this RequestPolicy. - * @param credential The TokenCredential implementation that can supply the bearer token. - * @param scopes The scopes for which the bearer token applies. - * @param tokenCache The cache for the most recent AccessToken returned from the TokenCredential. + * @param nextPolicy - The next RequestPolicy in the request pipeline. + * @param options - Options for this RequestPolicy. + * @param credential - The TokenCredential implementation that can supply the bearer token. + * @param scopes - The scopes for which the bearer token applies. + * @param tokenCache - The cache for the most recent AccessToken returned from the TokenCredential. */ function BearerTokenAuthenticationPolicy(nextPolicy, options, tokenCache, tokenRefresher) { var _this = _super.call(this, nextPolicy, options) || this; @@ -63519,7 +64663,6 @@ var BearerTokenAuthenticationPolicy = /** @class */ (function (_super) { } /** * Applies the Bearer token to the request through the Authorization header. - * @param webResource */ BearerTokenAuthenticationPolicy.prototype.sendRequest = function (webResource) { return tslib.__awaiter(this, void 0, void 0, function () { @@ -63601,14 +64744,10 @@ function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, max }; } /** - * @class - * Instantiates a new "ExponentialRetryPolicyFilter" instance. - * - * @constructor - * @param {number} retryCount The client retry count. - * @param {number} retryInterval The client retry interval, in milliseconds. - * @param {number} minRetryInterval The minimum retry interval, in milliseconds. - * @param {number} maxRetryInterval The maximum retry interval, in milliseconds. + * @param retryCount - The client retry count. + * @param retryInterval - The client retry interval, in milliseconds. + * @param minRetryInterval - The minimum retry interval, in milliseconds. + * @param maxRetryInterval - The maximum retry interval, in milliseconds. */ var SystemErrorRetryPolicy = /** @class */ (function (_super) { tslib.__extends(SystemErrorRetryPolicy, _super); @@ -63646,7 +64785,7 @@ function retry$1(policy, request, operationResponse, err, retryData) { } return false; } - var err_1; + var nestedErr_1; return tslib.__generator(this, function (_a) { switch (_a.label) { case 0: @@ -63660,8 +64799,8 @@ function retry$1(policy, request, operationResponse, err, retryData) { _a.sent(); return [2 /*return*/, policy._nextPolicy.sendRequest(request.clone())]; case 3: - err_1 = _a.sent(); - return [2 /*return*/, retry$1(policy, request, operationResponse, err_1, retryData)]; + nestedErr_1 = _a.sent(); + return [2 /*return*/, retry$1(policy, request, operationResponse, nestedErr_1, retryData)]; case 4: return [3 /*break*/, 6]; case 5: if (err) { @@ -63685,8 +64824,10 @@ function retry$1(policy, request, operationResponse, err, retryData) { })(exports.QueryCollectionFormat || (exports.QueryCollectionFormat = {})); // Copyright (c) Microsoft Corporation. -var noProxyList = []; -var isNoProxyInitalized = false; +/** + * @internal + */ +var noProxyList = loadNoProxy(); var byPassedList = new Map(); function loadEnvironmentProxyValue() { if (!process) { @@ -63697,45 +64838,53 @@ function loadEnvironmentProxyValue() { var httpProxy = getEnvironmentValue(Constants.HTTP_PROXY); return httpsProxy || allProxy || httpProxy; } -// Check whether the given `uri` matches the noProxyList. If it matches, any request sent to that same `uri` won't set the proxy settings. +// Check whether the host of a given `uri` is in the noProxyList. +// If there's a match, any request sent to the same host won't have the proxy settings set. +// This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210 function isBypassed(uri) { - if (byPassedList.has(uri)) { - return byPassedList.get(uri); + if (noProxyList.length === 0) { + return false; } - loadNoProxy(); - var isBypassed = false; var host = URLBuilder.parse(uri).getHost(); + if (byPassedList.has(host)) { + return byPassedList.get(host); + } + var isBypassedFlag = false; for (var _i = 0, noProxyList_1 = noProxyList; _i < noProxyList_1.length; _i++) { - var proxyString = noProxyList_1[_i]; - if (proxyString[0] === ".") { - if (uri.endsWith(proxyString)) { - isBypassed = true; + var pattern = noProxyList_1[_i]; + if (pattern[0] === ".") { + // This should match either domain it self or any subdomain or host + // .foo.com will match foo.com it self or *.foo.com + if (host.endsWith(pattern)) { + isBypassedFlag = true; } else { - if (host === proxyString.slice(1) && host.length === proxyString.length - 1) { - isBypassed = true; + if (host.length === pattern.length - 1 && host === pattern.slice(1)) { + isBypassedFlag = true; } } } else { - if (host === proxyString) { - isBypassed = true; + if (host === pattern) { + isBypassedFlag = true; } } } - byPassedList.set(uri, isBypassed); - return isBypassed; + byPassedList.set(host, isBypassedFlag); + return isBypassedFlag; } +/** + * @internal + */ function loadNoProxy() { - if (isNoProxyInitalized) { - return; - } var noProxy = getEnvironmentValue(Constants.NO_PROXY); if (noProxy) { - var list = noProxy.split(","); - noProxyList = list.map(function (item) { return item.trim(); }).filter(function (item) { return item.length; }); + return noProxy + .split(",") + .map(function (item) { return item.trim(); }) + .filter(function (item) { return item.length; }); } - isNoProxyInitalized = true; + return []; } function getDefaultProxySettings(proxyUrl) { if (!proxyUrl) { @@ -63921,9 +65070,9 @@ var KeepAlivePolicy = /** @class */ (function (_super) { /** * Creates an instance of KeepAlivePolicy. * - * @param {RequestPolicy} nextPolicy - * @param {RequestPolicyOptions} options - * @param {KeepAliveOptions} [keepAliveOptions] + * @param nextPolicy - + * @param options - + * @param keepAliveOptions - */ function KeepAlivePolicy(nextPolicy, options, keepAliveOptions) { var _this = _super.call(this, nextPolicy, options) || this; @@ -63933,9 +65082,8 @@ var KeepAlivePolicy = /** @class */ (function (_super) { /** * Sends out request. * - * @param {WebResourceLike} request - * @returns {Promise} - * @memberof KeepAlivePolicy + * @param request - + * @returns */ KeepAlivePolicy.prototype.sendRequest = function (request) { return tslib.__awaiter(this, void 0, void 0, function () { @@ -64041,8 +65189,8 @@ var DisableResponseDecompressionPolicy = /** @class */ (function (_super) { /** * Creates an instance of DisableResponseDecompressionPolicy. * - * @param {RequestPolicy} nextPolicy - * @param {RequestPolicyOptions} options + * @param nextPolicy - + * @param options - */ // The parent constructor is protected. /* eslint-disable-next-line @typescript-eslint/no-useless-constructor */ @@ -64052,8 +65200,8 @@ var DisableResponseDecompressionPolicy = /** @class */ (function (_super) { /** * Sends out request. * - * @param {WebResource} request - * @returns {Promise} + * @param request - + * @returns */ DisableResponseDecompressionPolicy.prototype.sendRequest = function (request) { return tslib.__awaiter(this, void 0, void 0, function () { @@ -64081,17 +65229,12 @@ var NdJsonPolicy = /** @class */ (function (_super) { tslib.__extends(NdJsonPolicy, _super); /** * Creates an instance of KeepAlivePolicy. - * - * @param nextPolicy - * @param options */ function NdJsonPolicy(nextPolicy, options) { return _super.call(this, nextPolicy, options) || this; } /** * Sends a request. - * - * @param request */ NdJsonPolicy.prototype.sendRequest = function (request) { return tslib.__awaiter(this, void 0, void 0, function () { @@ -64111,17 +65254,24 @@ var NdJsonPolicy = /** @class */ (function (_super) { return NdJsonPolicy; }(BaseRequestPolicy)); +// Copyright (c) Microsoft Corporation. +var cachedHttpClient; +function getCachedDefaultHttpClient() { + if (!cachedHttpClient) { + cachedHttpClient = new NodeFetchHttpClient(); + } + return cachedHttpClient; +} + // Copyright (c) Microsoft Corporation. /** - * @class - * Initializes a new instance of the ServiceClient. + * ServiceClient sends service requests and receives responses. */ var ServiceClient = /** @class */ (function () { /** * The ServiceClient constructor - * @constructor - * @param credentials The credentials used for authentication with the service. - * @param options The service client options that govern the behavior of the client. + * @param credentials - The credentials used for authentication with the service. + * @param options - The service client options that govern the behavior of the client. */ function ServiceClient(credentials, /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options */ @@ -64131,7 +65281,7 @@ var ServiceClient = /** @class */ (function () { options = {}; } this._withCredentials = options.withCredentials || false; - this._httpClient = options.httpClient || new NodeFetchHttpClient(); + this._httpClient = options.httpClient || getCachedDefaultHttpClient(); this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger); var requestPolicyFactories; if (Array.isArray(options.requestPolicyFactories)) { @@ -64154,7 +65304,7 @@ var ServiceClient = /** @class */ (function () { var serviceClient = _this; var serviceClientOptions = options; return { - create: function (nextPolicy, options) { + create: function (nextPolicy, createOptions) { var credentialScopes = getCredentialScopes(serviceClientOptions, serviceClient.baseUri); if (!credentialScopes) { throw new Error("When using credential, the ServiceClient must contain a baseUri or a credentialScopes in ServiceClientOptions. Unable to create a bearerTokenAuthenticationPolicy"); @@ -64162,7 +65312,7 @@ var ServiceClient = /** @class */ (function () { if (bearerTokenPolicyFactory === undefined || bearerTokenPolicyFactory === null) { bearerTokenPolicyFactory = bearerTokenAuthenticationPolicy(credentials, credentialScopes); } - return bearerTokenPolicyFactory.create(nextPolicy, options); + return bearerTokenPolicyFactory.create(nextPolicy, createOptions); } }; }; @@ -64219,9 +65369,9 @@ var ServiceClient = /** @class */ (function () { }; /** * Send an HTTP request that is populated using the provided OperationSpec. - * @param {OperationArguments} operationArguments The arguments that the HTTP request's templated values will be populated from. - * @param {OperationSpec} operationSpec The OperationSpec to use to populate the httpRequest. - * @param {ServiceCallback} callback The callback to call when the response is received. + * @param operationArguments - The arguments that the HTTP request's templated values will be populated from. + * @param operationSpec - The OperationSpec to use to populate the httpRequest. + * @param callback - The callback to call when the response is received. */ ServiceClient.prototype.sendOperationRequest = function (operationArguments, operationSpec, callback) { var _a; @@ -64312,7 +65462,7 @@ var ServiceClient = /** @class */ (function () { } httpRequest.url = requestUrl.toString(); contentType = operationSpec.contentType || this.requestContentType; - if (contentType) { + if (contentType && operationSpec.requestBody) { httpRequest.headers.set("Content-Type", contentType); } if (operationSpec.headerParameters) { @@ -64364,8 +65514,8 @@ var ServiceClient = /** @class */ (function () { } httpRequest.withCredentials = this._withCredentials; serializeRequestBody(this, httpRequest, operationArguments, operationSpec); - if (httpRequest.streamResponseBody === undefined || httpRequest.streamResponseBody === null) { - httpRequest.streamResponseBody = isStreamOperation(operationSpec); + if (httpRequest.streamResponseStatusCodes === undefined) { + httpRequest.streamResponseStatusCodes = getStreamResponseStatusCodes(operationSpec); } rawResponse = void 0; sendRequestError = void 0; @@ -64400,7 +65550,6 @@ var ServiceClient = /** @class */ (function () { cb = callback; if (cb) { result - // tslint:disable-next-line:no-null-keyword .then(function (res) { return cb(null, res._response.parsedBody, res._response.request, res._response); }) .catch(function (err) { return cb(err); }); } @@ -64702,9 +65851,9 @@ function getCredentialScopes(options, baseUri) { // Copyright (c) Microsoft Corporation. /** * Creates a function called createSpan to create spans using the global tracer. - * @ignore - * @param spanConfig The name of the operation being performed. - * @param tracingOptions The options for the underlying http request. + * @hidden + * @param spanConfig - The name of the operation being performed. + * @param tracingOptions - The options for the underlying http request. */ function createSpanFunction(_a) { var packagePrefix = _a.packagePrefix, namespace = _a.namespace; @@ -64734,10 +65883,9 @@ var BasicAuthenticationCredentials = /** @class */ (function () { /** * Creates a new BasicAuthenticationCredentials object. * - * @constructor - * @param {string} userName User name. - * @param {string} password Password. - * @param {string} [authorizationScheme] The authorization scheme. + * @param userName - User name. + * @param password - Password. + * @param authorizationScheme - The authorization scheme. */ function BasicAuthenticationCredentials(userName, password, authorizationScheme) { if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME; } @@ -64755,8 +65903,8 @@ var BasicAuthenticationCredentials = /** @class */ (function () { /** * Signs a request with the Authentication header. * - * @param {WebResourceLike} webResource The WebResourceLike to be signed. - * @returns {Promise} The signed request object. + * @param webResource - The WebResourceLike to be signed. + * @returns The signed request object. */ BasicAuthenticationCredentials.prototype.signRequest = function (webResource) { var credentials = this.userName + ":" + this.password; @@ -64775,8 +65923,7 @@ var BasicAuthenticationCredentials = /** @class */ (function () { */ var ApiKeyCredentials = /** @class */ (function () { /** - * @constructor - * @param {object} options Specifies the options to be provided for auth. Either header or query needs to be provided. + * @param options - Specifies the options to be provided for auth. Either header or query needs to be provided. */ function ApiKeyCredentials(options) { if (!options || (options && !options.inHeader && !options.inQuery)) { @@ -64788,8 +65935,8 @@ var ApiKeyCredentials = /** @class */ (function () { /** * Signs a request with the values provided in the inHeader and inQuery parameter. * - * @param {WebResourceLike} webResource The WebResourceLike to be signed. - * @returns {Promise} The signed request object. + * @param webResource - The WebResourceLike to be signed. + * @returns The signed request object. */ ApiKeyCredentials.prototype.signRequest = function (webResource) { if (!webResource) { @@ -64828,8 +65975,7 @@ var TopicCredentials = /** @class */ (function (_super) { /** * Creates a new EventGrid TopicCredentials object. * - * @constructor - * @param {string} topicKey The EventGrid topic key + * @param topicKey - The EventGrid topic key */ function TopicCredentials(topicKey) { var _this = this; diff --git a/dist/run/index.js b/dist/run/index.js index b33538dbe3..f9bfacd67c 100644 --- a/dist/run/index.js +++ b/dist/run/index.js @@ -1405,175 +1405,175 @@ rimraf.sync = rimrafSync /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __asyncValues = (this && this.__asyncValues) || function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(__webpack_require__(470)); -const exec = __importStar(__webpack_require__(986)); -const glob = __importStar(__webpack_require__(281)); -const io = __importStar(__webpack_require__(1)); -const fs = __importStar(__webpack_require__(747)); -const path = __importStar(__webpack_require__(622)); -const semver = __importStar(__webpack_require__(864)); -const util = __importStar(__webpack_require__(669)); -const uuid_1 = __webpack_require__(930); -const constants_1 = __webpack_require__(931); -// From https://github.com/actions/toolkit/blob/main/packages/tool-cache/src/tool-cache.ts#L23 -function createTempDirectory() { - return __awaiter(this, void 0, void 0, function* () { - const IS_WINDOWS = process.platform === 'win32'; - let tempDirectory = process.env['RUNNER_TEMP'] || ''; - if (!tempDirectory) { - let baseLocation; - if (IS_WINDOWS) { - // On Windows use the USERPROFILE env variable - baseLocation = process.env['USERPROFILE'] || 'C:\\'; - } - else { - if (process.platform === 'darwin') { - baseLocation = '/Users'; - } - else { - baseLocation = '/home'; - } - } - tempDirectory = path.join(baseLocation, 'actions', 'temp'); - } - const dest = path.join(tempDirectory, uuid_1.v4()); - yield io.mkdirP(dest); - return dest; - }); -} -exports.createTempDirectory = createTempDirectory; -function getArchiveFileSizeIsBytes(filePath) { - return fs.statSync(filePath).size; -} -exports.getArchiveFileSizeIsBytes = getArchiveFileSizeIsBytes; -function resolvePaths(patterns) { - var e_1, _a; - var _b; - return __awaiter(this, void 0, void 0, function* () { - const paths = []; - const workspace = (_b = process.env['GITHUB_WORKSPACE']) !== null && _b !== void 0 ? _b : process.cwd(); - const globber = yield glob.create(patterns.join('\n'), { - implicitDescendants: false - }); - try { - for (var _c = __asyncValues(globber.globGenerator()), _d; _d = yield _c.next(), !_d.done;) { - const file = _d.value; - const relativeFile = path - .relative(workspace, file) - .replace(new RegExp(`\\${path.sep}`, 'g'), '/'); - core.debug(`Matched: ${relativeFile}`); - // Paths are made relative so the tar entries are all relative to the root of the workspace. - paths.push(`${relativeFile}`); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_d && !_d.done && (_a = _c.return)) yield _a.call(_c); - } - finally { if (e_1) throw e_1.error; } - } - return paths; - }); -} -exports.resolvePaths = resolvePaths; -function unlinkFile(filePath) { - return __awaiter(this, void 0, void 0, function* () { - return util.promisify(fs.unlink)(filePath); - }); -} -exports.unlinkFile = unlinkFile; -function getVersion(app) { - return __awaiter(this, void 0, void 0, function* () { - core.debug(`Checking ${app} --version`); - let versionOutput = ''; - try { - yield exec.exec(`${app} --version`, [], { - ignoreReturnCode: true, - silent: true, - listeners: { - stdout: (data) => (versionOutput += data.toString()), - stderr: (data) => (versionOutput += data.toString()) - } - }); - } - catch (err) { - core.debug(err.message); - } - versionOutput = versionOutput.trim(); - core.debug(versionOutput); - return versionOutput; - }); -} -// Use zstandard if possible to maximize cache performance -function getCompressionMethod() { - return __awaiter(this, void 0, void 0, function* () { - if (process.platform === 'win32' && !(yield isGnuTarInstalled())) { - // Disable zstd due to bug https://github.com/actions/cache/issues/301 - return constants_1.CompressionMethod.Gzip; - } - const versionOutput = yield getVersion('zstd'); - const version = semver.clean(versionOutput); - if (!versionOutput.toLowerCase().includes('zstd command line interface')) { - // zstd is not installed - return constants_1.CompressionMethod.Gzip; - } - else if (!version || semver.lt(version, 'v1.3.2')) { - // zstd is installed but using a version earlier than v1.3.2 - // v1.3.2 is required to use the `--long` options in zstd - return constants_1.CompressionMethod.ZstdWithoutLong; - } - else { - return constants_1.CompressionMethod.Zstd; - } - }); -} -exports.getCompressionMethod = getCompressionMethod; -function getCacheFileName(compressionMethod) { - return compressionMethod === constants_1.CompressionMethod.Gzip - ? constants_1.CacheFilename.Gzip - : constants_1.CacheFilename.Zstd; -} -exports.getCacheFileName = getCacheFileName; -function isGnuTarInstalled() { - return __awaiter(this, void 0, void 0, function* () { - const versionOutput = yield getVersion('tar'); - return versionOutput.toLowerCase().includes('gnu tar'); - }); -} -exports.isGnuTarInstalled = isGnuTarInstalled; -function assertDefined(name, value) { - if (value === undefined) { - throw Error(`Expected ${name} but value was undefiend`); - } - return value; -} -exports.assertDefined = assertDefined; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __importStar(__webpack_require__(470)); +const exec = __importStar(__webpack_require__(986)); +const glob = __importStar(__webpack_require__(281)); +const io = __importStar(__webpack_require__(1)); +const fs = __importStar(__webpack_require__(747)); +const path = __importStar(__webpack_require__(622)); +const semver = __importStar(__webpack_require__(864)); +const util = __importStar(__webpack_require__(669)); +const uuid_1 = __webpack_require__(930); +const constants_1 = __webpack_require__(931); +// From https://github.com/actions/toolkit/blob/main/packages/tool-cache/src/tool-cache.ts#L23 +function createTempDirectory() { + return __awaiter(this, void 0, void 0, function* () { + const IS_WINDOWS = process.platform === 'win32'; + let tempDirectory = process.env['RUNNER_TEMP'] || ''; + if (!tempDirectory) { + let baseLocation; + if (IS_WINDOWS) { + // On Windows use the USERPROFILE env variable + baseLocation = process.env['USERPROFILE'] || 'C:\\'; + } + else { + if (process.platform === 'darwin') { + baseLocation = '/Users'; + } + else { + baseLocation = '/home'; + } + } + tempDirectory = path.join(baseLocation, 'actions', 'temp'); + } + const dest = path.join(tempDirectory, uuid_1.v4()); + yield io.mkdirP(dest); + return dest; + }); +} +exports.createTempDirectory = createTempDirectory; +function getArchiveFileSizeIsBytes(filePath) { + return fs.statSync(filePath).size; +} +exports.getArchiveFileSizeIsBytes = getArchiveFileSizeIsBytes; +function resolvePaths(patterns) { + var e_1, _a; + var _b; + return __awaiter(this, void 0, void 0, function* () { + const paths = []; + const workspace = (_b = process.env['GITHUB_WORKSPACE']) !== null && _b !== void 0 ? _b : process.cwd(); + const globber = yield glob.create(patterns.join('\n'), { + implicitDescendants: false + }); + try { + for (var _c = __asyncValues(globber.globGenerator()), _d; _d = yield _c.next(), !_d.done;) { + const file = _d.value; + const relativeFile = path + .relative(workspace, file) + .replace(new RegExp(`\\${path.sep}`, 'g'), '/'); + core.debug(`Matched: ${relativeFile}`); + // Paths are made relative so the tar entries are all relative to the root of the workspace. + paths.push(`${relativeFile}`); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_d && !_d.done && (_a = _c.return)) yield _a.call(_c); + } + finally { if (e_1) throw e_1.error; } + } + return paths; + }); +} +exports.resolvePaths = resolvePaths; +function unlinkFile(filePath) { + return __awaiter(this, void 0, void 0, function* () { + return util.promisify(fs.unlink)(filePath); + }); +} +exports.unlinkFile = unlinkFile; +function getVersion(app) { + return __awaiter(this, void 0, void 0, function* () { + core.debug(`Checking ${app} --version`); + let versionOutput = ''; + try { + yield exec.exec(`${app} --version`, [], { + ignoreReturnCode: true, + silent: true, + listeners: { + stdout: (data) => (versionOutput += data.toString()), + stderr: (data) => (versionOutput += data.toString()) + } + }); + } + catch (err) { + core.debug(err.message); + } + versionOutput = versionOutput.trim(); + core.debug(versionOutput); + return versionOutput; + }); +} +// Use zstandard if possible to maximize cache performance +function getCompressionMethod() { + return __awaiter(this, void 0, void 0, function* () { + if (process.platform === 'win32' && !(yield isGnuTarInstalled())) { + // Disable zstd due to bug https://github.com/actions/cache/issues/301 + return constants_1.CompressionMethod.Gzip; + } + const versionOutput = yield getVersion('zstd'); + const version = semver.clean(versionOutput); + if (!versionOutput.toLowerCase().includes('zstd command line interface')) { + // zstd is not installed + return constants_1.CompressionMethod.Gzip; + } + else if (!version || semver.lt(version, 'v1.3.2')) { + // zstd is installed but using a version earlier than v1.3.2 + // v1.3.2 is required to use the `--long` options in zstd + return constants_1.CompressionMethod.ZstdWithoutLong; + } + else { + return constants_1.CompressionMethod.Zstd; + } + }); +} +exports.getCompressionMethod = getCompressionMethod; +function getCacheFileName(compressionMethod) { + return compressionMethod === constants_1.CompressionMethod.Gzip + ? constants_1.CacheFilename.Gzip + : constants_1.CacheFilename.Zstd; +} +exports.getCacheFileName = getCacheFileName; +function isGnuTarInstalled() { + return __awaiter(this, void 0, void 0, function* () { + const versionOutput = yield getVersion('tar'); + return versionOutput.toLowerCase().includes('gnu tar'); + }); +} +exports.isGnuTarInstalled = isGnuTarInstalled; +function assertDefined(name, value) { + if (value === undefined) { + throw Error(`Expected ${name} but value was undefiend`); + } + return value; +} +exports.assertDefined = assertDefined; //# sourceMappingURL=cacheUtils.js.map /***/ }), @@ -2707,7 +2707,49 @@ exports.findLintVersion = findLintVersion; /***/ }), -/* 53 */, +/* 53 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +/*! + * Copyright 2019, OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const context_1 = __webpack_require__(560); +class NoopContextManager { + active() { + return context_1.Context.ROOT_CONTEXT; + } + with(context, fn) { + return fn(); + } + bind(target, context) { + return target; + } + enable() { + return this; + } + disable() { + return this; + } +} +exports.NoopContextManager = NoopContextManager; +//# sourceMappingURL=NoopContextManager.js.map + +/***/ }), /* 54 */, /* 55 */, /* 56 */, @@ -4107,7 +4149,7 @@ module.exports = bytesToUuid; Object.defineProperty(exports, '__esModule', { value: true }); -var tslib = __webpack_require__(422); +var tslib = __webpack_require__(640); var listenersMap = new WeakMap(); var abortedMap = new WeakMap(); @@ -4405,220 +4447,221 @@ Object.defineProperty(exports, "__esModule", { value: true }); /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(__webpack_require__(470)); -const http_client_1 = __webpack_require__(22); -const auth_1 = __webpack_require__(733); -const crypto = __importStar(__webpack_require__(417)); -const fs = __importStar(__webpack_require__(747)); -const url_1 = __webpack_require__(835); -const utils = __importStar(__webpack_require__(15)); -const constants_1 = __webpack_require__(931); -const downloadUtils_1 = __webpack_require__(251); -const options_1 = __webpack_require__(538); -const requestUtils_1 = __webpack_require__(899); -const versionSalt = '1.0'; -function getCacheApiUrl(resource) { - // Ideally we just use ACTIONS_CACHE_URL - const baseUrl = (process.env['ACTIONS_CACHE_URL'] || - process.env['ACTIONS_RUNTIME_URL'] || - '').replace('pipelines', 'artifactcache'); - if (!baseUrl) { - throw new Error('Cache Service Url not found, unable to restore cache.'); - } - const url = `${baseUrl}_apis/artifactcache/${resource}`; - core.debug(`Resource Url: ${url}`); - return url; -} -function createAcceptHeader(type, apiVersion) { - return `${type};api-version=${apiVersion}`; -} -function getRequestOptions() { - const requestOptions = { - headers: { - Accept: createAcceptHeader('application/json', '6.0-preview.1') - } - }; - return requestOptions; -} -function createHttpClient() { - const token = process.env['ACTIONS_RUNTIME_TOKEN'] || ''; - const bearerCredentialHandler = new auth_1.BearerCredentialHandler(token); - return new http_client_1.HttpClient('actions/cache', [bearerCredentialHandler], getRequestOptions()); -} -function getCacheVersion(paths, compressionMethod) { - const components = paths.concat(!compressionMethod || compressionMethod === constants_1.CompressionMethod.Gzip - ? [] - : [compressionMethod]); - // Add salt to cache version to support breaking changes in cache entry - components.push(versionSalt); - return crypto - .createHash('sha256') - .update(components.join('|')) - .digest('hex'); -} -exports.getCacheVersion = getCacheVersion; -function getCacheEntry(keys, paths, options) { - return __awaiter(this, void 0, void 0, function* () { - const httpClient = createHttpClient(); - const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod); - const resource = `cache?keys=${encodeURIComponent(keys.join(','))}&version=${version}`; - const response = yield requestUtils_1.retryTypedResponse('getCacheEntry', () => __awaiter(this, void 0, void 0, function* () { return httpClient.getJson(getCacheApiUrl(resource)); })); - if (response.statusCode === 204) { - return null; - } - if (!requestUtils_1.isSuccessStatusCode(response.statusCode)) { - throw new Error(`Cache service responded with ${response.statusCode}`); - } - const cacheResult = response.result; - const cacheDownloadUrl = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.archiveLocation; - if (!cacheDownloadUrl) { - throw new Error('Cache not found.'); - } - core.setSecret(cacheDownloadUrl); - core.debug(`Cache Result:`); - core.debug(JSON.stringify(cacheResult)); - return cacheResult; - }); -} -exports.getCacheEntry = getCacheEntry; -function downloadCache(archiveLocation, archivePath, options) { - return __awaiter(this, void 0, void 0, function* () { - const archiveUrl = new url_1.URL(archiveLocation); - const downloadOptions = options_1.getDownloadOptions(options); - if (downloadOptions.useAzureSdk && - archiveUrl.hostname.endsWith('.blob.core.windows.net')) { - // Use Azure storage SDK to download caches hosted on Azure to improve speed and reliability. - yield downloadUtils_1.downloadCacheStorageSDK(archiveLocation, archivePath, downloadOptions); - } - else { - // Otherwise, download using the Actions http-client. - yield downloadUtils_1.downloadCacheHttpClient(archiveLocation, archivePath); - } - }); -} -exports.downloadCache = downloadCache; -// Reserve Cache -function reserveCache(key, paths, options) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - const httpClient = createHttpClient(); - const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod); - const reserveCacheRequest = { - key, - version - }; - const response = yield requestUtils_1.retryTypedResponse('reserveCache', () => __awaiter(this, void 0, void 0, function* () { - return httpClient.postJson(getCacheApiUrl('caches'), reserveCacheRequest); - })); - return (_b = (_a = response === null || response === void 0 ? void 0 : response.result) === null || _a === void 0 ? void 0 : _a.cacheId) !== null && _b !== void 0 ? _b : -1; - }); -} -exports.reserveCache = reserveCache; -function getContentRange(start, end) { - // Format: `bytes start-end/filesize - // start and end are inclusive - // filesize can be * - // For a 200 byte chunk starting at byte 0: - // Content-Range: bytes 0-199/* - return `bytes ${start}-${end}/*`; -} -function uploadChunk(httpClient, resourceUrl, openStream, start, end) { - return __awaiter(this, void 0, void 0, function* () { - core.debug(`Uploading chunk of size ${end - - start + - 1} bytes at offset ${start} with content range: ${getContentRange(start, end)}`); - const additionalHeaders = { - 'Content-Type': 'application/octet-stream', - 'Content-Range': getContentRange(start, end) - }; - const uploadChunkResponse = yield requestUtils_1.retryHttpClientResponse(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter(this, void 0, void 0, function* () { - return httpClient.sendStream('PATCH', resourceUrl, openStream(), additionalHeaders); - })); - if (!requestUtils_1.isSuccessStatusCode(uploadChunkResponse.message.statusCode)) { - throw new Error(`Cache service responded with ${uploadChunkResponse.message.statusCode} during upload chunk.`); - } - }); -} -function uploadFile(httpClient, cacheId, archivePath, options) { - return __awaiter(this, void 0, void 0, function* () { - // Upload Chunks - const fileSize = fs.statSync(archivePath).size; - const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`); - const fd = fs.openSync(archivePath, 'r'); - const uploadOptions = options_1.getUploadOptions(options); - const concurrency = utils.assertDefined('uploadConcurrency', uploadOptions.uploadConcurrency); - const maxChunkSize = utils.assertDefined('uploadChunkSize', uploadOptions.uploadChunkSize); - const parallelUploads = [...new Array(concurrency).keys()]; - core.debug('Awaiting all uploads'); - let offset = 0; - try { - yield Promise.all(parallelUploads.map(() => __awaiter(this, void 0, void 0, function* () { - while (offset < fileSize) { - const chunkSize = Math.min(fileSize - offset, maxChunkSize); - const start = offset; - const end = offset + chunkSize - 1; - offset += maxChunkSize; - yield uploadChunk(httpClient, resourceUrl, () => fs - .createReadStream(archivePath, { - fd, - start, - end, - autoClose: false - }) - .on('error', error => { - throw new Error(`Cache upload failed because file read failed with ${error.message}`); - }), start, end); - } - }))); - } - finally { - fs.closeSync(fd); - } - return; - }); -} -function commitCache(httpClient, cacheId, filesize) { - return __awaiter(this, void 0, void 0, function* () { - const commitCacheRequest = { size: filesize }; - return yield requestUtils_1.retryTypedResponse('commitCache', () => __awaiter(this, void 0, void 0, function* () { - return httpClient.postJson(getCacheApiUrl(`caches/${cacheId.toString()}`), commitCacheRequest); - })); - }); -} -function saveCache(cacheId, archivePath, options) { - return __awaiter(this, void 0, void 0, function* () { - const httpClient = createHttpClient(); - core.debug('Upload cache'); - yield uploadFile(httpClient, cacheId, archivePath, options); - // Commit Cache - core.debug('Commiting cache'); - const cacheSize = utils.getArchiveFileSizeIsBytes(archivePath); - const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize); - if (!requestUtils_1.isSuccessStatusCode(commitCacheResponse.statusCode)) { - throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`); - } - core.info('Cache saved successfully'); - }); -} -exports.saveCache = saveCache; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __importStar(__webpack_require__(470)); +const http_client_1 = __webpack_require__(22); +const auth_1 = __webpack_require__(733); +const crypto = __importStar(__webpack_require__(417)); +const fs = __importStar(__webpack_require__(747)); +const url_1 = __webpack_require__(835); +const utils = __importStar(__webpack_require__(15)); +const constants_1 = __webpack_require__(931); +const downloadUtils_1 = __webpack_require__(251); +const options_1 = __webpack_require__(538); +const requestUtils_1 = __webpack_require__(899); +const versionSalt = '1.0'; +function getCacheApiUrl(resource) { + // Ideally we just use ACTIONS_CACHE_URL + const baseUrl = (process.env['ACTIONS_CACHE_URL'] || + process.env['ACTIONS_RUNTIME_URL'] || + '').replace('pipelines', 'artifactcache'); + if (!baseUrl) { + throw new Error('Cache Service Url not found, unable to restore cache.'); + } + const url = `${baseUrl}_apis/artifactcache/${resource}`; + core.debug(`Resource Url: ${url}`); + return url; +} +function createAcceptHeader(type, apiVersion) { + return `${type};api-version=${apiVersion}`; +} +function getRequestOptions() { + const requestOptions = { + headers: { + Accept: createAcceptHeader('application/json', '6.0-preview.1') + } + }; + return requestOptions; +} +function createHttpClient() { + const token = process.env['ACTIONS_RUNTIME_TOKEN'] || ''; + const bearerCredentialHandler = new auth_1.BearerCredentialHandler(token); + return new http_client_1.HttpClient('actions/cache', [bearerCredentialHandler], getRequestOptions()); +} +function getCacheVersion(paths, compressionMethod) { + const components = paths.concat(!compressionMethod || compressionMethod === constants_1.CompressionMethod.Gzip + ? [] + : [compressionMethod]); + // Add salt to cache version to support breaking changes in cache entry + components.push(versionSalt); + return crypto + .createHash('sha256') + .update(components.join('|')) + .digest('hex'); +} +exports.getCacheVersion = getCacheVersion; +function getCacheEntry(keys, paths, options) { + return __awaiter(this, void 0, void 0, function* () { + const httpClient = createHttpClient(); + const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod); + const resource = `cache?keys=${encodeURIComponent(keys.join(','))}&version=${version}`; + const response = yield requestUtils_1.retryTypedResponse('getCacheEntry', () => __awaiter(this, void 0, void 0, function* () { return httpClient.getJson(getCacheApiUrl(resource)); })); + if (response.statusCode === 204) { + return null; + } + if (!requestUtils_1.isSuccessStatusCode(response.statusCode)) { + throw new Error(`Cache service responded with ${response.statusCode}`); + } + const cacheResult = response.result; + const cacheDownloadUrl = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.archiveLocation; + if (!cacheDownloadUrl) { + throw new Error('Cache not found.'); + } + core.setSecret(cacheDownloadUrl); + core.debug(`Cache Result:`); + core.debug(JSON.stringify(cacheResult)); + return cacheResult; + }); +} +exports.getCacheEntry = getCacheEntry; +function downloadCache(archiveLocation, archivePath, options) { + return __awaiter(this, void 0, void 0, function* () { + const archiveUrl = new url_1.URL(archiveLocation); + const downloadOptions = options_1.getDownloadOptions(options); + if (downloadOptions.useAzureSdk && + archiveUrl.hostname.endsWith('.blob.core.windows.net')) { + // Use Azure storage SDK to download caches hosted on Azure to improve speed and reliability. + yield downloadUtils_1.downloadCacheStorageSDK(archiveLocation, archivePath, downloadOptions); + } + else { + // Otherwise, download using the Actions http-client. + yield downloadUtils_1.downloadCacheHttpClient(archiveLocation, archivePath); + } + }); +} +exports.downloadCache = downloadCache; +// Reserve Cache +function reserveCache(key, paths, options) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + const httpClient = createHttpClient(); + const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod); + const reserveCacheRequest = { + key, + version + }; + const response = yield requestUtils_1.retryTypedResponse('reserveCache', () => __awaiter(this, void 0, void 0, function* () { + return httpClient.postJson(getCacheApiUrl('caches'), reserveCacheRequest); + })); + return (_b = (_a = response === null || response === void 0 ? void 0 : response.result) === null || _a === void 0 ? void 0 : _a.cacheId) !== null && _b !== void 0 ? _b : -1; + }); +} +exports.reserveCache = reserveCache; +function getContentRange(start, end) { + // Format: `bytes start-end/filesize + // start and end are inclusive + // filesize can be * + // For a 200 byte chunk starting at byte 0: + // Content-Range: bytes 0-199/* + return `bytes ${start}-${end}/*`; +} +function uploadChunk(httpClient, resourceUrl, openStream, start, end) { + return __awaiter(this, void 0, void 0, function* () { + core.debug(`Uploading chunk of size ${end - + start + + 1} bytes at offset ${start} with content range: ${getContentRange(start, end)}`); + const additionalHeaders = { + 'Content-Type': 'application/octet-stream', + 'Content-Range': getContentRange(start, end) + }; + const uploadChunkResponse = yield requestUtils_1.retryHttpClientResponse(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter(this, void 0, void 0, function* () { + return httpClient.sendStream('PATCH', resourceUrl, openStream(), additionalHeaders); + })); + if (!requestUtils_1.isSuccessStatusCode(uploadChunkResponse.message.statusCode)) { + throw new Error(`Cache service responded with ${uploadChunkResponse.message.statusCode} during upload chunk.`); + } + }); +} +function uploadFile(httpClient, cacheId, archivePath, options) { + return __awaiter(this, void 0, void 0, function* () { + // Upload Chunks + const fileSize = fs.statSync(archivePath).size; + const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`); + const fd = fs.openSync(archivePath, 'r'); + const uploadOptions = options_1.getUploadOptions(options); + const concurrency = utils.assertDefined('uploadConcurrency', uploadOptions.uploadConcurrency); + const maxChunkSize = utils.assertDefined('uploadChunkSize', uploadOptions.uploadChunkSize); + const parallelUploads = [...new Array(concurrency).keys()]; + core.debug('Awaiting all uploads'); + let offset = 0; + try { + yield Promise.all(parallelUploads.map(() => __awaiter(this, void 0, void 0, function* () { + while (offset < fileSize) { + const chunkSize = Math.min(fileSize - offset, maxChunkSize); + const start = offset; + const end = offset + chunkSize - 1; + offset += maxChunkSize; + yield uploadChunk(httpClient, resourceUrl, () => fs + .createReadStream(archivePath, { + fd, + start, + end, + autoClose: false + }) + .on('error', error => { + throw new Error(`Cache upload failed because file read failed with ${error.message}`); + }), start, end); + } + }))); + } + finally { + fs.closeSync(fd); + } + return; + }); +} +function commitCache(httpClient, cacheId, filesize) { + return __awaiter(this, void 0, void 0, function* () { + const commitCacheRequest = { size: filesize }; + return yield requestUtils_1.retryTypedResponse('commitCache', () => __awaiter(this, void 0, void 0, function* () { + return httpClient.postJson(getCacheApiUrl(`caches/${cacheId.toString()}`), commitCacheRequest); + })); + }); +} +function saveCache(cacheId, archivePath, options) { + return __awaiter(this, void 0, void 0, function* () { + const httpClient = createHttpClient(); + core.debug('Upload cache'); + yield uploadFile(httpClient, cacheId, archivePath, options); + // Commit Cache + core.debug('Commiting cache'); + const cacheSize = utils.getArchiveFileSizeIsBytes(archivePath); + core.info(`Cache Size: ~${Math.round(cacheSize / (1024 * 1024))} MB (${cacheSize} B)`); + const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize); + if (!requestUtils_1.isSuccessStatusCode(commitCacheResponse.statusCode)) { + throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`); + } + core.info('Cache saved successfully'); + }); +} +exports.saveCache = saveCache; //# sourceMappingURL=cacheHttpClient.js.map /***/ }), @@ -7478,43 +7521,7 @@ exports.isTokenCredential = isTokenCredential; /***/ }), /* 230 */, -/* 231 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -__exportStar(__webpack_require__(328), exports); -__exportStar(__webpack_require__(715), exports); -__exportStar(__webpack_require__(924), exports); -//# sourceMappingURL=index.js.map - -/***/ }), +/* 231 */, /* 232 */, /* 233 */, /* 234 */, @@ -8125,235 +8132,235 @@ GlobSync.prototype._makeAbs = function (f) { /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(__webpack_require__(470)); -const http_client_1 = __webpack_require__(22); -const storage_blob_1 = __webpack_require__(373); -const buffer = __importStar(__webpack_require__(293)); -const fs = __importStar(__webpack_require__(747)); -const stream = __importStar(__webpack_require__(794)); -const util = __importStar(__webpack_require__(669)); -const utils = __importStar(__webpack_require__(15)); -const constants_1 = __webpack_require__(931); -const requestUtils_1 = __webpack_require__(899); -/** - * Pipes the body of a HTTP response to a stream - * - * @param response the HTTP response - * @param output the writable stream - */ -function pipeResponseToStream(response, output) { - return __awaiter(this, void 0, void 0, function* () { - const pipeline = util.promisify(stream.pipeline); - yield pipeline(response.message, output); - }); -} -/** - * Class for tracking the download state and displaying stats. - */ -class DownloadProgress { - constructor(contentLength) { - this.contentLength = contentLength; - this.segmentIndex = 0; - this.segmentSize = 0; - this.segmentOffset = 0; - this.receivedBytes = 0; - this.displayedComplete = false; - this.startTime = Date.now(); - } - /** - * Progress to the next segment. Only call this method when the previous segment - * is complete. - * - * @param segmentSize the length of the next segment - */ - nextSegment(segmentSize) { - this.segmentOffset = this.segmentOffset + this.segmentSize; - this.segmentIndex = this.segmentIndex + 1; - this.segmentSize = segmentSize; - this.receivedBytes = 0; - core.debug(`Downloading segment at offset ${this.segmentOffset} with length ${this.segmentSize}...`); - } - /** - * Sets the number of bytes received for the current segment. - * - * @param receivedBytes the number of bytes received - */ - setReceivedBytes(receivedBytes) { - this.receivedBytes = receivedBytes; - } - /** - * Returns the total number of bytes transferred. - */ - getTransferredBytes() { - return this.segmentOffset + this.receivedBytes; - } - /** - * Returns true if the download is complete. - */ - isDone() { - return this.getTransferredBytes() === this.contentLength; - } - /** - * Prints the current download stats. Once the download completes, this will print one - * last line and then stop. - */ - display() { - if (this.displayedComplete) { - return; - } - const transferredBytes = this.segmentOffset + this.receivedBytes; - const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); - const elapsedTime = Date.now() - this.startTime; - const downloadSpeed = (transferredBytes / - (1024 * 1024) / - (elapsedTime / 1000)).toFixed(1); - core.info(`Received ${transferredBytes} of ${this.contentLength} (${percentage}%), ${downloadSpeed} MBs/sec`); - if (this.isDone()) { - this.displayedComplete = true; - } - } - /** - * Returns a function used to handle TransferProgressEvents. - */ - onProgress() { - return (progress) => { - this.setReceivedBytes(progress.loadedBytes); - }; - } - /** - * Starts the timer that displays the stats. - * - * @param delayInMs the delay between each write - */ - startDisplayTimer(delayInMs = 1000) { - const displayCallback = () => { - this.display(); - if (!this.isDone()) { - this.timeoutHandle = setTimeout(displayCallback, delayInMs); - } - }; - this.timeoutHandle = setTimeout(displayCallback, delayInMs); - } - /** - * Stops the timer that displays the stats. As this typically indicates the download - * is complete, this will display one last line, unless the last line has already - * been written. - */ - stopDisplayTimer() { - if (this.timeoutHandle) { - clearTimeout(this.timeoutHandle); - this.timeoutHandle = undefined; - } - this.display(); - } -} -exports.DownloadProgress = DownloadProgress; -/** - * Download the cache using the Actions toolkit http-client - * - * @param archiveLocation the URL for the cache - * @param archivePath the local path where the cache is saved - */ -function downloadCacheHttpClient(archiveLocation, archivePath) { - return __awaiter(this, void 0, void 0, function* () { - const writeStream = fs.createWriteStream(archivePath); - const httpClient = new http_client_1.HttpClient('actions/cache'); - const downloadResponse = yield requestUtils_1.retryHttpClientResponse('downloadCache', () => __awaiter(this, void 0, void 0, function* () { return httpClient.get(archiveLocation); })); - // Abort download if no traffic received over the socket. - downloadResponse.message.socket.setTimeout(constants_1.SocketTimeout, () => { - downloadResponse.message.destroy(); - core.debug(`Aborting download, socket timed out after ${constants_1.SocketTimeout} ms`); - }); - yield pipeResponseToStream(downloadResponse, writeStream); - // Validate download size. - const contentLengthHeader = downloadResponse.message.headers['content-length']; - if (contentLengthHeader) { - const expectedLength = parseInt(contentLengthHeader); - const actualLength = utils.getArchiveFileSizeIsBytes(archivePath); - if (actualLength !== expectedLength) { - throw new Error(`Incomplete download. Expected file size: ${expectedLength}, actual file size: ${actualLength}`); - } - } - else { - core.debug('Unable to validate download, no Content-Length header'); - } - }); -} -exports.downloadCacheHttpClient = downloadCacheHttpClient; -/** - * Download the cache using the Azure Storage SDK. Only call this method if the - * URL points to an Azure Storage endpoint. - * - * @param archiveLocation the URL for the cache - * @param archivePath the local path where the cache is saved - * @param options the download options with the defaults set - */ -function downloadCacheStorageSDK(archiveLocation, archivePath, options) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const client = new storage_blob_1.BlockBlobClient(archiveLocation, undefined, { - retryOptions: { - // Override the timeout used when downloading each 4 MB chunk - // The default is 2 min / MB, which is way too slow - tryTimeoutInMs: options.timeoutInMs - } - }); - const properties = yield client.getProperties(); - const contentLength = (_a = properties.contentLength) !== null && _a !== void 0 ? _a : -1; - if (contentLength < 0) { - // We should never hit this condition, but just in case fall back to downloading the - // file as one large stream - core.debug('Unable to determine content length, downloading file with http-client...'); - yield downloadCacheHttpClient(archiveLocation, archivePath); - } - else { - // Use downloadToBuffer for faster downloads, since internally it splits the - // file into 4 MB chunks which can then be parallelized and retried independently - // - // If the file exceeds the buffer maximum length (~1 GB on 32-bit systems and ~2 GB - // on 64-bit systems), split the download into multiple segments - const maxSegmentSize = buffer.constants.MAX_LENGTH; - const downloadProgress = new DownloadProgress(contentLength); - const fd = fs.openSync(archivePath, 'w'); - try { - downloadProgress.startDisplayTimer(); - while (!downloadProgress.isDone()) { - const segmentStart = downloadProgress.segmentOffset + downloadProgress.segmentSize; - const segmentSize = Math.min(maxSegmentSize, contentLength - segmentStart); - downloadProgress.nextSegment(segmentSize); - const result = yield client.downloadToBuffer(segmentStart, segmentSize, { - concurrency: options.downloadConcurrency, - onProgress: downloadProgress.onProgress() - }); - fs.writeFileSync(fd, result); - } - } - finally { - downloadProgress.stopDisplayTimer(); - fs.closeSync(fd); - } - } - }); -} -exports.downloadCacheStorageSDK = downloadCacheStorageSDK; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __importStar(__webpack_require__(470)); +const http_client_1 = __webpack_require__(22); +const storage_blob_1 = __webpack_require__(373); +const buffer = __importStar(__webpack_require__(293)); +const fs = __importStar(__webpack_require__(747)); +const stream = __importStar(__webpack_require__(794)); +const util = __importStar(__webpack_require__(669)); +const utils = __importStar(__webpack_require__(15)); +const constants_1 = __webpack_require__(931); +const requestUtils_1 = __webpack_require__(899); +/** + * Pipes the body of a HTTP response to a stream + * + * @param response the HTTP response + * @param output the writable stream + */ +function pipeResponseToStream(response, output) { + return __awaiter(this, void 0, void 0, function* () { + const pipeline = util.promisify(stream.pipeline); + yield pipeline(response.message, output); + }); +} +/** + * Class for tracking the download state and displaying stats. + */ +class DownloadProgress { + constructor(contentLength) { + this.contentLength = contentLength; + this.segmentIndex = 0; + this.segmentSize = 0; + this.segmentOffset = 0; + this.receivedBytes = 0; + this.displayedComplete = false; + this.startTime = Date.now(); + } + /** + * Progress to the next segment. Only call this method when the previous segment + * is complete. + * + * @param segmentSize the length of the next segment + */ + nextSegment(segmentSize) { + this.segmentOffset = this.segmentOffset + this.segmentSize; + this.segmentIndex = this.segmentIndex + 1; + this.segmentSize = segmentSize; + this.receivedBytes = 0; + core.debug(`Downloading segment at offset ${this.segmentOffset} with length ${this.segmentSize}...`); + } + /** + * Sets the number of bytes received for the current segment. + * + * @param receivedBytes the number of bytes received + */ + setReceivedBytes(receivedBytes) { + this.receivedBytes = receivedBytes; + } + /** + * Returns the total number of bytes transferred. + */ + getTransferredBytes() { + return this.segmentOffset + this.receivedBytes; + } + /** + * Returns true if the download is complete. + */ + isDone() { + return this.getTransferredBytes() === this.contentLength; + } + /** + * Prints the current download stats. Once the download completes, this will print one + * last line and then stop. + */ + display() { + if (this.displayedComplete) { + return; + } + const transferredBytes = this.segmentOffset + this.receivedBytes; + const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); + const elapsedTime = Date.now() - this.startTime; + const downloadSpeed = (transferredBytes / + (1024 * 1024) / + (elapsedTime / 1000)).toFixed(1); + core.info(`Received ${transferredBytes} of ${this.contentLength} (${percentage}%), ${downloadSpeed} MBs/sec`); + if (this.isDone()) { + this.displayedComplete = true; + } + } + /** + * Returns a function used to handle TransferProgressEvents. + */ + onProgress() { + return (progress) => { + this.setReceivedBytes(progress.loadedBytes); + }; + } + /** + * Starts the timer that displays the stats. + * + * @param delayInMs the delay between each write + */ + startDisplayTimer(delayInMs = 1000) { + const displayCallback = () => { + this.display(); + if (!this.isDone()) { + this.timeoutHandle = setTimeout(displayCallback, delayInMs); + } + }; + this.timeoutHandle = setTimeout(displayCallback, delayInMs); + } + /** + * Stops the timer that displays the stats. As this typically indicates the download + * is complete, this will display one last line, unless the last line has already + * been written. + */ + stopDisplayTimer() { + if (this.timeoutHandle) { + clearTimeout(this.timeoutHandle); + this.timeoutHandle = undefined; + } + this.display(); + } +} +exports.DownloadProgress = DownloadProgress; +/** + * Download the cache using the Actions toolkit http-client + * + * @param archiveLocation the URL for the cache + * @param archivePath the local path where the cache is saved + */ +function downloadCacheHttpClient(archiveLocation, archivePath) { + return __awaiter(this, void 0, void 0, function* () { + const writeStream = fs.createWriteStream(archivePath); + const httpClient = new http_client_1.HttpClient('actions/cache'); + const downloadResponse = yield requestUtils_1.retryHttpClientResponse('downloadCache', () => __awaiter(this, void 0, void 0, function* () { return httpClient.get(archiveLocation); })); + // Abort download if no traffic received over the socket. + downloadResponse.message.socket.setTimeout(constants_1.SocketTimeout, () => { + downloadResponse.message.destroy(); + core.debug(`Aborting download, socket timed out after ${constants_1.SocketTimeout} ms`); + }); + yield pipeResponseToStream(downloadResponse, writeStream); + // Validate download size. + const contentLengthHeader = downloadResponse.message.headers['content-length']; + if (contentLengthHeader) { + const expectedLength = parseInt(contentLengthHeader); + const actualLength = utils.getArchiveFileSizeIsBytes(archivePath); + if (actualLength !== expectedLength) { + throw new Error(`Incomplete download. Expected file size: ${expectedLength}, actual file size: ${actualLength}`); + } + } + else { + core.debug('Unable to validate download, no Content-Length header'); + } + }); +} +exports.downloadCacheHttpClient = downloadCacheHttpClient; +/** + * Download the cache using the Azure Storage SDK. Only call this method if the + * URL points to an Azure Storage endpoint. + * + * @param archiveLocation the URL for the cache + * @param archivePath the local path where the cache is saved + * @param options the download options with the defaults set + */ +function downloadCacheStorageSDK(archiveLocation, archivePath, options) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const client = new storage_blob_1.BlockBlobClient(archiveLocation, undefined, { + retryOptions: { + // Override the timeout used when downloading each 4 MB chunk + // The default is 2 min / MB, which is way too slow + tryTimeoutInMs: options.timeoutInMs + } + }); + const properties = yield client.getProperties(); + const contentLength = (_a = properties.contentLength) !== null && _a !== void 0 ? _a : -1; + if (contentLength < 0) { + // We should never hit this condition, but just in case fall back to downloading the + // file as one large stream + core.debug('Unable to determine content length, downloading file with http-client...'); + yield downloadCacheHttpClient(archiveLocation, archivePath); + } + else { + // Use downloadToBuffer for faster downloads, since internally it splits the + // file into 4 MB chunks which can then be parallelized and retried independently + // + // If the file exceeds the buffer maximum length (~1 GB on 32-bit systems and ~2 GB + // on 64-bit systems), split the download into multiple segments + const maxSegmentSize = buffer.constants.MAX_LENGTH; + const downloadProgress = new DownloadProgress(contentLength); + const fd = fs.openSync(archivePath, 'w'); + try { + downloadProgress.startDisplayTimer(); + while (!downloadProgress.isDone()) { + const segmentStart = downloadProgress.segmentOffset + downloadProgress.segmentSize; + const segmentSize = Math.min(maxSegmentSize, contentLength - segmentStart); + downloadProgress.nextSegment(segmentSize); + const result = yield client.downloadToBuffer(segmentStart, segmentSize, { + concurrency: options.downloadConcurrency, + onProgress: downloadProgress.onProgress() + }); + fs.writeFileSync(fd, result); + } + } + finally { + downloadProgress.stopDisplayTimer(); + fs.closeSync(fd); + } + } + }); +} +exports.downloadCacheStorageSDK = downloadCacheStorageSDK; //# sourceMappingURL=downloadUtils.js.map /***/ }), @@ -10892,30 +10899,7 @@ var MatchKind; //# sourceMappingURL=internal-match-kind.js.map /***/ }), -/* 328 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -//# sourceMappingURL=types.js.map - -/***/ }), +/* 328 */, /* 329 */, /* 330 */, /* 331 */, @@ -12864,12 +12848,12 @@ var FilterBlobItem = { name: "String" } }, - tagValue: { - xmlName: "TagValue", - required: true, - serializedName: "TagValue", + tags: { + xmlName: "Tags", + serializedName: "Tags", type: { - name: "String" + name: "Composite", + className: "BlobTags" } } } @@ -13646,6 +13630,12 @@ var ServiceGetAccountInfoHeaders = { ] } }, + isHierarchicalNamespaceEnabled: { + serializedName: "x-ms-is-hns-enabled", + type: { + name: "Boolean" + } + }, errorCode: { serializedName: "x-ms-error-code", type: { @@ -15644,6 +15634,87 @@ var BlockBlobUploadHeaders = { } } }; +var BlockBlobPutBlobFromUrlHeaders = { + serializedName: "blockblob-putblobfromurl-headers", + type: { + name: "Composite", + className: "BlockBlobPutBlobFromUrlHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; var BlobUndeleteHeaders = { serializedName: "blob-undelete-headers", type: { @@ -17905,6 +17976,8 @@ var Mappers = /*#__PURE__*/Object.freeze({ __proto__: null, BlobServiceProperties: BlobServiceProperties, BlobServiceStatistics: BlobServiceStatistics, + BlobTag: BlobTag, + BlobTags: BlobTags, ContainerItem: ContainerItem, ContainerProperties: ContainerProperties, CorsRule: CorsRule, @@ -18135,6 +18208,21 @@ var blobContentType = { } } }; +var blobDeleteType = { + parameterPath: [ + "options", + "blobDeleteType" + ], + mapper: { + serializedName: "deletetype", + type: { + name: "Enum", + allowedValues: [ + "Permanent" + ] + } + } +}; var blobSequenceNumber = { parameterPath: [ "options", @@ -18601,6 +18689,18 @@ var copySource = { } } }; +var copySourceBlobProperties = { + parameterPath: [ + "options", + "copySourceBlobProperties" + ], + mapper: { + serializedName: "x-ms-copy-source-blob-properties", + type: { + name: "Boolean" + } + } +}; var defaultEncryptionScope = { parameterPath: [ "options", @@ -19574,7 +19674,7 @@ var version = { required: true, isConstant: true, serializedName: "x-ms-version", - defaultValue: '2020-02-10', + defaultValue: '2020-04-08', type: { name: "String" } @@ -20855,7 +20955,8 @@ var deleteMethodOperationSpec$1 = { queryParameters: [ snapshot, versionId, - timeoutInSeconds + timeoutInSeconds, + blobDeleteType ], headerParameters: [ deleteSnapshots, @@ -21571,7 +21672,8 @@ var getTagsOperationSpec = { headerParameters: [ version, requestId, - ifTags + ifTags, + leaseId0 ], responses: { 200: { @@ -21602,7 +21704,8 @@ var setTagsOperationSpec = { transactionalContentMD5, transactionalContentCrc64, requestId, - ifTags + ifTags, + leaseId0 ], requestBody: { parameterPath: [ @@ -22355,6 +22458,7 @@ var Mappers$5 = /*#__PURE__*/Object.freeze({ Block: Block, BlockBlobCommitBlockListHeaders: BlockBlobCommitBlockListHeaders, BlockBlobGetBlockListHeaders: BlockBlobGetBlockListHeaders, + BlockBlobPutBlobFromUrlHeaders: BlockBlobPutBlobFromUrlHeaders, BlockBlobStageBlockFromURLHeaders: BlockBlobStageBlockFromURLHeaders, BlockBlobStageBlockHeaders: BlockBlobStageBlockHeaders, BlockBlobUploadHeaders: BlockBlobUploadHeaders, @@ -22388,6 +22492,13 @@ var BlockBlob = /** @class */ (function () { options: options }, uploadOperationSpec, callback); }; + BlockBlob.prototype.putBlobFromUrl = function (contentLength, copySource, options, callback) { + return this.client.sendOperationRequest({ + contentLength: contentLength, + copySource: copySource, + options: options + }, putBlobFromUrlOperationSpec, callback); + }; BlockBlob.prototype.stageBlock = function (blockId, contentLength, body, options, callback) { return this.client.sendOperationRequest({ blockId: blockId, @@ -22478,6 +22589,61 @@ var uploadOperationSpec = { isXML: true, serializer: serializer$5 }; +var putBlobFromUrlOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds + ], + headerParameters: [ + transactionalContentMD5, + contentLength, + metadata, + encryptionScope, + tier0, + version, + requestId, + sourceContentMD5, + blobTagsString, + copySource, + copySourceBlobProperties, + blobType2, + blobContentType, + blobContentEncoding, + blobContentLanguage, + blobContentMD5, + blobCacheControl, + blobContentDisposition, + leaseId0, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags, + sourceIfModifiedSince, + sourceIfUnmodifiedSince, + sourceIfMatch, + sourceIfNoneMatch, + sourceIfTags + ], + responses: { + 201: { + headersMapper: BlockBlobPutBlobFromUrlHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlockBlobPutBlobFromUrlHeaders + } + }, + isXML: true, + serializer: serializer$5 +}; var stageBlockOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", @@ -22657,8 +22823,8 @@ var logger = logger$1.createClientLogger("storage-blob"); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -var SDK_VERSION = "12.3.0"; -var SERVICE_VERSION = "2020-02-10"; +var SDK_VERSION = "12.4.1"; +var SERVICE_VERSION = "2020-04-08"; var BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES = 256 * 1024 * 1024; // 256MB var BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES = 4000 * 1024 * 1024; // 4000MB var BLOCK_BLOB_MAX_BLOCKS = 50000; @@ -23054,6 +23220,18 @@ function setURLParameter(url, name, value) { urlParsed.setQueryParameter(name, value); return urlParsed.toString(); } +/** + * Get URL parameter by name. + * + * @export + * @param {string} url + * @param {string} name + * @returns {(string | string[] | undefined)} + */ +function getURLParameter(url, name) { + var urlParsed = coreHttp.URLBuilder.parse(url); + return urlParsed.getQueryParameterValue(name); +} /** * Set URL host. * @@ -23139,6 +23317,26 @@ function getURLQueries(url) { } return queries; } +/** + * Append a string to URL query. + * + * @export + * @param {string} url Source URL string. + * @param {string} queryParts String to be appended to the URL query. + * @returns {string} An updated URL string. + */ +function appendToURLQuery(url, queryParts) { + var urlParsed = coreHttp.URLBuilder.parse(url); + var query = urlParsed.getQuery(); + if (query) { + query += "&" + queryParts; + } + else { + query = queryParts; + } + urlParsed.setQuery(query); + return urlParsed.toString(); +} /** * Rounds a date off to seconds. * @@ -23444,6 +23642,18 @@ function parseObjectReplicationRecord(objectReplicationRecord) { } return orProperties; } +/** + * Attach a TokenCredential to an object. + * + * @export + * @param {T} thing + * @param {TokenCredential} credential + * @returns {T} + */ +function attachCredential(thing, credential) { + thing.credential = credential; + return thing; +} // Copyright (c) Microsoft Corporation. All rights reserved. /** @@ -23688,11 +23898,7 @@ var StorageRetryPolicy = /** @class */ (function (_super) { var retriableError = retriableErrors_1[_i]; if (err.name.toUpperCase().includes(retriableError) || err.message.toUpperCase().includes(retriableError) || - (err.code && - err.code - .toString() - .toUpperCase() - .includes(retriableError))) { + (err.code && err.code.toString().toUpperCase() === retriableError)) { logger.info("RetryPolicy: Network error " + retriableError + " found, will retry."); return true; } @@ -23713,6 +23919,10 @@ var StorageRetryPolicy = /** @class */ (function (_super) { return true; } } + if ((err === null || err === void 0 ? void 0 : err.code) === "PARSE_ERROR" && (err === null || err === void 0 ? void 0 : err.message.startsWith("Error \"Error: Unclosed root tag"))) { + logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry."); + return true; + } return false; }; /** @@ -23972,9 +24182,7 @@ var TelemetryPolicyFactory = /** @class */ (function () { var userAgentInfo = []; { if (telemetry) { - // FIXME: replace() only replaces the first space. And we have no idea why we need to replace spaces in the first place. - // But fixing this would be a breaking change. Logged an issue here: https://github.com/Azure/azure-sdk-for-js/issues/10793 - var telemetryString = (telemetry.userAgentPrefix || "").replace(" ", ""); + var telemetryString = telemetry.userAgentPrefix || ""; if (telemetryString.length > 0 && userAgentInfo.indexOf(telemetryString) === -1) { userAgentInfo.push(telemetryString); } @@ -24077,8 +24285,11 @@ function newPipeline(credential, pipelineOptions) { telemetryPolicy, coreHttp.generateClientRequestIdPolicy(), new StorageBrowserPolicyFactory(), - coreHttp.deserializationPolicy(), new StorageRetryPolicyFactory(pipelineOptions.retryOptions), + // Default deserializationPolicy is provided by protocol layer + // Use customized XML char key of "#" so we could deserialize metadata + // with "_" key + coreHttp.deserializationPolicy(undefined, { xmlCharKey: "#" }), coreHttp.logPolicy({ logger: logger.info, allowedHeaderNames: StorageBlobLoggingAllowedHeaderNames, @@ -24091,13 +24302,12 @@ function newPipeline(credential, pipelineOptions) { factories.push(coreHttp.disableResponseDecompressionPolicy()); } factories.push(coreHttp.isTokenCredential(credential) - ? coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes) + ? attachCredential(coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes), credential) : credential); return new Pipeline(factories, pipelineOptions); } // Copyright (c) Microsoft Corporation. All rights reserved. -var ABORT_ERROR = new abortController.AbortError("The operation was aborted."); /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -24121,36 +24331,9 @@ var RetriableReadableStream = /** @class */ (function (_super) { */ function RetriableReadableStream(source, getter, offset, count, options) { if (options === void 0) { options = {}; } - var _this = _super.call(this) || this; + var _this = _super.call(this, { highWaterMark: options.highWaterMark }) || this; _this.retries = 0; - _this.abortHandler = function () { - _this.source.pause(); - _this.emit("error", ABORT_ERROR); - }; - _this.aborter = options.abortSignal || abortController.AbortSignal.none; - _this.getter = getter; - _this.source = source; - _this.start = offset; - _this.offset = offset; - _this.end = offset + count - 1; - _this.maxRetryRequests = - options.maxRetryRequests && options.maxRetryRequests >= 0 ? options.maxRetryRequests : 0; - _this.onProgress = options.onProgress; - _this.options = options; - _this.aborter.addEventListener("abort", _this.abortHandler); - _this.setSourceDataHandler(); - _this.setSourceEndHandler(); - _this.setSourceErrorHandler(); - return _this; - } - RetriableReadableStream.prototype._read = function () { - if (!this.aborter.aborted) { - this.source.resume(); - } - }; - RetriableReadableStream.prototype.setSourceDataHandler = function () { - var _this = this; - this.source.on("data", function (data) { + _this.sourceDataHandler = function (data) { if (_this.options.doInjectErrorOnce) { _this.options.doInjectErrorOnce = undefined; _this.source.pause(); @@ -24168,18 +24351,19 @@ var RetriableReadableStream = /** @class */ (function (_super) { if (!_this.push(data)) { _this.source.pause(); } - }); - }; - RetriableReadableStream.prototype.setSourceEndHandler = function () { - var _this = this; - this.source.on("end", function () { + }; + _this.sourceErrorOrEndHandler = function (err) { + if (err && err.name === "AbortError") { + _this.destroy(err); + return; + } // console.log( - // `Source stream emits end, offset: ${ + // `Source stream emits end or error, offset: ${ // this.offset // }, dest end : ${this.end}` // ); + _this.removeSourceEventHandlers(); if (_this.offset - 1 === _this.end) { - _this.aborter.removeEventListener("abort", _this.abortHandler); _this.push(null); } else if (_this.offset <= _this.end) { @@ -24191,31 +24375,53 @@ var RetriableReadableStream = /** @class */ (function (_super) { _this.getter(_this.offset) .then(function (newSource) { _this.source = newSource; - _this.setSourceDataHandler(); - _this.setSourceEndHandler(); - _this.setSourceErrorHandler(); + _this.setSourceEventHandlers(); }) .catch(function (error) { - _this.emit("error", error); + _this.destroy(error); }); } else { - _this.emit("error", new Error( + _this.destroy(new Error( // tslint:disable-next-line:max-line-length "Data corruption failure: received less data than required and reached maxRetires limitation. Received data offset: " + (_this .offset - 1) + ", data needed offset: " + _this.end + ", retries: " + _this.retries + ", max retries: " + _this.maxRetryRequests)); } } else { - _this.emit("error", new Error("Data corruption failure: Received more data than original request, data needed offset is " + _this.end + ", received offset: " + (_this.offset - 1))); + _this.destroy(new Error("Data corruption failure: Received more data than original request, data needed offset is " + _this.end + ", received offset: " + (_this.offset - 1))); } - }); + }; + _this.getter = getter; + _this.source = source; + _this.start = offset; + _this.offset = offset; + _this.end = offset + count - 1; + _this.maxRetryRequests = + options.maxRetryRequests && options.maxRetryRequests >= 0 ? options.maxRetryRequests : 0; + _this.onProgress = options.onProgress; + _this.options = options; + _this.setSourceEventHandlers(); + return _this; + } + RetriableReadableStream.prototype._read = function () { + this.source.resume(); }; - RetriableReadableStream.prototype.setSourceErrorHandler = function () { - var _this = this; - this.source.on("error", function (error) { - _this.emit("error", error); - }); + RetriableReadableStream.prototype.setSourceEventHandlers = function () { + this.source.on("data", this.sourceDataHandler); + this.source.on("end", this.sourceErrorOrEndHandler); + this.source.on("error", this.sourceErrorOrEndHandler); + }; + RetriableReadableStream.prototype.removeSourceEventHandlers = function () { + this.source.removeListener("data", this.sourceDataHandler); + this.source.removeListener("end", this.sourceErrorOrEndHandler); + this.source.removeListener("error", this.sourceErrorOrEndHandler); + }; + RetriableReadableStream.prototype._destroy = function (error, callback) { + // remove listener from source and release source + this.removeSourceEventHandlers(); + this.source.destroy(); + callback(error === null ? undefined : error); }; return RetriableReadableStream; }(stream.Readable)); @@ -25674,7 +25880,7 @@ var AvroReadable = /** @class */ (function () { }()); // Copyright (c) Microsoft Corporation. -var ABORT_ERROR$1 = new abortController.AbortError("Reading from the avro stream was aborted."); +var ABORT_ERROR = new abortController.AbortError("Reading from the avro stream was aborted."); var AvroReadableFromStream = /** @class */ (function (_super) { tslib.__extends(AvroReadableFromStream, _super); function AvroReadableFromStream(readable) { @@ -25704,7 +25910,7 @@ var AvroReadableFromStream = /** @class */ (function (_super) { var _this = this; return tslib.__generator(this, function (_b) { if ((_a = options.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { - throw ABORT_ERROR$1; + throw ABORT_ERROR; } if (size < 0) { throw new Error("size parameter should be positive: " + size); @@ -25748,7 +25954,7 @@ var AvroReadableFromStream = /** @class */ (function (_super) { }; var abortHandler = function () { cleanUp(); - reject(ABORT_ERROR$1); + reject(ABORT_ERROR); }; _this._readable.on("readable", readableCallback); _this._readable.once("error", rejectCallback); @@ -25786,6 +25992,7 @@ var BlobQuickQueryStream = /** @class */ (function (_super) { function BlobQuickQueryStream(source, options) { if (options === void 0) { options = {}; } var _this = _super.call(this) || this; + _this.avroPaused = true; _this.source = source; _this.onProgress = options.onProgress; _this.onError = options.onError; @@ -25795,29 +26002,31 @@ var BlobQuickQueryStream = /** @class */ (function (_super) { } BlobQuickQueryStream.prototype._read = function () { var _this = this; - this.readInternal().catch(function (err) { - _this.emit("error", err); - }); + if (this.avroPaused) { + this.readInternal().catch(function (err) { + _this.emit("error", err); + }); + } }; BlobQuickQueryStream.prototype.readInternal = function () { - var e_1, _a; return tslib.__awaiter(this, void 0, void 0, function () { - var _b, _c, obj, schema, exit, data, bytesScanned, totalBytes, fatal, name_1, description, position, e_1_1; - return tslib.__generator(this, function (_d) { - switch (_d.label) { + var avroNext, obj, schema, data, bytesScanned, totalBytes, fatal, name_1, description, position; + return tslib.__generator(this, function (_a) { + switch (_a.label) { case 0: - _d.trys.push([0, 5, 6, 11]); - _b = tslib.__asyncValues(this.avroIter); - _d.label = 1; - case 1: return [4 /*yield*/, _b.next()]; + this.avroPaused = false; + _a.label = 1; + case 1: return [4 /*yield*/, this.avroIter.next()]; case 2: - if (!(_c = _d.sent(), !_c.done)) return [3 /*break*/, 4]; - obj = _c.value; + avroNext = _a.sent(); + if (avroNext.done) { + return [3 /*break*/, 4]; + } + obj = avroNext.value; schema = obj.$schema; if (typeof schema !== "string") { throw Error("Missing schema in avro record."); } - exit = false; switch (schema) { case "com.microsoft.azure.storage.queryBlobContents.resultData": data = obj.data; @@ -25825,7 +26034,7 @@ var BlobQuickQueryStream = /** @class */ (function (_super) { throw Error("Invalid data in avro result record."); } if (!this.push(Buffer.from(data))) { - exit = true; + this.avroPaused = true; } break; case "com.microsoft.azure.storage.queryBlobContents.progress": @@ -25876,29 +26085,11 @@ var BlobQuickQueryStream = /** @class */ (function (_super) { default: throw Error("Unknown schema " + schema + " in avro progress record."); } - if (exit) { - return [3 /*break*/, 4]; - } - _d.label = 3; - case 3: return [3 /*break*/, 1]; - case 4: return [3 /*break*/, 11]; - case 5: - e_1_1 = _d.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 11]; - case 6: - _d.trys.push([6, , 9, 10]); - if (!(_c && !_c.done && (_a = _b.return))) return [3 /*break*/, 8]; - return [4 /*yield*/, _a.call(_b)]; - case 7: - _d.sent(); - _d.label = 8; - case 8: return [3 /*break*/, 10]; - case 9: - if (e_1) throw e_1.error; - return [7 /*endfinally*/]; - case 10: return [7 /*endfinally*/]; - case 11: return [2 /*return*/]; + _a.label = 3; + case 3: + if (!avroNext.done && !this.avroPaused) return [3 /*break*/, 1]; + _a.label = 4; + case 4: return [2 /*return*/]; } }); }); @@ -26710,7 +26901,7 @@ var StorageSharedKeyCredential = /** @class */ (function (_super) { * regenerated. */ var packageName = "azure-storage-blob"; -var packageVersion = "12.3.0"; +var packageVersion = "12.4.1"; var StorageClientContext = /** @class */ (function (_super) { tslib.__extends(StorageClientContext, _super); /** @@ -26732,7 +26923,7 @@ var StorageClientContext = /** @class */ (function (_super) { options.userAgent = packageName + "/" + packageVersion + " " + defaultUserAgent; } _this = _super.call(this, undefined, options) || this; - _this.version = "2020-02-10"; + _this.version = '2020-04-08'; _this.baseUri = "{url}"; _this.requestContentType = "application/json; charset=utf-8"; _this.url = url; @@ -26845,7 +27036,7 @@ function rangeResponseFromModel(response) { * This is the poller returned by {@link BlobClient.beginCopyFromURL}. * This can not be instantiated directly outside of this package. * - * @ignore + * @hidden */ var BlobBeginCopyFromUrlPoller = /** @class */ (function (_super) { tslib.__extends(BlobBeginCopyFromUrlPoller, _super); @@ -26875,7 +27066,7 @@ var BlobBeginCopyFromUrlPoller = /** @class */ (function (_super) { * Note: Intentionally using function expression over arrow function expression * so that the function can be invoked with a different context. * This affects what `this` refers to. - * @ignore + * @hidden */ var cancel = function cancel(options) { if (options === void 0) { options = {}; } @@ -26910,7 +27101,7 @@ var cancel = function cancel(options) { * Note: Intentionally using function expression over arrow function expression * so that the function can be invoked with a different context. * This affects what `this` refers to. - * @ignore + * @hidden */ var update = function update(options) { if (options === void 0) { options = {}; } @@ -26975,7 +27166,7 @@ var update = function update(options) { * Note: Intentionally using function expression over arrow function expression * so that the function can be invoked with a different context. * This affects what `this` refers to. - * @ignore + * @hidden */ var toString = function toString() { return JSON.stringify({ state: this.state }, function (key, value) { @@ -26988,7 +27179,7 @@ var toString = function toString() { }; /** * Creates a poll operation given the provided state. - * @ignore + * @hidden */ function makeBlobBeginCopyFromURLPollOperation(state) { return { @@ -27048,10 +27239,14 @@ var StorageClient = /** @class */ (function () { for (var _i = 0, _a = this.pipeline.factories; _i < _a.length; _i++) { var factory = _a[_i]; if ((coreHttp.isNode && factory instanceof StorageSharedKeyCredential) || - factory instanceof AnonymousCredential || - coreHttp.isTokenCredential(factory)) { + factory instanceof AnonymousCredential) { this.credential = factory; } + else if (coreHttp.isTokenCredential(factory.credential)) { + // Only works if the factory has been attached a "credential" property. + // We do that in newPipeline() when using TokenCredential. + this.credential = factory.credential; + } } // Override protocol layer's default content-type var storageClientContext = this.storageClientContext; @@ -27900,1356 +28095,1502 @@ function readStreamToLocalFile(rs, file) { var fsStat = util.promisify(fs.stat); var fsCreateReadStream = fs.createReadStream; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. /** - * A BlobClient represents a URL to an Azure Storage blob; the blob may be a block blob, - * append blob, or page blob. + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a blob. Setting + * a value to true means that any SAS which uses these permissions will grant permissions for that operation. Once all + * the values are set, this should be serialized with toString and set as the permissions field on a + * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but + * the order of the permissions is particular and this class guarantees correctness. * * @export - * @class BlobClient + * @class BlobSASPermissions */ -var BlobClient = /** @class */ (function (_super) { - tslib.__extends(BlobClient, _super); - function BlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { - var _a; - var _this = this; - options = options || {}; - var pipeline; - var url; - if (credentialOrPipelineOrContainerName instanceof Pipeline) { - // (url: string, pipeline: Pipeline) - url = urlOrConnectionString; - pipeline = credentialOrPipelineOrContainerName; - } - else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || - credentialOrPipelineOrContainerName instanceof AnonymousCredential || - coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { - // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) - url = urlOrConnectionString; - options = blobNameOrOptions; - pipeline = newPipeline(credentialOrPipelineOrContainerName, options); - } - else if (!credentialOrPipelineOrContainerName && - typeof credentialOrPipelineOrContainerName !== "string") { - // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) - // The second parameter is undefined. Use anonymous credential. - url = urlOrConnectionString; - pipeline = newPipeline(new AnonymousCredential(), options); - } - else if (credentialOrPipelineOrContainerName && - typeof credentialOrPipelineOrContainerName === "string" && - blobNameOrOptions && - typeof blobNameOrOptions === "string") { - // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) - var containerName = credentialOrPipelineOrContainerName; - var blobName = blobNameOrOptions; - var extractedCreds = extractConnectionStringParts(urlOrConnectionString); - if (extractedCreds.kind === "AccountConnString") { - { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); - options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); - pipeline = newPipeline(sharedKeyCredential, options); - } - } - else if (extractedCreds.kind === "SASConnString") { - url = - appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + - "?" + - extractedCreds.accountSas; - pipeline = newPipeline(new AnonymousCredential(), options); - } - else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); - } - } - else { - throw new Error("Expecting non-empty strings for containerName and blobName parameters"); - } - _this = _super.call(this, url, pipeline) || this; - (_a = _this.getBlobAndContainerNamesFromUrl(), _this._name = _a.blobName, _this._containerName = _a.containerName); - _this.blobContext = new Blob$1(_this.storageClientContext); - return _this; - } - Object.defineProperty(BlobClient.prototype, "name", { +var BlobSASPermissions = /** @class */ (function () { + function BlobSASPermissions() { /** - * The name of the blob. + * Specifies Read access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions */ - get: function () { - return this._name; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobClient.prototype, "containerName", { + this.read = false; /** - * The name of the storage container the blob is associated with. + * Specifies Add access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions */ - get: function () { - return this._containerName; - }, - enumerable: false, - configurable: true - }); + this.add = false; + /** + * Specifies Create access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.create = false; + /** + * Specifies Write access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.write = false; + /** + * Specifies Delete access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.delete = false; + /** + * Specifies Delete version access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.deleteVersion = false; + /** + * Specfies Tag access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.tag = false; + /** + * Specifies Move access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.move = false; + /** + * Specifies Execute access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.execute = false; + } /** - * Creates a new BlobClient object identical to the source but with the specified snapshot timestamp. - * Provide "" will remove the snapshot and return a Client to the base blob. + * Creates a {@link BlobSASPermissions} from the specified permissions string. This method will throw an + * Error if it encounters a character that does not correspond to a valid permission. * - * @param {string} snapshot The snapshot timestamp. - * @returns {BlobClient} A new BlobClient object identical to the source but with the specified snapshot timestamp - * @memberof BlobClient + * @static + * @param {string} permissions + * @returns {BlobSASPermissions} + * @memberof BlobSASPermissions */ - BlobClient.prototype.withSnapshot = function (snapshot) { - return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); + BlobSASPermissions.parse = function (permissions) { + var blobSASPermissions = new BlobSASPermissions(); + for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { + var char = permissions_1[_i]; + switch (char) { + case "r": + blobSASPermissions.read = true; + break; + case "a": + blobSASPermissions.add = true; + break; + case "c": + blobSASPermissions.create = true; + break; + case "w": + blobSASPermissions.write = true; + break; + case "d": + blobSASPermissions.delete = true; + break; + case "x": + blobSASPermissions.deleteVersion = true; + break; + case "t": + blobSASPermissions.tag = true; + break; + case "m": + blobSASPermissions.move = true; + break; + case "e": + blobSASPermissions.execute = true; + break; + default: + throw new RangeError("Invalid permission: " + char); + } + } + return blobSASPermissions; }; /** - * Creates a new BlobClient object pointing to a version of this blob. - * Provide "" will remove the versionId and return a Client to the base blob. + * Creates a {@link BlobSASPermissions} from a raw object which contains same keys as it + * and boolean values for them. * - * @param {string} versionId The versionId. - * @returns {BlobClient} A new BlobClient object pointing to the version of this blob. - * @memberof BlobClient + * @static + * @param {BlobSASPermissionsLike} permissionLike + * @returns {BlobSASPermissions} + * @memberof BlobSASPermissions */ - BlobClient.prototype.withVersion = function (versionId) { - return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.VERSIONID, versionId.length === 0 ? undefined : versionId), this.pipeline); + BlobSASPermissions.from = function (permissionLike) { + var blobSASPermissions = new BlobSASPermissions(); + if (permissionLike.read) { + blobSASPermissions.read = true; + } + if (permissionLike.add) { + blobSASPermissions.add = true; + } + if (permissionLike.create) { + blobSASPermissions.create = true; + } + if (permissionLike.write) { + blobSASPermissions.write = true; + } + if (permissionLike.delete) { + blobSASPermissions.delete = true; + } + if (permissionLike.deleteVersion) { + blobSASPermissions.deleteVersion = true; + } + if (permissionLike.tag) { + blobSASPermissions.tag = true; + } + if (permissionLike.move) { + blobSASPermissions.move = true; + } + if (permissionLike.execute) { + blobSASPermissions.execute = true; + } + return blobSASPermissions; }; /** - * Creates a AppendBlobClient object. + * Converts the given permissions to a string. Using this method will guarantee the permissions are in an + * order accepted by the service. * - * @returns {AppendBlobClient} - * @memberof BlobClient + * @returns {string} A string which represents the BlobSASPermissions + * @memberof BlobSASPermissions */ - BlobClient.prototype.getAppendBlobClient = function () { - return new AppendBlobClient(this.url, this.pipeline); + BlobSASPermissions.prototype.toString = function () { + var permissions = []; + if (this.read) { + permissions.push("r"); + } + if (this.add) { + permissions.push("a"); + } + if (this.create) { + permissions.push("c"); + } + if (this.write) { + permissions.push("w"); + } + if (this.delete) { + permissions.push("d"); + } + if (this.deleteVersion) { + permissions.push("x"); + } + if (this.tag) { + permissions.push("t"); + } + if (this.move) { + permissions.push("m"); + } + if (this.execute) { + permissions.push("e"); + } + return permissions.join(""); }; + return BlobSASPermissions; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a container. + * Setting a value to true means that any SAS which uses these permissions will grant permissions for that operation. + * Once all the values are set, this should be serialized with toString and set as the permissions field on a + * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but + * the order of the permissions is particular and this class guarantees correctness. + * + * @export + * @class ContainerSASPermissions + */ +var ContainerSASPermissions = /** @class */ (function () { + function ContainerSASPermissions() { + /** + * Specifies Read access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.read = false; + /** + * Specifies Add access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.add = false; + /** + * Specifies Create access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.create = false; + /** + * Specifies Write access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.write = false; + /** + * Specifies Delete access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.delete = false; + /** + * Specifies Delete version access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.deleteVersion = false; + /** + * Specifies List access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.list = false; + /** + * Specfies Tag access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.tag = false; + /** + * Specifies Move access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.move = false; + /** + * Specifies Execute access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.execute = false; + } /** - * Creates a BlockBlobClient object. + * Creates an {@link ContainerSASPermissions} from the specified permissions string. This method will throw an + * Error if it encounters a character that does not correspond to a valid permission. * - * @returns {BlockBlobClient} - * @memberof BlobClient + * @static + * @param {string} permissions + * @returns {ContainerSASPermissions} + * @memberof ContainerSASPermissions */ - BlobClient.prototype.getBlockBlobClient = function () { - return new BlockBlobClient(this.url, this.pipeline); + ContainerSASPermissions.parse = function (permissions) { + var containerSASPermissions = new ContainerSASPermissions(); + for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { + var char = permissions_1[_i]; + switch (char) { + case "r": + containerSASPermissions.read = true; + break; + case "a": + containerSASPermissions.add = true; + break; + case "c": + containerSASPermissions.create = true; + break; + case "w": + containerSASPermissions.write = true; + break; + case "d": + containerSASPermissions.delete = true; + break; + case "l": + containerSASPermissions.list = true; + break; + case "t": + containerSASPermissions.tag = true; + break; + case "x": + containerSASPermissions.deleteVersion = true; + break; + case "m": + containerSASPermissions.move = true; + break; + case "e": + containerSASPermissions.execute = true; + break; + default: + throw new RangeError("Invalid permission " + char); + } + } + return containerSASPermissions; }; /** - * Creates a PageBlobClient object. + * Creates a {@link ContainerSASPermissions} from a raw object which contains same keys as it + * and boolean values for them. * - * @returns {PageBlobClient} - * @memberof BlobClient + * @static + * @param {ContainerSASPermissionsLike} permissionLike + * @returns {ContainerSASPermissions} + * @memberof ContainerSASPermissions */ - BlobClient.prototype.getPageBlobClient = function () { - return new PageBlobClient(this.url, this.pipeline); + ContainerSASPermissions.from = function (permissionLike) { + var containerSASPermissions = new ContainerSASPermissions(); + if (permissionLike.read) { + containerSASPermissions.read = true; + } + if (permissionLike.add) { + containerSASPermissions.add = true; + } + if (permissionLike.create) { + containerSASPermissions.create = true; + } + if (permissionLike.write) { + containerSASPermissions.write = true; + } + if (permissionLike.delete) { + containerSASPermissions.delete = true; + } + if (permissionLike.list) { + containerSASPermissions.list = true; + } + if (permissionLike.deleteVersion) { + containerSASPermissions.deleteVersion = true; + } + if (permissionLike.tag) { + containerSASPermissions.tag = true; + } + if (permissionLike.move) { + containerSASPermissions.move = true; + } + if (permissionLike.execute) { + containerSASPermissions.execute = true; + } + return containerSASPermissions; }; /** - * Reads or downloads a blob from the system, including its metadata and properties. - * You can also call Get Blob to read a snapshot. - * - * * In Node.js, data returns in a Readable stream readableStreamBody - * * In browsers, data returns in a promise blobBody - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob - * - * @param {number} [offset] From which position of the blob to download, >= 0 - * @param {number} [count] How much data to be downloaded, > 0. Will download to the end when undefined - * @param {BlobDownloadOptions} [options] Optional options to Blob Download operation. - * @returns {Promise} - * @memberof BlobClient - * - * Example usage (Node.js): - * - * ```js - * // Download and convert a blob to a string - * const downloadBlockBlobResponse = await blobClient.download(); - * const downloaded = await streamToBuffer(downloadBlockBlobResponse.readableStreamBody); - * console.log("Downloaded blob content:", downloaded.toString()); - * - * async function streamToBuffer(readableStream) { - * return new Promise((resolve, reject) => { - * const chunks = []; - * readableStream.on("data", (data) => { - * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); - * }); - * readableStream.on("end", () => { - * resolve(Buffer.concat(chunks)); - * }); - * readableStream.on("error", reject); - * }); - * } - * ``` - * - * Example usage (browser): + * Converts the given permissions to a string. Using this method will guarantee the permissions are in an + * order accepted by the service. * - * ```js - * // Download and convert a blob to a string - * const downloadBlockBlobResponse = await blobClient.download(); - * const downloaded = await blobToString(await downloadBlockBlobResponse.blobBody); - * console.log( - * "Downloaded blob content", - * downloaded - * ); + * The order of the characters should be as specified here to ensure correctness. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * - * async function blobToString(blob: Blob): Promise { - * const fileReader = new FileReader(); - * return new Promise((resolve, reject) => { - * fileReader.onloadend = (ev: any) => { - * resolve(ev.target!.result); - * }; - * fileReader.onerror = reject; - * fileReader.readAsText(blob); - * }); - * } - * ``` + * @returns {string} + * @memberof ContainerSASPermissions */ - BlobClient.prototype.download = function (offset, count, options) { - var _a; - if (offset === void 0) { offset = 0; } - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, res_1, wrappedRes, e_1; - var _this = this; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - options.conditions = options.conditions || {}; - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - _b = createSpan("BlobClient-download", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.download({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - onDownloadProgress: coreHttp.isNode ? undefined : options.onProgress, - range: offset === 0 && !count ? undefined : rangeToString({ offset: offset, count: count }), - rangeGetContentMD5: options.rangeGetContentMD5, - rangeGetContentCRC64: options.rangeGetContentCrc64, - snapshot: options.snapshot, - cpkInfo: options.customerProvidedKey, - spanOptions: spanOptions - })]; - case 2: - res_1 = _c.sent(); - wrappedRes = tslib.__assign(tslib.__assign({}, res_1), { _response: res_1._response, objectReplicationDestinationPolicyId: res_1.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res_1.objectReplicationRules) }); - // We support retrying when download stream unexpected ends in Node.js runtime - // Following code shouldn't be bundled into browser build, however some - // bundlers may try to bundle following code and "FileReadResponse.ts". - // In this case, "FileDownloadResponse.browser.ts" will be used as a shim of "FileDownloadResponse.ts" - // The config is in package.json "browser" field - if (options.maxRetryRequests === undefined || options.maxRetryRequests < 0) { - // TODO: Default value or make it a required parameter? - options.maxRetryRequests = DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS; - } - if (res_1.contentLength === undefined) { - throw new RangeError("File download response doesn't contain valid content length header"); - } - if (!res_1.etag) { - throw new RangeError("File download response doesn't contain valid etag header"); - } - return [2 /*return*/, new BlobDownloadResponse(wrappedRes, function (start) { return tslib.__awaiter(_this, void 0, void 0, function () { - var updatedOptions; - var _a; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - updatedOptions = { - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ifMatch: options.conditions.ifMatch || res_1.etag, - ifModifiedSince: options.conditions.ifModifiedSince, - ifNoneMatch: options.conditions.ifNoneMatch, - ifUnmodifiedSince: options.conditions.ifUnmodifiedSince, - ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions - }, - range: rangeToString({ - count: offset + res_1.contentLength - start, - offset: start - }), - rangeGetContentMD5: options.rangeGetContentMD5, - rangeGetContentCRC64: options.rangeGetContentCrc64, - snapshot: options.snapshot, - cpkInfo: options.customerProvidedKey - }; - return [4 /*yield*/, this.blobContext.download(tslib.__assign({ abortSignal: options.abortSignal }, updatedOptions))]; - case 1: - // Debug purpose only - // console.log( - // `Read from internal stream, range: ${ - // updatedOptions.range - // }, options: ${JSON.stringify(updatedOptions)}` - // ); - return [2 /*return*/, (_b.sent()).readableStreamBody]; - } - }); - }); }, offset, res_1.contentLength, { - abortSignal: options.abortSignal, - maxRetryRequests: options.maxRetryRequests, - onProgress: options.onProgress - })]; - case 3: - e_1 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_1.message - }); - throw e_1; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + ContainerSASPermissions.prototype.toString = function () { + var permissions = []; + if (this.read) { + permissions.push("r"); + } + if (this.add) { + permissions.push("a"); + } + if (this.create) { + permissions.push("c"); + } + if (this.write) { + permissions.push("w"); + } + if (this.delete) { + permissions.push("d"); + } + if (this.deleteVersion) { + permissions.push("x"); + } + if (this.list) { + permissions.push("l"); + } + if (this.tag) { + permissions.push("t"); + } + if (this.move) { + permissions.push("m"); + } + if (this.execute) { + permissions.push("e"); + } + return permissions.join(""); }; + return ContainerSASPermissions; +}()); + +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * UserDelegationKeyCredential is only used for generation of user delegation SAS. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas + * + * @export + * @class UserDelegationKeyCredential + */ +var UserDelegationKeyCredential = /** @class */ (function () { /** - * Returns true if the Azure blob resource represented by this client exists; false otherwise. - * - * NOTE: use this function with care since an existing blob might be deleted by other clients or - * applications. Vice versa new blobs might be added by other clients or applications after this - * function completes. - * - * @param {BlobExistsOptions} [options] options to Exists operation. - * @returns {Promise} - * @memberof BlobClient + * Creates an instance of UserDelegationKeyCredential. + * @param {string} accountName + * @param {UserDelegationKey} userDelegationKey + * @memberof UserDelegationKeyCredential */ - BlobClient.prototype.exists = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_2; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobClient-exists", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.getProperties({ - abortSignal: options.abortSignal, - customerProvidedKey: options.customerProvidedKey, - conditions: options.conditions, - tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) - })]; - case 2: - _b.sent(); - return [2 /*return*/, true]; - case 3: - e_2 = _b.sent(); - if (e_2.statusCode === 404) { - span.setStatus({ - code: api.CanonicalCode.NOT_FOUND, - message: "Expected exception when checking blob existence" - }); - return [2 /*return*/, false]; - } - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_2.message - }); - throw e_2; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; + function UserDelegationKeyCredential(accountName, userDelegationKey) { + this.accountName = accountName; + this.userDelegationKey = userDelegationKey; + this.key = Buffer.from(userDelegationKey.value, "base64"); + } /** - * Returns all user-defined metadata, standard HTTP properties, and system properties - * for the blob. It does not return the content of the blob. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-properties - * - * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if - * they originally contained uppercase characters. This differs from the metadata keys returned by - * the methods of {@link ContainerClient} that list blobs using the `includeMetadata` option, which - * will retain their original casing. + * Generates a hash signature for an HTTP request or for a SAS. * - * @param {BlobGetPropertiesOptions} [options] Optional options to Get Properties operation. - * @returns {Promise} - * @memberof BlobClient + * @param {string} stringToSign + * @returns {string} + * @memberof UserDelegationKeyCredential */ - BlobClient.prototype.getProperties = function (options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, res, e_3; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-getProperties", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - options.conditions = options.conditions || {}; - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blobContext.getProperties({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - cpkInfo: options.customerProvidedKey, - spanOptions: spanOptions - })]; - case 2: - res = _c.sent(); - return [2 /*return*/, tslib.__assign(tslib.__assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) })]; - case 3: - e_3 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_3.message - }); - throw e_3; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + UserDelegationKeyCredential.prototype.computeHMACSHA256 = function (stringToSign) { + // console.log(`stringToSign: ${JSON.stringify(stringToSign)}`); + return crypto.createHmac("sha256", this.key) + .update(stringToSign, "utf8") + .digest("base64"); }; + return UserDelegationKeyCredential; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * Generate SasIPRange format string. For example: + * + * "8.8.8.8" or "1.1.1.1-255.255.255.255" + * + * @export + * @param {SasIPRange} ipRange + * @returns {string} + */ +function ipRangeToString(ipRange) { + return ipRange.end ? ipRange.start + "-" + ipRange.end : ipRange.start; +} + +// Copyright (c) Microsoft Corporation. All rights reserved. +(function (SASProtocol) { /** - * Marks the specified blob or snapshot for deletion. The blob is later deleted - * during garbage collection. Note that in order to delete a blob, you must delete - * all of its snapshots. You can delete both at the same time with the Delete - * Blob operation. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob - * - * @param {BlobDeleteOptions} [options] Optional options to Blob Delete operation. - * @returns {Promise} - * @memberof BlobClient + * Protocol that allows HTTPS only */ - BlobClient.prototype.delete = function (options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_4; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-delete", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.deleteMethod({ - abortSignal: options.abortSignal, - deleteSnapshots: options.deleteSnapshots, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_4 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_4.message - }); - throw e_4; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; + SASProtocol["Https"] = "https"; /** - * Marks the specified blob or snapshot for deletion if it exists. The blob is later deleted - * during garbage collection. Note that in order to delete a blob, you must delete - * all of its snapshots. You can delete both at the same time with the Delete - * Blob operation. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob - * - * @param {BlobDeleteOptions} [options] Optional options to Blob Delete operation. - * @returns {Promise} - * @memberof BlobClient + * Protocol that allows both HTTPS and HTTP */ - BlobClient.prototype.deleteIfExists = function (options) { - var _a, _b; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _c, span, spanOptions, res, e_5; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _c = createSpan("BlobClient-deleteIfExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; - _d.label = 1; - case 1: - _d.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: - res = _d.sent(); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable - })]; - case 3: - e_5 = _d.sent(); - if (((_a = e_5.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobNotFound") { - span.setStatus({ - code: api.CanonicalCode.NOT_FOUND, - message: "Expected exception when deleting a blob or snapshot only if it exists." - }); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_5.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_5.response })]; - } - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_5.message - }); - throw e_5; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - /** - * Restores the contents and metadata of soft deleted blob and any associated - * soft deleted snapshots. Undelete Blob is supported only on version 2017-07-29 - * or later. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/undelete-blob - * - * @param {BlobUndeleteOptions} [options] Optional options to Blob Undelete operation. - * @returns {Promise} - * @memberof BlobClient - */ - BlobClient.prototype.undelete = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_6; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobClient-undelete", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.undelete({ - abortSignal: options.abortSignal, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_6 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_6.message - }); - throw e_6; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; + SASProtocol["HttpsAndHttp"] = "https,http"; +})(exports.SASProtocol || (exports.SASProtocol = {})); +/** + * Represents the components that make up an Azure Storage SAS' query parameters. This type is not constructed directly + * by the user; it is only generated by the {@link AccountSASSignatureValues} and {@link BlobSASSignatureValues} + * types. Once generated, it can be encoded into a {@code String} and appended to a URL directly (though caution should + * be taken here in case there are existing query parameters, which might affect the appropriate means of appending + * these query parameters). + * + * NOTE: Instances of this class are immutable. + * + * @export + * @class SASQueryParameters + */ +var SASQueryParameters = /** @class */ (function () { + function SASQueryParameters(version, signature, permissionsOrOptions, services, resourceTypes, protocol, startsOn, expiresOn, ipRange, identifier, resource, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType, userDelegationKey, preauthorizedAgentObjectId, correlationId) { + this.version = version; + this.signature = signature; + if (permissionsOrOptions !== undefined && typeof permissionsOrOptions !== "string") { + // SASQueryParametersOptions + this.permissions = permissionsOrOptions.permissions; + this.services = permissionsOrOptions.services; + this.resourceTypes = permissionsOrOptions.resourceTypes; + this.protocol = permissionsOrOptions.protocol; + this.startsOn = permissionsOrOptions.startsOn; + this.expiresOn = permissionsOrOptions.expiresOn; + this.ipRangeInner = permissionsOrOptions.ipRange; + this.identifier = permissionsOrOptions.identifier; + this.resource = permissionsOrOptions.resource; + this.cacheControl = permissionsOrOptions.cacheControl; + this.contentDisposition = permissionsOrOptions.contentDisposition; + this.contentEncoding = permissionsOrOptions.contentEncoding; + this.contentLanguage = permissionsOrOptions.contentLanguage; + this.contentType = permissionsOrOptions.contentType; + if (permissionsOrOptions.userDelegationKey) { + this.signedOid = permissionsOrOptions.userDelegationKey.signedObjectId; + this.signedTenantId = permissionsOrOptions.userDelegationKey.signedTenantId; + this.signedStartsOn = permissionsOrOptions.userDelegationKey.signedStartsOn; + this.signedExpiresOn = permissionsOrOptions.userDelegationKey.signedExpiresOn; + this.signedService = permissionsOrOptions.userDelegationKey.signedService; + this.signedVersion = permissionsOrOptions.userDelegationKey.signedVersion; + this.preauthorizedAgentObjectId = permissionsOrOptions.preauthorizedAgentObjectId; + this.correlationId = permissionsOrOptions.correlationId; + } + } + else { + this.services = services; + this.resourceTypes = resourceTypes; + this.expiresOn = expiresOn; + this.permissions = permissionsOrOptions; + this.protocol = protocol; + this.startsOn = startsOn; + this.ipRangeInner = ipRange; + this.identifier = identifier; + this.resource = resource; + this.cacheControl = cacheControl; + this.contentDisposition = contentDisposition; + this.contentEncoding = contentEncoding; + this.contentLanguage = contentLanguage; + this.contentType = contentType; + if (userDelegationKey) { + this.signedOid = userDelegationKey.signedObjectId; + this.signedTenantId = userDelegationKey.signedTenantId; + this.signedStartsOn = userDelegationKey.signedStartsOn; + this.signedExpiresOn = userDelegationKey.signedExpiresOn; + this.signedService = userDelegationKey.signedService; + this.signedVersion = userDelegationKey.signedVersion; + this.preauthorizedAgentObjectId = preauthorizedAgentObjectId; + this.correlationId = correlationId; + } + } + } + Object.defineProperty(SASQueryParameters.prototype, "ipRange", { + /** + * Optional. IP range allowed for this SAS. + * + * @readonly + * @type {(SasIPRange | undefined)} + * @memberof SASQueryParameters + */ + get: function () { + if (this.ipRangeInner) { + return { + end: this.ipRangeInner.end, + start: this.ipRangeInner.start + }; + } + return undefined; + }, + enumerable: false, + configurable: true + }); /** - * Sets system properties on the blob. - * - * If no value provided, or no value provided for the specified blob HTTP headers, - * these blob HTTP headers without a value will be cleared. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties + * Encodes all SAS query parameters into a string that can be appended to a URL. * - * @param {BlobHTTPHeaders} [blobHTTPHeaders] If no value provided, or no value provided for - * the specified blob HTTP headers, these blob HTTP - * headers without a value will be cleared. - * @param {BlobSetHTTPHeadersOptions} [options] Optional options to Blob Set HTTP Headers operation. - * @returns {Promise} - * @memberof BlobClient + * @returns {string} + * @memberof SASQueryParameters */ - BlobClient.prototype.setHTTPHeaders = function (blobHTTPHeaders, options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_7; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-setHTTPHeaders", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blobContext.setHTTPHeaders({ - abortSignal: options.abortSignal, - blobHTTPHeaders: blobHTTPHeaders, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - cpkInfo: options.customerProvidedKey, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_7 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_7.message - }); - throw e_7; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + SASQueryParameters.prototype.toString = function () { + var params = [ + "sv", + "ss", + "srt", + "spr", + "st", + "se", + "sip", + "si", + "skoid", + "sktid", + "skt", + "ske", + "sks", + "skv", + "sr", + "sp", + "sig", + "rscc", + "rscd", + "rsce", + "rscl", + "rsct", + "saoid", + "scid" + ]; + var queries = []; + for (var _i = 0, params_1 = params; _i < params_1.length; _i++) { + var param = params_1[_i]; + switch (param) { + case "sv": + this.tryAppendQueryParameter(queries, param, this.version); + break; + case "ss": + this.tryAppendQueryParameter(queries, param, this.services); + break; + case "srt": + this.tryAppendQueryParameter(queries, param, this.resourceTypes); + break; + case "spr": + this.tryAppendQueryParameter(queries, param, this.protocol); + break; + case "st": + this.tryAppendQueryParameter(queries, param, this.startsOn ? truncatedISO8061Date(this.startsOn, false) : undefined); + break; + case "se": + this.tryAppendQueryParameter(queries, param, this.expiresOn ? truncatedISO8061Date(this.expiresOn, false) : undefined); + break; + case "sip": + this.tryAppendQueryParameter(queries, param, this.ipRange ? ipRangeToString(this.ipRange) : undefined); + break; + case "si": + this.tryAppendQueryParameter(queries, param, this.identifier); + break; + case "skoid": // Signed object ID + this.tryAppendQueryParameter(queries, param, this.signedOid); + break; + case "sktid": // Signed tenant ID + this.tryAppendQueryParameter(queries, param, this.signedTenantId); + break; + case "skt": // Signed key start time + this.tryAppendQueryParameter(queries, param, this.signedStartsOn ? truncatedISO8061Date(this.signedStartsOn, false) : undefined); + break; + case "ske": // Signed key expiry time + this.tryAppendQueryParameter(queries, param, this.signedExpiresOn ? truncatedISO8061Date(this.signedExpiresOn, false) : undefined); + break; + case "sks": // Signed key service + this.tryAppendQueryParameter(queries, param, this.signedService); + break; + case "skv": // Signed key version + this.tryAppendQueryParameter(queries, param, this.signedVersion); + break; + case "sr": + this.tryAppendQueryParameter(queries, param, this.resource); + break; + case "sp": + this.tryAppendQueryParameter(queries, param, this.permissions); + break; + case "sig": + this.tryAppendQueryParameter(queries, param, this.signature); + break; + case "rscc": + this.tryAppendQueryParameter(queries, param, this.cacheControl); + break; + case "rscd": + this.tryAppendQueryParameter(queries, param, this.contentDisposition); + break; + case "rsce": + this.tryAppendQueryParameter(queries, param, this.contentEncoding); + break; + case "rscl": + this.tryAppendQueryParameter(queries, param, this.contentLanguage); + break; + case "rsct": + this.tryAppendQueryParameter(queries, param, this.contentType); + break; + case "saoid": + this.tryAppendQueryParameter(queries, param, this.preauthorizedAgentObjectId); + break; + case "scid": + this.tryAppendQueryParameter(queries, param, this.correlationId); + break; + } + } + return queries.join("&"); }; /** - * Sets user-defined metadata for the specified blob as one or more name-value pairs. - * - * If no option provided, or no metadata defined in the parameter, the blob - * metadata will be removed. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-metadata + * A private helper method used to filter and append query key/value pairs into an array. * - * @param {Metadata} [metadata] Replace existing metadata with this value. - * If no value provided the existing metadata will be removed. - * @param {BlobSetMetadataOptions} [options] Optional options to Set Metadata operation. - * @returns {Promise} - * @memberof BlobClient + * @private + * @param {string[]} queries + * @param {string} key + * @param {string} [value] + * @returns {void} + * @memberof SASQueryParameters */ - BlobClient.prototype.setMetadata = function (metadata, options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_8; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-setMetadata", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blobContext.setMetadata({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - metadata: metadata, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_8 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_8.message - }); - throw e_8; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + SASQueryParameters.prototype.tryAppendQueryParameter = function (queries, key, value) { + if (!value) { + return; + } + key = encodeURIComponent(key); + value = encodeURIComponent(value); + if (key.length > 0 && value.length > 0) { + queries.push(key + "=" + value); + } }; - /** - * Sets tags on the underlying blob. - * A blob can have up to 10 tags. Tag keys must be between 1 and 128 characters. Tag values must be between 0 and 256 characters. - * Valid tag key and value characters include lower and upper case letters, digits (0-9), - * space (' '), plus ('+'), minus ('-'), period ('.'), foward slash ('/'), colon (':'), equals ('='), and underscore ('_'). - * - * @param {Tags} tags - * @param {BlobSetTagsOptions} [options={}] - * @returns {Promise} - * @memberof BlobClient - */ - BlobClient.prototype.setTags = function (tags, options) { + return SASQueryParameters; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +function generateBlobSASQueryParameters(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { + var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + var sharedKeyCredential = sharedKeyCredentialOrUserDelegationKey instanceof StorageSharedKeyCredential + ? sharedKeyCredentialOrUserDelegationKey + : undefined; + var userDelegationKeyCredential; + if (sharedKeyCredential === undefined && accountName !== undefined) { + userDelegationKeyCredential = new UserDelegationKeyCredential(accountName, sharedKeyCredentialOrUserDelegationKey); + } + if (sharedKeyCredential === undefined && userDelegationKeyCredential === undefined) { + throw TypeError("Invalid sharedKeyCredential, userDelegationKey or accountName."); + } + // Version 2019-12-12 adds support for the blob tags permission. + // Version 2018-11-09 adds support for the signed resource and signed blob snapshot time fields. + // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas#constructing-the-signature-string + if (version >= "2018-11-09") { + if (sharedKeyCredential !== undefined) { + return generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential); + } + else { + // Version 2020-02-10 delegation SAS signature construction includes preauthorizedAgentObjectId, agentObjectId, correlationId. + if (version >= "2020-02-10") { + return generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userDelegationKeyCredential); + } + else { + return generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential); + } + } + } + if (version >= "2015-04-05") { + if (sharedKeyCredential !== undefined) { + return generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential); + } + else { + throw new RangeError("'version' must be >= '2018-11-09' when generating user delegation SAS using user delegation key."); + } + } + throw new RangeError("'version' must be >= '2015-04-05'."); +} +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * IMPLEMENTATION FOR API VERSION FROM 2015-04-05 AND BEFORE 2018-11-09. + * + * Creates an instance of SASQueryParameters. + * + * Only accepts required settings needed to create a SAS. For optional settings please + * set corresponding properties directly, such as permissions, startsOn and identifier. + * + * WARNING: When identifier is not provided, permissions and expiresOn are required. + * You MUST assign value to identifier or expiresOn & permissions manually if you initial with + * this constructor. + * + * @param {BlobSASSignatureValues} blobSASSignatureValues + * @param {StorageSharedKeyCredential} sharedKeyCredential + * @returns {SASQueryParameters} + */ +function generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential) { + blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); + if (!blobSASSignatureValues.identifier && + !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); + } + var resource = "c"; + if (blobSASSignatureValues.blobName) { + resource = "b"; + } + // Calling parse and toString guarantees the proper ordering and throws on invalid characters. + var verifiedPermissions; + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + // Signature is generated on the un-url-encoded values. + var stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn + ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) + : "", + blobSASSignatureValues.expiresOn + ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) + : "", + getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.identifier, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + blobSASSignatureValues.version, + blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", + blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", + blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", + blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", + blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" + ].join("\n"); + var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); +} +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. + * + * Creates an instance of SASQueryParameters. + * + * Only accepts required settings needed to create a SAS. For optional settings please + * set corresponding properties directly, such as permissions, startsOn and identifier. + * + * WARNING: When identifier is not provided, permissions and expiresOn are required. + * You MUST assign value to identifier or expiresOn & permissions manually if you initial with + * this constructor. + * + * @param {BlobSASSignatureValues} blobSASSignatureValues + * @param {StorageSharedKeyCredential} sharedKeyCredential + * @returns {SASQueryParameters} + */ +function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential) { + blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); + if (!blobSASSignatureValues.identifier && + !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); + } + var resource = "c"; + var timestamp = blobSASSignatureValues.snapshotTime; + if (blobSASSignatureValues.blobName) { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } + else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } + } + // Calling parse and toString guarantees the proper ordering and throws on invalid characters. + var verifiedPermissions; + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + // Signature is generated on the un-url-encoded values. + var stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn + ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) + : "", + blobSASSignatureValues.expiresOn + ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) + : "", + getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.identifier, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + blobSASSignatureValues.version, + resource, + timestamp, + blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", + blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", + blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", + blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", + blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" + ].join("\n"); + var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); +} +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. + * + * Creates an instance of SASQueryParameters. + * + * Only accepts required settings needed to create a SAS. For optional settings please + * set corresponding properties directly, such as permissions, startsOn. + * + * WARNING: identifier will be ignored, permissions and expiresOn are required. + * + * @param {BlobSASSignatureValues} blobSASSignatureValues + * @param {UserDelegationKeyCredential} userDelegationKeyCredential + * @returns {SASQueryParameters} + */ +function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential) { + blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); + // Stored access policies are not supported for a user delegation SAS. + if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); + } + var resource = "c"; + var timestamp = blobSASSignatureValues.snapshotTime; + if (blobSASSignatureValues.blobName) { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } + else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } + } + // Calling parse and toString guarantees the proper ordering and throws on invalid characters. + var verifiedPermissions; + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + // Signature is generated on the un-url-encoded values. + var stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn + ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) + : "", + blobSASSignatureValues.expiresOn + ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) + : "", + getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + userDelegationKeyCredential.userDelegationKey.signedObjectId, + userDelegationKeyCredential.userDelegationKey.signedTenantId, + userDelegationKeyCredential.userDelegationKey.signedStartsOn + ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) + : "", + userDelegationKeyCredential.userDelegationKey.signedExpiresOn + ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) + : "", + userDelegationKeyCredential.userDelegationKey.signedService, + userDelegationKeyCredential.userDelegationKey.signedVersion, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + blobSASSignatureValues.version, + resource, + timestamp, + blobSASSignatureValues.cacheControl, + blobSASSignatureValues.contentDisposition, + blobSASSignatureValues.contentEncoding, + blobSASSignatureValues.contentLanguage, + blobSASSignatureValues.contentType + ].join("\n"); + var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey); +} +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * IMPLEMENTATION FOR API VERSION FROM 2020-02-10. + * + * Creates an instance of SASQueryParameters. + * + * Only accepts required settings needed to create a SAS. For optional settings please + * set corresponding properties directly, such as permissions, startsOn. + * + * WARNING: identifier will be ignored, permissions and expiresOn are required. + * + * @param {BlobSASSignatureValues} blobSASSignatureValues + * @param {UserDelegationKeyCredential} userDelegationKeyCredential + * @returns {SASQueryParameters} + */ +function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userDelegationKeyCredential) { + blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); + // Stored access policies are not supported for a user delegation SAS. + if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); + } + var resource = "c"; + var timestamp = blobSASSignatureValues.snapshotTime; + if (blobSASSignatureValues.blobName) { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } + else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } + } + // Calling parse and toString guarantees the proper ordering and throws on invalid characters. + var verifiedPermissions; + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + // Signature is generated on the un-url-encoded values. + var stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn + ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) + : "", + blobSASSignatureValues.expiresOn + ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) + : "", + getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + userDelegationKeyCredential.userDelegationKey.signedObjectId, + userDelegationKeyCredential.userDelegationKey.signedTenantId, + userDelegationKeyCredential.userDelegationKey.signedStartsOn + ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) + : "", + userDelegationKeyCredential.userDelegationKey.signedExpiresOn + ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) + : "", + userDelegationKeyCredential.userDelegationKey.signedService, + userDelegationKeyCredential.userDelegationKey.signedVersion, + blobSASSignatureValues.preauthorizedAgentObjectId, + undefined, + blobSASSignatureValues.correlationId, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + blobSASSignatureValues.version, + resource, + timestamp, + blobSASSignatureValues.cacheControl, + blobSASSignatureValues.contentDisposition, + blobSASSignatureValues.contentEncoding, + blobSASSignatureValues.contentLanguage, + blobSASSignatureValues.contentType + ].join("\n"); + var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId); +} +function getCanonicalName(accountName, containerName, blobName) { + // Container: "/blob/account/containerName" + // Blob: "/blob/account/containerName/blobName" + var elements = ["/blob/" + accountName + "/" + containerName]; + if (blobName) { + elements.push("/" + blobName); + } + return elements.join(""); +} +function SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues) { + var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + if (blobSASSignatureValues.snapshotTime && version < "2018-11-09") { + throw RangeError("'version' must be >= '2018-11-09' when providing 'snapshotTime'."); + } + if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.snapshotTime) { + throw RangeError("Must provide 'blobName' when providing 'snapshotTime'."); + } + if (blobSASSignatureValues.versionId && version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when providing 'versionId'."); + } + if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.versionId) { + throw RangeError("Must provide 'blobName' when providing 'versionId'."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.deleteVersion && + version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when providing 'x' permission."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.tag && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when providing 't' permission."); + } + if (version < "2020-02-10" && + blobSASSignatureValues.permissions && + (blobSASSignatureValues.permissions.move || blobSASSignatureValues.permissions.execute)) { + throw RangeError("'version' must be >= '2020-02-10' when providing the 'm' or 'e' permission."); + } + if (version < "2020-02-10" && + (blobSASSignatureValues.preauthorizedAgentObjectId || blobSASSignatureValues.correlationId)) { + throw RangeError("'version' must be >= '2020-02-10' when providing 'preauthorizedAgentObjectId' or 'correlationId'."); + } + blobSASSignatureValues.version = version; + return blobSASSignatureValues; +} + +/** + * A BlobClient represents a URL to an Azure Storage blob; the blob may be a block blob, + * append blob, or page blob. + * + * @export + * @class BlobClient + */ +var BlobClient = /** @class */ (function (_super) { + tslib.__extends(BlobClient, _super); + function BlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_9; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-setTags", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.setTags({ - abortSignal: options.abortSignal, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - spanOptions: spanOptions, - tags: toBlobTags(tags) - })]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_9 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_9.message - }); - throw e_9; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + var _this = this; + options = options || {}; + var pipeline; + var url; + if (credentialOrPipelineOrContainerName instanceof Pipeline) { + // (url: string, pipeline: Pipeline) + url = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } + else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || + credentialOrPipelineOrContainerName instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + url = urlOrConnectionString; + options = blobNameOrOptions; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } + else if (!credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName !== "string") { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + // The second parameter is undefined. Use anonymous credential. + url = urlOrConnectionString; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else if (credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName === "string" && + blobNameOrOptions && + typeof blobNameOrOptions === "string") { + // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) + var containerName = credentialOrPipelineOrContainerName; + var blobName = blobNameOrOptions; + var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + { + var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); + options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); + pipeline = newPipeline(sharedKeyCredential, options); } - }); - }); - }; + } + else if (extractedCreds.kind === "SASConnString") { + url = + appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + + "?" + + extractedCreds.accountSas; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } + else { + throw new Error("Expecting non-empty strings for containerName and blobName parameters"); + } + _this = _super.call(this, url, pipeline) || this; + (_a = _this.getBlobAndContainerNamesFromUrl(), _this._name = _a.blobName, _this._containerName = _a.containerName); + _this.blobContext = new Blob$1(_this.storageClientContext); + _this._snapshot = getURLParameter(_this.url, URLConstants.Parameters.SNAPSHOT); + _this._versionId = getURLParameter(_this.url, URLConstants.Parameters.VERSIONID); + return _this; + } + Object.defineProperty(BlobClient.prototype, "name", { + /** + * The name of the blob. + */ + get: function () { + return this._name; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobClient.prototype, "containerName", { + /** + * The name of the storage container the blob is associated with. + */ + get: function () { + return this._containerName; + }, + enumerable: false, + configurable: true + }); /** - * Gets the tags associated with the underlying blob. + * Creates a new BlobClient object identical to the source but with the specified snapshot timestamp. + * Provide "" will remove the snapshot and return a Client to the base blob. * - * @param {BlobGetTagsOptions} [options={}] - * @returns {Promise} + * @param {string} snapshot The snapshot timestamp. + * @returns {BlobClient} A new BlobClient object identical to the source but with the specified snapshot timestamp * @memberof BlobClient */ - BlobClient.prototype.getTags = function (options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, response, wrappedResponse, e_10; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-getTags", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.getTags({ - abortSignal: options.abortSignal, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - spanOptions: spanOptions - })]; - case 2: - response = _c.sent(); - wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, tags: toTags({ blobTagSet: response.blobTagSet }) || {} }); - return [2 /*return*/, wrappedResponse]; - case 3: - e_10 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_10.message - }); - throw e_10; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + BlobClient.prototype.withSnapshot = function (snapshot) { + return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); }; /** - * Get a {@link BlobLeaseClient} that manages leases on the blob. + * Creates a new BlobClient object pointing to a version of this blob. + * Provide "" will remove the versionId and return a Client to the base blob. * - * @param {string} [proposeLeaseId] Initial proposed lease Id. - * @returns {BlobLeaseClient} A new BlobLeaseClient object for managing leases on the blob. + * @param {string} versionId The versionId. + * @returns {BlobClient} A new BlobClient object pointing to the version of this blob. * @memberof BlobClient */ - BlobClient.prototype.getBlobLeaseClient = function (proposeLeaseId) { - return new BlobLeaseClient(this, proposeLeaseId); + BlobClient.prototype.withVersion = function (versionId) { + return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.VERSIONID, versionId.length === 0 ? undefined : versionId), this.pipeline); }; /** - * Creates a read-only snapshot of a blob. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/snapshot-blob + * Creates a AppendBlobClient object. * - * @param {BlobCreateSnapshotOptions} [options] Optional options to the Blob Create Snapshot operation. - * @returns {Promise} + * @returns {AppendBlobClient} * @memberof BlobClient */ - BlobClient.prototype.createSnapshot = function (options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_11; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-createSnapshot", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blobContext.createSnapshot({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - metadata: options.metadata, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_11 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_11.message - }); - throw e_11; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - /** - * Asynchronously copies a blob to a destination within the storage account. - * This method returns a long running operation poller that allows you to wait - * indefinitely until the copy is completed. - * You can also cancel a copy before it is completed by calling `cancelOperation` on the poller. - * Note that the onProgress callback will not be invoked if the operation completes in the first - * request, and attempting to cancel a completed copy will result in an error being thrown. - * - * In version 2012-02-12 and later, the source for a Copy Blob operation can be - * a committed blob in any Azure storage account. - * Beginning with version 2015-02-21, the source for a Copy Blob operation can be - * an Azure file in any Azure storage account. - * Only storage accounts created on or after June 7th, 2012 allow the Copy Blob - * operation to copy from another storage account. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob - * - * Example using automatic polling: - * - * ```js - * const copyPoller = await blobClient.beginCopyFromURL('url'); - * const result = await copyPoller.pollUntilDone(); - * ``` - * - * Example using manual polling: - * - * ```js - * const copyPoller = await blobClient.beginCopyFromURL('url'); - * while (!poller.isDone()) { - * await poller.poll(); - * } - * const result = copyPoller.getResult(); - * ``` - * - * Example using progress updates: - * - * ```js - * const copyPoller = await blobClient.beginCopyFromURL('url', { - * onProgress(state) { - * console.log(`Progress: ${state.copyProgress}`); - * } - * }); - * const result = await copyPoller.pollUntilDone(); - * ``` - * - * Example using a changing polling interval (default 15 seconds): - * - * ```js - * const copyPoller = await blobClient.beginCopyFromURL('url', { - * intervalInMs: 1000 // poll blob every 1 second for copy progress - * }); - * const result = await copyPoller.pollUntilDone(); - * ``` - * - * Example using copy cancellation: - * - * ```js - * const copyPoller = await blobClient.beginCopyFromURL('url'); - * // cancel operation after starting it. - * try { - * await copyPoller.cancelOperation(); - * // calls to get the result now throw PollerCancelledError - * await copyPoller.getResult(); - * } catch (err) { - * if (err.name === 'PollerCancelledError') { - * console.log('The copy was cancelled.'); - * } - * } - * ``` - * - * @param {string} copySource url to the source Azure Blob/File. - * @param {BlobBeginCopyFromURLOptions} [options] Optional options to the Blob Start Copy From URL operation. - */ - BlobClient.prototype.beginCopyFromURL = function (copySource, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var client, poller; - var _this = this; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - client = { - abortCopyFromURL: function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return _this.abortCopyFromURL.apply(_this, args); - }, - getProperties: function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return _this.getProperties.apply(_this, args); - }, - startCopyFromURL: function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return _this.startCopyFromURL.apply(_this, args); - } - }; - poller = new BlobBeginCopyFromUrlPoller({ - blobClient: client, - copySource: copySource, - intervalInMs: options.intervalInMs, - onProgress: options.onProgress, - resumeFrom: options.resumeFrom, - startCopyFromURLOptions: options - }); - // Trigger the startCopyFromURL call by calling poll. - // Any errors from this method should be surfaced to the user. - return [4 /*yield*/, poller.poll()]; - case 1: - // Trigger the startCopyFromURL call by calling poll. - // Any errors from this method should be surfaced to the user. - _a.sent(); - return [2 /*return*/, poller]; - } - }); - }); + BlobClient.prototype.getAppendBlobClient = function () { + return new AppendBlobClient(this.url, this.pipeline); }; /** - * Aborts a pending asynchronous Copy Blob operation, and leaves a destination blob with zero - * length and full metadata. Version 2012-02-12 and newer. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/abort-copy-blob + * Creates a BlockBlobClient object. * - * @param {string} copyId Id of the Copy From URL operation. - * @param {BlobAbortCopyFromURLOptions} [options] Optional options to the Blob Abort Copy From URL operation. - * @returns {Promise} + * @returns {BlockBlobClient} * @memberof BlobClient */ - BlobClient.prototype.abortCopyFromURL = function (copyId, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_12; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobClient-abortCopyFromURL", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.abortCopyFromURL(copyId, { - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_12 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_12.message - }); - throw e_12; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + BlobClient.prototype.getBlockBlobClient = function () { + return new BlockBlobClient(this.url, this.pipeline); }; /** - * The synchronous Copy From URL operation copies a blob or an internet resource to a new blob. It will not - * return a response until the copy is complete. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob-from-url + * Creates a PageBlobClient object. * - * @param {string} copySource The source URL to copy from, Shared Access Signature(SAS) maybe needed for authentication - * @param {BlobSyncCopyFromURLOptions} [options={}] - * @returns {Promise} + * @returns {PageBlobClient} * @memberof BlobClient */ - BlobClient.prototype.syncCopyFromURL = function (copySource, options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_13; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-syncCopyFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - options.conditions = options.conditions || {}; - options.sourceConditions = options.sourceConditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.copyFromURL(copySource, { - abortSignal: options.abortSignal, - metadata: options.metadata, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions.ifMatch, - sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince - }, - sourceContentMD5: options.sourceContentMD5, - blobTagsString: toBlobTagsString(options.tags), - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_13 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_13.message - }); - throw e_13; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + BlobClient.prototype.getPageBlobClient = function () { + return new PageBlobClient(this.url, this.pipeline); }; /** - * Sets the tier on a blob. The operation is allowed on a page blob in a premium - * storage account and on a block blob in a blob storage account (locally redundant - * storage only). A premium page blob's tier determines the allowed size, IOPS, - * and bandwidth of the blob. A block blob's tier determines Hot/Cool/Archive - * storage type. This operation does not update the blob's ETag. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-tier + * Reads or downloads a blob from the system, including its metadata and properties. + * You can also call Get Blob to read a snapshot. * - * @param {BlockBlobTier | PremiumPageBlobTier | string} tier The tier to be set on the blob. Valid values are Hot, Cool, or Archive. - * @param {BlobSetTierOptions} [options] Optional options to the Blob Set Tier operation. - * @returns {Promise} + * * In Node.js, data returns in a Readable stream readableStreamBody + * * In browsers, data returns in a promise blobBody + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob + * + * @param {number} [offset] From which position of the blob to download, >= 0 + * @param {number} [count] How much data to be downloaded, > 0. Will download to the end when undefined + * @param {BlobDownloadOptions} [options] Optional options to Blob Download operation. + * @returns {Promise} * @memberof BlobClient + * + * Example usage (Node.js): + * + * ```js + * // Download and convert a blob to a string + * const downloadBlockBlobResponse = await blobClient.download(); + * const downloaded = await streamToBuffer(downloadBlockBlobResponse.readableStreamBody); + * console.log("Downloaded blob content:", downloaded.toString()); + * + * async function streamToBuffer(readableStream) { + * return new Promise((resolve, reject) => { + * const chunks = []; + * readableStream.on("data", (data) => { + * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); + * }); + * readableStream.on("end", () => { + * resolve(Buffer.concat(chunks)); + * }); + * readableStream.on("error", reject); + * }); + * } + * ``` + * + * Example usage (browser): + * + * ```js + * // Download and convert a blob to a string + * const downloadBlockBlobResponse = await blobClient.download(); + * const downloaded = await blobToString(await downloadBlockBlobResponse.blobBody); + * console.log( + * "Downloaded blob content", + * downloaded + * ); + * + * async function blobToString(blob: Blob): Promise { + * const fileReader = new FileReader(); + * return new Promise((resolve, reject) => { + * fileReader.onloadend = (ev: any) => { + * resolve(ev.target!.result); + * }; + * fileReader.onerror = reject; + * fileReader.readAsText(blob); + * }); + * } + * ``` */ - BlobClient.prototype.setAccessTier = function (tier, options) { + BlobClient.prototype.download = function (offset, count, options) { var _a; + if (offset === void 0) { offset = 0; } if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_14; + var _b, span, spanOptions, res_1, wrappedRes, e_1; + var _this = this; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: - _b = createSpan("BlobClient-setAccessTier", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + options.conditions = options.conditions || {}; + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + _b = createSpan("BlobClient-download", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.setTier(toAccessTier(tier), { + return [4 /*yield*/, this.blobContext.download({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - rehydratePriority: options.rehydratePriority, + onDownloadProgress: coreHttp.isNode ? undefined : options.onProgress, + range: offset === 0 && !count ? undefined : rangeToString({ offset: offset, count: count }), + rangeGetContentMD5: options.rangeGetContentMD5, + rangeGetContentCRC64: options.rangeGetContentCrc64, + snapshot: options.snapshot, + cpkInfo: options.customerProvidedKey, spanOptions: spanOptions })]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_14 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_14.message - }); - throw e_14; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - BlobClient.prototype.downloadToBuffer = function (param1, param2, param3, param4) { - if (param4 === void 0) { param4 = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var buffer, offset, count, options, _a, span, spanOptions, response, transferProgress_1, batch, _loop_1, off, e_15; - var _this = this; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - offset = 0; - count = 0; - options = param4; - if (param1 instanceof Buffer) { - buffer = param1; - offset = param2 || 0; - count = typeof param3 === "number" ? param3 : 0; - } - else { - offset = typeof param1 === "number" ? param1 : 0; - count = typeof param2 === "number" ? param2 : 0; - options = param3 || {}; - } - _a = createSpan("BlobClient-downloadToBuffer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 5, 6, 7]); - if (!options.blockSize) { - options.blockSize = 0; - } - if (options.blockSize < 0) { - throw new RangeError("blockSize option must be >= 0"); - } - if (options.blockSize === 0) { - options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; - } - if (offset < 0) { - throw new RangeError("offset option must be >= 0"); - } - if (count && count <= 0) { - throw new RangeError("count option must be > 0"); - } - if (!options.conditions) { - options.conditions = {}; - } - if (!!count) return [3 /*break*/, 3]; - return [4 /*yield*/, this.getProperties(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: - response = _b.sent(); - count = response.contentLength - offset; - if (count < 0) { - throw new RangeError("offset " + offset + " shouldn't be larger than blob size " + response.contentLength); + res_1 = _c.sent(); + wrappedRes = tslib.__assign(tslib.__assign({}, res_1), { _response: res_1._response, objectReplicationDestinationPolicyId: res_1.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res_1.objectReplicationRules) }); + // We support retrying when download stream unexpected ends in Node.js runtime + // Following code shouldn't be bundled into browser build, however some + // bundlers may try to bundle following code and "FileReadResponse.ts". + // In this case, "FileDownloadResponse.browser.ts" will be used as a shim of "FileDownloadResponse.ts" + // The config is in package.json "browser" field + if (options.maxRetryRequests === undefined || options.maxRetryRequests < 0) { + // TODO: Default value or make it a required parameter? + options.maxRetryRequests = DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS; } - _b.label = 3; - case 3: - // Allocate the buffer of size = count if the buffer is not provided - if (!buffer) { - try { - buffer = Buffer.alloc(count); - } - catch (error) { - throw new Error("Unable to allocate the buffer of size: " + count + "(in bytes). Please try passing your own buffer to the \"downloadToBuffer\" method or try using other methods like \"download\" or \"downloadToFile\".\t " + error.message); - } + if (res_1.contentLength === undefined) { + throw new RangeError("File download response doesn't contain valid content length header"); } - if (buffer.length < count) { - throw new RangeError("The buffer's size should be equal to or larger than the request count of bytes: " + count); + if (!res_1.etag) { + throw new RangeError("File download response doesn't contain valid etag header"); } - transferProgress_1 = 0; - batch = new Batch(options.concurrency); - _loop_1 = function (off) { - batch.addOperation(function () { return tslib.__awaiter(_this, void 0, void 0, function () { - var chunkEnd, response, stream; - return tslib.__generator(this, function (_a) { - switch (_a.label) { + return [2 /*return*/, new BlobDownloadResponse(wrappedRes, function (start) { return tslib.__awaiter(_this, void 0, void 0, function () { + var updatedOptions; + var _a; + return tslib.__generator(this, function (_b) { + switch (_b.label) { case 0: - chunkEnd = offset + count; - if (off + options.blockSize < chunkEnd) { - chunkEnd = off + options.blockSize; - } - return [4 /*yield*/, this.download(off, chunkEnd - off, { - abortSignal: options.abortSignal, - conditions: options.conditions, - maxRetryRequests: options.maxRetryRequestsPerBlock, - customerProvidedKey: options.customerProvidedKey, - tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) - })]; - case 1: - response = _a.sent(); - stream = response.readableStreamBody; - return [4 /*yield*/, streamToBuffer(stream, buffer, off - offset, chunkEnd - offset)]; - case 2: - _a.sent(); - // Update progress after block is downloaded, in case of block trying - // Could provide finer grained progress updating inside HTTP requests, - // only if convenience layer download try is enabled - transferProgress_1 += chunkEnd - off; - if (options.onProgress) { - options.onProgress({ loadedBytes: transferProgress_1 }); - } - return [2 /*return*/]; + updatedOptions = { + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ifMatch: options.conditions.ifMatch || res_1.etag, + ifModifiedSince: options.conditions.ifModifiedSince, + ifNoneMatch: options.conditions.ifNoneMatch, + ifUnmodifiedSince: options.conditions.ifUnmodifiedSince, + ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions + }, + range: rangeToString({ + count: offset + res_1.contentLength - start, + offset: start + }), + rangeGetContentMD5: options.rangeGetContentMD5, + rangeGetContentCRC64: options.rangeGetContentCrc64, + snapshot: options.snapshot, + cpkInfo: options.customerProvidedKey + }; + return [4 /*yield*/, this.blobContext.download(tslib.__assign({ abortSignal: options.abortSignal }, updatedOptions))]; + case 1: + // Debug purpose only + // console.log( + // `Read from internal stream, range: ${ + // updatedOptions.range + // }, options: ${JSON.stringify(updatedOptions)}` + // ); + return [2 /*return*/, (_b.sent()).readableStreamBody]; } }); - }); }); - }; - for (off = offset; off < offset + count; off = off + options.blockSize) { - _loop_1(off); - } - return [4 /*yield*/, batch.do()]; - case 4: - _b.sent(); - return [2 /*return*/, buffer]; - case 5: - e_15 = _b.sent(); + }); }, offset, res_1.contentLength, { + maxRetryRequests: options.maxRetryRequests, + onProgress: options.onProgress + })]; + case 3: + e_1 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_15.message + message: e_1.message }); - throw e_15; - case 6: + throw e_1; + case 4: span.end(); return [7 /*endfinally*/]; - case 7: return [2 /*return*/]; + case 5: return [2 /*return*/]; } }); }); }; /** - * ONLY AVAILABLE IN NODE.JS RUNTIME. + * Returns true if the Azure blob resource represented by this client exists; false otherwise. * - * Downloads an Azure Blob to a local file. - * Fails if the the given file path already exits. - * Offset and count are optional, pass 0 and undefined respectively to download the entire blob. + * NOTE: use this function with care since an existing blob might be deleted by other clients or + * applications. Vice versa new blobs might be added by other clients or applications after this + * function completes. * - * @param {string} filePath - * @param {number} [offset] From which position of the block blob to download. - * @param {number} [count] How much data to be downloaded. Will download to the end when passing undefined. - * @param {BlobDownloadOptions} [options] Options to Blob download options. - * @returns {Promise} The response data for blob download operation, - * but with readableStreamBody set to undefined since its - * content is already read and written into a local file - * at the specified path. + * @param {BlobExistsOptions} [options] options to Exists operation. + * @returns {Promise} * @memberof BlobClient */ - BlobClient.prototype.downloadToFile = function (filePath, offset, count, options) { - if (offset === void 0) { offset = 0; } + BlobClient.prototype.exists = function (options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, response, e_16; + var _a, span, spanOptions, e_2; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("BlobClient-downloadToFile", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("BlobClient-exists", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: - _b.trys.push([1, 5, 6, 7]); - return [4 /*yield*/, this.download(offset, count, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + _b.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.getProperties({ + abortSignal: options.abortSignal, + customerProvidedKey: options.customerProvidedKey, + conditions: options.conditions, + tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) + })]; case 2: - response = _b.sent(); - if (!response.readableStreamBody) return [3 /*break*/, 4]; - return [4 /*yield*/, readStreamToLocalFile(response.readableStreamBody, filePath)]; - case 3: _b.sent(); - _b.label = 4; - case 4: - // The stream is no longer accessible so setting it to undefined. - response.blobDownloadStream = undefined; - return [2 /*return*/, response]; - case 5: - e_16 = _b.sent(); + return [2 /*return*/, true]; + case 3: + e_2 = _b.sent(); + if (e_2.statusCode === 404) { + span.setStatus({ + code: api.CanonicalCode.NOT_FOUND, + message: "Expected exception when checking blob existence" + }); + return [2 /*return*/, false]; + } span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_16.message + message: e_2.message }); - throw e_16; - case 6: + throw e_2; + case 4: span.end(); return [7 /*endfinally*/]; - case 7: return [2 /*return*/]; + case 5: return [2 /*return*/]; } }); }); }; - BlobClient.prototype.getBlobAndContainerNamesFromUrl = function () { - var containerName; - var blobName; - try { - // URL may look like the following - // "https://myaccount.blob.core.windows.net/mycontainer/blob?sasString"; - // "https://myaccount.blob.core.windows.net/mycontainer/blob"; - // "https://myaccount.blob.core.windows.net/mycontainer/blob/a.txt?sasString"; - // "https://myaccount.blob.core.windows.net/mycontainer/blob/a.txt"; - // IPv4/IPv6 address hosts, Endpoints - `http://127.0.0.1:10000/devstoreaccount1/containername/blob` - // http://localhost:10001/devstoreaccount1/containername/blob - var parsedUrl = coreHttp.URLBuilder.parse(this.url); - if (parsedUrl.getHost().split(".")[1] === "blob") { - // "https://myaccount.blob.core.windows.net/containername/blob". - // .getPath() -> /containername/blob - var pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); - containerName = pathComponents[1]; - blobName = pathComponents[3]; - } - else if (isIpEndpointStyle(parsedUrl)) { - // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/containername/blob - // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/containername/blob - // .getPath() -> /devstoreaccount1/containername/blob - var pathComponents = parsedUrl.getPath().match("/([^/]*)/([^/]*)(/(.*))?"); - containerName = pathComponents[2]; - blobName = pathComponents[4]; - } - else { - // "https://customdomain.com/containername/blob". - // .getPath() -> /containername/blob - var pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); - containerName = pathComponents[1]; - blobName = pathComponents[3]; - } - // decode the encoded blobName, containerName - to get all the special characters that might be present in them - containerName = decodeURIComponent(containerName); - blobName = decodeURIComponent(blobName); - // Azure Storage Server will replace "\" with "/" in the blob names - // doing the same in the SDK side so that the user doesn't have to replace "\" instances in the blobName - blobName = blobName.replace(/\\/g, "/"); - if (!blobName) { - throw new Error("Provided blobName is invalid."); - } - else if (!containerName) { - throw new Error("Provided containerName is invalid."); - } - return { blobName: blobName, containerName: containerName }; - } - catch (error) { - throw new Error("Unable to extract blobName and containerName with provided information."); - } - }; /** - * Asynchronously copies a blob to a destination within the storage account. - * In version 2012-02-12 and later, the source for a Copy Blob operation can be - * a committed blob in any Azure storage account. - * Beginning with version 2015-02-21, the source for a Copy Blob operation can be - * an Azure file in any Azure storage account. - * Only storage accounts created on or after June 7th, 2012 allow the Copy Blob - * operation to copy from another storage account. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob + * Returns all user-defined metadata, standard HTTP properties, and system properties + * for the blob. It does not return the content of the blob. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-properties * - * @param {string} copySource url to the source Azure Blob/File. - * @param {BlobStartCopyFromURLOptions} [options] Optional options to the Blob Start Copy From URL operation. - * @returns {Promise} + * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if + * they originally contained uppercase characters. This differs from the metadata keys returned by + * the methods of {@link ContainerClient} that list blobs using the `includeMetadata` option, which + * will retain their original casing. + * + * @param {BlobGetPropertiesOptions} [options] Optional options to Get Properties operation. + * @returns {Promise} * @memberof BlobClient */ - BlobClient.prototype.startCopyFromURL = function (copySource, options) { + BlobClient.prototype.getProperties = function (options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_17; + var _b, span, spanOptions, res, e_3; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: - _b = createSpan("BlobClient-startCopyFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - options.conditions = options.conditions || {}; - options.sourceConditions = options.sourceConditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.startCopyFromURL(copySource, { - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - metadata: options.metadata, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions.ifMatch, - sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince, - sourceIfTags: options.sourceConditions.tagConditions - }, - rehydratePriority: options.rehydratePriority, - tier: toAccessTier(options.tier), - blobTagsString: toBlobTagsString(options.tags), - sealBlob: options.sealBlob, + _b = createSpan("BlobClient-getProperties", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blobContext.getProperties({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, spanOptions: spanOptions })]; - case 2: return [2 /*return*/, _c.sent()]; + case 2: + res = _c.sent(); + return [2 /*return*/, tslib.__assign(tslib.__assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) })]; case 3: - e_17 = _c.sent(); + e_3 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_17.message + message: e_3.message }); - throw e_17; + throw e_3; case 4: span.end(); return [7 /*endfinally*/]; @@ -29258,138 +29599,45 @@ var BlobClient = /** @class */ (function (_super) { }); }); }; - return BlobClient; -}(StorageClient)); -/** - * AppendBlobClient defines a set of operations applicable to append blobs. - * - * @export - * @class AppendBlobClient - * @extends {BlobClient} - */ -var AppendBlobClient = /** @class */ (function (_super) { - tslib.__extends(AppendBlobClient, _super); - function AppendBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { - var _this = this; - // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. - // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); - var pipeline; - var url; - options = options || {}; - if (credentialOrPipelineOrContainerName instanceof Pipeline) { - // (url: string, pipeline: Pipeline) - url = urlOrConnectionString; - pipeline = credentialOrPipelineOrContainerName; - } - else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || - credentialOrPipelineOrContainerName instanceof AnonymousCredential || - coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { - // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) url = urlOrConnectionString; - url = urlOrConnectionString; - options = blobNameOrOptions; - pipeline = newPipeline(credentialOrPipelineOrContainerName, options); - } - else if (!credentialOrPipelineOrContainerName && - typeof credentialOrPipelineOrContainerName !== "string") { - // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) - url = urlOrConnectionString; - // The second parameter is undefined. Use anonymous credential. - pipeline = newPipeline(new AnonymousCredential(), options); - } - else if (credentialOrPipelineOrContainerName && - typeof credentialOrPipelineOrContainerName === "string" && - blobNameOrOptions && - typeof blobNameOrOptions === "string") { - // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) - var containerName = credentialOrPipelineOrContainerName; - var blobName = blobNameOrOptions; - var extractedCreds = extractConnectionStringParts(urlOrConnectionString); - if (extractedCreds.kind === "AccountConnString") { - { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); - options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); - pipeline = newPipeline(sharedKeyCredential, options); - } - } - else if (extractedCreds.kind === "SASConnString") { - url = - appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + - "?" + - extractedCreds.accountSas; - pipeline = newPipeline(new AnonymousCredential(), options); - } - else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); - } - } - else { - throw new Error("Expecting non-empty strings for containerName and blobName parameters"); - } - _this = _super.call(this, url, pipeline) || this; - _this.appendBlobContext = new AppendBlob(_this.storageClientContext); - return _this; - } - /** - * Creates a new AppendBlobClient object identical to the source but with the - * specified snapshot timestamp. - * Provide "" will remove the snapshot and return a Client to the base blob. - * - * @param {string} snapshot The snapshot timestamp. - * @returns {AppendBlobClient} A new AppendBlobClient object identical to the source but with the specified snapshot timestamp. - * @memberof AppendBlobClient - */ - AppendBlobClient.prototype.withSnapshot = function (snapshot) { - return new AppendBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); - }; /** - * Creates a 0-length append blob. Call AppendBlock to append data to an append blob. - * @see https://docs.microsoft.com/rest/api/storageservices/put-blob - * - * @param {AppendBlobCreateOptions} [options] Options to the Append Block Create operation. - * @returns {Promise} - * @memberof AppendBlobClient - * - * Example usage: + * Marks the specified blob or snapshot for deletion. The blob is later deleted + * during garbage collection. Note that in order to delete a blob, you must delete + * all of its snapshots. You can delete both at the same time with the Delete + * Blob operation. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob * - * ```js - * const appendBlobClient = containerClient.getAppendBlobClient(""); - * await appendBlobClient.create(); - * ``` + * @param {BlobDeleteOptions} [options] Optional options to Blob Delete operation. + * @returns {Promise} + * @memberof BlobClient */ - AppendBlobClient.prototype.create = function (options) { + BlobClient.prototype.delete = function (options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_18; + var _b, span, spanOptions, e_4; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: - _b = createSpan("AppendBlobClient-create", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _b = createSpan("BlobClient-delete", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; options.conditions = options.conditions || {}; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.appendBlobContext.create(0, { + return [4 /*yield*/, this.blobContext.deleteMethod({ abortSignal: options.abortSignal, - blobHTTPHeaders: options.blobHTTPHeaders, + deleteSnapshots: options.deleteSnapshots, leaseAccessConditions: options.conditions, - metadata: options.metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - blobTagsString: toBlobTagsString(options.tags), spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_18 = _c.sent(); + e_4 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_18.message + message: e_4.message }); - throw e_18; + throw e_4; case 4: span.end(); return [7 /*endfinally*/]; @@ -29399,46 +29647,47 @@ var AppendBlobClient = /** @class */ (function (_super) { }); }; /** - * Creates a 0-length append blob. Call AppendBlock to append data to an append blob. - * If the blob with the same name already exists, the content of the existing blob will remain unchanged. - * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * Marks the specified blob or snapshot for deletion if it exists. The blob is later deleted + * during garbage collection. Note that in order to delete a blob, you must delete + * all of its snapshots. You can delete both at the same time with the Delete + * Blob operation. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob * - * @param {AppendBlobCreateIfNotExistsOptions} [options] - * @returns {Promise} - * @memberof AppendBlobClient + * @param {BlobDeleteOptions} [options] Optional options to Blob Delete operation. + * @returns {Promise} + * @memberof BlobClient */ - AppendBlobClient.prototype.createIfNotExists = function (options) { + BlobClient.prototype.deleteIfExists = function (options) { var _a, _b; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _c, span, spanOptions, conditions, res, e_19; + var _c, span, spanOptions, res, e_5; return tslib.__generator(this, function (_d) { switch (_d.label) { case 0: - _c = createSpan("AppendBlobClient-createIfNotExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; - conditions = { ifNoneMatch: ETagAny }; + _c = createSpan("BlobClient-deleteIfExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; _d.label = 1; case 1: _d.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.create(tslib.__assign(tslib.__assign({}, options), { conditions: conditions, tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + return [4 /*yield*/, this.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: res = _d.sent(); return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable })]; case 3: - e_19 = _d.sent(); - if (((_a = e_19.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { + e_5 = _d.sent(); + if (((_a = e_5.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobNotFound") { span.setStatus({ - code: api.CanonicalCode.ALREADY_EXISTS, - message: "Expected exception when creating a blob only if it does not already exist." + code: api.CanonicalCode.NOT_FOUND, + message: "Expected exception when deleting a blob or snapshot only if it exists." }); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_19.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_19.response })]; + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_5.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_5.response })]; } span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_19.message + message: e_5.message }); - throw e_19; + throw e_5; case 4: span.end(); return [7 /*endfinally*/]; @@ -29448,40 +29697,90 @@ var AppendBlobClient = /** @class */ (function (_super) { }); }; /** - * Seals the append blob, making it read only. + * Restores the contents and metadata of soft deleted blob and any associated + * soft deleted snapshots. Undelete Blob is supported only on version 2017-07-29 + * or later. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/undelete-blob * - * @param {AppendBlobSealOptions} [options={}] - * @returns {Promise} - * @memberof AppendBlobClient + * @param {BlobUndeleteOptions} [options] Optional options to Blob Undelete operation. + * @returns {Promise} + * @memberof BlobClient */ - AppendBlobClient.prototype.seal = function (options) { + BlobClient.prototype.undelete = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_6; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobClient-undelete", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.blobContext.undelete({ + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_6 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_6.message + }); + throw e_6; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Sets system properties on the blob. + * + * If no value provided, or no value provided for the specified blob HTTP headers, + * these blob HTTP headers without a value will be cleared. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties + * + * @param {BlobHTTPHeaders} [blobHTTPHeaders] If no value provided, or no value provided for + * the specified blob HTTP headers, these blob HTTP + * headers without a value will be cleared. + * @param {BlobSetHTTPHeadersOptions} [options] Optional options to Blob Set HTTP Headers operation. + * @returns {Promise} + * @memberof BlobClient + */ + BlobClient.prototype.setHTTPHeaders = function (blobHTTPHeaders, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_20; + var _b, span, spanOptions, e_7; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: - _b = createSpan("AppendBlobClient-seal", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _b = createSpan("BlobClient-setHTTPHeaders", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; options.conditions = options.conditions || {}; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.appendBlobContext.seal({ + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blobContext.setHTTPHeaders({ abortSignal: options.abortSignal, - appendPositionAccessConditions: options.conditions, + blobHTTPHeaders: blobHTTPHeaders, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_20 = _c.sent(); + e_7 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_20.message + message: e_7.message }); - throw e_20; + throw e_7; case 4: span.end(); return [7 /*endfinally*/]; @@ -29491,64 +29790,49 @@ var AppendBlobClient = /** @class */ (function (_super) { }); }; /** - * Commits a new block of data to the end of the existing append blob. - * @see https://docs.microsoft.com/rest/api/storageservices/append-block - * - * @param {HttpRequestBody} body Data to be appended. - * @param {number} contentLength Length of the body in bytes. - * @param {AppendBlobAppendBlockOptions} [options] Options to the Append Block operation. - * @returns {Promise} - * @memberof AppendBlobClient - * - * Example usage: - * - * ```js - * const content = "Hello World!"; + * Sets user-defined metadata for the specified blob as one or more name-value pairs. * - * // Create a new append blob and append data to the blob. - * const newAppendBlobClient = containerClient.getAppendBlobClient(""); - * await newAppendBlobClient.create(); - * await newAppendBlobClient.appendBlock(content, content.length); + * If no option provided, or no metadata defined in the parameter, the blob + * metadata will be removed. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-metadata * - * // Append data to an existing append blob. - * const existingAppendBlobClient = containerClient.getAppendBlobClient(""); - * await existingAppendBlobClient.appendBlock(content, content.length); - * ``` + * @param {Metadata} [metadata] Replace existing metadata with this value. + * If no value provided the existing metadata will be removed. + * @param {BlobSetMetadataOptions} [options] Optional options to Set Metadata operation. + * @returns {Promise} + * @memberof BlobClient */ - AppendBlobClient.prototype.appendBlock = function (body, contentLength, options) { + BlobClient.prototype.setMetadata = function (metadata, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_21; + var _b, span, spanOptions, e_8; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: - _b = createSpan("AppendBlobClient-appendBlock", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _b = createSpan("BlobClient-setMetadata", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; options.conditions = options.conditions || {}; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.appendBlobContext.appendBlock(body, contentLength, { + return [4 /*yield*/, this.blobContext.setMetadata({ abortSignal: options.abortSignal, - appendPositionAccessConditions: options.conditions, leaseAccessConditions: options.conditions, + metadata: metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - onUploadProgress: options.onProgress, - transactionalContentMD5: options.transactionalContentMD5, - transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_21 = _c.sent(); + e_8 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_21.message + message: e_8.message }); - throw e_21; + throw e_8; case 4: span.end(); return [7 /*endfinally*/]; @@ -29558,62 +29842,43 @@ var AppendBlobClient = /** @class */ (function (_super) { }); }; /** - * The Append Block operation commits a new block of data to the end of an existing append blob - * where the contents are read from a source url. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/append-block-from-url + * Sets tags on the underlying blob. + * A blob can have up to 10 tags. Tag keys must be between 1 and 128 characters. Tag values must be between 0 and 256 characters. + * Valid tag key and value characters include lower and upper case letters, digits (0-9), + * space (' '), plus ('+'), minus ('-'), period ('.'), foward slash ('/'), colon (':'), equals ('='), and underscore ('_'). * - * @param {string} sourceURL - * The url to the blob that will be the source of the copy. A source blob in the same storage account can - * be authenticated via Shared Key. However, if the source is a blob in another account, the source blob - * must either be public or must be authenticated via a shared access signature. If the source blob is - * public, no authentication is required to perform the operation. - * @param {number} sourceOffset Offset in source to be appended - * @param {number} count Number of bytes to be appended as a block - * @param {AppendBlobAppendBlockFromURLOptions} [options={}] - * @returns {Promise} - * @memberof AppendBlobClient + * @param {Tags} tags + * @param {BlobSetTagsOptions} [options={}] + * @returns {Promise} + * @memberof BlobClient */ - AppendBlobClient.prototype.appendBlockFromURL = function (sourceURL, sourceOffset, count, options) { + BlobClient.prototype.setTags = function (tags, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_22; + var _b, span, spanOptions, e_9; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: - _b = createSpan("AppendBlobClient-appendBlockFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - options.conditions = options.conditions || {}; - options.sourceConditions = options.sourceConditions || {}; + _b = createSpan("BlobClient-setTags", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.appendBlobContext.appendBlockFromUrl(sourceURL, 0, { + return [4 /*yield*/, this.blobContext.setTags({ abortSignal: options.abortSignal, - sourceRange: rangeToString({ offset: sourceOffset, count: count }), - sourceContentMD5: options.sourceContentMD5, - sourceContentCrc64: options.sourceContentCrc64, leaseAccessConditions: options.conditions, - appendPositionAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions.ifMatch, - sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince - }, - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - spanOptions: spanOptions + spanOptions: spanOptions, + tags: toBlobTags(tags) })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_22 = _c.sent(); + e_9 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_22.message + message: e_9.message }); - throw e_22; + throw e_9; case 4: span.end(); return [7 /*endfinally*/]; @@ -29622,161 +29887,42 @@ var AppendBlobClient = /** @class */ (function (_super) { }); }); }; - return AppendBlobClient; -}(BlobClient)); -/** - * BlockBlobClient defines a set of operations applicable to block blobs. - * - * @export - * @class BlockBlobClient - * @extends {BlobClient} - */ -var BlockBlobClient = /** @class */ (function (_super) { - tslib.__extends(BlockBlobClient, _super); - function BlockBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { - var _this = this; - // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. - // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); - var pipeline; - var url; - options = options || {}; - if (credentialOrPipelineOrContainerName instanceof Pipeline) { - // (url: string, pipeline: Pipeline) - url = urlOrConnectionString; - pipeline = credentialOrPipelineOrContainerName; - } - else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || - credentialOrPipelineOrContainerName instanceof AnonymousCredential || - coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { - // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) - url = urlOrConnectionString; - options = blobNameOrOptions; - pipeline = newPipeline(credentialOrPipelineOrContainerName, options); - } - else if (!credentialOrPipelineOrContainerName && - typeof credentialOrPipelineOrContainerName !== "string") { - // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) - // The second parameter is undefined. Use anonymous credential. - url = urlOrConnectionString; - pipeline = newPipeline(new AnonymousCredential(), options); - } - else if (credentialOrPipelineOrContainerName && - typeof credentialOrPipelineOrContainerName === "string" && - blobNameOrOptions && - typeof blobNameOrOptions === "string") { - // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) - var containerName = credentialOrPipelineOrContainerName; - var blobName = blobNameOrOptions; - var extractedCreds = extractConnectionStringParts(urlOrConnectionString); - if (extractedCreds.kind === "AccountConnString") { - { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); - options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); - pipeline = newPipeline(sharedKeyCredential, options); - } - } - else if (extractedCreds.kind === "SASConnString") { - url = - appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + - "?" + - extractedCreds.accountSas; - pipeline = newPipeline(new AnonymousCredential(), options); - } - else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); - } - } - else { - throw new Error("Expecting non-empty strings for containerName and blobName parameters"); - } - _this = _super.call(this, url, pipeline) || this; - _this.blockBlobContext = new BlockBlob(_this.storageClientContext); - _this._blobContext = new Blob$1(_this.storageClientContext); - return _this; - } - /** - * Creates a new BlockBlobClient object identical to the source but with the - * specified snapshot timestamp. - * Provide "" will remove the snapshot and return a URL to the base blob. - * - * @param {string} snapshot The snapshot timestamp. - * @returns {BlockBlobClient} A new BlockBlobClient object identical to the source but with the specified snapshot timestamp. - * @memberof BlockBlobClient - */ - BlockBlobClient.prototype.withSnapshot = function (snapshot) { - return new BlockBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); - }; /** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * Quick query for a JSON or CSV formatted blob. - * - * Example usage (Node.js): - * - * ```js - * // Query and convert a blob to a string - * const queryBlockBlobResponse = await blockBlobClient.query("select * from BlobStorage"); - * const downloaded = (await streamToBuffer(queryBlockBlobResponse.readableStreamBody)).toString(); - * console.log("Query blob content:", downloaded); - * - * async function streamToBuffer(readableStream) { - * return new Promise((resolve, reject) => { - * const chunks = []; - * readableStream.on("data", (data) => { - * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); - * }); - * readableStream.on("end", () => { - * resolve(Buffer.concat(chunks)); - * }); - * readableStream.on("error", reject); - * }); - * } - * ``` + * Gets the tags associated with the underlying blob. * - * @param {string} query - * @param {BlockBlobQueryOptions} [options={}] - * @returns {Promise} - * @memberof BlockBlobClient + * @param {BlobGetTagsOptions} [options={}] + * @returns {Promise} + * @memberof BlobClient */ - BlockBlobClient.prototype.query = function (query, options) { + BlobClient.prototype.getTags = function (options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, response, e_23; + var _b, span, spanOptions, response, wrappedResponse, e_10; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - _b = createSpan("BlockBlobClient-query", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _b = createSpan("BlobClient-getTags", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this._blobContext.query({ + return [4 /*yield*/, this.blobContext.getTags({ abortSignal: options.abortSignal, - queryRequest: { - expression: query, - inputSerialization: toQuerySerialization(options.inputTextConfiguration), - outputSerialization: toQuerySerialization(options.outputTextConfiguration) - }, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), spanOptions: spanOptions })]; case 2: response = _c.sent(); - return [2 /*return*/, new BlobQueryResponse(response, { - abortSignal: options.abortSignal, - onProgress: options.onProgress, - onError: options.onError - })]; + wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, tags: toTags({ blobTagSet: response.blobTagSet }) || {} }); + return [2 /*return*/, wrappedResponse]; case 3: - e_23 = _c.sent(); + e_10 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_23.message + message: e_10.message }); - throw e_23; + throw e_10; case 4: span.end(); return [7 /*endfinally*/]; @@ -29786,68 +29932,54 @@ var BlockBlobClient = /** @class */ (function (_super) { }); }; /** - * Creates a new block blob, or updates the content of an existing block blob. - * Updating an existing block blob overwrites any existing metadata on the blob. - * Partial updates are not supported; the content of the existing blob is - * overwritten with the new content. To perform a partial update of a block blob's, - * use {@link stageBlock} and {@link commitBlockList}. - * - * This is a non-parallel uploading method, please use {@link uploadFile}, - * {@link uploadStream} or {@link uploadBrowserData} for better performance - * with concurrency uploading. - * - * @see https://docs.microsoft.com/rest/api/storageservices/put-blob - * - * @param {HttpRequestBody} body Blob, string, ArrayBuffer, ArrayBufferView or a function - * which returns a new Readable stream whose offset is from data source beginning. - * @param {number} contentLength Length of body in bytes. Use Buffer.byteLength() to calculate body length for a - * string including non non-Base64/Hex-encoded characters. - * @param {BlockBlobUploadOptions} [options] Options to the Block Blob Upload operation. - * @returns {Promise} Response data for the Block Blob Upload operation. - * @memberof BlockBlobClient - * - * Example usage: + * Get a {@link BlobLeaseClient} that manages leases on the blob. + * + * @param {string} [proposeLeaseId] Initial proposed lease Id. + * @returns {BlobLeaseClient} A new BlobLeaseClient object for managing leases on the blob. + * @memberof BlobClient + */ + BlobClient.prototype.getBlobLeaseClient = function (proposeLeaseId) { + return new BlobLeaseClient(this, proposeLeaseId); + }; + /** + * Creates a read-only snapshot of a blob. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/snapshot-blob * - * ```js - * const content = "Hello world!"; - * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); - * ``` + * @param {BlobCreateSnapshotOptions} [options] Optional options to the Blob Create Snapshot operation. + * @returns {Promise} + * @memberof BlobClient */ - BlockBlobClient.prototype.upload = function (body, contentLength, options) { + BlobClient.prototype.createSnapshot = function (options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_24; + var _b, span, spanOptions, e_11; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: + _b = createSpan("BlobClient-createSnapshot", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; options.conditions = options.conditions || {}; - _b = createSpan("BlockBlobClient-upload", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blockBlobContext.upload(body, contentLength, { + return [4 /*yield*/, this.blobContext.createSnapshot({ abortSignal: options.abortSignal, - blobHTTPHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - onUploadProgress: options.onProgress, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, - tier: toAccessTier(options.tier), - blobTagsString: toBlobTagsString(options.tags), spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_24 = _c.sent(); + e_11 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_24.message + message: e_11.message }); - throw e_24; + throw e_11; case 4: span.end(); return [7 /*endfinally*/]; @@ -29857,108 +29989,162 @@ var BlockBlobClient = /** @class */ (function (_super) { }); }; /** - * Uploads the specified block to the block blob's "staging area" to be later - * committed by a call to commitBlockList. - * @see https://docs.microsoft.com/rest/api/storageservices/put-block + * Asynchronously copies a blob to a destination within the storage account. + * This method returns a long running operation poller that allows you to wait + * indefinitely until the copy is completed. + * You can also cancel a copy before it is completed by calling `cancelOperation` on the poller. + * Note that the onProgress callback will not be invoked if the operation completes in the first + * request, and attempting to cancel a completed copy will result in an error being thrown. * - * @param {string} blockId A 64-byte value that is base64-encoded - * @param {HttpRequestBody} body Data to upload to the staging area. - * @param {number} contentLength Number of bytes to upload. - * @param {BlockBlobStageBlockOptions} [options] Options to the Block Blob Stage Block operation. - * @returns {Promise} Response data for the Block Blob Stage Block operation. - * @memberof BlockBlobClient + * In version 2012-02-12 and later, the source for a Copy Blob operation can be + * a committed blob in any Azure storage account. + * Beginning with version 2015-02-21, the source for a Copy Blob operation can be + * an Azure file in any Azure storage account. + * Only storage accounts created on or after June 7th, 2012 allow the Copy Blob + * operation to copy from another storage account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob + * + * Example using automatic polling: + * + * ```js + * const copyPoller = await blobClient.beginCopyFromURL('url'); + * const result = await copyPoller.pollUntilDone(); + * ``` + * + * Example using manual polling: + * + * ```js + * const copyPoller = await blobClient.beginCopyFromURL('url'); + * while (!poller.isDone()) { + * await poller.poll(); + * } + * const result = copyPoller.getResult(); + * ``` + * + * Example using progress updates: + * + * ```js + * const copyPoller = await blobClient.beginCopyFromURL('url', { + * onProgress(state) { + * console.log(`Progress: ${state.copyProgress}`); + * } + * }); + * const result = await copyPoller.pollUntilDone(); + * ``` + * + * Example using a changing polling interval (default 15 seconds): + * + * ```js + * const copyPoller = await blobClient.beginCopyFromURL('url', { + * intervalInMs: 1000 // poll blob every 1 second for copy progress + * }); + * const result = await copyPoller.pollUntilDone(); + * ``` + * + * Example using copy cancellation: + * + * ```js + * const copyPoller = await blobClient.beginCopyFromURL('url'); + * // cancel operation after starting it. + * try { + * await copyPoller.cancelOperation(); + * // calls to get the result now throw PollerCancelledError + * await copyPoller.getResult(); + * } catch (err) { + * if (err.name === 'PollerCancelledError') { + * console.log('The copy was cancelled.'); + * } + * } + * ``` + * + * @param {string} copySource url to the source Azure Blob/File. + * @param {BlobBeginCopyFromURLOptions} [options] Optional options to the Blob Start Copy From URL operation. */ - BlockBlobClient.prototype.stageBlock = function (blockId, body, contentLength, options) { + BlobClient.prototype.beginCopyFromURL = function (copySource, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_25; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var client, poller; + var _this = this; + return tslib.__generator(this, function (_a) { + switch (_a.label) { case 0: - _a = createSpan("BlockBlobClient-stageBlock", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blockBlobContext.stageBlock(blockId, contentLength, body, { - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - onUploadProgress: options.onProgress, - transactionalContentMD5: options.transactionalContentMD5, - transactionalContentCrc64: options.transactionalContentCrc64, - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_25 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_25.message + client = { + abortCopyFromURL: function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return _this.abortCopyFromURL.apply(_this, args); + }, + getProperties: function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return _this.getProperties.apply(_this, args); + }, + startCopyFromURL: function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return _this.startCopyFromURL.apply(_this, args); + } + }; + poller = new BlobBeginCopyFromUrlPoller({ + blobClient: client, + copySource: copySource, + intervalInMs: options.intervalInMs, + onProgress: options.onProgress, + resumeFrom: options.resumeFrom, + startCopyFromURLOptions: options }); - throw e_25; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + // Trigger the startCopyFromURL call by calling poll. + // Any errors from this method should be surfaced to the user. + return [4 /*yield*/, poller.poll()]; + case 1: + // Trigger the startCopyFromURL call by calling poll. + // Any errors from this method should be surfaced to the user. + _a.sent(); + return [2 /*return*/, poller]; } }); }); }; /** - * The Stage Block From URL operation creates a new block to be committed as part - * of a blob where the contents are read from a URL. - * This API is available starting in version 2018-03-28. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-from-url + * Aborts a pending asynchronous Copy Blob operation, and leaves a destination blob with zero + * length and full metadata. Version 2012-02-12 and newer. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/abort-copy-blob * - * @param {string} blockId A 64-byte value that is base64-encoded - * @param {string} sourceURL Specifies the URL of the blob. The value - * may be a URL of up to 2 KB in length that specifies a blob. - * The value should be URL-encoded as it would appear - * in a request URI. The source blob must either be public - * or must be authenticated via a shared access signature. - * If the source blob is public, no authentication is required - * to perform the operation. Here are some examples of source object URLs: - * - https://myaccount.blob.core.windows.net/mycontainer/myblob - * - https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= - * @param {number} [offset] From which position of the blob to download, >= 0 - * @param {number} [count] How much data to be downloaded, > 0. Will download to the end when undefined - * @param {BlockBlobStageBlockFromURLOptions} [options={}] Options to the Block Blob Stage Block From URL operation. - * @returns {Promise} Response data for the Block Blob Stage Block From URL operation. - * @memberof BlockBlobClient + * @param {string} copyId Id of the Copy From URL operation. + * @param {BlobAbortCopyFromURLOptions} [options] Optional options to the Blob Abort Copy From URL operation. + * @returns {Promise} + * @memberof BlobClient */ - BlockBlobClient.prototype.stageBlockFromURL = function (blockId, sourceURL, offset, count, options) { - if (offset === void 0) { offset = 0; } + BlobClient.prototype.abortCopyFromURL = function (copyId, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_26; + var _a, span, spanOptions, e_12; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("BlockBlobClient-stageBlockFromURL", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("BlobClient-abortCopyFromURL", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blockBlobContext.stageBlockFromURL(blockId, 0, sourceURL, { + return [4 /*yield*/, this.blobContext.abortCopyFromURL(copyId, { abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, - sourceContentMD5: options.sourceContentMD5, - sourceContentCrc64: options.sourceContentCrc64, - sourceRange: offset === 0 && !count ? undefined : rangeToString({ offset: offset, count: count }), - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _b.sent()]; case 3: - e_26 = _b.sent(); + e_12 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_26.message + message: e_12.message }); - throw e_26; + throw e_12; case 4: span.end(); return [7 /*endfinally*/]; @@ -29968,52 +30154,52 @@ var BlockBlobClient = /** @class */ (function (_super) { }); }; /** - * Writes a blob by specifying the list of block IDs that make up the blob. - * In order to be written as part of a blob, a block must have been successfully written - * to the server in a prior {@link stageBlock} operation. You can call {@link commitBlockList} to - * update a blob by uploading only those blocks that have changed, then committing the new and existing - * blocks together. Any blocks not specified in the block list and permanently deleted. - * @see https://docs.microsoft.com/rest/api/storageservices/put-block-list + * The synchronous Copy From URL operation copies a blob or an internet resource to a new blob. It will not + * return a response until the copy is complete. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob-from-url * - * @param {string[]} blocks Array of 64-byte value that is base64-encoded - * @param {BlockBlobCommitBlockListOptions} [options] Options to the Block Blob Commit Block List operation. - * @returns {Promise} Response data for the Block Blob Commit Block List operation. - * @memberof BlockBlobClient + * @param {string} copySource The source URL to copy from, Shared Access Signature(SAS) maybe needed for authentication + * @param {BlobSyncCopyFromURLOptions} [options={}] + * @returns {Promise} + * @memberof BlobClient */ - BlockBlobClient.prototype.commitBlockList = function (blocks, options) { + BlobClient.prototype.syncCopyFromURL = function (copySource, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_27; + var _b, span, spanOptions, e_13; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: + _b = createSpan("BlobClient-syncCopyFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; options.conditions = options.conditions || {}; - _b = createSpan("BlockBlobClient-commitBlockList", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + options.sourceConditions = options.sourceConditions || {}; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blockBlobContext.commitBlockList({ latest: blocks }, { + return [4 /*yield*/, this.blobContext.copyFromURL(copySource, { abortSignal: options.abortSignal, - blobHTTPHeaders: options.blobHTTPHeaders, - leaseAccessConditions: options.conditions, metadata: options.metadata, + leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - tier: toAccessTier(options.tier), + sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince + }, + sourceContentMD5: options.sourceContentMD5, blobTagsString: toBlobTagsString(options.tags), spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_27 = _c.sent(); + e_13 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_27.message + message: e_13.message }); - throw e_27; + throw e_13; case 4: span.end(); return [7 /*endfinally*/]; @@ -30023,50 +30209,45 @@ var BlockBlobClient = /** @class */ (function (_super) { }); }; /** - * Returns the list of blocks that have been uploaded as part of a block blob - * using the specified block list filter. - * @see https://docs.microsoft.com/rest/api/storageservices/get-block-list + * Sets the tier on a blob. The operation is allowed on a page blob in a premium + * storage account and on a block blob in a blob storage account (locally redundant + * storage only). A premium page blob's tier determines the allowed size, IOPS, + * and bandwidth of the blob. A block blob's tier determines Hot/Cool/Archive + * storage type. This operation does not update the blob's ETag. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-tier * - * @param {BlockListType} listType Specifies whether to return the list of committed blocks, - * the list of uncommitted blocks, or both lists together. - * @param {BlockBlobGetBlockListOptions} [options] Options to the Block Blob Get Block List operation. - * @returns {Promise} Response data for the Block Blob Get Block List operation. - * @memberof BlockBlobClient + * @param {BlockBlobTier | PremiumPageBlobTier | string} tier The tier to be set on the blob. Valid values are Hot, Cool, or Archive. + * @param {BlobSetTierOptions} [options] Optional options to the Blob Set Tier operation. + * @returns {Promise} + * @memberof BlobClient */ - BlockBlobClient.prototype.getBlockList = function (listType, options) { + BlobClient.prototype.setAccessTier = function (tier, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, res, e_28; + var _b, span, spanOptions, e_14; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: - _b = createSpan("BlockBlobClient-getBlockList", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _b = createSpan("BlobClient-setAccessTier", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blockBlobContext.getBlockList(listType, { + return [4 /*yield*/, this.blobContext.setTier(toAccessTier(tier), { abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + rehydratePriority: options.rehydratePriority, spanOptions: spanOptions })]; - case 2: - res = _c.sent(); - if (!res.committedBlocks) { - res.committedBlocks = []; - } - if (!res.uncommittedBlocks) { - res.uncommittedBlocks = []; - } - return [2 /*return*/, res]; + case 2: return [2 /*return*/, _c.sent()]; case 3: - e_28 = _c.sent(); + e_14 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_28.message + message: e_14.message }); - throw e_28; + throw e_14; case 4: span.end(); return [7 /*endfinally*/]; @@ -30075,220 +30256,122 @@ var BlockBlobClient = /** @class */ (function (_super) { }); }); }; - // High level functions - /** - * Uploads a Buffer(Node.js)/Blob(browsers)/ArrayBuffer/ArrayBufferView object to a BlockBlob. - * - * When data length is no more than the specifiled {@link BlockBlobParallelUploadOptions.maxSingleShotSize} (default is - * {@link BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}), this method will use 1 {@link upload} call to finish the upload. - * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} - * to commit the block list. - * - * @export - * @param {Buffer | Blob | ArrayBuffer | ArrayBufferView} data Buffer(Node.js), Blob, ArrayBuffer or ArrayBufferView - * @param {BlockBlobParallelUploadOptions} [options] - * @returns {Promise} - * @memberof BlockBlobClient - */ - BlockBlobClient.prototype.uploadData = function (data, options) { - if (options === void 0) { options = {}; } + BlobClient.prototype.downloadToBuffer = function (param1, param2, param3, param4) { + if (param4 === void 0) { param4 = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, buffer_1, browserBlob_1; + var buffer, offset, count, options, _a, span, spanOptions, response, transferProgress_1, batch, _loop_1, off, e_15; + var _this = this; return tslib.__generator(this, function (_b) { - _a = createSpan("BlockBlobClient-uploadData", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - try { - if (true) { - if (data instanceof Buffer) { - buffer_1 = data; - } - else if (data instanceof ArrayBuffer) { - buffer_1 = Buffer.from(data); + switch (_b.label) { + case 0: + offset = 0; + count = 0; + options = param4; + if (param1 instanceof Buffer) { + buffer = param1; + offset = param2 || 0; + count = typeof param3 === "number" ? param3 : 0; } else { - data = data; - buffer_1 = Buffer.from(data.buffer, data.byteOffset, data.byteLength); + offset = typeof param1 === "number" ? param1 : 0; + count = typeof param2 === "number" ? param2 : 0; + options = param3 || {}; } - return [2 /*return*/, this.uploadSeekableInternal(function (offset, size) { return buffer_1.slice(offset, offset + size); }, buffer_1.byteLength, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - } - else {} - } - catch (e) { - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e.message - }); - throw e; - } - finally { - span.end(); - } - return [2 /*return*/]; - }); - }); - }; - /** - * ONLY AVAILABLE IN BROWSERS. - * - * Uploads a browser Blob/File/ArrayBuffer/ArrayBufferView object to block blob. - * - * When buffer length <= 256MB, this method will use 1 upload call to finish the upload. - * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call - * {@link commitBlockList} to commit the block list. - * - * @deprecated Use {@link uploadData} instead. - * - * @export - * @param {Blob | ArrayBuffer | ArrayBufferView} browserData Blob, File, ArrayBuffer or ArrayBufferView - * @param {BlockBlobParallelUploadOptions} [options] Options to upload browser data. - * @returns {Promise} Response data for the Blob Upload operation. - * @memberof BlockBlobClient - */ - BlockBlobClient.prototype.uploadBrowserData = function (browserData, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, browserBlob_2, e_29; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlockBlobClient-uploadBrowserData", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("BlobClient-downloadToBuffer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: - _b.trys.push([1, 3, 4, 5]); - browserBlob_2 = new Blob([browserData]); - return [4 /*yield*/, this.uploadSeekableInternal(function (offset, size) { return browserBlob_2.slice(offset, offset + size); }, browserBlob_2.size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_29 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_29.message - }); - throw e_29; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - /** - * - * Uploads data to block blob. Requires a bodyFactory as the data source, - * which need to return a {@link HttpRequestBody} object with the offset and size provided. - * - * When data length is no more than the specifiled {@link BlockBlobParallelUploadOptions.maxSingleShotSize} (default is - * {@link BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}), this method will use 1 {@link upload} call to finish the upload. - * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} - * to commit the block list. - * - * @param {(offset: number, size: number) => HttpRequestBody} bodyFactory - * @param {number} size size of the data to upload. - * @param {BlockBlobParallelUploadOptions} [options] Options to Upload to Block Blob operation. - * @returns {Promise} Response data for the Blob Upload operation. - * @memberof BlockBlobClient - */ - BlockBlobClient.prototype.uploadSeekableInternal = function (bodyFactory, size, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, numBlocks_1, blockList_1, blockIDPrefix_1, transferProgress_2, batch, _loop_2, i, e_30; - var _this = this; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: + _b.trys.push([1, 5, 6, 7]); if (!options.blockSize) { options.blockSize = 0; } - if (options.blockSize < 0 || options.blockSize > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES) { - throw new RangeError("blockSize option must be >= 0 and <= " + BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES); - } - if (options.maxSingleShotSize !== 0 && !options.maxSingleShotSize) { - options.maxSingleShotSize = BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES; - } - if (options.maxSingleShotSize < 0 || - options.maxSingleShotSize > BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES) { - throw new RangeError("maxSingleShotSize option must be >= 0 and <= " + BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES); + if (options.blockSize < 0) { + throw new RangeError("blockSize option must be >= 0"); } if (options.blockSize === 0) { - if (size > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES * BLOCK_BLOB_MAX_BLOCKS) { - throw new RangeError(size + " is too larger to upload to a block blob."); - } - if (size > options.maxSingleShotSize) { - options.blockSize = Math.ceil(size / BLOCK_BLOB_MAX_BLOCKS); - if (options.blockSize < DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES) { - options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; - } - } + options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; } - if (!options.blobHTTPHeaders) { - options.blobHTTPHeaders = {}; + if (offset < 0) { + throw new RangeError("offset option must be >= 0"); + } + if (count && count <= 0) { + throw new RangeError("count option must be > 0"); } if (!options.conditions) { options.conditions = {}; } - _a = createSpan("BlockBlobClient-uploadSeekableInternal", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 5, 6, 7]); - if (!(size <= options.maxSingleShotSize)) return [3 /*break*/, 3]; - return [4 /*yield*/, this.upload(bodyFactory(0, size), size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: return [2 /*return*/, _b.sent()]; + if (!!count) return [3 /*break*/, 3]; + return [4 /*yield*/, this.getProperties(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: + response = _b.sent(); + count = response.contentLength - offset; + if (count < 0) { + throw new RangeError("offset " + offset + " shouldn't be larger than blob size " + response.contentLength); + } + _b.label = 3; case 3: - numBlocks_1 = Math.floor((size - 1) / options.blockSize) + 1; - if (numBlocks_1 > BLOCK_BLOB_MAX_BLOCKS) { - throw new RangeError("The buffer's size is too big or the BlockSize is too small;" + - ("the number of blocks must be <= " + BLOCK_BLOB_MAX_BLOCKS)); + // Allocate the buffer of size = count if the buffer is not provided + if (!buffer) { + try { + buffer = Buffer.alloc(count); + } + catch (error) { + throw new Error("Unable to allocate the buffer of size: " + count + "(in bytes). Please try passing your own buffer to the \"downloadToBuffer\" method or try using other methods like \"download\" or \"downloadToFile\".\t " + error.message); + } } - blockList_1 = []; - blockIDPrefix_1 = coreHttp.generateUuid(); - transferProgress_2 = 0; + if (buffer.length < count) { + throw new RangeError("The buffer's size should be equal to or larger than the request count of bytes: " + count); + } + transferProgress_1 = 0; batch = new Batch(options.concurrency); - _loop_2 = function (i) { + _loop_1 = function (off) { batch.addOperation(function () { return tslib.__awaiter(_this, void 0, void 0, function () { - var blockID, start, end, contentLength; + var chunkEnd, response, stream; return tslib.__generator(this, function (_a) { switch (_a.label) { case 0: - blockID = generateBlockID(blockIDPrefix_1, i); - start = options.blockSize * i; - end = i === numBlocks_1 - 1 ? size : start + options.blockSize; - contentLength = end - start; - blockList_1.push(blockID); - return [4 /*yield*/, this.stageBlock(blockID, bodyFactory(start, contentLength), contentLength, { + chunkEnd = offset + count; + if (off + options.blockSize < chunkEnd) { + chunkEnd = off + options.blockSize; + } + return [4 /*yield*/, this.download(off, chunkEnd - off, { abortSignal: options.abortSignal, conditions: options.conditions, - encryptionScope: options.encryptionScope, + maxRetryRequests: options.maxRetryRequestsPerBlock, + customerProvidedKey: options.customerProvidedKey, tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) })]; case 1: + response = _a.sent(); + stream = response.readableStreamBody; + return [4 /*yield*/, streamToBuffer(stream, buffer, off - offset, chunkEnd - offset)]; + case 2: _a.sent(); - // Update progress after block is successfully uploaded to server, in case of block trying - // TODO: Hook with convenience layer progress event in finer level - transferProgress_2 += contentLength; + // Update progress after block is downloaded, in case of block trying + // Could provide finer grained progress updating inside HTTP requests, + // only if convenience layer download try is enabled + transferProgress_1 += chunkEnd - off; if (options.onProgress) { - options.onProgress({ - loadedBytes: transferProgress_2 - }); + options.onProgress({ loadedBytes: transferProgress_1 }); } return [2 /*return*/]; } }); }); }); }; - for (i = 0; i < numBlocks_1; i++) { - _loop_2(i); + for (off = offset; off < offset + count; off = off + options.blockSize) { + _loop_1(off); } return [4 /*yield*/, batch.do()]; case 4: _b.sent(); - return [2 /*return*/, this.commitBlockList(blockList_1, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + return [2 /*return*/, buffer]; case 5: - e_30 = _b.sent(); + e_15 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_30.message + message: e_15.message }); - throw e_30; + throw e_15; case 6: span.end(); return [7 /*endfinally*/]; @@ -30300,158 +30383,205 @@ var BlockBlobClient = /** @class */ (function (_super) { /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * - * Uploads a local file in blocks to a block blob. - * - * When file size <= 256MB, this method will use 1 upload call to finish the upload. - * Otherwise, this method will call stageBlock to upload blocks, and finally call commitBlockList - * to commit the block list. + * Downloads an Azure Blob to a local file. + * Fails if the the given file path already exits. + * Offset and count are optional, pass 0 and undefined respectively to download the entire blob. * - * @param {string} filePath Full path of local file - * @param {BlockBlobParallelUploadOptions} [options] Options to Upload to Block Blob operation. - * @returns {(Promise)} Response data for the Blob Upload operation. - * @memberof BlockBlobClient + * @param {string} filePath + * @param {number} [offset] From which position of the block blob to download. + * @param {number} [count] How much data to be downloaded. Will download to the end when passing undefined. + * @param {BlobDownloadOptions} [options] Options to Blob download options. + * @returns {Promise} The response data for blob download operation, + * but with readableStreamBody set to undefined since its + * content is already read and written into a local file + * at the specified path. + * @memberof BlobClient */ - BlockBlobClient.prototype.uploadFile = function (filePath, options) { + BlobClient.prototype.downloadToFile = function (filePath, offset, count, options) { + if (offset === void 0) { offset = 0; } if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, size, e_31; + var _a, span, spanOptions, response, e_16; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("BlockBlobClient-uploadFile", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("BlobClient-downloadToFile", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: - _b.trys.push([1, 4, 5, 6]); - return [4 /*yield*/, fsStat(filePath)]; + _b.trys.push([1, 5, 6, 7]); + return [4 /*yield*/, this.download(offset, count, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: - size = (_b.sent()).size; - return [4 /*yield*/, this.uploadSeekableInternal(function (offset, count) { - return function () { - return fsCreateReadStream(filePath, { - autoClose: true, - end: count ? offset + count - 1 : Infinity, - start: offset - }); - }; - }, size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 3: return [2 /*return*/, _b.sent()]; + response = _b.sent(); + if (!response.readableStreamBody) return [3 /*break*/, 4]; + return [4 /*yield*/, readStreamToLocalFile(response.readableStreamBody, filePath)]; + case 3: + _b.sent(); + _b.label = 4; case 4: - e_31 = _b.sent(); + // The stream is no longer accessible so setting it to undefined. + response.blobDownloadStream = undefined; + return [2 /*return*/, response]; + case 5: + e_16 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_31.message + message: e_16.message }); - throw e_31; - case 5: + throw e_16; + case 6: span.end(); return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; + case 7: return [2 /*return*/]; } }); }); }; + BlobClient.prototype.getBlobAndContainerNamesFromUrl = function () { + var containerName; + var blobName; + try { + // URL may look like the following + // "https://myaccount.blob.core.windows.net/mycontainer/blob?sasString"; + // "https://myaccount.blob.core.windows.net/mycontainer/blob"; + // "https://myaccount.blob.core.windows.net/mycontainer/blob/a.txt?sasString"; + // "https://myaccount.blob.core.windows.net/mycontainer/blob/a.txt"; + // IPv4/IPv6 address hosts, Endpoints - `http://127.0.0.1:10000/devstoreaccount1/containername/blob` + // http://localhost:10001/devstoreaccount1/containername/blob + var parsedUrl = coreHttp.URLBuilder.parse(this.url); + if (parsedUrl.getHost().split(".")[1] === "blob") { + // "https://myaccount.blob.core.windows.net/containername/blob". + // .getPath() -> /containername/blob + var pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); + containerName = pathComponents[1]; + blobName = pathComponents[3]; + } + else if (isIpEndpointStyle(parsedUrl)) { + // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/containername/blob + // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/containername/blob + // .getPath() -> /devstoreaccount1/containername/blob + var pathComponents = parsedUrl.getPath().match("/([^/]*)/([^/]*)(/(.*))?"); + containerName = pathComponents[2]; + blobName = pathComponents[4]; + } + else { + // "https://customdomain.com/containername/blob". + // .getPath() -> /containername/blob + var pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); + containerName = pathComponents[1]; + blobName = pathComponents[3]; + } + // decode the encoded blobName, containerName - to get all the special characters that might be present in them + containerName = decodeURIComponent(containerName); + blobName = decodeURIComponent(blobName); + // Azure Storage Server will replace "\" with "/" in the blob names + // doing the same in the SDK side so that the user doesn't have to replace "\" instances in the blobName + blobName = blobName.replace(/\\/g, "/"); + if (!containerName) { + throw new Error("Provided containerName is invalid."); + } + return { blobName: blobName, containerName: containerName }; + } + catch (error) { + throw new Error("Unable to extract blobName and containerName with provided information."); + } + }; /** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * Uploads a Node.js Readable stream into block blob. - * - * PERFORMANCE IMPROVEMENT TIPS: - * * Input stream highWaterMark is better to set a same value with bufferSize - * parameter, which will avoid Buffer.concat() operations. + * Asynchronously copies a blob to a destination within the storage account. + * In version 2012-02-12 and later, the source for a Copy Blob operation can be + * a committed blob in any Azure storage account. + * Beginning with version 2015-02-21, the source for a Copy Blob operation can be + * an Azure file in any Azure storage account. + * Only storage accounts created on or after June 7th, 2012 allow the Copy Blob + * operation to copy from another storage account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob * - * @param {Readable} stream Node.js Readable stream - * @param {number} bufferSize Size of every buffer allocated, also the block size in the uploaded block blob. Default value is 8MB - * @param {number} maxConcurrency Max concurrency indicates the max number of buffers that can be allocated, - * positive correlation with max uploading concurrency. Default value is 5 - * @param {BlockBlobUploadStreamOptions} [options] Options to Upload Stream to Block Blob operation. - * @returns {Promise} Response data for the Blob Upload operation. - * @memberof BlockBlobClient + * @param {string} copySource url to the source Azure Blob/File. + * @param {BlobStartCopyFromURLOptions} [options] Optional options to the Blob Start Copy From URL operation. + * @returns {Promise} + * @memberof BlobClient */ - BlockBlobClient.prototype.uploadStream = function (stream, bufferSize, maxConcurrency, options) { - if (bufferSize === void 0) { bufferSize = DEFAULT_BLOCK_BUFFER_SIZE_BYTES; } - if (maxConcurrency === void 0) { maxConcurrency = 5; } + BlobClient.prototype.startCopyFromURL = function (copySource, options) { + var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, blockNum_1, blockIDPrefix_2, transferProgress_3, blockList_2, scheduler, e_32; - var _this = this; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var _b, span, spanOptions, e_17; + return tslib.__generator(this, function (_c) { + switch (_c.label) { case 0: - if (!options.blobHTTPHeaders) { - options.blobHTTPHeaders = {}; - } - if (!options.conditions) { - options.conditions = {}; - } - _a = createSpan("BlockBlobClient-uploadStream", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + _b = createSpan("BlobClient-startCopyFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + _c.label = 1; case 1: - _b.trys.push([1, 4, 5, 6]); - blockNum_1 = 0; - blockIDPrefix_2 = coreHttp.generateUuid(); - transferProgress_3 = 0; - blockList_2 = []; - scheduler = new BufferScheduler(stream, bufferSize, maxConcurrency, function (body, length) { return tslib.__awaiter(_this, void 0, void 0, function () { - var blockID; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - blockID = generateBlockID(blockIDPrefix_2, blockNum_1); - blockList_2.push(blockID); - blockNum_1++; - return [4 /*yield*/, this.stageBlock(blockID, body, length, { - conditions: options.conditions, - encryptionScope: options.encryptionScope, - tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) - })]; - case 1: - _a.sent(); - // Update progress after block is successfully uploaded to server, in case of block trying - transferProgress_3 += length; - if (options.onProgress) { - options.onProgress({ loadedBytes: transferProgress_3 }); - } - return [2 /*return*/]; - } - }); - }); }, - // concurrency should set a smaller value than maxConcurrency, which is helpful to - // reduce the possibility when a outgoing handler waits for stream data, in - // this situation, outgoing handlers are blocked. - // Outgoing queue shouldn't be empty. - Math.ceil((maxConcurrency / 4) * 3)); - return [4 /*yield*/, scheduler.do()]; - case 2: - _b.sent(); - return [4 /*yield*/, this.commitBlockList(blockList_2, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 3: return [2 /*return*/, _b.sent()]; - case 4: - e_32 = _b.sent(); + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.blobContext.startCopyFromURL(copySource, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince, + sourceIfTags: options.sourceConditions.tagConditions + }, + rehydratePriority: options.rehydratePriority, + tier: toAccessTier(options.tier), + blobTagsString: toBlobTagsString(options.tags), + sealBlob: options.sealBlob, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_17 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_32.message + message: e_17.message }); - throw e_32; - case 5: + throw e_17; + case 4: span.end(); return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; + case 5: return [2 /*return*/]; } }); }); }; - return BlockBlobClient; -}(BlobClient)); + /** + * Only available for BlobClient constructed with a shared key credential. + * + * Generates a Blob Service Shared Access Signature (SAS) URI based on the client properties + * and parameters passed in. The SAS is signed by the shared key credential of the client. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas + * + * @param {BlobGenerateSasUrlOptions} options Optional parameters. + * @returns {Promise} The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + * @memberof BlobClient + */ + BlobClient.prototype.generateSasUrl = function (options) { + var _this = this; + return new Promise(function (resolve) { + if (!(_this.credential instanceof StorageSharedKeyCredential)) { + throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); + } + var sas = generateBlobSASQueryParameters(tslib.__assign({ containerName: _this._containerName, blobName: _this._name, snapshotTime: _this._snapshot, versionId: _this._versionId }, options), _this.credential).toString(); + resolve(appendToURLQuery(_this.url, sas)); + }); + }; + return BlobClient; +}(StorageClient)); /** - * PageBlobClient defines a set of operations applicable to page blobs. + * AppendBlobClient defines a set of operations applicable to append blobs. * * @export - * @class PageBlobClient + * @class AppendBlobClient * @extends {BlobClient} */ -var PageBlobClient = /** @class */ (function (_super) { - tslib.__extends(PageBlobClient, _super); - function PageBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { +var AppendBlobClient = /** @class */ (function (_super) { + tslib.__extends(AppendBlobClient, _super); + function AppendBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { var _this = this; // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); @@ -30466,7 +30596,7 @@ var PageBlobClient = /** @class */ (function (_super) { else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { - // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) url = urlOrConnectionString; url = urlOrConnectionString; options = blobNameOrOptions; pipeline = newPipeline(credentialOrPipelineOrContainerName, options); @@ -30474,8 +30604,8 @@ var PageBlobClient = /** @class */ (function (_super) { else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) - // The second parameter is undefined. Use anonymous credential. url = urlOrConnectionString; + // The second parameter is undefined. Use anonymous credential. pipeline = newPipeline(new AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && @@ -30509,66 +30639,69 @@ var PageBlobClient = /** @class */ (function (_super) { throw new Error("Expecting non-empty strings for containerName and blobName parameters"); } _this = _super.call(this, url, pipeline) || this; - _this.pageBlobContext = new PageBlob(_this.storageClientContext); + _this.appendBlobContext = new AppendBlob(_this.storageClientContext); return _this; } /** - * Creates a new PageBlobClient object identical to the source but with the + * Creates a new AppendBlobClient object identical to the source but with the * specified snapshot timestamp. * Provide "" will remove the snapshot and return a Client to the base blob. * * @param {string} snapshot The snapshot timestamp. - * @returns {PageBlobClient} A new PageBlobClient object identical to the source but with the specified snapshot timestamp. - * @memberof PageBlobClient + * @returns {AppendBlobClient} A new AppendBlobClient object identical to the source but with the specified snapshot timestamp. + * @memberof AppendBlobClient */ - PageBlobClient.prototype.withSnapshot = function (snapshot) { - return new PageBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); + AppendBlobClient.prototype.withSnapshot = function (snapshot) { + return new AppendBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); }; /** - * Creates a page blob of the specified length. Call uploadPages to upload data - * data to a page blob. + * Creates a 0-length append blob. Call AppendBlock to append data to an append blob. * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * - * @param {number} size size of the page blob. - * @param {PageBlobCreateOptions} [options] Options to the Page Blob Create operation. - * @returns {Promise} Response data for the Page Blob Create operation. - * @memberof PageBlobClient + * @param {AppendBlobCreateOptions} [options] Options to the Append Block Create operation. + * @returns {Promise} + * @memberof AppendBlobClient + * + * Example usage: + * + * ```js + * const appendBlobClient = containerClient.getAppendBlobClient(""); + * await appendBlobClient.create(); + * ``` */ - PageBlobClient.prototype.create = function (size, options) { + AppendBlobClient.prototype.create = function (options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_33; + var _b, span, spanOptions, e_18; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: + _b = createSpan("AppendBlobClient-create", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-create", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.pageBlobContext.create(0, size, { + return [4 /*yield*/, this.appendBlobContext.create(0, { abortSignal: options.abortSignal, blobHTTPHeaders: options.blobHTTPHeaders, - blobSequenceNumber: options.blobSequenceNumber, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, - tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_33 = _c.sent(); + e_18 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_33.message + message: e_18.message }); - throw e_33; + throw e_18; case 4: span.end(); return [7 /*endfinally*/]; @@ -30578,48 +30711,46 @@ var PageBlobClient = /** @class */ (function (_super) { }); }; /** - * Creates a page blob of the specified length. Call uploadPages to upload data - * data to a page blob. If the blob with the same name already exists, the content - * of the existing blob will remain unchanged. + * Creates a 0-length append blob. Call AppendBlock to append data to an append blob. + * If the blob with the same name already exists, the content of the existing blob will remain unchanged. * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * - * @param {number} size size of the page blob. - * @param {PageBlobCreateIfNotExistsOptions} [options] - * @returns {Promise} - * @memberof PageBlobClient + * @param {AppendBlobCreateIfNotExistsOptions} [options] + * @returns {Promise} + * @memberof AppendBlobClient */ - PageBlobClient.prototype.createIfNotExists = function (size, options) { + AppendBlobClient.prototype.createIfNotExists = function (options) { var _a, _b; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _c, span, spanOptions, conditions, res, e_34; + var _c, span, spanOptions, conditions, res, e_19; return tslib.__generator(this, function (_d) { switch (_d.label) { case 0: - _c = createSpan("PageBlobClient-createIfNotExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; + _c = createSpan("AppendBlobClient-createIfNotExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; + conditions = { ifNoneMatch: ETagAny }; _d.label = 1; case 1: _d.trys.push([1, 3, 4, 5]); - conditions = { ifNoneMatch: ETagAny }; - return [4 /*yield*/, this.create(size, tslib.__assign(tslib.__assign({}, options), { conditions: conditions, tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + return [4 /*yield*/, this.create(tslib.__assign(tslib.__assign({}, options), { conditions: conditions, tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: res = _d.sent(); return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable })]; case 3: - e_34 = _d.sent(); - if (((_a = e_34.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { + e_19 = _d.sent(); + if (((_a = e_19.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { span.setStatus({ code: api.CanonicalCode.ALREADY_EXISTS, message: "Expected exception when creating a blob only if it does not already exist." }); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_34.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_34.response })]; + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_19.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_19.response })]; } span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_34.message + message: e_19.message }); - throw e_34; + throw e_19; case 4: span.end(); return [7 /*endfinally*/]; @@ -30629,51 +30760,40 @@ var PageBlobClient = /** @class */ (function (_super) { }); }; /** - * Writes 1 or more pages to the page blob. The start and end offsets must be a multiple of 512. - * @see https://docs.microsoft.com/rest/api/storageservices/put-page + * Seals the append blob, making it read only. * - * @param {HttpRequestBody} body Data to upload - * @param {number} offset Offset of destination page blob - * @param {number} count Content length of the body, also number of bytes to be uploaded - * @param {PageBlobUploadPagesOptions} [options] Options to the Page Blob Upload Pages operation. - * @returns {Promise} Response data for the Page Blob Upload Pages operation. - * @memberof PageBlobClient + * @param {AppendBlobSealOptions} [options={}] + * @returns {Promise} + * @memberof AppendBlobClient */ - PageBlobClient.prototype.uploadPages = function (body, offset, count, options) { + AppendBlobClient.prototype.seal = function (options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_35; + var _b, span, spanOptions, e_20; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: + _b = createSpan("AppendBlobClient-seal", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-uploadPages", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.pageBlobContext.uploadPages(body, count, { + return [4 /*yield*/, this.appendBlobContext.seal({ abortSignal: options.abortSignal, + appendPositionAccessConditions: options.conditions, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - onUploadProgress: options.onProgress, - range: rangeToString({ offset: offset, count: count }), - sequenceNumberAccessConditions: options.conditions, - transactionalContentMD5: options.transactionalContentMD5, - transactionalContentCrc64: options.transactionalContentCrc64, - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_35 = _c.sent(); + e_20 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_35.message + message: e_20.message }); - throw e_35; + throw e_20; case 4: span.end(); return [7 /*endfinally*/]; @@ -30683,108 +30803,64 @@ var PageBlobClient = /** @class */ (function (_super) { }); }; /** - * The Upload Pages operation writes a range of pages to a page blob where the - * contents are read from a URL. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-page-from-url + * Commits a new block of data to the end of the existing append blob. + * @see https://docs.microsoft.com/rest/api/storageservices/append-block * - * @param {string} sourceURL Specify a URL to the copy source, Shared Access Signature(SAS) maybe needed for authentication - * @param {number} sourceOffset The source offset to copy from. Pass 0 to copy from the beginning of source page blob - * @param {number} destOffset Offset of destination page blob - * @param {number} count Number of bytes to be uploaded from source page blob - * @param {PageBlobUploadPagesFromURLOptions} [options={}] - * @returns {Promise} - * @memberof PageBlobClient - */ - PageBlobClient.prototype.uploadPagesFromURL = function (sourceURL, sourceOffset, destOffset, count, options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_36; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - options.sourceConditions = options.sourceConditions || {}; - _b = createSpan("PageBlobClient-uploadPagesFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.pageBlobContext.uploadPagesFromURL(sourceURL, rangeToString({ offset: sourceOffset, count: count }), 0, rangeToString({ offset: destOffset, count: count }), { - abortSignal: options.abortSignal, - sourceContentMD5: options.sourceContentMD5, - sourceContentCrc64: options.sourceContentCrc64, - leaseAccessConditions: options.conditions, - sequenceNumberAccessConditions: options.conditions, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions.ifMatch, - sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince - }, - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_36 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_36.message - }); - throw e_36; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - /** - * Frees the specified pages from the page blob. - * @see https://docs.microsoft.com/rest/api/storageservices/put-page + * @param {HttpRequestBody} body Data to be appended. + * @param {number} contentLength Length of the body in bytes. + * @param {AppendBlobAppendBlockOptions} [options] Options to the Append Block operation. + * @returns {Promise} + * @memberof AppendBlobClient * - * @param {number} [offset] Starting byte position of the pages to clear. - * @param {number} [count] Number of bytes to clear. - * @param {PageBlobClearPagesOptions} [options] Options to the Page Blob Clear Pages operation. - * @returns {Promise} Response data for the Page Blob Clear Pages operation. - * @memberof PageBlobClient + * Example usage: + * + * ```js + * const content = "Hello World!"; + * + * // Create a new append blob and append data to the blob. + * const newAppendBlobClient = containerClient.getAppendBlobClient(""); + * await newAppendBlobClient.create(); + * await newAppendBlobClient.appendBlock(content, content.length); + * + * // Append data to an existing append blob. + * const existingAppendBlobClient = containerClient.getAppendBlobClient(""); + * await existingAppendBlobClient.appendBlock(content, content.length); + * ``` */ - PageBlobClient.prototype.clearPages = function (offset, count, options) { + AppendBlobClient.prototype.appendBlock = function (body, contentLength, options) { var _a; - if (offset === void 0) { offset = 0; } if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_37; + var _b, span, spanOptions, e_21; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: + _b = createSpan("AppendBlobClient-appendBlock", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-clearPages", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext.clearPages(0, { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.appendBlobContext.appendBlock(body, contentLength, { abortSignal: options.abortSignal, + appendPositionAccessConditions: options.conditions, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - range: rangeToString({ offset: offset, count: count }), - sequenceNumberAccessConditions: options.conditions, + onUploadProgress: options.onProgress, + transactionalContentMD5: options.transactionalContentMD5, + transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_37 = _c.sent(); + e_21 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_37.message + message: e_21.message }); - throw e_37; + throw e_21; case 4: span.end(); return [7 /*endfinally*/]; @@ -30794,46 +30870,62 @@ var PageBlobClient = /** @class */ (function (_super) { }); }; /** - * Returns the list of valid page ranges for a page blob or snapshot of a page blob. - * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * The Append Block operation commits a new block of data to the end of an existing append blob + * where the contents are read from a source url. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/append-block-from-url * - * @param {number} [offset] Starting byte position of the page ranges. - * @param {number} [count] Number of bytes to get. - * @param {PageBlobGetPageRangesOptions} [options] Options to the Page Blob Get Ranges operation. - * @returns {Promise} Response data for the Page Blob Get Ranges operation. - * @memberof PageBlobClient + * @param {string} sourceURL + * The url to the blob that will be the source of the copy. A source blob in the same storage account can + * be authenticated via Shared Key. However, if the source is a blob in another account, the source blob + * must either be public or must be authenticated via a shared access signature. If the source blob is + * public, no authentication is required to perform the operation. + * @param {number} sourceOffset Offset in source to be appended + * @param {number} count Number of bytes to be appended as a block + * @param {AppendBlobAppendBlockFromURLOptions} [options={}] + * @returns {Promise} + * @memberof AppendBlobClient */ - PageBlobClient.prototype.getPageRanges = function (offset, count, options) { + AppendBlobClient.prototype.appendBlockFromURL = function (sourceURL, sourceOffset, count, options) { var _a; - if (offset === void 0) { offset = 0; } if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_38; + var _b, span, spanOptions, e_22; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: + _b = createSpan("AppendBlobClient-appendBlockFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-getPageRanges", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + options.sourceConditions = options.sourceConditions || {}; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext - .getPageRanges({ + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.appendBlobContext.appendBlockFromUrl(sourceURL, 0, { abortSignal: options.abortSignal, + sourceRange: rangeToString({ offset: sourceOffset, count: count }), + sourceContentMD5: options.sourceContentMD5, + sourceContentCrc64: options.sourceContentCrc64, leaseAccessConditions: options.conditions, + appendPositionAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - range: rangeToString({ offset: offset, count: count }), + sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince + }, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, spanOptions: spanOptions - }) - .then(rangeResponseFromModel)]; + })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_38 = _c.sent(); + e_22 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_38.message + message: e_22.message }); - throw e_38; + throw e_22; case 4: span.end(); return [7 /*endfinally*/]; @@ -30842,48 +30934,161 @@ var PageBlobClient = /** @class */ (function (_super) { }); }); }; + return AppendBlobClient; +}(BlobClient)); +/** + * BlockBlobClient defines a set of operations applicable to block blobs. + * + * @export + * @class BlockBlobClient + * @extends {BlobClient} + */ +var BlockBlobClient = /** @class */ (function (_super) { + tslib.__extends(BlockBlobClient, _super); + function BlockBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { + var _this = this; + // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. + // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); + var pipeline; + var url; + options = options || {}; + if (credentialOrPipelineOrContainerName instanceof Pipeline) { + // (url: string, pipeline: Pipeline) + url = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } + else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || + credentialOrPipelineOrContainerName instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + url = urlOrConnectionString; + options = blobNameOrOptions; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } + else if (!credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName !== "string") { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + // The second parameter is undefined. Use anonymous credential. + url = urlOrConnectionString; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else if (credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName === "string" && + blobNameOrOptions && + typeof blobNameOrOptions === "string") { + // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) + var containerName = credentialOrPipelineOrContainerName; + var blobName = blobNameOrOptions; + var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + { + var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); + options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); + pipeline = newPipeline(sharedKeyCredential, options); + } + } + else if (extractedCreds.kind === "SASConnString") { + url = + appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + + "?" + + extractedCreds.accountSas; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } + else { + throw new Error("Expecting non-empty strings for containerName and blobName parameters"); + } + _this = _super.call(this, url, pipeline) || this; + _this.blockBlobContext = new BlockBlob(_this.storageClientContext); + _this._blobContext = new Blob$1(_this.storageClientContext); + return _this; + } + /** + * Creates a new BlockBlobClient object identical to the source but with the + * specified snapshot timestamp. + * Provide "" will remove the snapshot and return a URL to the base blob. + * + * @param {string} snapshot The snapshot timestamp. + * @returns {BlockBlobClient} A new BlockBlobClient object identical to the source but with the specified snapshot timestamp. + * @memberof BlockBlobClient + */ + BlockBlobClient.prototype.withSnapshot = function (snapshot) { + return new BlockBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); + }; /** - * Gets the collection of page ranges that differ between a specified snapshot and this page blob. - * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * ONLY AVAILABLE IN NODE.JS RUNTIME. * - * @param {number} offset Starting byte position of the page blob - * @param {number} count Number of bytes to get ranges diff. - * @param {string} prevSnapshot Timestamp of snapshot to retrieve the difference. - * @param {PageBlobGetPageRangesDiffOptions} [options] Options to the Page Blob Get Page Ranges Diff operation. - * @returns {Promise} Response data for the Page Blob Get Page Range Diff operation. - * @memberof PageBlobClient + * Quick query for a JSON or CSV formatted blob. + * + * Example usage (Node.js): + * + * ```js + * // Query and convert a blob to a string + * const queryBlockBlobResponse = await blockBlobClient.query("select * from BlobStorage"); + * const downloaded = (await streamToBuffer(queryBlockBlobResponse.readableStreamBody)).toString(); + * console.log("Query blob content:", downloaded); + * + * async function streamToBuffer(readableStream) { + * return new Promise((resolve, reject) => { + * const chunks = []; + * readableStream.on("data", (data) => { + * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); + * }); + * readableStream.on("end", () => { + * resolve(Buffer.concat(chunks)); + * }); + * readableStream.on("error", reject); + * }); + * } + * ``` + * + * @param {string} query + * @param {BlockBlobQueryOptions} [options={}] + * @returns {Promise} + * @memberof BlockBlobClient */ - PageBlobClient.prototype.getPageRangesDiff = function (offset, count, prevSnapshot, options) { + BlockBlobClient.prototype.query = function (query, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_39; + var _b, span, spanOptions, response, e_23; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: - options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-getPageRangesDiff", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + _b = createSpan("BlockBlobClient-query", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext - .getPageRangesDiff({ + return [4 /*yield*/, this._blobContext.query({ abortSignal: options.abortSignal, + queryRequest: { + expression: query, + inputSerialization: toQuerySerialization(options.inputTextConfiguration), + outputSerialization: toQuerySerialization(options.outputTextConfiguration) + }, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - prevsnapshot: prevSnapshot, - range: rangeToString({ offset: offset, count: count }), spanOptions: spanOptions - }) - .then(rangeResponseFromModel)]; - case 2: return [2 /*return*/, _c.sent()]; + })]; + case 2: + response = _c.sent(); + return [2 /*return*/, new BlobQueryResponse(response, { + abortSignal: options.abortSignal, + onProgress: options.onProgress, + onError: options.onError + })]; case 3: - e_39 = _c.sent(); + e_23 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_39.message + message: e_23.message }); - throw e_39; + throw e_23; case 4: span.end(); return [7 /*endfinally*/]; @@ -30893,47 +31098,68 @@ var PageBlobClient = /** @class */ (function (_super) { }); }; /** - * Gets the collection of page ranges that differ between a specified snapshot and this page blob for managed disks. - * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * Creates a new block blob, or updates the content of an existing block blob. + * Updating an existing block blob overwrites any existing metadata on the blob. + * Partial updates are not supported; the content of the existing blob is + * overwritten with the new content. To perform a partial update of a block blob's, + * use {@link stageBlock} and {@link commitBlockList}. * - * @param {number} offset Starting byte position of the page blob - * @param {number} count Number of bytes to get ranges diff. - * @param {string} prevSnapshotUrl URL of snapshot to retrieve the difference. - * @param {PageBlobGetPageRangesDiffOptions} [options] Options to the Page Blob Get Page Ranges Diff operation. - * @returns {Promise} Response data for the Page Blob Get Page Range Diff operation. - * @memberof PageBlobClient + * This is a non-parallel uploading method, please use {@link uploadFile}, + * {@link uploadStream} or {@link uploadBrowserData} for better performance + * with concurrency uploading. + * + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * + * @param {HttpRequestBody} body Blob, string, ArrayBuffer, ArrayBufferView or a function + * which returns a new Readable stream whose offset is from data source beginning. + * @param {number} contentLength Length of body in bytes. Use Buffer.byteLength() to calculate body length for a + * string including non non-Base64/Hex-encoded characters. + * @param {BlockBlobUploadOptions} [options] Options to the Block Blob Upload operation. + * @returns {Promise} Response data for the Block Blob Upload operation. + * @memberof BlockBlobClient + * + * Example usage: + * + * ```js + * const content = "Hello world!"; + * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); + * ``` */ - PageBlobClient.prototype.getPageRangesDiffForManagedDisks = function (offset, count, prevSnapshotUrl, options) { + BlockBlobClient.prototype.upload = function (body, contentLength, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_40; + var _b, span, spanOptions, e_24; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-GetPageRangesDiffForManagedDisks", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _b = createSpan("BlockBlobClient-upload", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext - .getPageRangesDiff({ + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blockBlobContext.upload(body, contentLength, { abortSignal: options.abortSignal, + blobHTTPHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, + metadata: options.metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - prevSnapshotUrl: prevSnapshotUrl, - range: rangeToString({ offset: offset, count: count }), + onUploadProgress: options.onProgress, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tier: toAccessTier(options.tier), + blobTagsString: toBlobTagsString(options.tags), spanOptions: spanOptions - }) - .then(rangeResponseFromModel)]; + })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_40 = _c.sent(); + e_24 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_40.message + message: e_24.message }); - throw e_40; + throw e_24; case 4: span.end(); return [7 /*endfinally*/]; @@ -30943,42 +31169,54 @@ var PageBlobClient = /** @class */ (function (_super) { }); }; /** - * Resizes the page blob to the specified size (which must be a multiple of 512). - * @see https://docs.microsoft.com/rest/api/storageservices/set-blob-properties + * Creates a new Block Blob where the contents of the blob are read from a given URL. + * This API is supported beginning with the 2020-04-08 version. Partial updates + * are not supported with Put Blob from URL; the content of an existing blob is overwritten with + * the content of the new blob. To perform partial updates to a block blob’s contents using a + * source URL, use {@link stageBlockFromURL} and {@link commitBlockList}. * - * @param {number} size Target size - * @param {PageBlobResizeOptions} [options] Options to the Page Blob Resize operation. - * @returns {Promise} Response data for the Page Blob Resize operation. - * @memberof PageBlobClient + * @param {string} sourceURL Specifies the URL of the blob. The value + * may be a URL of up to 2 KB in length that specifies a blob. + * The value should be URL-encoded as it would appear + * in a request URI. The source blob must either be public + * or must be authenticated via a shared access signature. + * If the source blob is public, no authentication is required + * to perform the operation. Here are some examples of source object URLs: + * - https://myaccount.blob.core.windows.net/mycontainer/myblob + * - https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= + * @param {BlockBlobSyncUploadFromURLOptions} [options={}] Optional parameters. + * @returns Promise + * @memberof BlockBlobClient */ - PageBlobClient.prototype.resize = function (size, options) { - var _a; + BlockBlobClient.prototype.syncUploadFromURL = function (sourceURL, options) { + var _a, _b, _c, _d, _e; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_41; - return tslib.__generator(this, function (_c) { - switch (_c.label) { + var _f, span, spanOptions, e_25; + return tslib.__generator(this, function (_g) { + switch (_g.label) { case 0: options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-resize", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - _c.label = 1; + _f = createSpan("BlockBlobClient-syncUploadFromURL", options.tracingOptions), span = _f.span, spanOptions = _f.spanOptions; + _g.label = 1; case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext.resize(size, { - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - encryptionScope: options.encryptionScope, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _c.sent()]; + _g.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blockBlobContext.putBlobFromUrl(0, sourceURL, tslib.__assign(tslib.__assign({}, options), { leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: options.conditions.tagConditions }), sourceModifiedAccessConditions: { + sourceIfMatch: (_a = options.sourceConditions) === null || _a === void 0 ? void 0 : _a.ifMatch, + sourceIfModifiedSince: (_b = options.sourceConditions) === null || _b === void 0 ? void 0 : _b.ifModifiedSince, + sourceIfNoneMatch: (_c = options.sourceConditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch, + sourceIfUnmodifiedSince: (_d = options.sourceConditions) === null || _d === void 0 ? void 0 : _d.ifUnmodifiedSince, + sourceIfTags: (_e = options.sourceConditions) === null || _e === void 0 ? void 0 : _e.tagConditions + }, cpkInfo: options.customerProvidedKey, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), spanOptions: spanOptions }))]; + case 2: return [2 /*return*/, _g.sent()]; case 3: - e_41 = _c.sent(); + e_25 = _g.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_41.message + message: e_25.message }); - throw e_41; + throw e_25; case 4: span.end(); return [7 /*endfinally*/]; @@ -30988,43 +31226,47 @@ var PageBlobClient = /** @class */ (function (_super) { }); }; /** - * Sets a page blob's sequence number. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties + * Uploads the specified block to the block blob's "staging area" to be later + * committed by a call to commitBlockList. + * @see https://docs.microsoft.com/rest/api/storageservices/put-block * - * @param {SequenceNumberActionType} sequenceNumberAction Indicates how the service should modify the blob's sequence number. - * @param {number} [sequenceNumber] Required if sequenceNumberAction is max or update - * @param {PageBlobUpdateSequenceNumberOptions} [options] Options to the Page Blob Update Sequence Number operation. - * @returns {Promise} Response data for the Page Blob Update Sequence Number operation. - * @memberof PageBlobClient + * @param {string} blockId A 64-byte value that is base64-encoded + * @param {HttpRequestBody} body Data to upload to the staging area. + * @param {number} contentLength Number of bytes to upload. + * @param {BlockBlobStageBlockOptions} [options] Options to the Block Blob Stage Block operation. + * @returns {Promise} Response data for the Block Blob Stage Block operation. + * @memberof BlockBlobClient */ - PageBlobClient.prototype.updateSequenceNumber = function (sequenceNumberAction, sequenceNumber, options) { - var _a; + BlockBlobClient.prototype.stageBlock = function (blockId, body, contentLength, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_42; - return tslib.__generator(this, function (_c) { - switch (_c.label) { + var _a, span, spanOptions, e_26; + return tslib.__generator(this, function (_b) { + switch (_b.label) { case 0: - options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-updateSequenceNumber", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - _c.label = 1; + _a = createSpan("BlockBlobClient-stageBlock", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext.updateSequenceNumber(sequenceNumberAction, { + _b.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blockBlobContext.stageBlock(blockId, contentLength, body, { abortSignal: options.abortSignal, - blobSequenceNumber: sequenceNumber, leaseAccessConditions: options.conditions, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + onUploadProgress: options.onProgress, + transactionalContentMD5: options.transactionalContentMD5, + transactionalContentCrc64: options.transactionalContentCrc64, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, spanOptions: spanOptions })]; - case 2: return [2 /*return*/, _c.sent()]; + case 2: return [2 /*return*/, _b.sent()]; case 3: - e_42 = _c.sent(); + e_26 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_42.message + message: e_26.message }); - throw e_42; + throw e_26; case 4: span.end(); return [7 /*endfinally*/]; @@ -31034,156 +31276,113 @@ var PageBlobClient = /** @class */ (function (_super) { }); }; /** - * Begins an operation to start an incremental copy from one page blob's snapshot to this page blob. - * The snapshot is copied such that only the differential changes between the previously - * copied snapshot are transferred to the destination. - * The copied snapshots are complete copies of the original snapshot and can be read or copied from as usual. - * @see https://docs.microsoft.com/rest/api/storageservices/incremental-copy-blob - * @see https://docs.microsoft.com/en-us/azure/virtual-machines/windows/incremental-snapshots + * The Stage Block From URL operation creates a new block to be committed as part + * of a blob where the contents are read from a URL. + * This API is available starting in version 2018-03-28. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-from-url * - * @param {string} copySource Specifies the name of the source page blob snapshot. For example, - * https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= - * @param {PageBlobStartCopyIncrementalOptions} [options] Options to the Page Blob Copy Incremental operation. - * @returns {Promise} Response data for the Page Blob Copy Incremental operation. - * @memberof PageBlobClient + * @param {string} blockId A 64-byte value that is base64-encoded + * @param {string} sourceURL Specifies the URL of the blob. The value + * may be a URL of up to 2 KB in length that specifies a blob. + * The value should be URL-encoded as it would appear + * in a request URI. The source blob must either be public + * or must be authenticated via a shared access signature. + * If the source blob is public, no authentication is required + * to perform the operation. Here are some examples of source object URLs: + * - https://myaccount.blob.core.windows.net/mycontainer/myblob + * - https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= + * @param {number} [offset] From which position of the blob to download, >= 0 + * @param {number} [count] How much data to be downloaded, > 0. Will download to the end when undefined + * @param {BlockBlobStageBlockFromURLOptions} [options={}] Options to the Block Blob Stage Block From URL operation. + * @returns {Promise} Response data for the Block Blob Stage Block From URL operation. + * @memberof BlockBlobClient */ - PageBlobClient.prototype.startCopyIncremental = function (copySource, options) { - var _a; + BlockBlobClient.prototype.stageBlockFromURL = function (blockId, sourceURL, offset, count, options) { + if (offset === void 0) { offset = 0; } if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_43; - return tslib.__generator(this, function (_c) { - switch (_c.label) { + var _a, span, spanOptions, e_27; + return tslib.__generator(this, function (_b) { + switch (_b.label) { case 0: - _b = createSpan("PageBlobClient-startCopyIncremental", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - _c.label = 1; + _a = createSpan("BlockBlobClient-stageBlockFromURL", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext.copyIncremental(copySource, { + _b.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blockBlobContext.stageBlockFromURL(blockId, 0, sourceURL, { abortSignal: options.abortSignal, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + leaseAccessConditions: options.conditions, + sourceContentMD5: options.sourceContentMD5, + sourceContentCrc64: options.sourceContentCrc64, + sourceRange: offset === 0 && !count ? undefined : rangeToString({ offset: offset, count: count }), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, spanOptions: spanOptions })]; - case 2: return [2 /*return*/, _c.sent()]; + case 2: return [2 /*return*/, _b.sent()]; case 3: - e_43 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_43.message - }); - throw e_43; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - return PageBlobClient; -}(BlobClient)); -/** - * A client that manages leases for a {@link ContainerClient} or a {@link BlobClient}. - * - * @export - * @class BlobLeaseClient - */ -var BlobLeaseClient = /** @class */ (function () { - /** - * Creates an instance of BlobLeaseClient. - * @param {(ContainerClient | BlobClient)} client The client to make the lease operation requests. - * @param {string} leaseId Initial proposed lease id. - * @memberof BlobLeaseClient - */ - function BlobLeaseClient(client, leaseId) { - var clientContext = new StorageClientContext(client.url, client.pipeline.toServiceClientOptions()); - this._url = client.url; - if (client instanceof ContainerClient) { - this._isContainer = true; - this._containerOrBlobOperation = new Container(clientContext); - } - else { - this._isContainer = false; - this._containerOrBlobOperation = new Blob$1(clientContext); - } - if (!leaseId) { - leaseId = coreHttp.generateUuid(); - } - this._leaseId = leaseId; - } - Object.defineProperty(BlobLeaseClient.prototype, "leaseId", { - /** - * Gets the lease Id. - * - * @readonly - * @memberof BlobLeaseClient - * @type {string} - */ - get: function () { - return this._leaseId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobLeaseClient.prototype, "url", { - /** - * Gets the url. - * - * @readonly - * @memberof BlobLeaseClient - * @type {string} - */ - get: function () { - return this._url; - }, - enumerable: false, - configurable: true - }); + e_27 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_27.message + }); + throw e_27; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; /** - * Establishes and manages a lock on a container for delete operations, or on a blob - * for write and delete operations. - * The lock duration can be 15 to 60 seconds, or can be infinite. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container - * and - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob + * Writes a blob by specifying the list of block IDs that make up the blob. + * In order to be written as part of a blob, a block must have been successfully written + * to the server in a prior {@link stageBlock} operation. You can call {@link commitBlockList} to + * update a blob by uploading only those blocks that have changed, then committing the new and existing + * blocks together. Any blocks not specified in the block list and permanently deleted. + * @see https://docs.microsoft.com/rest/api/storageservices/put-block-list * - * @param {number} duration Must be between 15 to 60 seconds, or infinite (-1) - * @param {LeaseOperationOptions} [options={}] option to configure lease management operations. - * @returns {Promise} Response data for acquire lease operation. - * @memberof BlobLeaseClient + * @param {string[]} blocks Array of 64-byte value that is base64-encoded + * @param {BlockBlobCommitBlockListOptions} [options] Options to the Block Blob Commit Block List operation. + * @returns {Promise} Response data for the Block Blob Commit Block List operation. + * @memberof BlockBlobClient */ - BlobLeaseClient.prototype.acquireLease = function (duration, options) { - var _a, _b, _c, _d, _e, _f; + BlockBlobClient.prototype.commitBlockList = function (blocks, options) { + var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _g, span, spanOptions, e_44; - return tslib.__generator(this, function (_h) { - switch (_h.label) { + var _b, span, spanOptions, e_28; + return tslib.__generator(this, function (_c) { + switch (_c.label) { case 0: - _g = createSpan("BlobLeaseClient-acquireLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; - if (this._isContainer && - ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || - (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); - } - _h.label = 1; + options.conditions = options.conditions || {}; + _b = createSpan("BlockBlobClient-commitBlockList", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; case 1: - _h.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this._containerOrBlobOperation.acquireLease({ + _c.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blockBlobContext.commitBlockList({ latest: blocks }, { abortSignal: options.abortSignal, - duration: duration, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), - proposedLeaseId: this._leaseId, + blobHTTPHeaders: options.blobHTTPHeaders, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tier: toAccessTier(options.tier), + blobTagsString: toBlobTagsString(options.tags), spanOptions: spanOptions })]; - case 2: return [2 /*return*/, _h.sent()]; + case 2: return [2 /*return*/, _c.sent()]; case 3: - e_44 = _h.sent(); + e_28 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_44.message + message: e_28.message }); - throw e_44; + throw e_28; case 4: span.end(); return [7 /*endfinally*/]; @@ -31193,49 +31392,50 @@ var BlobLeaseClient = /** @class */ (function () { }); }; /** - * To change the ID of the lease. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container - * and - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob + * Returns the list of blocks that have been uploaded as part of a block blob + * using the specified block list filter. + * @see https://docs.microsoft.com/rest/api/storageservices/get-block-list * - * @param {string} proposedLeaseId the proposed new lease Id. - * @param {LeaseOperationOptions} [options={}] option to configure lease management operations. - * @returns {Promise} Response data for change lease operation. - * @memberof BlobLeaseClient + * @param {BlockListType} listType Specifies whether to return the list of committed blocks, + * the list of uncommitted blocks, or both lists together. + * @param {BlockBlobGetBlockListOptions} [options] Options to the Block Blob Get Block List operation. + * @returns {Promise} Response data for the Block Blob Get Block List operation. + * @memberof BlockBlobClient */ - BlobLeaseClient.prototype.changeLease = function (proposedLeaseId, options) { - var _a, _b, _c, _d, _e, _f; + BlockBlobClient.prototype.getBlockList = function (listType, options) { + var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _g, span, spanOptions, response, e_45; - return tslib.__generator(this, function (_h) { - switch (_h.label) { + var _b, span, spanOptions, res, e_29; + return tslib.__generator(this, function (_c) { + switch (_c.label) { case 0: - _g = createSpan("BlobLeaseClient-changeLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; - if (this._isContainer && - ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || - (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); - } - _h.label = 1; + _b = createSpan("BlockBlobClient-getBlockList", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; case 1: - _h.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this._containerOrBlobOperation.changeLease(this._leaseId, proposedLeaseId, { + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.blockBlobContext.getBlockList(listType, { abortSignal: options.abortSignal, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), spanOptions: spanOptions })]; case 2: - response = _h.sent(); - this._leaseId = proposedLeaseId; - return [2 /*return*/, response]; + res = _c.sent(); + if (!res.committedBlocks) { + res.committedBlocks = []; + } + if (!res.uncommittedBlocks) { + res.uncommittedBlocks = []; + } + return [2 /*return*/, res]; case 3: - e_45 = _h.sent(); + e_29 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_45.message + message: e_29.message }); - throw e_45; + throw e_29; case 4: span.end(); return [7 /*endfinally*/]; @@ -31244,47 +31444,95 @@ var BlobLeaseClient = /** @class */ (function () { }); }); }; + // High level functions /** - * To free the lease if it is no longer needed so that another client may - * immediately acquire a lease against the container or the blob. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container - * and - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob + * Uploads a Buffer(Node.js)/Blob(browsers)/ArrayBuffer/ArrayBufferView object to a BlockBlob. * - * @param {LeaseOperationOptions} [options={}] option to configure lease management operations. - * @returns {Promise} Response data for release lease operation. - * @memberof BlobLeaseClient + * When data length is no more than the specifiled {@link BlockBlobParallelUploadOptions.maxSingleShotSize} (default is + * {@link BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}), this method will use 1 {@link upload} call to finish the upload. + * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} + * to commit the block list. + * + * @export + * @param {Buffer | Blob | ArrayBuffer | ArrayBufferView} data Buffer(Node.js), Blob, ArrayBuffer or ArrayBufferView + * @param {BlockBlobParallelUploadOptions} [options] + * @returns {Promise} + * @memberof BlockBlobClient */ - BlobLeaseClient.prototype.releaseLease = function (options) { - var _a, _b, _c, _d, _e, _f; + BlockBlobClient.prototype.uploadData = function (data, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _g, span, spanOptions, e_46; - return tslib.__generator(this, function (_h) { - switch (_h.label) { - case 0: - _g = createSpan("BlobLeaseClient-releaseLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; - if (this._isContainer && - ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || - (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + var _a, span, spanOptions, buffer_1, browserBlob_1; + return tslib.__generator(this, function (_b) { + _a = createSpan("BlockBlobClient-uploadData", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + try { + if (true) { + if (data instanceof Buffer) { + buffer_1 = data; } - _h.label = 1; + else if (data instanceof ArrayBuffer) { + buffer_1 = Buffer.from(data); + } + else { + data = data; + buffer_1 = Buffer.from(data.buffer, data.byteOffset, data.byteLength); + } + return [2 /*return*/, this.uploadSeekableInternal(function (offset, size) { return buffer_1.slice(offset, offset + size); }, buffer_1.byteLength, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + } + else {} + } + catch (e) { + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e.message + }); + throw e; + } + finally { + span.end(); + } + return [2 /*return*/]; + }); + }); + }; + /** + * ONLY AVAILABLE IN BROWSERS. + * + * Uploads a browser Blob/File/ArrayBuffer/ArrayBufferView object to block blob. + * + * When buffer length <= 256MB, this method will use 1 upload call to finish the upload. + * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call + * {@link commitBlockList} to commit the block list. + * + * @deprecated Use {@link uploadData} instead. + * + * @export + * @param {Blob | ArrayBuffer | ArrayBufferView} browserData Blob, File, ArrayBuffer or ArrayBufferView + * @param {BlockBlobParallelUploadOptions} [options] Options to upload browser data. + * @returns {Promise} Response data for the Blob Upload operation. + * @memberof BlockBlobClient + */ + BlockBlobClient.prototype.uploadBrowserData = function (browserData, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, browserBlob_2, e_30; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlockBlobClient-uploadBrowserData", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; case 1: - _h.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this._containerOrBlobOperation.releaseLease(this._leaseId, { - abortSignal: options.abortSignal, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _h.sent()]; + _b.trys.push([1, 3, 4, 5]); + browserBlob_2 = new Blob([browserData]); + return [4 /*yield*/, this.uploadSeekableInternal(function (offset, size) { return browserBlob_2.slice(offset, offset + size); }, browserBlob_2.size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: return [2 /*return*/, _b.sent()]; case 3: - e_46 = _h.sent(); + e_30 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_46.message + message: e_30.message }); - throw e_46; + throw e_30; case 4: span.end(); return [7 /*endfinally*/]; @@ -31294,118 +31542,288 @@ var BlobLeaseClient = /** @class */ (function () { }); }; /** - * To renew the lease. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container - * and - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * - * @param {LeaseOperationOptions} [options={}] Optional option to configure lease management operations. - * @returns {Promise} Response data for renew lease operation. - * @memberof BlobLeaseClient + * Uploads data to block blob. Requires a bodyFactory as the data source, + * which need to return a {@link HttpRequestBody} object with the offset and size provided. + * + * When data length is no more than the specifiled {@link BlockBlobParallelUploadOptions.maxSingleShotSize} (default is + * {@link BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}), this method will use 1 {@link upload} call to finish the upload. + * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} + * to commit the block list. + * + * @param {(offset: number, size: number) => HttpRequestBody} bodyFactory + * @param {number} size size of the data to upload. + * @param {BlockBlobParallelUploadOptions} [options] Options to Upload to Block Blob operation. + * @returns {Promise} Response data for the Blob Upload operation. + * @memberof BlockBlobClient */ - BlobLeaseClient.prototype.renewLease = function (options) { - var _a, _b, _c, _d, _e, _f; + BlockBlobClient.prototype.uploadSeekableInternal = function (bodyFactory, size, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _g, span, spanOptions, e_47; - return tslib.__generator(this, function (_h) { - switch (_h.label) { + var _a, span, spanOptions, numBlocks_1, blockList_1, blockIDPrefix_1, transferProgress_2, batch, _loop_2, i, e_31; + var _this = this; + return tslib.__generator(this, function (_b) { + switch (_b.label) { case 0: - _g = createSpan("BlobLeaseClient-renewLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; - if (this._isContainer && - ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || - (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + if (!options.blockSize) { + options.blockSize = 0; } - _h.label = 1; + if (options.blockSize < 0 || options.blockSize > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES) { + throw new RangeError("blockSize option must be >= 0 and <= " + BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES); + } + if (options.maxSingleShotSize !== 0 && !options.maxSingleShotSize) { + options.maxSingleShotSize = BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES; + } + if (options.maxSingleShotSize < 0 || + options.maxSingleShotSize > BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES) { + throw new RangeError("maxSingleShotSize option must be >= 0 and <= " + BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES); + } + if (options.blockSize === 0) { + if (size > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES * BLOCK_BLOB_MAX_BLOCKS) { + throw new RangeError(size + " is too larger to upload to a block blob."); + } + if (size > options.maxSingleShotSize) { + options.blockSize = Math.ceil(size / BLOCK_BLOB_MAX_BLOCKS); + if (options.blockSize < DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES) { + options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; + } + } + } + if (!options.blobHTTPHeaders) { + options.blobHTTPHeaders = {}; + } + if (!options.conditions) { + options.conditions = {}; + } + _a = createSpan("BlockBlobClient-uploadSeekableInternal", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; case 1: - _h.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this._containerOrBlobOperation.renewLease(this._leaseId, { - abortSignal: options.abortSignal, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _h.sent()]; + _b.trys.push([1, 5, 6, 7]); + if (!(size <= options.maxSingleShotSize)) return [3 /*break*/, 3]; + return [4 /*yield*/, this.upload(bodyFactory(0, size), size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: return [2 /*return*/, _b.sent()]; case 3: - e_47 = _h.sent(); + numBlocks_1 = Math.floor((size - 1) / options.blockSize) + 1; + if (numBlocks_1 > BLOCK_BLOB_MAX_BLOCKS) { + throw new RangeError("The buffer's size is too big or the BlockSize is too small;" + + ("the number of blocks must be <= " + BLOCK_BLOB_MAX_BLOCKS)); + } + blockList_1 = []; + blockIDPrefix_1 = coreHttp.generateUuid(); + transferProgress_2 = 0; + batch = new Batch(options.concurrency); + _loop_2 = function (i) { + batch.addOperation(function () { return tslib.__awaiter(_this, void 0, void 0, function () { + var blockID, start, end, contentLength; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + blockID = generateBlockID(blockIDPrefix_1, i); + start = options.blockSize * i; + end = i === numBlocks_1 - 1 ? size : start + options.blockSize; + contentLength = end - start; + blockList_1.push(blockID); + return [4 /*yield*/, this.stageBlock(blockID, bodyFactory(start, contentLength), contentLength, { + abortSignal: options.abortSignal, + conditions: options.conditions, + encryptionScope: options.encryptionScope, + tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) + })]; + case 1: + _a.sent(); + // Update progress after block is successfully uploaded to server, in case of block trying + // TODO: Hook with convenience layer progress event in finer level + transferProgress_2 += contentLength; + if (options.onProgress) { + options.onProgress({ + loadedBytes: transferProgress_2 + }); + } + return [2 /*return*/]; + } + }); + }); }); + }; + for (i = 0; i < numBlocks_1; i++) { + _loop_2(i); + } + return [4 /*yield*/, batch.do()]; + case 4: + _b.sent(); + return [2 /*return*/, this.commitBlockList(blockList_1, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 5: + e_31 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_47.message + message: e_31.message }); - throw e_47; + throw e_31; + case 6: + span.end(); + return [7 /*endfinally*/]; + case 7: return [2 /*return*/]; + } + }); + }); + }; + /** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * Uploads a local file in blocks to a block blob. + * + * When file size <= 256MB, this method will use 1 upload call to finish the upload. + * Otherwise, this method will call stageBlock to upload blocks, and finally call commitBlockList + * to commit the block list. + * + * @param {string} filePath Full path of local file + * @param {BlockBlobParallelUploadOptions} [options] Options to Upload to Block Blob operation. + * @returns {(Promise)} Response data for the Blob Upload operation. + * @memberof BlockBlobClient + */ + BlockBlobClient.prototype.uploadFile = function (filePath, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, size, e_32; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlockBlobClient-uploadFile", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 4, 5, 6]); + return [4 /*yield*/, fsStat(filePath)]; + case 2: + size = (_b.sent()).size; + return [4 /*yield*/, this.uploadSeekableInternal(function (offset, count) { + return function () { + return fsCreateReadStream(filePath, { + autoClose: true, + end: count ? offset + count - 1 : Infinity, + start: offset + }); + }; + }, size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 3: return [2 /*return*/, _b.sent()]; case 4: + e_32 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_32.message + }); + throw e_32; + case 5: span.end(); return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + case 6: return [2 /*return*/]; } }); }); }; /** - * To end the lease but ensure that another client cannot acquire a new lease - * until the current lease period has expired. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container - * and - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob + * ONLY AVAILABLE IN NODE.JS RUNTIME. * - * @static - * @param {number} breakPeriod Break period - * @param {LeaseOperationOptions} [options={}] Optional options to configure lease management operations. - * @returns {Promise} Response data for break lease operation. - * @memberof BlobLeaseClient + * Uploads a Node.js Readable stream into block blob. + * + * PERFORMANCE IMPROVEMENT TIPS: + * * Input stream highWaterMark is better to set a same value with bufferSize + * parameter, which will avoid Buffer.concat() operations. + * + * @param {Readable} stream Node.js Readable stream + * @param {number} bufferSize Size of every buffer allocated, also the block size in the uploaded block blob. Default value is 8MB + * @param {number} maxConcurrency Max concurrency indicates the max number of buffers that can be allocated, + * positive correlation with max uploading concurrency. Default value is 5 + * @param {BlockBlobUploadStreamOptions} [options] Options to Upload Stream to Block Blob operation. + * @returns {Promise} Response data for the Blob Upload operation. + * @memberof BlockBlobClient */ - BlobLeaseClient.prototype.breakLease = function (breakPeriod, options) { - var _a, _b, _c, _d, _e, _f; + BlockBlobClient.prototype.uploadStream = function (stream, bufferSize, maxConcurrency, options) { + if (bufferSize === void 0) { bufferSize = DEFAULT_BLOCK_BUFFER_SIZE_BYTES; } + if (maxConcurrency === void 0) { maxConcurrency = 5; } if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _g, span, spanOptions, operationOptions, e_48; - return tslib.__generator(this, function (_h) { - switch (_h.label) { + var _a, span, spanOptions, blockNum_1, blockIDPrefix_2, transferProgress_3, blockList_2, scheduler, e_33; + var _this = this; + return tslib.__generator(this, function (_b) { + switch (_b.label) { case 0: - _g = createSpan("BlobLeaseClient-breakLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; - if (this._isContainer && - ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || - (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + if (!options.blobHTTPHeaders) { + options.blobHTTPHeaders = {}; } - _h.label = 1; + if (!options.conditions) { + options.conditions = {}; + } + _a = createSpan("BlockBlobClient-uploadStream", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; case 1: - _h.trys.push([1, 3, 4, 5]); - operationOptions = { - abortSignal: options.abortSignal, - breakPeriod: breakPeriod, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), - spanOptions: spanOptions - }; - return [4 /*yield*/, this._containerOrBlobOperation.breakLease(operationOptions)]; - case 2: return [2 /*return*/, _h.sent()]; - case 3: - e_48 = _h.sent(); + _b.trys.push([1, 4, 5, 6]); + blockNum_1 = 0; + blockIDPrefix_2 = coreHttp.generateUuid(); + transferProgress_3 = 0; + blockList_2 = []; + scheduler = new BufferScheduler(stream, bufferSize, maxConcurrency, function (body, length) { return tslib.__awaiter(_this, void 0, void 0, function () { + var blockID; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + blockID = generateBlockID(blockIDPrefix_2, blockNum_1); + blockList_2.push(blockID); + blockNum_1++; + return [4 /*yield*/, this.stageBlock(blockID, body, length, { + conditions: options.conditions, + encryptionScope: options.encryptionScope, + tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) + })]; + case 1: + _a.sent(); + // Update progress after block is successfully uploaded to server, in case of block trying + transferProgress_3 += length; + if (options.onProgress) { + options.onProgress({ loadedBytes: transferProgress_3 }); + } + return [2 /*return*/]; + } + }); + }); }, + // concurrency should set a smaller value than maxConcurrency, which is helpful to + // reduce the possibility when a outgoing handler waits for stream data, in + // this situation, outgoing handlers are blocked. + // Outgoing queue shouldn't be empty. + Math.ceil((maxConcurrency / 4) * 3)); + return [4 /*yield*/, scheduler.do()]; + case 2: + _b.sent(); + return [4 /*yield*/, this.commitBlockList(blockList_2, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 3: return [2 /*return*/, _b.sent()]; + case 4: + e_33 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_48.message + message: e_33.message }); - throw e_48; - case 4: + throw e_33; + case 5: span.end(); return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + case 6: return [2 /*return*/]; } }); }); }; - return BlobLeaseClient; -}()); + return BlockBlobClient; +}(BlobClient)); /** - * A ContainerClient represents a URL to the Azure Storage container allowing you to manipulate its blobs. + * PageBlobClient defines a set of operations applicable to page blobs. * * @export - * @class ContainerClient + * @class PageBlobClient + * @extends {BlobClient} */ -var ContainerClient = /** @class */ (function (_super) { - tslib.__extends(ContainerClient, _super); - function ContainerClient(urlOrConnectionString, credentialOrPipelineOrContainerName, options) { +var PageBlobClient = /** @class */ (function (_super) { + tslib.__extends(PageBlobClient, _super); + function PageBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { var _this = this; + // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. + // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); var pipeline; var url; options = options || {}; @@ -31419,6 +31837,7 @@ var ContainerClient = /** @class */ (function (_super) { coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) url = urlOrConnectionString; + options = blobNameOrOptions; pipeline = newPipeline(credentialOrPipelineOrContainerName, options); } else if (!credentialOrPipelineOrContainerName && @@ -31429,21 +31848,24 @@ var ContainerClient = /** @class */ (function (_super) { pipeline = newPipeline(new AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && - typeof credentialOrPipelineOrContainerName === "string") { + typeof credentialOrPipelineOrContainerName === "string" && + blobNameOrOptions && + typeof blobNameOrOptions === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) var containerName = credentialOrPipelineOrContainerName; + var blobName = blobNameOrOptions; var extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { { var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - url = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)); + url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); pipeline = newPipeline(sharedKeyCredential, options); } } else if (extractedCreds.kind === "SASConnString") { url = - appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)) + + appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + "?" + extractedCreds.accountSas; pipeline = newPipeline(new AnonymousCredential(), options); @@ -31453,63 +31875,69 @@ var ContainerClient = /** @class */ (function (_super) { } } else { - throw new Error("Expecting non-empty strings for containerName parameter"); + throw new Error("Expecting non-empty strings for containerName and blobName parameters"); } _this = _super.call(this, url, pipeline) || this; - _this._containerName = _this.getContainerNameFromUrl(); - _this.containerContext = new Container(_this.storageClientContext); + _this.pageBlobContext = new PageBlob(_this.storageClientContext); return _this; } - Object.defineProperty(ContainerClient.prototype, "containerName", { - /** - * The name of the container. - */ - get: function () { - return this._containerName; - }, - enumerable: false, - configurable: true - }); /** - * Creates a new container under the specified account. If the container with - * the same name already exists, the operation fails. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container - * - * @param {ContainerCreateOptions} [options] Options to Container Create operation. - * @returns {Promise} - * @memberof ContainerClient + * Creates a new PageBlobClient object identical to the source but with the + * specified snapshot timestamp. + * Provide "" will remove the snapshot and return a Client to the base blob. * - * Example usage: + * @param {string} snapshot The snapshot timestamp. + * @returns {PageBlobClient} A new PageBlobClient object identical to the source but with the specified snapshot timestamp. + * @memberof PageBlobClient + */ + PageBlobClient.prototype.withSnapshot = function (snapshot) { + return new PageBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); + }; + /** + * Creates a page blob of the specified length. Call uploadPages to upload data + * data to a page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * - * ```js - * const containerClient = blobServiceClient.getContainerClient(""); - * const createContainerResponse = await containerClient.create(); - * console.log("Container was created successfully", createContainerResponse.requestId); - * ``` + * @param {number} size size of the page blob. + * @param {PageBlobCreateOptions} [options] Options to the Page Blob Create operation. + * @returns {Promise} Response data for the Page Blob Create operation. + * @memberof PageBlobClient */ - ContainerClient.prototype.create = function (options) { + PageBlobClient.prototype.create = function (size, options) { + var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_49; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var _b, span, spanOptions, e_34; + return tslib.__generator(this, function (_c) { + switch (_c.label) { case 0: - _a = createSpan("ContainerClient-create", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-create", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.create(tslib.__assign(tslib.__assign({}, options), { spanOptions: spanOptions }))]; - case 2: - // Spread operator in destructuring assignments, - // this will filter out unwanted properties from the response object into result object - return [2 /*return*/, _b.sent()]; + _c.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.pageBlobContext.create(0, size, { + abortSignal: options.abortSignal, + blobHTTPHeaders: options.blobHTTPHeaders, + blobSequenceNumber: options.blobSequenceNumber, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tier: toAccessTier(options.tier), + blobTagsString: toBlobTagsString(options.tags), + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; case 3: - e_49 = _b.sent(); + e_34 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_49.message + message: e_34.message }); - throw e_49; + throw e_34; case 4: span.end(); return [7 /*endfinally*/]; @@ -31519,45 +31947,48 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * Creates a new container under the specified account. If the container with - * the same name already exists, it is not changed. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container + * Creates a page blob of the specified length. Call uploadPages to upload data + * data to a page blob. If the blob with the same name already exists, the content + * of the existing blob will remain unchanged. + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * - * @param {ContainerCreateOptions} [options] - * @returns {Promise} - * @memberof ContainerClient + * @param {number} size size of the page blob. + * @param {PageBlobCreateIfNotExistsOptions} [options] + * @returns {Promise} + * @memberof PageBlobClient */ - ContainerClient.prototype.createIfNotExists = function (options) { + PageBlobClient.prototype.createIfNotExists = function (size, options) { var _a, _b; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _c, span, spanOptions, res, e_50; + var _c, span, spanOptions, conditions, res, e_35; return tslib.__generator(this, function (_d) { switch (_d.label) { case 0: - _c = createSpan("ContainerClient-createIfNotExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; + _c = createSpan("PageBlobClient-createIfNotExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; _d.label = 1; case 1: _d.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.create(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + conditions = { ifNoneMatch: ETagAny }; + return [4 /*yield*/, this.create(size, tslib.__assign(tslib.__assign({}, options), { conditions: conditions, tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: res = _d.sent(); return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable })]; case 3: - e_50 = _d.sent(); - if (((_a = e_50.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerAlreadyExists") { + e_35 = _d.sent(); + if (((_a = e_35.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { span.setStatus({ code: api.CanonicalCode.ALREADY_EXISTS, - message: "Expected exception when creating a container only if it does not already exist." + message: "Expected exception when creating a blob only if it does not already exist." }); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_50.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_50.response })]; + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_35.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_35.response })]; } span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_50.message + message: e_35.message }); - throw e_50; + throw e_35; case 4: span.end(); return [7 /*endfinally*/]; @@ -31567,48 +31998,51 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * Returns true if the Azure container resource represented by this client exists; false otherwise. - * - * NOTE: use this function with care since an existing container might be deleted by other clients or - * applications. Vice versa new containers with the same name might be added by other clients or - * applications after this function completes. + * Writes 1 or more pages to the page blob. The start and end offsets must be a multiple of 512. + * @see https://docs.microsoft.com/rest/api/storageservices/put-page * - * @param {ContainerExistsOptions} [options={}] - * @returns {Promise} - * @memberof ContainerClient + * @param {HttpRequestBody} body Data to upload + * @param {number} offset Offset of destination page blob + * @param {number} count Content length of the body, also number of bytes to be uploaded + * @param {PageBlobUploadPagesOptions} [options] Options to the Page Blob Upload Pages operation. + * @returns {Promise} Response data for the Page Blob Upload Pages operation. + * @memberof PageBlobClient */ - ContainerClient.prototype.exists = function (options) { + PageBlobClient.prototype.uploadPages = function (body, offset, count, options) { + var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_51; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var _b, span, spanOptions, e_36; + return tslib.__generator(this, function (_c) { + switch (_c.label) { case 0: - _a = createSpan("ContainerClient-exists", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-uploadPages", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.getProperties({ + _c.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.pageBlobContext.uploadPages(body, count, { abortSignal: options.abortSignal, - tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + onUploadProgress: options.onProgress, + range: rangeToString({ offset: offset, count: count }), + sequenceNumberAccessConditions: options.conditions, + transactionalContentMD5: options.transactionalContentMD5, + transactionalContentCrc64: options.transactionalContentCrc64, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + spanOptions: spanOptions })]; - case 2: - _b.sent(); - return [2 /*return*/, true]; + case 2: return [2 /*return*/, _c.sent()]; case 3: - e_51 = _b.sent(); - if (e_51.statusCode === 404) { - span.setStatus({ - code: api.CanonicalCode.NOT_FOUND, - message: "Expected exception when checking container existence" - }); - return [2 /*return*/, false]; - } + e_36 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_51.message + message: e_36.message }); - throw e_51; + throw e_36; case 4: span.end(); return [7 /*endfinally*/]; @@ -31618,91 +32052,302 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * Creates a {@link BlobClient} + * The Upload Pages operation writes a range of pages to a page blob where the + * contents are read from a URL. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-page-from-url * - * @param {string} blobName A blob name - * @returns {BlobClient} A new BlobClient object for the given blob name. - * @memberof ContainerClient + * @param {string} sourceURL Specify a URL to the copy source, Shared Access Signature(SAS) maybe needed for authentication + * @param {number} sourceOffset The source offset to copy from. Pass 0 to copy from the beginning of source page blob + * @param {number} destOffset Offset of destination page blob + * @param {number} count Number of bytes to be uploaded from source page blob + * @param {PageBlobUploadPagesFromURLOptions} [options={}] + * @returns {Promise} + * @memberof PageBlobClient */ - ContainerClient.prototype.getBlobClient = function (blobName) { - return new BlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); + PageBlobClient.prototype.uploadPagesFromURL = function (sourceURL, sourceOffset, destOffset, count, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_37; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + _b = createSpan("PageBlobClient-uploadPagesFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.pageBlobContext.uploadPagesFromURL(sourceURL, rangeToString({ offset: sourceOffset, count: count }), 0, rangeToString({ offset: destOffset, count: count }), { + abortSignal: options.abortSignal, + sourceContentMD5: options.sourceContentMD5, + sourceContentCrc64: options.sourceContentCrc64, + leaseAccessConditions: options.conditions, + sequenceNumberAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince + }, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_37 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_37.message + }); + throw e_37; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; /** - * Creates an {@link AppendBlobClient} + * Frees the specified pages from the page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/put-page * - * @param {string} blobName An append blob name - * @returns {AppendBlobClient} - * @memberof ContainerClient + * @param {number} [offset] Starting byte position of the pages to clear. + * @param {number} [count] Number of bytes to clear. + * @param {PageBlobClearPagesOptions} [options] Options to the Page Blob Clear Pages operation. + * @returns {Promise} Response data for the Page Blob Clear Pages operation. + * @memberof PageBlobClient */ - ContainerClient.prototype.getAppendBlobClient = function (blobName) { - return new AppendBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); + PageBlobClient.prototype.clearPages = function (offset, count, options) { + var _a; + if (offset === void 0) { offset = 0; } + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_38; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-clearPages", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext.clearPages(0, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + range: rangeToString({ offset: offset, count: count }), + sequenceNumberAccessConditions: options.conditions, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_38 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_38.message + }); + throw e_38; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; /** - * Creates a {@link BlockBlobClient} - * - * @param {string} blobName A block blob name - * @returns {BlockBlobClient} - * @memberof ContainerClient - * - * Example usage: - * - * ```js - * const content = "Hello world!"; + * Returns the list of valid page ranges for a page blob or snapshot of a page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges * - * const blockBlobClient = containerClient.getBlockBlobClient(""); - * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); - * ``` + * @param {number} [offset] Starting byte position of the page ranges. + * @param {number} [count] Number of bytes to get. + * @param {PageBlobGetPageRangesOptions} [options] Options to the Page Blob Get Ranges operation. + * @returns {Promise} Response data for the Page Blob Get Ranges operation. + * @memberof PageBlobClient */ - ContainerClient.prototype.getBlockBlobClient = function (blobName) { - return new BlockBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); + PageBlobClient.prototype.getPageRanges = function (offset, count, options) { + var _a; + if (offset === void 0) { offset = 0; } + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_39; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-getPageRanges", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext + .getPageRanges({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + range: rangeToString({ offset: offset, count: count }), + spanOptions: spanOptions + }) + .then(rangeResponseFromModel)]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_39 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_39.message + }); + throw e_39; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; /** - * Creates a {@link PageBlobClient} + * Gets the collection of page ranges that differ between a specified snapshot and this page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges * - * @param {string} blobName A page blob name - * @returns {PageBlobClient} - * @memberof ContainerClient + * @param {number} offset Starting byte position of the page blob + * @param {number} count Number of bytes to get ranges diff. + * @param {string} prevSnapshot Timestamp of snapshot to retrieve the difference. + * @param {PageBlobGetPageRangesDiffOptions} [options] Options to the Page Blob Get Page Ranges Diff operation. + * @returns {Promise} Response data for the Page Blob Get Page Range Diff operation. + * @memberof PageBlobClient */ - ContainerClient.prototype.getPageBlobClient = function (blobName) { - return new PageBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); + PageBlobClient.prototype.getPageRangesDiff = function (offset, count, prevSnapshot, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_40; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-getPageRangesDiff", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext + .getPageRangesDiff({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + prevsnapshot: prevSnapshot, + range: rangeToString({ offset: offset, count: count }), + spanOptions: spanOptions + }) + .then(rangeResponseFromModel)]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_40 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_40.message + }); + throw e_40; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; /** - * Returns all user-defined metadata and system properties for the specified - * container. The data returned does not include the container's list of blobs. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-properties - * - * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if - * they originally contained uppercase characters. This differs from the metadata keys returned by - * the `listContainers` method of {@link BlobServiceClient} using the `includeMetadata` option, which - * will retain their original casing. + * Gets the collection of page ranges that differ between a specified snapshot and this page blob for managed disks. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges * - * @param {ContainerGetPropertiesOptions} [options] Options to Container Get Properties operation. - * @returns {Promise} - * @memberof ContainerClient + * @param {number} offset Starting byte position of the page blob + * @param {number} count Number of bytes to get ranges diff. + * @param {string} prevSnapshotUrl URL of snapshot to retrieve the difference. + * @param {PageBlobGetPageRangesDiffOptions} [options] Options to the Page Blob Get Page Ranges Diff operation. + * @returns {Promise} Response data for the Page Blob Get Page Range Diff operation. + * @memberof PageBlobClient */ - ContainerClient.prototype.getProperties = function (options) { + PageBlobClient.prototype.getPageRangesDiffForManagedDisks = function (offset, count, prevSnapshotUrl, options) { + var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_52; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var _b, span, spanOptions, e_41; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-GetPageRangesDiffForManagedDisks", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext + .getPageRangesDiff({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + prevSnapshotUrl: prevSnapshotUrl, + range: rangeToString({ offset: offset, count: count }), + spanOptions: spanOptions + }) + .then(rangeResponseFromModel)]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_41 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_41.message + }); + throw e_41; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Resizes the page blob to the specified size (which must be a multiple of 512). + * @see https://docs.microsoft.com/rest/api/storageservices/set-blob-properties + * + * @param {number} size Target size + * @param {PageBlobResizeOptions} [options] Options to the Page Blob Resize operation. + * @returns {Promise} Response data for the Page Blob Resize operation. + * @memberof PageBlobClient + */ + PageBlobClient.prototype.resize = function (size, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_42; + return tslib.__generator(this, function (_c) { + switch (_c.label) { case 0: - if (!options.conditions) { - options.conditions = {}; - } - _a = createSpan("ContainerClient-getProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-resize", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.getProperties(tslib.__assign(tslib.__assign({ abortSignal: options.abortSignal }, options.conditions), { spanOptions: spanOptions }))]; - case 2: return [2 /*return*/, _b.sent()]; + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext.resize(size, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + encryptionScope: options.encryptionScope, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; case 3: - e_52 = _b.sent(); + e_42 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_52.message + message: e_42.message }); - throw e_52; + throw e_42; case 4: span.end(); return [7 /*endfinally*/]; @@ -31712,42 +32357,43 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * Marks the specified container for deletion. The container and any blobs - * contained within it are later deleted during garbage collection. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container + * Sets a page blob's sequence number. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties * - * @param {ContainerDeleteMethodOptions} [options] Options to Container Delete operation. - * @returns {Promise} - * @memberof ContainerClient + * @param {SequenceNumberActionType} sequenceNumberAction Indicates how the service should modify the blob's sequence number. + * @param {number} [sequenceNumber] Required if sequenceNumberAction is max or update + * @param {PageBlobUpdateSequenceNumberOptions} [options] Options to the Page Blob Update Sequence Number operation. + * @returns {Promise} Response data for the Page Blob Update Sequence Number operation. + * @memberof PageBlobClient */ - ContainerClient.prototype.delete = function (options) { + PageBlobClient.prototype.updateSequenceNumber = function (sequenceNumberAction, sequenceNumber, options) { + var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_53; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var _b, span, spanOptions, e_43; + return tslib.__generator(this, function (_c) { + switch (_c.label) { case 0: - if (!options.conditions) { - options.conditions = {}; - } - _a = createSpan("ContainerClient-delete", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-updateSequenceNumber", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.deleteMethod({ + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext.updateSequenceNumber(sequenceNumberAction, { abortSignal: options.abortSignal, + blobSequenceNumber: sequenceNumber, leaseAccessConditions: options.conditions, - modifiedAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), spanOptions: spanOptions })]; - case 2: return [2 /*return*/, _b.sent()]; + case 2: return [2 /*return*/, _c.sent()]; case 3: - e_53 = _b.sent(); + e_43 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_53.message + message: e_43.message }); - throw e_53; + throw e_43; case 4: span.end(); return [7 /*endfinally*/]; @@ -31757,45 +32403,44 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * Marks the specified container for deletion if it exists. The container and any blobs - * contained within it are later deleted during garbage collection. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container + * Begins an operation to start an incremental copy from one page blob's snapshot to this page blob. + * The snapshot is copied such that only the differential changes between the previously + * copied snapshot are transferred to the destination. + * The copied snapshots are complete copies of the original snapshot and can be read or copied from as usual. + * @see https://docs.microsoft.com/rest/api/storageservices/incremental-copy-blob + * @see https://docs.microsoft.com/en-us/azure/virtual-machines/windows/incremental-snapshots * - * @param {ContainerDeleteMethodOptions} [options] Options to Container Delete operation. - * @returns {Promise} - * @memberof ContainerClient + * @param {string} copySource Specifies the name of the source page blob snapshot. For example, + * https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= + * @param {PageBlobStartCopyIncrementalOptions} [options] Options to the Page Blob Copy Incremental operation. + * @returns {Promise} Response data for the Page Blob Copy Incremental operation. + * @memberof PageBlobClient */ - ContainerClient.prototype.deleteIfExists = function (options) { - var _a, _b; + PageBlobClient.prototype.startCopyIncremental = function (copySource, options) { + var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _c, span, spanOptions, res, e_54; - return tslib.__generator(this, function (_d) { - switch (_d.label) { + var _b, span, spanOptions, e_44; + return tslib.__generator(this, function (_c) { + switch (_c.label) { case 0: - _c = createSpan("ContainerClient-deleteIfExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; - _d.label = 1; + _b = createSpan("PageBlobClient-startCopyIncremental", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; case 1: - _d.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: - res = _d.sent(); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable - })]; + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext.copyIncremental(copySource, { + abortSignal: options.abortSignal, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; case 3: - e_54 = _d.sent(); - if (((_a = e_54.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerNotFound") { - span.setStatus({ - code: api.CanonicalCode.NOT_FOUND, - message: "Expected exception when deleting a container only if it exists." - }); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_54.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_54.response })]; - } + e_44 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_54.message + message: e_44.message }); - throw e_54; + throw e_44; case 4: span.end(); return [7 /*endfinally*/]; @@ -31804,52 +32449,110 @@ var ContainerClient = /** @class */ (function (_super) { }); }); }; + return PageBlobClient; +}(BlobClient)); +/** + * A client that manages leases for a {@link ContainerClient} or a {@link BlobClient}. + * + * @export + * @class BlobLeaseClient + */ +var BlobLeaseClient = /** @class */ (function () { /** - * Sets one or more user-defined name-value pairs for the specified container. - * - * If no option provided, or no metadata defined in the parameter, the container - * metadata will be removed. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-metadata + * Creates an instance of BlobLeaseClient. + * @param {(ContainerClient | BlobClient)} client The client to make the lease operation requests. + * @param {string} leaseId Initial proposed lease id. + * @memberof BlobLeaseClient + */ + function BlobLeaseClient(client, leaseId) { + var clientContext = new StorageClientContext(client.url, client.pipeline.toServiceClientOptions()); + this._url = client.url; + if (client instanceof ContainerClient) { + this._isContainer = true; + this._containerOrBlobOperation = new Container(clientContext); + } + else { + this._isContainer = false; + this._containerOrBlobOperation = new Blob$1(clientContext); + } + if (!leaseId) { + leaseId = coreHttp.generateUuid(); + } + this._leaseId = leaseId; + } + Object.defineProperty(BlobLeaseClient.prototype, "leaseId", { + /** + * Gets the lease Id. + * + * @readonly + * @memberof BlobLeaseClient + * @type {string} + */ + get: function () { + return this._leaseId; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobLeaseClient.prototype, "url", { + /** + * Gets the url. + * + * @readonly + * @memberof BlobLeaseClient + * @type {string} + */ + get: function () { + return this._url; + }, + enumerable: false, + configurable: true + }); + /** + * Establishes and manages a lock on a container for delete operations, or on a blob + * for write and delete operations. + * The lock duration can be 15 to 60 seconds, or can be infinite. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container + * and + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * - * @param {Metadata} [metadata] Replace existing metadata with this value. - * If no value provided the existing metadata will be removed. - * @param {ContainerSetMetadataOptions} [options] Options to Container Set Metadata operation. - * @returns {Promise} - * @memberof ContainerClient + * @param {number} duration Must be between 15 to 60 seconds, or infinite (-1) + * @param {LeaseOperationOptions} [options={}] option to configure lease management operations. + * @returns {Promise} Response data for acquire lease operation. + * @memberof BlobLeaseClient */ - ContainerClient.prototype.setMetadata = function (metadata, options) { + BlobLeaseClient.prototype.acquireLease = function (duration, options) { + var _a, _b, _c, _d, _e, _f; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_55; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var _g, span, spanOptions, e_45; + return tslib.__generator(this, function (_h) { + switch (_h.label) { case 0: - if (!options.conditions) { - options.conditions = {}; - } - if (options.conditions.ifUnmodifiedSince) { - throw new RangeError("the IfUnmodifiedSince must have their default values because they are ignored by the blob service"); + _g = createSpan("BlobLeaseClient-acquireLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); } - _a = createSpan("ContainerClient-setMetadata", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + _h.label = 1; case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.setMetadata({ + _h.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this._containerOrBlobOperation.acquireLease({ abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - metadata: metadata, - modifiedAccessConditions: options.conditions, + duration: duration, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), + proposedLeaseId: this._leaseId, spanOptions: spanOptions })]; - case 2: return [2 /*return*/, _b.sent()]; + case 2: return [2 /*return*/, _h.sent()]; case 3: - e_55 = _b.sent(); + e_45 = _h.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_55.message + message: e_45.message }); - throw e_55; + throw e_45; case 4: span.end(); return [7 /*endfinally*/]; @@ -31859,78 +32562,49 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * Gets the permissions for the specified container. The permissions indicate - * whether container data may be accessed publicly. - * - * WARNING: JavaScript Date will potentially lose precision when parsing startsOn and expiresOn strings. - * For example, new Date("2018-12-31T03:44:23.8827891Z").toISOString() will get "2018-12-31T03:44:23.882Z". - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-acl + * To change the ID of the lease. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container + * and + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * - * @param {ContainerGetAccessPolicyOptions} [options] Options to Container Get Access Policy operation. - * @returns {Promise} - * @memberof ContainerClient + * @param {string} proposedLeaseId the proposed new lease Id. + * @param {LeaseOperationOptions} [options={}] option to configure lease management operations. + * @returns {Promise} Response data for change lease operation. + * @memberof BlobLeaseClient */ - ContainerClient.prototype.getAccessPolicy = function (options) { + BlobLeaseClient.prototype.changeLease = function (proposedLeaseId, options) { + var _a, _b, _c, _d, _e, _f; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, response, res, _i, response_1, identifier, accessPolicy, e_56; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var _g, span, spanOptions, response, e_46; + return tslib.__generator(this, function (_h) { + switch (_h.label) { case 0: - if (!options.conditions) { - options.conditions = {}; + _g = createSpan("BlobLeaseClient-changeLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); } - _a = createSpan("ContainerClient-getAccessPolicy", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + _h.label = 1; case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.getAccessPolicy({ + _h.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this._containerOrBlobOperation.changeLease(this._leaseId, proposedLeaseId, { abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), spanOptions: spanOptions })]; case 2: - response = _b.sent(); - res = { - _response: response._response, - blobPublicAccess: response.blobPublicAccess, - date: response.date, - etag: response.etag, - errorCode: response.errorCode, - lastModified: response.lastModified, - requestId: response.requestId, - clientRequestId: response.clientRequestId, - signedIdentifiers: [], - version: response.version - }; - for (_i = 0, response_1 = response; _i < response_1.length; _i++) { - identifier = response_1[_i]; - accessPolicy = undefined; - if (identifier.accessPolicy) { - accessPolicy = { - permissions: identifier.accessPolicy.permissions - }; - if (identifier.accessPolicy.expiresOn) { - accessPolicy.expiresOn = new Date(identifier.accessPolicy.expiresOn); - } - if (identifier.accessPolicy.startsOn) { - accessPolicy.startsOn = new Date(identifier.accessPolicy.startsOn); - } - } - res.signedIdentifiers.push({ - accessPolicy: accessPolicy, - id: identifier.id - }); - } - return [2 /*return*/, res]; + response = _h.sent(); + this._leaseId = proposedLeaseId; + return [2 /*return*/, response]; case 3: - e_56 = _b.sent(); + e_46 = _h.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_56.message + message: e_46.message }); - throw e_56; + throw e_46; case 4: span.end(); return [7 /*endfinally*/]; @@ -31940,68 +32614,46 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * Sets the permissions for the specified container. The permissions indicate - * whether blobs in a container may be accessed publicly. - * - * When you set permissions for a container, the existing permissions are replaced. - * If no access or containerAcl provided, the existing container ACL will be - * removed. - * - * When you establish a stored access policy on a container, it may take up to 30 seconds to take effect. - * During this interval, a shared access signature that is associated with the stored access policy will - * fail with status code 403 (Forbidden), until the access policy becomes active. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-acl + * To free the lease if it is no longer needed so that another client may + * immediately acquire a lease against the container or the blob. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container + * and + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * - * @param {PublicAccessType} [access] The level of public access to data in the container. - * @param {SignedIdentifier[]} [containerAcl] Array of elements each having a unique Id and details of the access policy. - * @param {ContainerSetAccessPolicyOptions} [options] Options to Container Set Access Policy operation. - * @returns {Promise} - * @memberof ContainerClient + * @param {LeaseOperationOptions} [options={}] option to configure lease management operations. + * @returns {Promise} Response data for release lease operation. + * @memberof BlobLeaseClient */ - ContainerClient.prototype.setAccessPolicy = function (access, containerAcl, options) { + BlobLeaseClient.prototype.releaseLease = function (options) { + var _a, _b, _c, _d, _e, _f; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, acl, _i, _b, identifier, e_57; - return tslib.__generator(this, function (_c) { - switch (_c.label) { + var _g, span, spanOptions, e_47; + return tslib.__generator(this, function (_h) { + switch (_h.label) { case 0: - options.conditions = options.conditions || {}; - _a = createSpan("ContainerClient-setAccessPolicy", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - acl = []; - for (_i = 0, _b = containerAcl || []; _i < _b.length; _i++) { - identifier = _b[_i]; - acl.push({ - accessPolicy: { - expiresOn: identifier.accessPolicy.expiresOn - ? truncatedISO8061Date(identifier.accessPolicy.expiresOn) - : "", - permissions: identifier.accessPolicy.permissions, - startsOn: identifier.accessPolicy.startsOn - ? truncatedISO8061Date(identifier.accessPolicy.startsOn) - : "" - }, - id: identifier.id - }); + _g = createSpan("BlobLeaseClient-releaseLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); } - return [4 /*yield*/, this.containerContext.setAccessPolicy({ + _h.label = 1; + case 1: + _h.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this._containerOrBlobOperation.releaseLease(this._leaseId, { abortSignal: options.abortSignal, - access: access, - containerAcl: acl, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), spanOptions: spanOptions })]; - case 2: return [2 /*return*/, _c.sent()]; + case 2: return [2 /*return*/, _h.sent()]; case 3: - e_57 = _c.sent(); + e_47 = _h.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_57.message + message: e_47.message }); - throw e_57; + throw e_47; case 4: span.end(); return [7 /*endfinally*/]; @@ -32011,64 +32663,98 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * Get a {@link BlobLeaseClient} that manages leases on the container. + * To renew the lease. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container + * and + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * - * @param {string} [proposeLeaseId] Initial proposed lease Id. - * @returns {BlobLeaseClient} A new BlobLeaseClient object for managing leases on the container. - * @memberof ContainerClient + * @param {LeaseOperationOptions} [options={}] Optional option to configure lease management operations. + * @returns {Promise} Response data for renew lease operation. + * @memberof BlobLeaseClient */ - ContainerClient.prototype.getBlobLeaseClient = function (proposeLeaseId) { - return new BlobLeaseClient(this, proposeLeaseId); + BlobLeaseClient.prototype.renewLease = function (options) { + var _a, _b, _c, _d, _e, _f; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _g, span, spanOptions, e_48; + return tslib.__generator(this, function (_h) { + switch (_h.label) { + case 0: + _g = createSpan("BlobLeaseClient-renewLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + _h.label = 1; + case 1: + _h.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this._containerOrBlobOperation.renewLease(this._leaseId, { + abortSignal: options.abortSignal, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _h.sent()]; + case 3: + e_48 = _h.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_48.message + }); + throw e_48; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; /** - * Creates a new block blob, or updates the content of an existing block blob. - * - * Updating an existing block blob overwrites any existing metadata on the blob. - * Partial updates are not supported; the content of the existing blob is - * overwritten with the new content. To perform a partial update of a block blob's, - * use {@link BlockBlobClient.stageBlock} and {@link BlockBlobClient.commitBlockList}. - * - * This is a non-parallel uploading method, please use {@link BlockBlobClient.uploadFile}, - * {@link BlockBlobClient.uploadStream} or {@link BlockBlobClient.uploadBrowserData} for better - * performance with concurrency uploading. - * - * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * To end the lease but ensure that another client cannot acquire a new lease + * until the current lease period has expired. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container + * and + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * - * @param {string} blobName Name of the block blob to create or update. - * @param {HttpRequestBody} body Blob, string, ArrayBuffer, ArrayBufferView or a function - * which returns a new Readable stream whose offset is from data source beginning. - * @param {number} contentLength Length of body in bytes. Use Buffer.byteLength() to calculate body length for a - * string including non non-Base64/Hex-encoded characters. - * @param {BlockBlobUploadOptions} [options] Options to configure the Block Blob Upload operation. - * @returns {Promise<{ blockBlobClient: BlockBlobClient; response: BlockBlobUploadResponse }>} Block Blob upload response data and the corresponding BlockBlobClient instance. - * @memberof ContainerClient + * @static + * @param {number} breakPeriod Break period + * @param {LeaseOperationOptions} [options={}] Optional options to configure lease management operations. + * @returns {Promise} Response data for break lease operation. + * @memberof BlobLeaseClient */ - ContainerClient.prototype.uploadBlockBlob = function (blobName, body, contentLength, options) { + BlobLeaseClient.prototype.breakLease = function (breakPeriod, options) { + var _a, _b, _c, _d, _e, _f; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, blockBlobClient, response, e_58; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var _g, span, spanOptions, operationOptions, e_49; + return tslib.__generator(this, function (_h) { + switch (_h.label) { case 0: - _a = createSpan("ContainerClient-uploadBlockBlob", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + _g = createSpan("BlobLeaseClient-breakLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + _h.label = 1; case 1: - _b.trys.push([1, 3, 4, 5]); - blockBlobClient = this.getBlockBlobClient(blobName); - return [4 /*yield*/, blockBlobClient.upload(body, contentLength, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: - response = _b.sent(); - return [2 /*return*/, { - blockBlobClient: blockBlobClient, - response: response - }]; + _h.trys.push([1, 3, 4, 5]); + operationOptions = { + abortSignal: options.abortSignal, + breakPeriod: breakPeriod, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), + spanOptions: spanOptions + }; + return [4 /*yield*/, this._containerOrBlobOperation.breakLease(operationOptions)]; + case 2: return [2 /*return*/, _h.sent()]; case 3: - e_58 = _b.sent(); + e_49 = _h.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_58.message + message: e_49.message }); - throw e_58; + throw e_49; case 4: span.end(); return [7 /*endfinally*/]; @@ -32077,42 +32763,122 @@ var ContainerClient = /** @class */ (function (_super) { }); }); }; + return BlobLeaseClient; +}()); +/** + * A ContainerClient represents a URL to the Azure Storage container allowing you to manipulate its blobs. + * + * @export + * @class ContainerClient + */ +var ContainerClient = /** @class */ (function (_super) { + tslib.__extends(ContainerClient, _super); + function ContainerClient(urlOrConnectionString, credentialOrPipelineOrContainerName, options) { + var _this = this; + var pipeline; + var url; + options = options || {}; + if (credentialOrPipelineOrContainerName instanceof Pipeline) { + // (url: string, pipeline: Pipeline) + url = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } + else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || + credentialOrPipelineOrContainerName instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + url = urlOrConnectionString; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } + else if (!credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName !== "string") { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + // The second parameter is undefined. Use anonymous credential. + url = urlOrConnectionString; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else if (credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName === "string") { + // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) + var containerName = credentialOrPipelineOrContainerName; + var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + { + var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)); + options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); + pipeline = newPipeline(sharedKeyCredential, options); + } + } + else if (extractedCreds.kind === "SASConnString") { + url = + appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)) + + "?" + + extractedCreds.accountSas; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } + else { + throw new Error("Expecting non-empty strings for containerName parameter"); + } + _this = _super.call(this, url, pipeline) || this; + _this._containerName = _this.getContainerNameFromUrl(); + _this.containerContext = new Container(_this.storageClientContext); + return _this; + } + Object.defineProperty(ContainerClient.prototype, "containerName", { + /** + * The name of the container. + */ + get: function () { + return this._containerName; + }, + enumerable: false, + configurable: true + }); /** - * Marks the specified blob or snapshot for deletion. The blob is later deleted - * during garbage collection. Note that in order to delete a blob, you must delete - * all of its snapshots. You can delete both at the same time with the Delete - * Blob operation. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob + * Creates a new container under the specified account. If the container with + * the same name already exists, the operation fails. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container * - * @param {string} blobName - * @param {ContainerDeleteBlobOptions} [options] Options to Blob Delete operation. - * @returns {Promise} Block blob deletion response data. + * @param {ContainerCreateOptions} [options] Options to Container Create operation. + * @returns {Promise} * @memberof ContainerClient + * + * Example usage: + * + * ```js + * const containerClient = blobServiceClient.getContainerClient(""); + * const createContainerResponse = await containerClient.create(); + * console.log("Container was created successfully", createContainerResponse.requestId); + * ``` */ - ContainerClient.prototype.deleteBlob = function (blobName, options) { + ContainerClient.prototype.create = function (options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, blobClient, e_59; + var _a, span, spanOptions, e_50; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("ContainerClient-deleteBlob", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("ContainerClient-create", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - blobClient = this.getBlobClient(blobName); - if (options.versionId) { - blobClient = blobClient.withVersion(options.versionId); - } - return [4 /*yield*/, blobClient.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: return [2 /*return*/, _b.sent()]; + return [4 /*yield*/, this.containerContext.create(tslib.__assign(tslib.__assign({}, options), { spanOptions: spanOptions }))]; + case 2: + // Spread operator in destructuring assignments, + // this will filter out unwanted properties from the response object into result object + return [2 /*return*/, _b.sent()]; case 3: - e_59 = _b.sent(); + e_50 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_59.message + message: e_50.message }); - throw e_59; + throw e_50; case 4: span.end(); return [7 /*endfinally*/]; @@ -32122,43 +32888,45 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * listBlobFlatSegment returns a single segment of blobs starting from the - * specified Marker. Use an empty Marker to start enumeration from the beginning. - * After getting a segment, process it, and then call listBlobsFlatSegment again - * (passing the the previously-returned Marker) to get the next segment. - * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs + * Creates a new container under the specified account. If the container with + * the same name already exists, it is not changed. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container * - * @param {string} [marker] A string value that identifies the portion of the list to be returned with the next list operation. - * @param {ContainerListBlobsSegmentOptions} [options] Options to Container List Blob Flat Segment operation. - * @returns {Promise} + * @param {ContainerCreateOptions} [options] + * @returns {Promise} * @memberof ContainerClient */ - ContainerClient.prototype.listBlobFlatSegment = function (marker, options) { + ContainerClient.prototype.createIfNotExists = function (options) { + var _a, _b; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, response, wrappedResponse, e_60; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var _c, span, spanOptions, res, e_51; + return tslib.__generator(this, function (_d) { + switch (_d.label) { case 0: - _a = createSpan("ContainerClient-listBlobFlatSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + _c = createSpan("ContainerClient-createIfNotExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; + _d.label = 1; case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.listBlobFlatSegment(tslib.__assign(tslib.__assign({ marker: marker }, options), { spanOptions: spanOptions }))]; + _d.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.create(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: - response = _b.sent(); - wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, segment: tslib.__assign(tslib.__assign({}, response.segment), { blobItems: response.segment.blobItems.map(function (blobItemInteral) { - var blobItem = tslib.__assign(tslib.__assign({}, blobItemInteral), { tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); - return blobItem; - }) }) }); - return [2 /*return*/, wrappedResponse]; + res = _d.sent(); + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable + })]; case 3: - e_60 = _b.sent(); + e_51 = _d.sent(); + if (((_a = e_51.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerAlreadyExists") { + span.setStatus({ + code: api.CanonicalCode.ALREADY_EXISTS, + message: "Expected exception when creating a container only if it does not already exist." + }); + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_51.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_51.response })]; + } span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_60.message + message: e_51.message }); - throw e_60; + throw e_51; case 4: span.end(); return [7 /*endfinally*/]; @@ -32168,44 +32936,48 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * listBlobHierarchySegment returns a single segment of blobs starting from - * the specified Marker. Use an empty Marker to start enumeration from the - * beginning. After getting a segment, process it, and then call listBlobsHierarchicalSegment - * again (passing the the previously-returned Marker) to get the next segment. - * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs + * Returns true if the Azure container resource represented by this client exists; false otherwise. * - * @param {string} delimiter The character or string used to define the virtual hierarchy - * @param {string} [marker] A string value that identifies the portion of the list to be returned with the next list operation. - * @param {ContainerListBlobsSegmentOptions} [options] Options to Container List Blob Hierarchy Segment operation. - * @returns {Promise} + * NOTE: use this function with care since an existing container might be deleted by other clients or + * applications. Vice versa new containers with the same name might be added by other clients or + * applications after this function completes. + * + * @param {ContainerExistsOptions} [options={}] + * @returns {Promise} * @memberof ContainerClient */ - ContainerClient.prototype.listBlobHierarchySegment = function (delimiter, marker, options) { + ContainerClient.prototype.exists = function (options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, response, wrappedResponse, e_61; + var _a, span, spanOptions, e_52; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("ContainerClient-listBlobHierarchySegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("ContainerClient-exists", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.listBlobHierarchySegment(delimiter, tslib.__assign(tslib.__assign({ marker: marker }, options), { spanOptions: spanOptions }))]; + return [4 /*yield*/, this.getProperties({ + abortSignal: options.abortSignal, + tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) + })]; case 2: - response = _b.sent(); - wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, segment: tslib.__assign(tslib.__assign({}, response.segment), { blobItems: response.segment.blobItems.map(function (blobItemInteral) { - var blobItem = tslib.__assign(tslib.__assign({}, blobItemInteral), { tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); - return blobItem; - }) }) }); - return [2 /*return*/, wrappedResponse]; + _b.sent(); + return [2 /*return*/, true]; case 3: - e_61 = _b.sent(); + e_52 = _b.sent(); + if (e_52.statusCode === 404) { + span.setStatus({ + code: api.CanonicalCode.NOT_FOUND, + message: "Expected exception when checking container existence" + }); + return [2 /*return*/, false]; + } span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_61.message + message: e_52.message }); - throw e_61; + throw e_52; case 4: span.end(); return [7 /*endfinally*/]; @@ -32215,883 +32987,501 @@ var ContainerClient = /** @class */ (function (_super) { }); }; /** - * Returns an AsyncIterableIterator for ContainerListBlobFlatSegmentResponse + * Creates a {@link BlobClient} * - * @private - * @param {string} [marker] A string value that identifies the portion of - * the list of blobs to be returned with the next listing operation. The - * operation returns the ContinuationToken value within the response body if the - * listing operation did not return all blobs remaining to be listed - * with the current page. The ContinuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. - * @returns {AsyncIterableIterator} + * @param {string} blobName A blob name + * @returns {BlobClient} A new BlobClient object for the given blob name. * @memberof ContainerClient */ - ContainerClient.prototype.listSegments = function (marker, options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listSegments_1() { - var listBlobsFlatSegmentResponse; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!(!!marker || marker === undefined)) return [3 /*break*/, 7]; - _a.label = 1; - case 1: return [4 /*yield*/, tslib.__await(this.listBlobFlatSegment(marker, options))]; - case 2: - listBlobsFlatSegmentResponse = _a.sent(); - marker = listBlobsFlatSegmentResponse.continuationToken; - return [4 /*yield*/, tslib.__await(listBlobsFlatSegmentResponse)]; - case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_a.sent()])]; - case 4: return [4 /*yield*/, _a.sent()]; - case 5: - _a.sent(); - _a.label = 6; - case 6: - if (marker) return [3 /*break*/, 1]; - _a.label = 7; - case 7: return [2 /*return*/]; - } - }); - }); + ContainerClient.prototype.getBlobClient = function (blobName) { + return new BlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); }; /** - * Returns an AsyncIterableIterator of {@link BlobItem} objects + * Creates an {@link AppendBlobClient} * - * @private - * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. - * @returns {AsyncIterableIterator} + * @param {string} blobName An append blob name + * @returns {AppendBlobClient} * @memberof ContainerClient */ - ContainerClient.prototype.listItems = function (options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listItems_1() { - var marker, _a, _b, listBlobsFlatSegmentResponse, e_62_1; - var e_62, _c; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _d.trys.push([0, 7, 8, 13]); - _a = tslib.__asyncValues(this.listSegments(marker, options)); - _d.label = 1; - case 1: return [4 /*yield*/, tslib.__await(_a.next())]; - case 2: - if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; - listBlobsFlatSegmentResponse = _b.value; - return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(listBlobsFlatSegmentResponse.segment.blobItems)))]; - case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; - case 4: - _d.sent(); - _d.label = 5; - case 5: return [3 /*break*/, 1]; - case 6: return [3 /*break*/, 13]; - case 7: - e_62_1 = _d.sent(); - e_62 = { error: e_62_1 }; - return [3 /*break*/, 13]; - case 8: - _d.trys.push([8, , 11, 12]); - if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; - return [4 /*yield*/, tslib.__await(_c.call(_a))]; - case 9: - _d.sent(); - _d.label = 10; - case 10: return [3 /*break*/, 12]; - case 11: - if (e_62) throw e_62.error; - return [7 /*endfinally*/]; - case 12: return [7 /*endfinally*/]; - case 13: return [2 /*return*/]; - } - }); - }); + ContainerClient.prototype.getAppendBlobClient = function (blobName) { + return new AppendBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); }; /** - * Returns an async iterable iterator to list all the blobs - * under the specified account. - * - * .byPage() returns an async iterable iterator to list the blobs in pages. - * - * Example using `for await` syntax: + * Creates a {@link BlockBlobClient} * - * ```js - * // Get the containerClient before you run these snippets, - * // Can be obtained from `blobServiceClient.getContainerClient("");` - * let i = 1; - * for await (const blob of containerClient.listBlobsFlat()) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * ``` + * @param {string} blobName A block blob name + * @returns {BlockBlobClient} + * @memberof ContainerClient * - * Example using `iter.next()`: + * Example usage: * * ```js - * let i = 1; - * let iter = containerClient.listBlobsFlat(); - * let blobItem = await iter.next(); - * while (!blobItem.done) { - * console.log(`Blob ${i++}: ${blobItem.value.name}`); - * blobItem = await iter.next(); - * } - * ``` - * - * Example using `byPage()`: + * const content = "Hello world!"; * - * ```js - * // passing optional maxPageSize in the page settings - * let i = 1; - * for await (const response of containerClient.listBlobsFlat().byPage({ maxPageSize: 20 })) { - * for (const blob of response.segment.blobItems) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } + * const blockBlobClient = containerClient.getBlockBlobClient(""); + * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); * ``` + */ + ContainerClient.prototype.getBlockBlobClient = function (blobName) { + return new BlockBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); + }; + /** + * Creates a {@link PageBlobClient} * - * Example using paging with a marker: - * - * ```js - * let i = 1; - * let iterator = containerClient.listBlobsFlat().byPage({ maxPageSize: 2 }); - * let response = (await iterator.next()).value; - * - * // Prints 2 blob names - * for (const blob of response.segment.blobItems) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * - * // Gets next marker - * let marker = response.continuationToken; - * - * // Passing next marker as continuationToken - * - * iterator = containerClient.listBlobsFlat().byPage({ continuationToken: marker, maxPageSize: 10 }); - * response = (await iterator.next()).value; + * @param {string} blobName A page blob name + * @returns {PageBlobClient} + * @memberof ContainerClient + */ + ContainerClient.prototype.getPageBlobClient = function (blobName) { + return new PageBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); + }; + /** + * Returns all user-defined metadata and system properties for the specified + * container. The data returned does not include the container's list of blobs. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-properties * - * // Prints 10 blob names - * for (const blob of response.segment.blobItems) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * ``` + * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if + * they originally contained uppercase characters. This differs from the metadata keys returned by + * the `listContainers` method of {@link BlobServiceClient} using the `includeMetadata` option, which + * will retain their original casing. * - * @param {ContainerListBlobsOptions} [options={}] Options to list blobs. - * @returns {PagedAsyncIterableIterator} An asyncIterableIterator that supports paging. + * @param {ContainerGetPropertiesOptions} [options] Options to Container Get Properties operation. + * @returns {Promise} * @memberof ContainerClient */ - ContainerClient.prototype.listBlobsFlat = function (options) { - var _a; - var _this = this; + ContainerClient.prototype.getProperties = function (options) { if (options === void 0) { options = {}; } - var include = []; - if (options.includeCopy) { - include.push("copy"); - } - if (options.includeDeleted) { - include.push("deleted"); - } - if (options.includeMetadata) { - include.push("metadata"); - } - if (options.includeSnapshots) { - include.push("snapshots"); - } - if (options.includeVersions) { - include.push("versions"); - } - if (options.includeUncommitedBlobs) { - include.push("uncommittedblobs"); - } - if (options.includeTags) { - include.push("tags"); - } - if (options.prefix === "") { - options.prefix = undefined; - } - var updatedOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); - // AsyncIterableIterator to iterate over blobs - var iter = this.listItems(updatedOptions); - return _a = { - /** - * @member {Promise} [next] The next method, part of the iteration protocol - */ - next: function () { - return iter.next(); + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_53; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!options.conditions) { + options.conditions = {}; + } + _a = createSpan("ContainerClient-getProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.containerContext.getProperties(tslib.__assign(tslib.__assign({ abortSignal: options.abortSignal }, options.conditions), { spanOptions: spanOptions }))]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_53 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_53.message + }); + throw e_53; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; } - }, - /** - * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol - */ - _a[Symbol.asyncIterator] = function () { - return this; - }, - /** - * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time - */ - _a.byPage = function (settings) { - if (settings === void 0) { settings = {}; } - return _this.listSegments(settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); - }, - _a; + }); + }); + }; + /** + * Marks the specified container for deletion. The container and any blobs + * contained within it are later deleted during garbage collection. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container + * + * @param {ContainerDeleteMethodOptions} [options] Options to Container Delete operation. + * @returns {Promise} + * @memberof ContainerClient + */ + ContainerClient.prototype.delete = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_54; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!options.conditions) { + options.conditions = {}; + } + _a = createSpan("ContainerClient-delete", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.containerContext.deleteMethod({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: options.conditions, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_54 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_54.message + }); + throw e_54; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; /** - * Returns an AsyncIterableIterator for ContainerListBlobHierarchySegmentResponse + * Marks the specified container for deletion if it exists. The container and any blobs + * contained within it are later deleted during garbage collection. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container * - * @private - * @param {string} delimiter The character or string used to define the virtual hierarchy - * @param {string} [marker] A string value that identifies the portion of - * the list of blobs to be returned with the next listing operation. The - * operation returns the ContinuationToken value within the response body if the - * listing operation did not return all blobs remaining to be listed - * with the current page. The ContinuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. - * @returns {AsyncIterableIterator} + * @param {ContainerDeleteMethodOptions} [options] Options to Container Delete operation. + * @returns {Promise} * @memberof ContainerClient */ - ContainerClient.prototype.listHierarchySegments = function (delimiter, marker, options) { + ContainerClient.prototype.deleteIfExists = function (options) { + var _a, _b; if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listHierarchySegments_1() { - var listBlobsHierarchySegmentResponse; - return tslib.__generator(this, function (_a) { - switch (_a.label) { + return tslib.__awaiter(this, void 0, void 0, function () { + var _c, span, spanOptions, res, e_55; + return tslib.__generator(this, function (_d) { + switch (_d.label) { case 0: - if (!(!!marker || marker === undefined)) return [3 /*break*/, 7]; - _a.label = 1; - case 1: return [4 /*yield*/, tslib.__await(this.listBlobHierarchySegment(delimiter, marker, options))]; + _c = createSpan("ContainerClient-deleteIfExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; + _d.label = 1; + case 1: + _d.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: - listBlobsHierarchySegmentResponse = _a.sent(); - marker = listBlobsHierarchySegmentResponse.continuationToken; - return [4 /*yield*/, tslib.__await(listBlobsHierarchySegmentResponse)]; - case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_a.sent()])]; - case 4: return [4 /*yield*/, _a.sent()]; - case 5: - _a.sent(); - _a.label = 6; - case 6: - if (marker) return [3 /*break*/, 1]; - _a.label = 7; - case 7: return [2 /*return*/]; + res = _d.sent(); + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable + })]; + case 3: + e_55 = _d.sent(); + if (((_a = e_55.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerNotFound") { + span.setStatus({ + code: api.CanonicalCode.NOT_FOUND, + message: "Expected exception when deleting a container only if it exists." + }); + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_55.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_55.response })]; + } + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_55.message + }); + throw e_55; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; } }); }); }; /** - * Returns an AsyncIterableIterator for {@link BlobPrefix} and {@link BlobItem} objects. + * Sets one or more user-defined name-value pairs for the specified container. * - * @private - * @param {string} delimiter The character or string used to define the virtual hierarchy - * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. - * @returns {AsyncIterableIterator<{ kind: "prefix" } & BlobPrefix | { kind: "blob" } & BlobItem>} + * If no option provided, or no metadata defined in the parameter, the container + * metadata will be removed. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-metadata + * + * @param {Metadata} [metadata] Replace existing metadata with this value. + * If no value provided the existing metadata will be removed. + * @param {ContainerSetMetadataOptions} [options] Options to Container Set Metadata operation. + * @returns {Promise} * @memberof ContainerClient */ - ContainerClient.prototype.listItemsByHierarchy = function (delimiter, options) { + ContainerClient.prototype.setMetadata = function (metadata, options) { if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listItemsByHierarchy_1() { - var marker, _a, _b, listBlobsHierarchySegmentResponse, segment, _i, _c, prefix, _d, _e, blob, e_63_1; - var e_63, _f; - return tslib.__generator(this, function (_g) { - switch (_g.label) { + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_56; + return tslib.__generator(this, function (_b) { + switch (_b.label) { case 0: - _g.trys.push([0, 14, 15, 20]); - _a = tslib.__asyncValues(this.listHierarchySegments(delimiter, marker, options)); - _g.label = 1; - case 1: return [4 /*yield*/, tslib.__await(_a.next())]; - case 2: - if (!(_b = _g.sent(), !_b.done)) return [3 /*break*/, 13]; - listBlobsHierarchySegmentResponse = _b.value; - segment = listBlobsHierarchySegmentResponse.segment; - if (!segment.blobPrefixes) return [3 /*break*/, 7]; - _i = 0, _c = segment.blobPrefixes; - _g.label = 3; + if (!options.conditions) { + options.conditions = {}; + } + if (options.conditions.ifUnmodifiedSince) { + throw new RangeError("the IfUnmodifiedSince must have their default values because they are ignored by the blob service"); + } + _a = createSpan("ContainerClient-setMetadata", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.containerContext.setMetadata({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + metadata: metadata, + modifiedAccessConditions: options.conditions, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; case 3: - if (!(_i < _c.length)) return [3 /*break*/, 7]; - prefix = _c[_i]; - return [4 /*yield*/, tslib.__await(tslib.__assign({ kind: "prefix" }, prefix))]; - case 4: return [4 /*yield*/, _g.sent()]; - case 5: - _g.sent(); - _g.label = 6; - case 6: - _i++; - return [3 /*break*/, 3]; - case 7: - _d = 0, _e = segment.blobItems; - _g.label = 8; - case 8: - if (!(_d < _e.length)) return [3 /*break*/, 12]; - blob = _e[_d]; - return [4 /*yield*/, tslib.__await(tslib.__assign({ kind: "blob" }, blob))]; - case 9: return [4 /*yield*/, _g.sent()]; - case 10: - _g.sent(); - _g.label = 11; - case 11: - _d++; - return [3 /*break*/, 8]; - case 12: return [3 /*break*/, 1]; - case 13: return [3 /*break*/, 20]; - case 14: - e_63_1 = _g.sent(); - e_63 = { error: e_63_1 }; - return [3 /*break*/, 20]; - case 15: - _g.trys.push([15, , 18, 19]); - if (!(_b && !_b.done && (_f = _a.return))) return [3 /*break*/, 17]; - return [4 /*yield*/, tslib.__await(_f.call(_a))]; - case 16: - _g.sent(); - _g.label = 17; - case 17: return [3 /*break*/, 19]; - case 18: - if (e_63) throw e_63.error; + e_56 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_56.message + }); + throw e_56; + case 4: + span.end(); return [7 /*endfinally*/]; - case 19: return [7 /*endfinally*/]; - case 20: return [2 /*return*/]; + case 5: return [2 /*return*/]; } }); }); }; /** - * Returns an async iterable iterator to list all the blobs by hierarchy. - * under the specified account. - * - * .byPage() returns an async iterable iterator to list the blobs by hierarchy in pages. - * - * Example using `for await` syntax: - * - * ```js - * for await (const item of containerClient.listBlobsByHierarchy("/")) { - * if (item.kind === "prefix") { - * console.log(`\tBlobPrefix: ${item.name}`); - * } else { - * console.log(`\tBlobItem: name - ${item.name}, last modified - ${item.properties.lastModified}`); - * } - * } - * ``` - * - * Example using `iter.next()`: - * - * ```js - * let iter = containerClient.listBlobsByHierarchy("/", { prefix: "prefix1/" }); - * let entity = await iter.next(); - * while (!entity.done) { - * let item = entity.value; - * if (item.kind === "prefix") { - * console.log(`\tBlobPrefix: ${item.name}`); - * } else { - * console.log(`\tBlobItem: name - ${item.name}, last modified - ${item.properties.lastModified}`); - * } - * entity = await iter.next(); - * } - * ```js - * - * Example using `byPage()`: - * - * ```js - * console.log("Listing blobs by hierarchy by page"); - * for await (const response of containerClient.listBlobsByHierarchy("/").byPage()) { - * const segment = response.segment; - * if (segment.blobPrefixes) { - * for (const prefix of segment.blobPrefixes) { - * console.log(`\tBlobPrefix: ${prefix.name}`); - * } - * } - * for (const blob of response.segment.blobItems) { - * console.log(`\tBlobItem: name - ${blob.name}, last modified - ${blob.properties.lastModified}`); - * } - * } - * ``` - * - * Example using paging with a max page size: - * - * ```js - * console.log("Listing blobs by hierarchy by page, specifying a prefix and a max page size"); - * - * let i = 1; - * for await (const response of containerClient.listBlobsByHierarchy("/", { prefix: "prefix2/sub1/"}).byPage({ maxPageSize: 2 })) { - * console.log(`Page ${i++}`); - * const segment = response.segment; + * Gets the permissions for the specified container. The permissions indicate + * whether container data may be accessed publicly. * - * if (segment.blobPrefixes) { - * for (const prefix of segment.blobPrefixes) { - * console.log(`\tBlobPrefix: ${prefix.name}`); - * } - * } + * WARNING: JavaScript Date will potentially lose precision when parsing startsOn and expiresOn strings. + * For example, new Date("2018-12-31T03:44:23.8827891Z").toISOString() will get "2018-12-31T03:44:23.882Z". * - * for (const blob of response.segment.blobItems) { - * console.log(`\tBlobItem: name - ${blob.name}, last modified - ${blob.properties.lastModified}`); - * } - * } - * ``` + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-acl * - * @param {string} delimiter The character or string used to define the virtual hierarchy - * @param {ContainerListBlobsOptions} [options={}] Options to list blobs operation. - * @returns {(PagedAsyncIterableIterator< - * { kind: "prefix" } & BlobPrefix | { kind: "blob" } & BlobItem, - * ContainerListBlobHierarchySegmentResponse - * >)} + * @param {ContainerGetAccessPolicyOptions} [options] Options to Container Get Access Policy operation. + * @returns {Promise} * @memberof ContainerClient */ - ContainerClient.prototype.listBlobsByHierarchy = function (delimiter, options) { - var _a; - var _this = this; + ContainerClient.prototype.getAccessPolicy = function (options) { if (options === void 0) { options = {}; } - if (delimiter === "") { - throw new RangeError("delimiter should contain one or more characters"); - } - var include = []; - if (options.includeCopy) { - include.push("copy"); - } - if (options.includeDeleted) { - include.push("deleted"); - } - if (options.includeMetadata) { - include.push("metadata"); - } - if (options.includeSnapshots) { - include.push("snapshots"); - } - if (options.includeVersions) { - include.push("versions"); - } - if (options.includeUncommitedBlobs) { - include.push("uncommittedblobs"); - } - if (options.includeTags) { - include.push("tags"); - } - if (options.prefix === "") { - options.prefix = undefined; - } - var updatedOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); - // AsyncIterableIterator to iterate over blob prefixes and blobs - var iter = this.listItemsByHierarchy(delimiter, updatedOptions); - return _a = { - /** - * @member {Promise} [next] The next method, part of the iteration protocol - */ - next: function () { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - return [2 /*return*/, iter.next()]; - }); - }); - } - }, - /** - * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol - */ - _a[Symbol.asyncIterator] = function () { - return this; - }, - /** - * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time - */ - _a.byPage = function (settings) { - if (settings === void 0) { settings = {}; } - return _this.listHierarchySegments(delimiter, settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); - }, - _a; - }; - ContainerClient.prototype.getContainerNameFromUrl = function () { - var containerName; - try { - // URL may look like the following - // "https://myaccount.blob.core.windows.net/mycontainer?sasString"; - // "https://myaccount.blob.core.windows.net/mycontainer"; - // IPv4/IPv6 address hosts, Endpoints - `http://127.0.0.1:10000/devstoreaccount1/containername` - // http://localhost:10001/devstoreaccount1/containername - var parsedUrl = coreHttp.URLBuilder.parse(this.url); - if (parsedUrl.getHost().split(".")[1] === "blob") { - // "https://myaccount.blob.core.windows.net/containername". - // "https://customdomain.com/containername". - // .getPath() -> /containername - containerName = parsedUrl.getPath().split("/")[1]; - } - else if (isIpEndpointStyle(parsedUrl)) { - // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/containername - // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/containername - // .getPath() -> /devstoreaccount1/containername - containerName = parsedUrl.getPath().split("/")[2]; - } - else { - // "https://customdomain.com/containername". - // .getPath() -> /containername - containerName = parsedUrl.getPath().split("/")[1]; - } - // decode the encoded containerName - to get all the special characters that might be present in it - containerName = decodeURIComponent(containerName); - if (!containerName) { - throw new Error("Provided containerName is invalid."); - } - return containerName; - } - catch (error) { - throw new Error("Unable to extract containerName with provided information."); - } - }; - return ContainerClient; -}(StorageClient)); - -function getBodyAsText(batchResponse) { - return tslib.__awaiter(this, void 0, void 0, function () { - var buffer, responseLength; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - buffer = Buffer.alloc(BATCH_MAX_PAYLOAD_IN_BYTES); - return [4 /*yield*/, streamToBuffer2(batchResponse.readableStreamBody, buffer)]; - case 1: - responseLength = _a.sent(); - // Slice the buffer to trim the empty ending. - buffer = buffer.slice(0, responseLength); - return [2 /*return*/, buffer.toString()]; - } - }); - }); -} -function utf8ByteLength(str) { - return Buffer.byteLength(str); -} - -var HTTP_HEADER_DELIMITER = ": "; -var SPACE_DELIMITER = " "; -var NOT_FOUND = -1; -/** - * Util class for parsing batch response. - */ -var BatchResponseParser = /** @class */ (function () { - function BatchResponseParser(batchResponse, subRequests) { - if (!batchResponse || !batchResponse.contentType) { - // In special case(reported), server may return invalid content-type which could not be parsed. - throw new RangeError("batchResponse is malformed or doesn't contain valid content-type."); - } - if (!subRequests || subRequests.size === 0) { - // This should be prevent during coding. - throw new RangeError("Invalid state: subRequests is not provided or size is 0."); - } - this.batchResponse = batchResponse; - this.subRequests = subRequests; - this.responseBatchBoundary = this.batchResponse.contentType.split("=")[1]; - this.perResponsePrefix = "--" + this.responseBatchBoundary + HTTP_LINE_ENDING; - this.batchResponseEnding = "--" + this.responseBatchBoundary + "--"; - } - // For example of response, please refer to https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#response - BatchResponseParser.prototype.parseBatchResponse = function () { return tslib.__awaiter(this, void 0, void 0, function () { - var responseBodyAsText, subResponses, subResponseCount, deserializedSubResponses, subResponsesSucceededCount, subResponsesFailedCount, index, subResponse, deserializedSubResponse, responseLines, subRespHeaderStartFound, subRespHeaderEndFound, subRespFailed, contentId, _i, responseLines_1, responseLine, tokens, tokens; - return tslib.__generator(this, function (_a) { - switch (_a.label) { + var _a, span, spanOptions, response, res, _i, response_1, identifier, accessPolicy, e_57; + return tslib.__generator(this, function (_b) { + switch (_b.label) { case 0: - // When logic reach here, suppose batch request has already succeeded with 202, so we can further parse - // sub request's response. - if (this.batchResponse._response.status != HTTPURLConnection.HTTP_ACCEPTED) { - throw new Error("Invalid state: batch request failed with status: '" + this.batchResponse._response.status + "'."); + if (!options.conditions) { + options.conditions = {}; } - return [4 /*yield*/, getBodyAsText(this.batchResponse)]; + _a = createSpan("ContainerClient-getAccessPolicy", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; case 1: - responseBodyAsText = _a.sent(); - subResponses = responseBodyAsText - .split(this.batchResponseEnding)[0] // string after ending is useless - .split(this.perResponsePrefix) - .slice(1); - subResponseCount = subResponses.length; - // Defensive coding in case of potential error parsing. - // Note: subResponseCount == 1 is special case where sub request is invalid. - // We try to prevent such cases through early validation, e.g. validate sub request count >= 1. - // While in unexpected sub request invalid case, we allow sub response to be parsed and return to user. - if (subResponseCount != this.subRequests.size && subResponseCount != 1) { - throw new Error("Invalid state: sub responses' count is not equal to sub requests' count."); - } - deserializedSubResponses = new Array(subResponseCount); - subResponsesSucceededCount = 0; - subResponsesFailedCount = 0; - // Parse sub subResponses. - for (index = 0; index < subResponseCount; index++) { - subResponse = subResponses[index]; - deserializedSubResponses[index] = {}; - deserializedSubResponse = deserializedSubResponses[index]; - deserializedSubResponse.headers = new coreHttp.HttpHeaders(); - responseLines = subResponse.split("" + HTTP_LINE_ENDING); - subRespHeaderStartFound = false; - subRespHeaderEndFound = false; - subRespFailed = false; - contentId = NOT_FOUND; - for (_i = 0, responseLines_1 = responseLines; _i < responseLines_1.length; _i++) { - responseLine = responseLines_1[_i]; - if (!subRespHeaderStartFound) { - // Convention line to indicate content ID - if (responseLine.startsWith(HeaderConstants.CONTENT_ID)) { - contentId = parseInt(responseLine.split(HTTP_HEADER_DELIMITER)[1]); - } - // Http version line with status code indicates the start of sub request's response. - // Example: HTTP/1.1 202 Accepted - if (responseLine.startsWith(HTTP_VERSION_1_1)) { - subRespHeaderStartFound = true; - tokens = responseLine.split(SPACE_DELIMITER); - deserializedSubResponse.status = parseInt(tokens[1]); - deserializedSubResponse.statusMessage = tokens.slice(2).join(SPACE_DELIMITER); - } - continue; // Skip convention headers not specifically for sub request i.e. Content-Type: application/http and Content-ID: * - } - if (responseLine.trim() === "") { - // Sub response's header start line already found, and the first empty line indicates header end line found. - if (!subRespHeaderEndFound) { - subRespHeaderEndFound = true; - } - continue; // Skip empty line - } - // Note: when code reach here, it indicates subRespHeaderStartFound == true - if (!subRespHeaderEndFound) { - if (responseLine.indexOf(HTTP_HEADER_DELIMITER) === -1) { - // Defensive coding to prevent from missing valuable lines. - throw new Error("Invalid state: find non-empty line '" + responseLine + "' without HTTP header delimiter '" + HTTP_HEADER_DELIMITER + "'."); - } - tokens = responseLine.split(HTTP_HEADER_DELIMITER); - deserializedSubResponse.headers.set(tokens[0], tokens[1]); - if (tokens[0] === HeaderConstants.X_MS_ERROR_CODE) { - deserializedSubResponse.errorCode = tokens[1]; - subRespFailed = true; - } + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.containerContext.getAccessPolicy({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + spanOptions: spanOptions + })]; + case 2: + response = _b.sent(); + res = { + _response: response._response, + blobPublicAccess: response.blobPublicAccess, + date: response.date, + etag: response.etag, + errorCode: response.errorCode, + lastModified: response.lastModified, + requestId: response.requestId, + clientRequestId: response.clientRequestId, + signedIdentifiers: [], + version: response.version + }; + for (_i = 0, response_1 = response; _i < response_1.length; _i++) { + identifier = response_1[_i]; + accessPolicy = undefined; + if (identifier.accessPolicy) { + accessPolicy = { + permissions: identifier.accessPolicy.permissions + }; + if (identifier.accessPolicy.expiresOn) { + accessPolicy.expiresOn = new Date(identifier.accessPolicy.expiresOn); } - else { - // Assemble body of sub response. - if (!deserializedSubResponse.bodyAsText) { - deserializedSubResponse.bodyAsText = ""; - } - deserializedSubResponse.bodyAsText += responseLine; + if (identifier.accessPolicy.startsOn) { + accessPolicy.startsOn = new Date(identifier.accessPolicy.startsOn); } - } // Inner for end - if (contentId != NOT_FOUND) { - deserializedSubResponse._request = this.subRequests.get(contentId); - } - if (subRespFailed) { - subResponsesFailedCount++; - } - else { - subResponsesSucceededCount++; } + res.signedIdentifiers.push({ + accessPolicy: accessPolicy, + id: identifier.id + }); } - return [2 /*return*/, { - subResponses: deserializedSubResponses, - subResponsesSucceededCount: subResponsesSucceededCount, - subResponsesFailedCount: subResponsesFailedCount - }]; + return [2 /*return*/, res]; + case 3: + e_57 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_57.message + }); + throw e_57; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; } }); }); }; - return BatchResponseParser; -}()); - -var MutexLockStatus; -(function (MutexLockStatus) { - MutexLockStatus[MutexLockStatus["LOCKED"] = 0] = "LOCKED"; - MutexLockStatus[MutexLockStatus["UNLOCKED"] = 1] = "UNLOCKED"; -})(MutexLockStatus || (MutexLockStatus = {})); -/** - * An async mutex lock. - * - * @export - * @class Mutex - */ -var Mutex = /** @class */ (function () { - function Mutex() { - } /** - * Lock for a specific key. If the lock has been acquired by another customer, then - * will wait until getting the lock. + * Sets the permissions for the specified container. The permissions indicate + * whether blobs in a container may be accessed publicly. * - * @static - * @param {string} key lock key - * @returns {Promise} - * @memberof Mutex + * When you set permissions for a container, the existing permissions are replaced. + * If no access or containerAcl provided, the existing container ACL will be + * removed. + * + * When you establish a stored access policy on a container, it may take up to 30 seconds to take effect. + * During this interval, a shared access signature that is associated with the stored access policy will + * fail with status code 403 (Forbidden), until the access policy becomes active. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-acl + * + * @param {PublicAccessType} [access] The level of public access to data in the container. + * @param {SignedIdentifier[]} [containerAcl] Array of elements each having a unique Id and details of the access policy. + * @param {ContainerSetAccessPolicyOptions} [options] Options to Container Set Access Policy operation. + * @returns {Promise} + * @memberof ContainerClient */ - Mutex.lock = function (key) { + ContainerClient.prototype.setAccessPolicy = function (access, containerAcl, options) { + if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _this = this; - return tslib.__generator(this, function (_a) { - return [2 /*return*/, new Promise(function (resolve) { - if (_this.keys[key] === undefined || _this.keys[key] === MutexLockStatus.UNLOCKED) { - _this.keys[key] = MutexLockStatus.LOCKED; - resolve(); - } - else { - _this.onUnlockEvent(key, function () { - _this.keys[key] = MutexLockStatus.LOCKED; - resolve(); + var _a, span, spanOptions, acl, _i, _b, identifier, e_58; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _a = createSpan("ContainerClient-setAccessPolicy", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + acl = []; + for (_i = 0, _b = containerAcl || []; _i < _b.length; _i++) { + identifier = _b[_i]; + acl.push({ + accessPolicy: { + expiresOn: identifier.accessPolicy.expiresOn + ? truncatedISO8061Date(identifier.accessPolicy.expiresOn) + : "", + permissions: identifier.accessPolicy.permissions, + startsOn: identifier.accessPolicy.startsOn + ? truncatedISO8061Date(identifier.accessPolicy.startsOn) + : "" + }, + id: identifier.id }); } - })]; + return [4 /*yield*/, this.containerContext.setAccessPolicy({ + abortSignal: options.abortSignal, + access: access, + containerAcl: acl, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: options.conditions, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_58 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_58.message + }); + throw e_58; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } }); }); }; /** - * Unlock a key. + * Get a {@link BlobLeaseClient} that manages leases on the container. * - * @static - * @param {string} key - * @returns {Promise} - * @memberof Mutex - */ - Mutex.unlock = function (key) { - return tslib.__awaiter(this, void 0, void 0, function () { - var _this = this; - return tslib.__generator(this, function (_a) { - return [2 /*return*/, new Promise(function (resolve) { - if (_this.keys[key] === MutexLockStatus.LOCKED) { - _this.emitUnlockEvent(key); - } - delete _this.keys[key]; - resolve(); - })]; - }); - }); - }; - Mutex.onUnlockEvent = function (key, handler) { - if (this.listeners[key] === undefined) { - this.listeners[key] = [handler]; - } - else { - this.listeners[key].push(handler); - } - }; - Mutex.emitUnlockEvent = function (key) { - var _this = this; - if (this.listeners[key] !== undefined && this.listeners[key].length > 0) { - var handler_1 = this.listeners[key].shift(); - setImmediate(function () { - handler_1.call(_this); - }); - } - }; - Mutex.keys = {}; - Mutex.listeners = {}; - return Mutex; -}()); - -/** - * A BlobBatch represents an aggregated set of operations on blobs. - * Currently, only `delete` and `setAccessTier` are supported. - * - * @export - * @class BlobBatch - */ -var BlobBatch = /** @class */ (function () { - function BlobBatch() { - this.batch = "batch"; - this.batchRequest = new InnerBatchRequest(); - } - /** - * Get the value of Content-Type for a batch request. - * The value must be multipart/mixed with a batch boundary. - * Example: multipart/mixed; boundary=batch_a81786c8-e301-4e42-a729-a32ca24ae252 - */ - BlobBatch.prototype.getMultiPartContentType = function () { - return this.batchRequest.getMultipartContentType(); - }; - /** - * Get assembled HTTP request body for sub requests. + * @param {string} [proposeLeaseId] Initial proposed lease Id. + * @returns {BlobLeaseClient} A new BlobLeaseClient object for managing leases on the container. + * @memberof ContainerClient */ - BlobBatch.prototype.getHttpRequestBody = function () { - return this.batchRequest.getHttpRequestBody(); + ContainerClient.prototype.getBlobLeaseClient = function (proposeLeaseId) { + return new BlobLeaseClient(this, proposeLeaseId); }; /** - * Get sub requests that are added into the batch request. + * Creates a new block blob, or updates the content of an existing block blob. + * + * Updating an existing block blob overwrites any existing metadata on the blob. + * Partial updates are not supported; the content of the existing blob is + * overwritten with the new content. To perform a partial update of a block blob's, + * use {@link BlockBlobClient.stageBlock} and {@link BlockBlobClient.commitBlockList}. + * + * This is a non-parallel uploading method, please use {@link BlockBlobClient.uploadFile}, + * {@link BlockBlobClient.uploadStream} or {@link BlockBlobClient.uploadBrowserData} for better + * performance with concurrency uploading. + * + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * + * @param {string} blobName Name of the block blob to create or update. + * @param {HttpRequestBody} body Blob, string, ArrayBuffer, ArrayBufferView or a function + * which returns a new Readable stream whose offset is from data source beginning. + * @param {number} contentLength Length of body in bytes. Use Buffer.byteLength() to calculate body length for a + * string including non non-Base64/Hex-encoded characters. + * @param {BlockBlobUploadOptions} [options] Options to configure the Block Blob Upload operation. + * @returns {Promise<{ blockBlobClient: BlockBlobClient; response: BlockBlobUploadResponse }>} Block Blob upload response data and the corresponding BlockBlobClient instance. + * @memberof ContainerClient */ - BlobBatch.prototype.getSubRequests = function () { - return this.batchRequest.getSubRequests(); - }; - BlobBatch.prototype.addSubRequestInternal = function (subRequest, assembleSubRequestFunc) { + ContainerClient.prototype.uploadBlockBlob = function (blobName, body, contentLength, options) { + if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, Mutex.lock(this.batch)]; + var _a, span, spanOptions, blockBlobClient, response, e_59; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("ContainerClient-uploadBlockBlob", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; case 1: - _a.sent(); - _a.label = 2; + _b.trys.push([1, 3, 4, 5]); + blockBlobClient = this.getBlockBlobClient(blobName); + return [4 /*yield*/, blockBlobClient.upload(body, contentLength, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: - _a.trys.push([2, , 4, 6]); - this.batchRequest.preAddSubRequest(subRequest); - return [4 /*yield*/, assembleSubRequestFunc()]; + response = _b.sent(); + return [2 /*return*/, { + blockBlobClient: blockBlobClient, + response: response + }]; case 3: - _a.sent(); - this.batchRequest.postAddSubRequest(subRequest); - return [3 /*break*/, 6]; - case 4: return [4 /*yield*/, Mutex.unlock(this.batch)]; - case 5: - _a.sent(); + e_59 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_59.message + }); + throw e_59; + case 4: + span.end(); return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; + case 5: return [2 /*return*/]; } }); }); }; - BlobBatch.prototype.setBatchType = function (batchType) { - if (!this.batchType) { - this.batchType = batchType; - } - if (this.batchType !== batchType) { - throw new RangeError("BlobBatch only supports one operation type per batch and it already is being used for " + this.batchType + " operations."); - } - }; - BlobBatch.prototype.deleteBlob = function (urlOrBlobClient, credentialOrOptions, options) { + /** + * Marks the specified blob or snapshot for deletion. The blob is later deleted + * during garbage collection. Note that in order to delete a blob, you must delete + * all of its snapshots. You can delete both at the same time with the Delete + * Blob operation. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob + * + * @param {string} blobName + * @param {ContainerDeleteBlobOptions} [options] Options to Blob Delete operation. + * @returns {Promise} Block blob deletion response data. + * @memberof ContainerClient + */ + ContainerClient.prototype.deleteBlob = function (blobName, options) { + if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var url, credential, _a, span, spanOptions, e_1; - var _this = this; + var _a, span, spanOptions, blobClient, e_60; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - if (typeof urlOrBlobClient === "string" && - ((coreHttp.isNode && credentialOrOptions instanceof StorageSharedKeyCredential) || - credentialOrOptions instanceof AnonymousCredential || - coreHttp.isTokenCredential(credentialOrOptions))) { - // First overload - url = urlOrBlobClient; - credential = credentialOrOptions; - } - else if (urlOrBlobClient instanceof BlobClient) { - // Second overload - url = urlOrBlobClient.url; - credential = urlOrBlobClient.credential; - options = credentialOrOptions; - } - else { - throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); - } - if (!options) { - options = {}; - } - _a = createSpan("BatchDeleteRequest-addSubRequest", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("ContainerClient-deleteBlob", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - this.setBatchType("delete"); - return [4 /*yield*/, this.addSubRequestInternal({ - url: url, - credential: credential - }, function () { return tslib.__awaiter(_this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, new BlobClient(url, this.batchRequest.createPipeline(credential)).delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); })]; - case 2: - _b.sent(); - return [3 /*break*/, 5]; + blobClient = this.getBlobClient(blobName); + if (options.versionId) { + blobClient = blobClient.withVersion(options.versionId); + } + return [4 /*yield*/, blobClient.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: return [2 /*return*/, _b.sent()]; case 3: - e_1 = _b.sent(); + e_60 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_1.message + message: e_60.message }); - throw e_1; + throw e_60; case 4: span.end(); return [7 /*endfinally*/]; @@ -33100,63 +33490,44 @@ var BlobBatch = /** @class */ (function () { }); }); }; - BlobBatch.prototype.setBlobAccessTier = function (urlOrBlobClient, credentialOrTier, tierOrOptions, options) { + /** + * listBlobFlatSegment returns a single segment of blobs starting from the + * specified Marker. Use an empty Marker to start enumeration from the beginning. + * After getting a segment, process it, and then call listBlobsFlatSegment again + * (passing the the previously-returned Marker) to get the next segment. + * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs + * + * @param {string} [marker] A string value that identifies the portion of the list to be returned with the next list operation. + * @param {ContainerListBlobsSegmentOptions} [options] Options to Container List Blob Flat Segment operation. + * @returns {Promise} + * @memberof ContainerClient + */ + ContainerClient.prototype.listBlobFlatSegment = function (marker, options) { + if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var url, credential, tier, _a, span, spanOptions, e_2; - var _this = this; + var _a, span, spanOptions, response, wrappedResponse, e_61; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - if (typeof urlOrBlobClient === "string" && - ((coreHttp.isNode && credentialOrTier instanceof StorageSharedKeyCredential) || - credentialOrTier instanceof AnonymousCredential || - coreHttp.isTokenCredential(credentialOrTier))) { - // First overload - url = urlOrBlobClient; - credential = credentialOrTier; - tier = tierOrOptions; - } - else if (urlOrBlobClient instanceof BlobClient) { - // Second overload - url = urlOrBlobClient.url; - credential = urlOrBlobClient.credential; - tier = credentialOrTier; - options = tierOrOptions; - } - else { - throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); - } - if (!options) { - options = {}; - } - _a = createSpan("BatchSetTierRequest-addSubRequest", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("ContainerClient-listBlobFlatSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - this.setBatchType("setAccessTier"); - return [4 /*yield*/, this.addSubRequestInternal({ - url: url, - credential: credential - }, function () { return tslib.__awaiter(_this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, new BlobClient(url, this.batchRequest.createPipeline(credential)).setAccessTier(tier, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); })]; + return [4 /*yield*/, this.containerContext.listBlobFlatSegment(tslib.__assign(tslib.__assign({ marker: marker }, options), { spanOptions: spanOptions }))]; case 2: - _b.sent(); - return [3 /*break*/, 5]; + response = _b.sent(); + wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, segment: tslib.__assign(tslib.__assign({}, response.segment), { blobItems: response.segment.blobItems.map(function (blobItemInteral) { + var blobItem = tslib.__assign(tslib.__assign({}, blobItemInteral), { tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); + return blobItem; + }) }) }); + return [2 /*return*/, wrappedResponse]; case 3: - e_2 = _b.sent(); + e_61 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_2.message + message: e_61.message }); - throw e_2; + throw e_61; case 4: span.end(); return [7 /*endfinally*/]; @@ -33165,648 +33536,963 @@ var BlobBatch = /** @class */ (function () { }); }); }; - return BlobBatch; -}()); -/** - * Inner batch request class which is responsible for assembling and serializing sub requests. - * See https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#request-body for how requests are assembled. - */ -var InnerBatchRequest = /** @class */ (function () { - function InnerBatchRequest() { - this.operationCount = 0; - this.body = ""; - var tempGuid = coreHttp.generateUuid(); - // batch_{batchid} - this.boundary = "batch_" + tempGuid; - // --batch_{batchid} - // Content-Type: application/http - // Content-Transfer-Encoding: binary - this.subRequestPrefix = "--" + this.boundary + HTTP_LINE_ENDING + HeaderConstants.CONTENT_TYPE + ": application/http" + HTTP_LINE_ENDING + HeaderConstants.CONTENT_TRANSFER_ENCODING + ": binary"; - // multipart/mixed; boundary=batch_{batchid} - this.multipartContentType = "multipart/mixed; boundary=" + this.boundary; - // --batch_{batchid}-- - this.batchRequestEnding = "--" + this.boundary + "--"; - this.subRequests = new Map(); - } /** - * Create pipeline to assemble sub requests. The idea here is to use existing - * credential and serialization/deserialization components, with additional policies to - * filter unnecessary headers, assemble sub requests into request's body - * and intercept request from going to wire. - * @param {StorageSharedKeyCredential | AnonymousCredential | TokenCredential} credential Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the @azure/identity package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used. - */ - InnerBatchRequest.prototype.createPipeline = function (credential) { - var isAnonymousCreds = credential instanceof AnonymousCredential; - var policyFactoryLength = 3 + (isAnonymousCreds ? 0 : 1); // [deserializationPolicy, BatchHeaderFilterPolicyFactory, (Optional)Credential, BatchRequestAssemblePolicyFactory] - var factories = new Array(policyFactoryLength); - factories[0] = coreHttp.deserializationPolicy(); // Default deserializationPolicy is provided by protocol layer - factories[1] = new BatchHeaderFilterPolicyFactory(); // Use batch header filter policy to exclude unnecessary headers - if (!isAnonymousCreds) { - factories[2] = coreHttp.isTokenCredential(credential) - ? coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes) - : credential; - } - factories[policyFactoryLength - 1] = new BatchRequestAssemblePolicyFactory(this); // Use batch assemble policy to assemble request and intercept request from going to wire - return new Pipeline(factories, {}); - }; - InnerBatchRequest.prototype.appendSubRequestToBody = function (request) { - // Start to assemble sub request - this.body += [ - this.subRequestPrefix, - HeaderConstants.CONTENT_ID + ": " + this.operationCount, - "", - request.method.toString() + " " + getURLPathAndQuery(request.url) + " " + HTTP_VERSION_1_1 + HTTP_LINE_ENDING // sub request start line with method - ].join(HTTP_LINE_ENDING); - for (var _i = 0, _a = request.headers.headersArray(); _i < _a.length; _i++) { - var header = _a[_i]; - this.body += header.name + ": " + header.value + HTTP_LINE_ENDING; - } - this.body += HTTP_LINE_ENDING; // sub request's headers need be ending with an empty line - // No body to assemble for current batch request support - // End to assemble sub request - }; - InnerBatchRequest.prototype.preAddSubRequest = function (subRequest) { - if (this.operationCount >= BATCH_MAX_REQUEST) { - throw new RangeError("Cannot exceed " + BATCH_MAX_REQUEST + " sub requests in a single batch"); - } - // Fast fail if url for sub request is invalid - var path = getURLPath(subRequest.url); - if (!path || path == "") { - throw new RangeError("Invalid url for sub request: '" + subRequest.url + "'"); - } - }; - InnerBatchRequest.prototype.postAddSubRequest = function (subRequest) { - this.subRequests.set(this.operationCount, subRequest); - this.operationCount++; - }; - // Return the http request body with assembling the ending line to the sub request body. - InnerBatchRequest.prototype.getHttpRequestBody = function () { - return "" + this.body + this.batchRequestEnding + HTTP_LINE_ENDING; - }; - InnerBatchRequest.prototype.getMultipartContentType = function () { - return this.multipartContentType; - }; - InnerBatchRequest.prototype.getSubRequests = function () { - return this.subRequests; - }; - return InnerBatchRequest; -}()); -var BatchRequestAssemblePolicy = /** @class */ (function (_super) { - tslib.__extends(BatchRequestAssemblePolicy, _super); - function BatchRequestAssemblePolicy(batchRequest, nextPolicy, options) { - var _this = _super.call(this, nextPolicy, options) || this; - _this.dummyResponse = { - request: new coreHttp.WebResource(), - status: 200, - headers: new coreHttp.HttpHeaders() - }; - _this.batchRequest = batchRequest; - return _this; - } - BatchRequestAssemblePolicy.prototype.sendRequest = function (request) { + * listBlobHierarchySegment returns a single segment of blobs starting from + * the specified Marker. Use an empty Marker to start enumeration from the + * beginning. After getting a segment, process it, and then call listBlobsHierarchicalSegment + * again (passing the the previously-returned Marker) to get the next segment. + * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs + * + * @param {string} delimiter The character or string used to define the virtual hierarchy + * @param {string} [marker] A string value that identifies the portion of the list to be returned with the next list operation. + * @param {ContainerListBlobsSegmentOptions} [options] Options to Container List Blob Hierarchy Segment operation. + * @returns {Promise} + * @memberof ContainerClient + */ + ContainerClient.prototype.listBlobHierarchySegment = function (delimiter, marker, options) { + if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, response, wrappedResponse, e_62; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("ContainerClient-listBlobHierarchySegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.containerContext.listBlobHierarchySegment(delimiter, tslib.__assign(tslib.__assign({ marker: marker }, options), { spanOptions: spanOptions }))]; + case 2: + response = _b.sent(); + wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, segment: tslib.__assign(tslib.__assign({}, response.segment), { blobItems: response.segment.blobItems.map(function (blobItemInteral) { + var blobItem = tslib.__assign(tslib.__assign({}, blobItemInteral), { tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); + return blobItem; + }) }) }); + return [2 /*return*/, wrappedResponse]; + case 3: + e_62 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_62.message + }); + throw e_62; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an AsyncIterableIterator for ContainerListBlobFlatSegmentResponse + * + * @private + * @param {string} [marker] A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the ContinuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The ContinuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. + * @returns {AsyncIterableIterator} + * @memberof ContainerClient + */ + ContainerClient.prototype.listSegments = function (marker, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listSegments_1() { + var listBlobsFlatSegmentResponse; return tslib.__generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, this.batchRequest.appendSubRequestToBody(request)]; - case 1: + case 0: + if (!(!!marker || marker === undefined)) return [3 /*break*/, 7]; + _a.label = 1; + case 1: return [4 /*yield*/, tslib.__await(this.listBlobFlatSegment(marker, options))]; + case 2: + listBlobsFlatSegmentResponse = _a.sent(); + marker = listBlobsFlatSegmentResponse.continuationToken; + return [4 /*yield*/, tslib.__await(listBlobsFlatSegmentResponse)]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_a.sent()])]; + case 4: return [4 /*yield*/, _a.sent()]; + case 5: _a.sent(); - return [2 /*return*/, this.dummyResponse]; // Intercept request from going to wire + _a.label = 6; + case 6: + if (marker) return [3 /*break*/, 1]; + _a.label = 7; + case 7: return [2 /*return*/]; } }); }); }; - return BatchRequestAssemblePolicy; -}(coreHttp.BaseRequestPolicy)); -var BatchRequestAssemblePolicyFactory = /** @class */ (function () { - function BatchRequestAssemblePolicyFactory(batchRequest) { - this.batchRequest = batchRequest; - } - BatchRequestAssemblePolicyFactory.prototype.create = function (nextPolicy, options) { - return new BatchRequestAssemblePolicy(this.batchRequest, nextPolicy, options); - }; - return BatchRequestAssemblePolicyFactory; -}()); -var BatchHeaderFilterPolicy = /** @class */ (function (_super) { - tslib.__extends(BatchHeaderFilterPolicy, _super); - function BatchHeaderFilterPolicy(nextPolicy, options) { - return _super.call(this, nextPolicy, options) || this; - } - BatchHeaderFilterPolicy.prototype.sendRequest = function (request) { - return tslib.__awaiter(this, void 0, void 0, function () { - var xMsHeaderName, _i, _a, header; - return tslib.__generator(this, function (_b) { - xMsHeaderName = ""; - for (_i = 0, _a = request.headers.headersArray(); _i < _a.length; _i++) { - header = _a[_i]; - if (iEqual(header.name, HeaderConstants.X_MS_VERSION)) { - xMsHeaderName = header.name; - } - } - if (xMsHeaderName !== "") { - request.headers.remove(xMsHeaderName); // The subrequests should not have the x-ms-version header. + /** + * Returns an AsyncIterableIterator of {@link BlobItem} objects + * + * @private + * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. + * @returns {AsyncIterableIterator} + * @memberof ContainerClient + */ + ContainerClient.prototype.listItems = function (options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listItems_1() { + var marker, _a, _b, listBlobsFlatSegmentResponse, e_63_1; + var e_63, _c; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _d.trys.push([0, 7, 8, 13]); + _a = tslib.__asyncValues(this.listSegments(marker, options)); + _d.label = 1; + case 1: return [4 /*yield*/, tslib.__await(_a.next())]; + case 2: + if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; + listBlobsFlatSegmentResponse = _b.value; + return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(listBlobsFlatSegmentResponse.segment.blobItems)))]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; + case 4: + _d.sent(); + _d.label = 5; + case 5: return [3 /*break*/, 1]; + case 6: return [3 /*break*/, 13]; + case 7: + e_63_1 = _d.sent(); + e_63 = { error: e_63_1 }; + return [3 /*break*/, 13]; + case 8: + _d.trys.push([8, , 11, 12]); + if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; + return [4 /*yield*/, tslib.__await(_c.call(_a))]; + case 9: + _d.sent(); + _d.label = 10; + case 10: return [3 /*break*/, 12]; + case 11: + if (e_63) throw e_63.error; + return [7 /*endfinally*/]; + case 12: return [7 /*endfinally*/]; + case 13: return [2 /*return*/]; } - return [2 /*return*/, this._nextPolicy.sendRequest(request)]; }); }); }; - return BatchHeaderFilterPolicy; -}(coreHttp.BaseRequestPolicy)); -var BatchHeaderFilterPolicyFactory = /** @class */ (function () { - function BatchHeaderFilterPolicyFactory() { - } - BatchHeaderFilterPolicyFactory.prototype.create = function (nextPolicy, options) { - return new BatchHeaderFilterPolicy(nextPolicy, options); - }; - return BatchHeaderFilterPolicyFactory; -}()); - -// Copyright (c) Microsoft Corporation. All rights reserved. -/** - * A BlobBatchClient allows you to make batched requests to the Azure Storage Blob service. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch - */ -var BlobBatchClient = /** @class */ (function () { - function BlobBatchClient(url, credentialOrPipeline, options) { - var pipeline; - if (credentialOrPipeline instanceof Pipeline) { - pipeline = credentialOrPipeline; + /** + * Returns an async iterable iterator to list all the blobs + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the blobs in pages. + * + * Example using `for await` syntax: + * + * ```js + * // Get the containerClient before you run these snippets, + * // Can be obtained from `blobServiceClient.getContainerClient("");` + * let i = 1; + * for await (const blob of containerClient.listBlobsFlat()) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * let iter = containerClient.listBlobsFlat(); + * let blobItem = await iter.next(); + * while (!blobItem.done) { + * console.log(`Blob ${i++}: ${blobItem.value.name}`); + * blobItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of containerClient.listBlobsFlat().byPage({ maxPageSize: 20 })) { + * for (const blob of response.segment.blobItems) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = containerClient.listBlobsFlat().byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 blob names + * for (const blob of response.segment.blobItems) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * + * // Passing next marker as continuationToken + * + * iterator = containerClient.listBlobsFlat().byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints 10 blob names + * for (const blob of response.segment.blobItems) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * ``` + * + * @param {ContainerListBlobsOptions} [options={}] Options to list blobs. + * @returns {PagedAsyncIterableIterator} An asyncIterableIterator that supports paging. + * @memberof ContainerClient + */ + ContainerClient.prototype.listBlobsFlat = function (options) { + var _a; + var _this = this; + if (options === void 0) { options = {}; } + var include = []; + if (options.includeCopy) { + include.push("copy"); } - else if (!credentialOrPipeline) { - // no credential provided - pipeline = newPipeline(new AnonymousCredential(), options); + if (options.includeDeleted) { + include.push("deleted"); } - else { - pipeline = newPipeline(credentialOrPipeline, options); + if (options.includeMetadata) { + include.push("metadata"); } - var storageClientContext = new StorageClientContext(url, pipeline.toServiceClientOptions()); - this._serviceContext = new Service(storageClientContext); - } + if (options.includeSnapshots) { + include.push("snapshots"); + } + if (options.includeVersions) { + include.push("versions"); + } + if (options.includeUncommitedBlobs) { + include.push("uncommittedblobs"); + } + if (options.includeTags) { + include.push("tags"); + } + if (options.prefix === "") { + options.prefix = undefined; + } + var updatedOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); + // AsyncIterableIterator to iterate over blobs + var iter = this.listItems(updatedOptions); + return _a = { + /** + * @member {Promise} [next] The next method, part of the iteration protocol + */ + next: function () { + return iter.next(); + } + }, + /** + * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol + */ + _a[Symbol.asyncIterator] = function () { + return this; + }, + /** + * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time + */ + _a.byPage = function (settings) { + if (settings === void 0) { settings = {}; } + return _this.listSegments(settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); + }, + _a; + }; /** - * Creates a {@link BlobBatch}. - * A BlobBatch represents an aggregated set of operations on blobs. + * Returns an AsyncIterableIterator for ContainerListBlobHierarchySegmentResponse + * + * @private + * @param {string} delimiter The character or string used to define the virtual hierarchy + * @param {string} [marker] A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the ContinuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The ContinuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. + * @returns {AsyncIterableIterator} + * @memberof ContainerClient */ - BlobBatchClient.prototype.createBatch = function () { - return new BlobBatch(); - }; - BlobBatchClient.prototype.deleteBlobs = function (urlsOrBlobClients, credentialOrOptions, options) { - return tslib.__awaiter(this, void 0, void 0, function () { - var batch, _i, urlsOrBlobClients_1, urlOrBlobClient; + ContainerClient.prototype.listHierarchySegments = function (delimiter, marker, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listHierarchySegments_1() { + var listBlobsHierarchySegmentResponse; return tslib.__generator(this, function (_a) { switch (_a.label) { case 0: - batch = new BlobBatch(); - _i = 0, urlsOrBlobClients_1 = urlsOrBlobClients; + if (!(!!marker || marker === undefined)) return [3 /*break*/, 7]; _a.label = 1; - case 1: - if (!(_i < urlsOrBlobClients_1.length)) return [3 /*break*/, 6]; - urlOrBlobClient = urlsOrBlobClients_1[_i]; - if (!(typeof urlOrBlobClient === "string")) return [3 /*break*/, 3]; - return [4 /*yield*/, batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options)]; + case 1: return [4 /*yield*/, tslib.__await(this.listBlobHierarchySegment(delimiter, marker, options))]; case 2: - _a.sent(); - return [3 /*break*/, 5]; - case 3: return [4 /*yield*/, batch.deleteBlob(urlOrBlobClient, credentialOrOptions)]; - case 4: - _a.sent(); - _a.label = 5; + listBlobsHierarchySegmentResponse = _a.sent(); + marker = listBlobsHierarchySegmentResponse.continuationToken; + return [4 /*yield*/, tslib.__await(listBlobsHierarchySegmentResponse)]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_a.sent()])]; + case 4: return [4 /*yield*/, _a.sent()]; case 5: - _i++; - return [3 /*break*/, 1]; - case 6: return [2 /*return*/, this.submitBatch(batch)]; + _a.sent(); + _a.label = 6; + case 6: + if (marker) return [3 /*break*/, 1]; + _a.label = 7; + case 7: return [2 /*return*/]; } }); }); }; - BlobBatchClient.prototype.setBlobsAccessTier = function (urlsOrBlobClients, credentialOrTier, tierOrOptions, options) { - return tslib.__awaiter(this, void 0, void 0, function () { - var batch, _i, urlsOrBlobClients_2, urlOrBlobClient; - return tslib.__generator(this, function (_a) { - switch (_a.label) { + /** + * Returns an AsyncIterableIterator for {@link BlobPrefix} and {@link BlobItem} objects. + * + * @private + * @param {string} delimiter The character or string used to define the virtual hierarchy + * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. + * @returns {AsyncIterableIterator<{ kind: "prefix" } & BlobPrefix | { kind: "blob" } & BlobItem>} + * @memberof ContainerClient + */ + ContainerClient.prototype.listItemsByHierarchy = function (delimiter, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listItemsByHierarchy_1() { + var marker, _a, _b, listBlobsHierarchySegmentResponse, segment, _i, _c, prefix, _d, _e, blob, e_64_1; + var e_64, _f; + return tslib.__generator(this, function (_g) { + switch (_g.label) { case 0: - batch = new BlobBatch(); - _i = 0, urlsOrBlobClients_2 = urlsOrBlobClients; - _a.label = 1; - case 1: - if (!(_i < urlsOrBlobClients_2.length)) return [3 /*break*/, 6]; - urlOrBlobClient = urlsOrBlobClients_2[_i]; - if (!(typeof urlOrBlobClient === "string")) return [3 /*break*/, 3]; - return [4 /*yield*/, batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options)]; + _g.trys.push([0, 14, 15, 20]); + _a = tslib.__asyncValues(this.listHierarchySegments(delimiter, marker, options)); + _g.label = 1; + case 1: return [4 /*yield*/, tslib.__await(_a.next())]; case 2: - _a.sent(); - return [3 /*break*/, 5]; - case 3: return [4 /*yield*/, batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions)]; - case 4: - _a.sent(); - _a.label = 5; + if (!(_b = _g.sent(), !_b.done)) return [3 /*break*/, 13]; + listBlobsHierarchySegmentResponse = _b.value; + segment = listBlobsHierarchySegmentResponse.segment; + if (!segment.blobPrefixes) return [3 /*break*/, 7]; + _i = 0, _c = segment.blobPrefixes; + _g.label = 3; + case 3: + if (!(_i < _c.length)) return [3 /*break*/, 7]; + prefix = _c[_i]; + return [4 /*yield*/, tslib.__await(tslib.__assign({ kind: "prefix" }, prefix))]; + case 4: return [4 /*yield*/, _g.sent()]; case 5: + _g.sent(); + _g.label = 6; + case 6: _i++; - return [3 /*break*/, 1]; - case 6: return [2 /*return*/, this.submitBatch(batch)]; + return [3 /*break*/, 3]; + case 7: + _d = 0, _e = segment.blobItems; + _g.label = 8; + case 8: + if (!(_d < _e.length)) return [3 /*break*/, 12]; + blob = _e[_d]; + return [4 /*yield*/, tslib.__await(tslib.__assign({ kind: "blob" }, blob))]; + case 9: return [4 /*yield*/, _g.sent()]; + case 10: + _g.sent(); + _g.label = 11; + case 11: + _d++; + return [3 /*break*/, 8]; + case 12: return [3 /*break*/, 1]; + case 13: return [3 /*break*/, 20]; + case 14: + e_64_1 = _g.sent(); + e_64 = { error: e_64_1 }; + return [3 /*break*/, 20]; + case 15: + _g.trys.push([15, , 18, 19]); + if (!(_b && !_b.done && (_f = _a.return))) return [3 /*break*/, 17]; + return [4 /*yield*/, tslib.__await(_f.call(_a))]; + case 16: + _g.sent(); + _g.label = 17; + case 17: return [3 /*break*/, 19]; + case 18: + if (e_64) throw e_64.error; + return [7 /*endfinally*/]; + case 19: return [7 /*endfinally*/]; + case 20: return [2 /*return*/]; } }); }); }; /** - * Submit batch request which consists of multiple subrequests. + * Returns an async iterable iterator to list all the blobs by hierarchy. + * under the specified account. * - * Get `blobBatchClient` and other details before running the snippets. - * `blobServiceClient.getBlobBatchClient()` gives the `blobBatchClient` + * .byPage() returns an async iterable iterator to list the blobs by hierarchy in pages. * - * Example usage: + * Example using `for await` syntax: * * ```js - * let batchRequest = new BlobBatch(); - * await batchRequest.deleteBlob(urlInString0, credential0); - * await batchRequest.deleteBlob(urlInString1, credential1, { - * deleteSnapshots: "include" - * }); - * const batchResp = await blobBatchClient.submitBatch(batchRequest); - * console.log(batchResp.subResponsesSucceededCount); + * for await (const item of containerClient.listBlobsByHierarchy("/")) { + * if (item.kind === "prefix") { + * console.log(`\tBlobPrefix: ${item.name}`); + * } else { + * console.log(`\tBlobItem: name - ${item.name}, last modified - ${item.properties.lastModified}`); + * } + * } * ``` * - * Example using a lease: + * Example using `iter.next()`: * * ```js - * let batchRequest = new BlobBatch(); - * await batchRequest.setBlobAccessTier(blockBlobClient0, "Cool"); - * await batchRequest.setBlobAccessTier(blockBlobClient1, "Cool", { - * conditions: { leaseId: leaseId } - * }); - * const batchResp = await blobBatchClient.submitBatch(batchRequest); - * console.log(batchResp.subResponsesSucceededCount); + * let iter = containerClient.listBlobsByHierarchy("/", { prefix: "prefix1/" }); + * let entity = await iter.next(); + * while (!entity.done) { + * let item = entity.value; + * if (item.kind === "prefix") { + * console.log(`\tBlobPrefix: ${item.name}`); + * } else { + * console.log(`\tBlobItem: name - ${item.name}, last modified - ${item.properties.lastModified}`); + * } + * entity = await iter.next(); + * } * ``` * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch + * Example using `byPage()`: + * + * ```js + * console.log("Listing blobs by hierarchy by page"); + * for await (const response of containerClient.listBlobsByHierarchy("/").byPage()) { + * const segment = response.segment; + * if (segment.blobPrefixes) { + * for (const prefix of segment.blobPrefixes) { + * console.log(`\tBlobPrefix: ${prefix.name}`); + * } + * } + * for (const blob of response.segment.blobItems) { + * console.log(`\tBlobItem: name - ${blob.name}, last modified - ${blob.properties.lastModified}`); + * } + * } + * ``` + * + * Example using paging with a max page size: + * + * ```js + * console.log("Listing blobs by hierarchy by page, specifying a prefix and a max page size"); + * + * let i = 1; + * for await (const response of containerClient.listBlobsByHierarchy("/", { prefix: "prefix2/sub1/"}).byPage({ maxPageSize: 2 })) { + * console.log(`Page ${i++}`); + * const segment = response.segment; + * + * if (segment.blobPrefixes) { + * for (const prefix of segment.blobPrefixes) { + * console.log(`\tBlobPrefix: ${prefix.name}`); + * } + * } + * + * for (const blob of response.segment.blobItems) { + * console.log(`\tBlobItem: name - ${blob.name}, last modified - ${blob.properties.lastModified}`); + * } + * } + * ``` * - * @param {BlobBatch} batchRequest A set of Delete or SetTier operations. - * @param {BlobBatchSubmitBatchOptionalParams} [options] - * @returns {Promise} - * @memberof BlobBatchClient + * @param {string} delimiter The character or string used to define the virtual hierarchy + * @param {ContainerListBlobsOptions} [options={}] Options to list blobs operation. + * @returns {(PagedAsyncIterableIterator< + * { kind: "prefix" } & BlobPrefix | { kind: "blob" } & BlobItem, + * ContainerListBlobHierarchySegmentResponse>)} + * @memberof ContainerClient */ - BlobBatchClient.prototype.submitBatch = function (batchRequest, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, batchRequestBody, rawBatchResponse, batchResponseParser, responseSummary, res, e_1; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!batchRequest || batchRequest.getSubRequests().size == 0) { - throw new RangeError("Batch request should contain one or more sub requests."); - } - _a = createSpan("BlobBatchClient-submitBatch", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 4, 5, 6]); - batchRequestBody = batchRequest.getHttpRequestBody(); - return [4 /*yield*/, this._serviceContext.submitBatch(batchRequestBody, utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), tslib.__assign(tslib.__assign({}, options), { spanOptions: spanOptions }))]; - case 2: - rawBatchResponse = _b.sent(); - batchResponseParser = new BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests()); - return [4 /*yield*/, batchResponseParser.parseBatchResponse()]; - case 3: - responseSummary = _b.sent(); - res = { - _response: rawBatchResponse._response, - contentType: rawBatchResponse.contentType, - errorCode: rawBatchResponse.errorCode, - requestId: rawBatchResponse.requestId, - clientRequestId: rawBatchResponse.clientRequestId, - version: rawBatchResponse.version, - subResponses: responseSummary.subResponses, - subResponsesSucceededCount: responseSummary.subResponsesSucceededCount, - subResponsesFailedCount: responseSummary.subResponsesFailedCount - }; - return [2 /*return*/, res]; - case 4: - e_1 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_1.message - }); - throw e_1; - case 5: - span.end(); - return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; - } - }); - }); - }; - return BlobBatchClient; -}()); - -/** - * A BlobServiceClient represents a Client to the Azure Storage Blob service allowing you - * to manipulate blob containers. - * - * @export - * @class BlobServiceClient - */ -var BlobServiceClient = /** @class */ (function (_super) { - tslib.__extends(BlobServiceClient, _super); - function BlobServiceClient(url, credentialOrPipeline, options) { + ContainerClient.prototype.listBlobsByHierarchy = function (delimiter, options) { + var _a; var _this = this; - var pipeline; - if (credentialOrPipeline instanceof Pipeline) { - pipeline = credentialOrPipeline; + if (options === void 0) { options = {}; } + if (delimiter === "") { + throw new RangeError("delimiter should contain one or more characters"); } - else if ((coreHttp.isNode && credentialOrPipeline instanceof StorageSharedKeyCredential) || - credentialOrPipeline instanceof AnonymousCredential || - coreHttp.isTokenCredential(credentialOrPipeline)) { - pipeline = newPipeline(credentialOrPipeline, options); + var include = []; + if (options.includeCopy) { + include.push("copy"); } - else { - // The second parameter is undefined. Use anonymous credential - pipeline = newPipeline(new AnonymousCredential(), options); + if (options.includeDeleted) { + include.push("deleted"); } - _this = _super.call(this, url, pipeline) || this; - _this.serviceContext = new Service(_this.storageClientContext); - return _this; - } - /** - * - * Creates an instance of BlobServiceClient from connection string. - * - * @param {string} connectionString Account connection string or a SAS connection string of an Azure storage account. - * [ Note - Account connection string can only be used in NODE.JS runtime. ] - * Account connection string example - - * `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net` - * SAS connection string example - - * `BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString` - * @param {StoragePipelineOptions} [options] Optional. Options to configure the HTTP pipeline. - * @memberof BlobServiceClient - */ - BlobServiceClient.fromConnectionString = function (connectionString, options) { - options = options || {}; - var extractedCreds = extractConnectionStringParts(connectionString); - if (extractedCreds.kind === "AccountConnString") { - { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); - var pipeline = newPipeline(sharedKeyCredential, options); - return new BlobServiceClient(extractedCreds.url, pipeline); - } + if (options.includeMetadata) { + include.push("metadata"); } - else if (extractedCreds.kind === "SASConnString") { - var pipeline = newPipeline(new AnonymousCredential(), options); - return new BlobServiceClient(extractedCreds.url + "?" + extractedCreds.accountSas, pipeline); + if (options.includeSnapshots) { + include.push("snapshots"); } - else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + if (options.includeVersions) { + include.push("versions"); + } + if (options.includeUncommitedBlobs) { + include.push("uncommittedblobs"); + } + if (options.includeTags) { + include.push("tags"); + } + if (options.prefix === "") { + options.prefix = undefined; + } + var updatedOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); + // AsyncIterableIterator to iterate over blob prefixes and blobs + var iter = this.listItemsByHierarchy(delimiter, updatedOptions); + return _a = { + /** + * @member {Promise} [next] The next method, part of the iteration protocol + */ + next: function () { + return tslib.__awaiter(this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + return [2 /*return*/, iter.next()]; + }); + }); + } + }, + /** + * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol + */ + _a[Symbol.asyncIterator] = function () { + return this; + }, + /** + * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time + */ + _a.byPage = function (settings) { + if (settings === void 0) { settings = {}; } + return _this.listHierarchySegments(delimiter, settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); + }, + _a; + }; + ContainerClient.prototype.getContainerNameFromUrl = function () { + var containerName; + try { + // URL may look like the following + // "https://myaccount.blob.core.windows.net/mycontainer?sasString"; + // "https://myaccount.blob.core.windows.net/mycontainer"; + // IPv4/IPv6 address hosts, Endpoints - `http://127.0.0.1:10000/devstoreaccount1/containername` + // http://localhost:10001/devstoreaccount1/containername + var parsedUrl = coreHttp.URLBuilder.parse(this.url); + if (parsedUrl.getHost().split(".")[1] === "blob") { + // "https://myaccount.blob.core.windows.net/containername". + // "https://customdomain.com/containername". + // .getPath() -> /containername + containerName = parsedUrl.getPath().split("/")[1]; + } + else if (isIpEndpointStyle(parsedUrl)) { + // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/containername + // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/containername + // .getPath() -> /devstoreaccount1/containername + containerName = parsedUrl.getPath().split("/")[2]; + } + else { + // "https://customdomain.com/containername". + // .getPath() -> /containername + containerName = parsedUrl.getPath().split("/")[1]; + } + // decode the encoded containerName - to get all the special characters that might be present in it + containerName = decodeURIComponent(containerName); + if (!containerName) { + throw new Error("Provided containerName is invalid."); + } + return containerName; + } + catch (error) { + throw new Error("Unable to extract containerName with provided information."); } }; /** - * Creates a {@link ContainerClient} object + * Only available for ContainerClient constructed with a shared key credential. * - * @param {string} containerName A container name - * @returns {ContainerClient} A new ContainerClient object for the given container name. - * @memberof BlobServiceClient + * Generates a Blob Container Service Shared Access Signature (SAS) URI based on the client properties + * and parameters passed in. The SAS is signed by the shared key credential of the client. * - * Example usage: + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * - * ```js - * const containerClient = blobServiceClient.getContainerClient(""); - * ``` + * @param {ContainerGenerateSasUrlOptions} options Optional parameters. + * @returns {Promise} The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + * @memberof ContainerClient */ - BlobServiceClient.prototype.getContainerClient = function (containerName) { - return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline); + ContainerClient.prototype.generateSasUrl = function (options) { + var _this = this; + return new Promise(function (resolve) { + if (!(_this.credential instanceof StorageSharedKeyCredential)) { + throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); + } + var sas = generateBlobSASQueryParameters(tslib.__assign({ containerName: _this._containerName }, options), _this.credential).toString(); + resolve(appendToURLQuery(_this.url, sas)); + }); }; - /** - * Create a Blob container. - * - * @param {string} containerName Name of the container to create. - * @param {ContainerCreateOptions} [options] Options to configure Container Create operation. - * @returns {Promise<{ containerClient: ContainerClient; containerCreateResponse: ContainerCreateResponse }>} Container creation response and the corresponding container client. - * @memberof BlobServiceClient - */ - BlobServiceClient.prototype.createContainer = function (containerName, options) { - if (options === void 0) { options = {}; } + return ContainerClient; +}(StorageClient)); + +function getBodyAsText(batchResponse) { + return tslib.__awaiter(this, void 0, void 0, function () { + var buffer, responseLength; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + buffer = Buffer.alloc(BATCH_MAX_PAYLOAD_IN_BYTES); + return [4 /*yield*/, streamToBuffer2(batchResponse.readableStreamBody, buffer)]; + case 1: + responseLength = _a.sent(); + // Slice the buffer to trim the empty ending. + buffer = buffer.slice(0, responseLength); + return [2 /*return*/, buffer.toString()]; + } + }); + }); +} +function utf8ByteLength(str) { + return Buffer.byteLength(str); +} + +var HTTP_HEADER_DELIMITER = ": "; +var SPACE_DELIMITER = " "; +var NOT_FOUND = -1; +/** + * Util class for parsing batch response. + */ +var BatchResponseParser = /** @class */ (function () { + function BatchResponseParser(batchResponse, subRequests) { + if (!batchResponse || !batchResponse.contentType) { + // In special case(reported), server may return invalid content-type which could not be parsed. + throw new RangeError("batchResponse is malformed or doesn't contain valid content-type."); + } + if (!subRequests || subRequests.size === 0) { + // This should be prevent during coding. + throw new RangeError("Invalid state: subRequests is not provided or size is 0."); + } + this.batchResponse = batchResponse; + this.subRequests = subRequests; + this.responseBatchBoundary = this.batchResponse.contentType.split("=")[1]; + this.perResponsePrefix = "--" + this.responseBatchBoundary + HTTP_LINE_ENDING; + this.batchResponseEnding = "--" + this.responseBatchBoundary + "--"; + } + // For example of response, please refer to https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#response + BatchResponseParser.prototype.parseBatchResponse = function () { return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, containerClient, containerCreateResponse, e_1; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + var responseBodyAsText, subResponses, subResponseCount, deserializedSubResponses, subResponsesSucceededCount, subResponsesFailedCount, index, subResponse, deserializedSubResponse, responseLines, subRespHeaderStartFound, subRespHeaderEndFound, subRespFailed, contentId, _i, responseLines_1, responseLine, tokens, tokens; + return tslib.__generator(this, function (_a) { + switch (_a.label) { case 0: - _a = createSpan("BlobServiceClient-createContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + // When logic reach here, suppose batch request has already succeeded with 202, so we can further parse + // sub request's response. + if (this.batchResponse._response.status != HTTPURLConnection.HTTP_ACCEPTED) { + throw new Error("Invalid state: batch request failed with status: '" + this.batchResponse._response.status + "'."); + } + return [4 /*yield*/, getBodyAsText(this.batchResponse)]; case 1: - _b.trys.push([1, 3, 4, 5]); - containerClient = this.getContainerClient(containerName); - return [4 /*yield*/, containerClient.create(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: - containerCreateResponse = _b.sent(); + responseBodyAsText = _a.sent(); + subResponses = responseBodyAsText + .split(this.batchResponseEnding)[0] // string after ending is useless + .split(this.perResponsePrefix) + .slice(1); + subResponseCount = subResponses.length; + // Defensive coding in case of potential error parsing. + // Note: subResponseCount == 1 is special case where sub request is invalid. + // We try to prevent such cases through early validation, e.g. validate sub request count >= 1. + // While in unexpected sub request invalid case, we allow sub response to be parsed and return to user. + if (subResponseCount != this.subRequests.size && subResponseCount != 1) { + throw new Error("Invalid state: sub responses' count is not equal to sub requests' count."); + } + deserializedSubResponses = new Array(subResponseCount); + subResponsesSucceededCount = 0; + subResponsesFailedCount = 0; + // Parse sub subResponses. + for (index = 0; index < subResponseCount; index++) { + subResponse = subResponses[index]; + deserializedSubResponse = {}; + deserializedSubResponse.headers = new coreHttp.HttpHeaders(); + responseLines = subResponse.split("" + HTTP_LINE_ENDING); + subRespHeaderStartFound = false; + subRespHeaderEndFound = false; + subRespFailed = false; + contentId = NOT_FOUND; + for (_i = 0, responseLines_1 = responseLines; _i < responseLines_1.length; _i++) { + responseLine = responseLines_1[_i]; + if (!subRespHeaderStartFound) { + // Convention line to indicate content ID + if (responseLine.startsWith(HeaderConstants.CONTENT_ID)) { + contentId = parseInt(responseLine.split(HTTP_HEADER_DELIMITER)[1]); + } + // Http version line with status code indicates the start of sub request's response. + // Example: HTTP/1.1 202 Accepted + if (responseLine.startsWith(HTTP_VERSION_1_1)) { + subRespHeaderStartFound = true; + tokens = responseLine.split(SPACE_DELIMITER); + deserializedSubResponse.status = parseInt(tokens[1]); + deserializedSubResponse.statusMessage = tokens.slice(2).join(SPACE_DELIMITER); + } + continue; // Skip convention headers not specifically for sub request i.e. Content-Type: application/http and Content-ID: * + } + if (responseLine.trim() === "") { + // Sub response's header start line already found, and the first empty line indicates header end line found. + if (!subRespHeaderEndFound) { + subRespHeaderEndFound = true; + } + continue; // Skip empty line + } + // Note: when code reach here, it indicates subRespHeaderStartFound == true + if (!subRespHeaderEndFound) { + if (responseLine.indexOf(HTTP_HEADER_DELIMITER) === -1) { + // Defensive coding to prevent from missing valuable lines. + throw new Error("Invalid state: find non-empty line '" + responseLine + "' without HTTP header delimiter '" + HTTP_HEADER_DELIMITER + "'."); + } + tokens = responseLine.split(HTTP_HEADER_DELIMITER); + deserializedSubResponse.headers.set(tokens[0], tokens[1]); + if (tokens[0] === HeaderConstants.X_MS_ERROR_CODE) { + deserializedSubResponse.errorCode = tokens[1]; + subRespFailed = true; + } + } + else { + // Assemble body of sub response. + if (!deserializedSubResponse.bodyAsText) { + deserializedSubResponse.bodyAsText = ""; + } + deserializedSubResponse.bodyAsText += responseLine; + } + } // Inner for end + // The response will contain the Content-ID header for each corresponding subrequest response to use for tracking. + // The Content-IDs are set to a valid index in the subrequests we sent. In the status code 202 path, we could expect it + // to be 1-1 mapping from the [0, subRequests.size) to the Content-IDs returned. If not, we simply don't return that + // unexpected subResponse in the parsed reponse and we can always look it up in the raw response for debugging purpose. + if (contentId != NOT_FOUND && + Number.isInteger(contentId) && + contentId >= 0 && + contentId < this.subRequests.size && + deserializedSubResponses[contentId] === undefined) { + deserializedSubResponse._request = this.subRequests.get(contentId); + deserializedSubResponses[contentId] = deserializedSubResponse; + } + else { + logger.error("subResponses[" + index + "] is dropped as the Content-ID is not found or invalid, Content-ID: " + contentId); + } + if (subRespFailed) { + subResponsesFailedCount++; + } + else { + subResponsesSucceededCount++; + } + } return [2 /*return*/, { - containerClient: containerClient, - containerCreateResponse: containerCreateResponse + subResponses: deserializedSubResponses, + subResponsesSucceededCount: subResponsesSucceededCount, + subResponsesFailedCount: subResponsesFailedCount }]; - case 3: - e_1 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_1.message - }); - throw e_1; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; } }); }); }; + return BatchResponseParser; +}()); + +var MutexLockStatus; +(function (MutexLockStatus) { + MutexLockStatus[MutexLockStatus["LOCKED"] = 0] = "LOCKED"; + MutexLockStatus[MutexLockStatus["UNLOCKED"] = 1] = "UNLOCKED"; +})(MutexLockStatus || (MutexLockStatus = {})); +/** + * An async mutex lock. + * + * @export + * @class Mutex + */ +var Mutex = /** @class */ (function () { + function Mutex() { + } /** - * Deletes a Blob container. + * Lock for a specific key. If the lock has been acquired by another customer, then + * will wait until getting the lock. * - * @param {string} containerName Name of the container to delete. - * @param {ContainerDeleteMethodOptions} [options] Options to configure Container Delete operation. - * @returns {Promise} Container deletion response. - * @memberof BlobServiceClient + * @static + * @param {string} key lock key + * @returns {Promise} + * @memberof Mutex */ - BlobServiceClient.prototype.deleteContainer = function (containerName, options) { - if (options === void 0) { options = {}; } + Mutex.lock = function (key) { return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, containerClient, e_2; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-deleteContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - containerClient = this.getContainerClient(containerName); - return [4 /*yield*/, containerClient.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_2 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_2.message - }); - throw e_2; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + var _this = this; + return tslib.__generator(this, function (_a) { + return [2 /*return*/, new Promise(function (resolve) { + if (_this.keys[key] === undefined || _this.keys[key] === MutexLockStatus.UNLOCKED) { + _this.keys[key] = MutexLockStatus.LOCKED; + resolve(); + } + else { + _this.onUnlockEvent(key, function () { + _this.keys[key] = MutexLockStatus.LOCKED; + resolve(); + }); + } + })]; }); }); }; /** - * Restore a previously deleted Blob container. - * This API is only functional if Container Soft Delete is enabled for the storage account associated with the container. + * Unlock a key. * - * @param {string} deletedContainerName Name of the previously deleted container. - * @param {string} deletedContainerVersion Version of the previously deleted container, used to uniquely identify the deleted container. - * @returns {Promise} Container deletion response. - * @memberof BlobServiceClient + * @static + * @param {string} key + * @returns {Promise} + * @memberof Mutex */ - BlobServiceClient.prototype.undeleteContainer = function (deletedContainerName, deletedContainerVersion, options) { - if (options === void 0) { options = {}; } + Mutex.unlock = function (key) { return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, containerClient, containerContext, containerUndeleteResponse, e_3; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-undeleteContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - containerClient = this.getContainerClient(options.destinationContainerName || deletedContainerName); - containerContext = new Container(containerClient["storageClientContext"]); - return [4 /*yield*/, containerContext.restore(tslib.__assign(tslib.__assign({ deletedContainerName: deletedContainerName, - deletedContainerVersion: deletedContainerVersion }, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: - containerUndeleteResponse = _b.sent(); - return [2 /*return*/, { containerClient: containerClient, containerUndeleteResponse: containerUndeleteResponse }]; - case 3: - e_3 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_3.message - }); - throw e_3; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + var _this = this; + return tslib.__generator(this, function (_a) { + return [2 /*return*/, new Promise(function (resolve) { + if (_this.keys[key] === MutexLockStatus.LOCKED) { + _this.emitUnlockEvent(key); + } + delete _this.keys[key]; + resolve(); + })]; }); }); }; + Mutex.onUnlockEvent = function (key, handler) { + if (this.listeners[key] === undefined) { + this.listeners[key] = [handler]; + } + else { + this.listeners[key].push(handler); + } + }; + Mutex.emitUnlockEvent = function (key) { + var _this = this; + if (this.listeners[key] !== undefined && this.listeners[key].length > 0) { + var handler_1 = this.listeners[key].shift(); + setImmediate(function () { + handler_1.call(_this); + }); + } + }; + Mutex.keys = {}; + Mutex.listeners = {}; + return Mutex; +}()); + +/** + * A BlobBatch represents an aggregated set of operations on blobs. + * Currently, only `delete` and `setAccessTier` are supported. + * + * @export + * @class BlobBatch + */ +var BlobBatch = /** @class */ (function () { + function BlobBatch() { + this.batch = "batch"; + this.batchRequest = new InnerBatchRequest(); + } /** - * Gets the properties of a storage account’s Blob service, including properties - * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties - * - * @param {ServiceGetPropertiesOptions} [options] Options to the Service Get Properties operation. - * @returns {Promise} Response data for the Service Get Properties operation. - * @memberof BlobServiceClient + * Get the value of Content-Type for a batch request. + * The value must be multipart/mixed with a batch boundary. + * Example: multipart/mixed; boundary=batch_a81786c8-e301-4e42-a729-a32ca24ae252 */ - BlobServiceClient.prototype.getProperties = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_4; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-getProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getProperties({ - abortSignal: options.abortSignal, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_4 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_4.message - }); - throw e_4; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + BlobBatch.prototype.getMultiPartContentType = function () { + return this.batchRequest.getMultipartContentType(); }; /** - * Sets properties for a storage account’s Blob service endpoint, including properties - * for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules and soft delete settings. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties} - * - * @param {BlobServiceProperties} properties - * @param {ServiceSetPropertiesOptions} [options] Options to the Service Set Properties operation. - * @returns {Promise} Response data for the Service Set Properties operation. - * @memberof BlobServiceClient + * Get assembled HTTP request body for sub requests. */ - BlobServiceClient.prototype.setProperties = function (properties, options) { - if (options === void 0) { options = {}; } + BlobBatch.prototype.getHttpRequestBody = function () { + return this.batchRequest.getHttpRequestBody(); + }; + /** + * Get sub requests that are added into the batch request. + */ + BlobBatch.prototype.getSubRequests = function () { + return this.batchRequest.getSubRequests(); + }; + BlobBatch.prototype.addSubRequestInternal = function (subRequest, assembleSubRequestFunc) { return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_5; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-setProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Mutex.lock(this.batch)]; case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.setProperties(properties, { - abortSignal: options.abortSignal, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; + _a.sent(); + _a.label = 2; + case 2: + _a.trys.push([2, , 4, 6]); + this.batchRequest.preAddSubRequest(subRequest); + return [4 /*yield*/, assembleSubRequestFunc()]; case 3: - e_5 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_5.message - }); - throw e_5; - case 4: - span.end(); + _a.sent(); + this.batchRequest.postAddSubRequest(subRequest); + return [3 /*break*/, 6]; + case 4: return [4 /*yield*/, Mutex.unlock(this.batch)]; + case 5: + _a.sent(); return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + case 6: return [2 /*return*/]; } }); }); }; - /** - * Retrieves statistics related to replication for the Blob service. It is only - * available on the secondary location endpoint when read-access geo-redundant - * replication is enabled for the storage account. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-stats} - * - * @param {ServiceGetStatisticsOptions} [options] Options to the Service Get Statistics operation. - * @returns {Promise} Response data for the Service Get Statistics operation. - * @memberof BlobServiceClient - */ - BlobServiceClient.prototype.getStatistics = function (options) { - if (options === void 0) { options = {}; } + BlobBatch.prototype.setBatchType = function (batchType) { + if (!this.batchType) { + this.batchType = batchType; + } + if (this.batchType !== batchType) { + throw new RangeError("BlobBatch only supports one operation type per batch and it already is being used for " + this.batchType + " operations."); + } + }; + BlobBatch.prototype.deleteBlob = function (urlOrBlobClient, credentialOrOptions, options) { return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_6; + var url, credential, _a, span, spanOptions, e_1; + var _this = this; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("BlobServiceClient-getStatistics", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + if (typeof urlOrBlobClient === "string" && + ((coreHttp.isNode && credentialOrOptions instanceof StorageSharedKeyCredential) || + credentialOrOptions instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrOptions))) { + // First overload + url = urlOrBlobClient; + credential = credentialOrOptions; + } + else if (urlOrBlobClient instanceof BlobClient) { + // Second overload + url = urlOrBlobClient.url; + credential = urlOrBlobClient.credential; + options = credentialOrOptions; + } + else { + throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + } + if (!options) { + options = {}; + } + _a = createSpan("BatchDeleteRequest-addSubRequest", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getStatistics({ - abortSignal: options.abortSignal, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; + this.setBatchType("delete"); + return [4 /*yield*/, this.addSubRequestInternal({ + url: url, + credential: credential + }, function () { return tslib.__awaiter(_this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, new BlobClient(url, this.batchRequest.createPipeline(credential)).delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); })]; + case 2: + _b.sent(); + return [3 /*break*/, 5]; case 3: - e_6 = _b.sent(); + e_1 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_6.message + message: e_1.message }); - throw e_6; + throw e_1; case 4: span.end(); return [7 /*endfinally*/]; @@ -33815,40 +34501,63 @@ var BlobServiceClient = /** @class */ (function (_super) { }); }); }; - /** - * The Get Account Information operation returns the sku name and account kind - * for the specified account. - * The Get Account Information operation is available on service versions beginning - * with version 2018-03-28. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information - * - * @param {ServiceGetAccountInfoOptions} [options] Options to the Service Get Account Info operation. - * @returns {Promise} Response data for the Service Get Account Info operation. - * @memberof BlobServiceClient - */ - BlobServiceClient.prototype.getAccountInfo = function (options) { - if (options === void 0) { options = {}; } + BlobBatch.prototype.setBlobAccessTier = function (urlOrBlobClient, credentialOrTier, tierOrOptions, options) { return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_7; + var url, credential, tier, _a, span, spanOptions, e_2; + var _this = this; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("BlobServiceClient-getAccountInfo", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + if (typeof urlOrBlobClient === "string" && + ((coreHttp.isNode && credentialOrTier instanceof StorageSharedKeyCredential) || + credentialOrTier instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrTier))) { + // First overload + url = urlOrBlobClient; + credential = credentialOrTier; + tier = tierOrOptions; + } + else if (urlOrBlobClient instanceof BlobClient) { + // Second overload + url = urlOrBlobClient.url; + credential = urlOrBlobClient.credential; + tier = credentialOrTier; + options = tierOrOptions; + } + else { + throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + } + if (!options) { + options = {}; + } + _a = createSpan("BatchSetTierRequest-addSubRequest", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getAccountInfo({ - abortSignal: options.abortSignal, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; + this.setBatchType("setAccessTier"); + return [4 /*yield*/, this.addSubRequestInternal({ + url: url, + credential: credential + }, function () { return tslib.__awaiter(_this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, new BlobClient(url, this.batchRequest.createPipeline(credential)).setAccessTier(tier, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); })]; + case 2: + _b.sent(); + return [3 /*break*/, 5]; case 3: - e_7 = _b.sent(); + e_2 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_7.message + message: e_2.message }); - throw e_7; + throw e_2; case 4: span.end(); return [7 /*endfinally*/]; @@ -33857,598 +34566,336 @@ var BlobServiceClient = /** @class */ (function (_super) { }); }); }; + return BlobBatch; +}()); +/** + * Inner batch request class which is responsible for assembling and serializing sub requests. + * See https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#request-body for how requests are assembled. + */ +var InnerBatchRequest = /** @class */ (function () { + function InnerBatchRequest() { + this.operationCount = 0; + this.body = ""; + var tempGuid = coreHttp.generateUuid(); + // batch_{batchid} + this.boundary = "batch_" + tempGuid; + // --batch_{batchid} + // Content-Type: application/http + // Content-Transfer-Encoding: binary + this.subRequestPrefix = "--" + this.boundary + HTTP_LINE_ENDING + HeaderConstants.CONTENT_TYPE + ": application/http" + HTTP_LINE_ENDING + HeaderConstants.CONTENT_TRANSFER_ENCODING + ": binary"; + // multipart/mixed; boundary=batch_{batchid} + this.multipartContentType = "multipart/mixed; boundary=" + this.boundary; + // --batch_{batchid}-- + this.batchRequestEnding = "--" + this.boundary + "--"; + this.subRequests = new Map(); + } /** - * Returns a list of the containers under the specified account. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/list-containers2 - * - * @param {string} [marker] A string value that identifies the portion of - * the list of containers to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all containers remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param {ServiceListContainersSegmentOptions} [options] Options to the Service List Container Segment operation. - * @returns {Promise} Response data for the Service List Container Segment operation. - * @memberof BlobServiceClient + * Create pipeline to assemble sub requests. The idea here is to use existing + * credential and serialization/deserialization components, with additional policies to + * filter unnecessary headers, assemble sub requests into request's body + * and intercept request from going to wire. + * @param {StorageSharedKeyCredential | AnonymousCredential | TokenCredential} credential Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the @azure/identity package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used. */ - BlobServiceClient.prototype.listContainersSegment = function (marker, options) { - if (options === void 0) { options = {}; } + InnerBatchRequest.prototype.createPipeline = function (credential) { + var isAnonymousCreds = credential instanceof AnonymousCredential; + var policyFactoryLength = 3 + (isAnonymousCreds ? 0 : 1); // [deserializationPolicy, BatchHeaderFilterPolicyFactory, (Optional)Credential, BatchRequestAssemblePolicyFactory] + var factories = new Array(policyFactoryLength); + factories[0] = coreHttp.deserializationPolicy(); // Default deserializationPolicy is provided by protocol layer + factories[1] = new BatchHeaderFilterPolicyFactory(); // Use batch header filter policy to exclude unnecessary headers + if (!isAnonymousCreds) { + factories[2] = coreHttp.isTokenCredential(credential) + ? attachCredential(coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes), credential) + : credential; + } + factories[policyFactoryLength - 1] = new BatchRequestAssemblePolicyFactory(this); // Use batch assemble policy to assemble request and intercept request from going to wire + return new Pipeline(factories, {}); + }; + InnerBatchRequest.prototype.appendSubRequestToBody = function (request) { + // Start to assemble sub request + this.body += [ + this.subRequestPrefix, + HeaderConstants.CONTENT_ID + ": " + this.operationCount, + "", + request.method.toString() + " " + getURLPathAndQuery(request.url) + " " + HTTP_VERSION_1_1 + HTTP_LINE_ENDING // sub request start line with method + ].join(HTTP_LINE_ENDING); + for (var _i = 0, _a = request.headers.headersArray(); _i < _a.length; _i++) { + var header = _a[_i]; + this.body += header.name + ": " + header.value + HTTP_LINE_ENDING; + } + this.body += HTTP_LINE_ENDING; // sub request's headers need be ending with an empty line + // No body to assemble for current batch request support + // End to assemble sub request + }; + InnerBatchRequest.prototype.preAddSubRequest = function (subRequest) { + if (this.operationCount >= BATCH_MAX_REQUEST) { + throw new RangeError("Cannot exceed " + BATCH_MAX_REQUEST + " sub requests in a single batch"); + } + // Fast fail if url for sub request is invalid + var path = getURLPath(subRequest.url); + if (!path || path == "") { + throw new RangeError("Invalid url for sub request: '" + subRequest.url + "'"); + } + }; + InnerBatchRequest.prototype.postAddSubRequest = function (subRequest) { + this.subRequests.set(this.operationCount, subRequest); + this.operationCount++; + }; + // Return the http request body with assembling the ending line to the sub request body. + InnerBatchRequest.prototype.getHttpRequestBody = function () { + return "" + this.body + this.batchRequestEnding + HTTP_LINE_ENDING; + }; + InnerBatchRequest.prototype.getMultipartContentType = function () { + return this.multipartContentType; + }; + InnerBatchRequest.prototype.getSubRequests = function () { + return this.subRequests; + }; + return InnerBatchRequest; +}()); +var BatchRequestAssemblePolicy = /** @class */ (function (_super) { + tslib.__extends(BatchRequestAssemblePolicy, _super); + function BatchRequestAssemblePolicy(batchRequest, nextPolicy, options) { + var _this = _super.call(this, nextPolicy, options) || this; + _this.dummyResponse = { + request: new coreHttp.WebResource(), + status: 200, + headers: new coreHttp.HttpHeaders() + }; + _this.batchRequest = batchRequest; + return _this; + } + BatchRequestAssemblePolicy.prototype.sendRequest = function (request) { return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_8; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-listContainersSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.batchRequest.appendSubRequestToBody(request)]; case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.listContainersSegment(tslib.__assign(tslib.__assign({ abortSignal: options.abortSignal, marker: marker }, options), { include: typeof options.include === "string" ? [options.include] : options.include, spanOptions: spanOptions }))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_8 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_8.message - }); - throw e_8; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + _a.sent(); + return [2 /*return*/, this.dummyResponse]; // Intercept request from going to wire } }); }); }; - /** - * The Filter Blobs operation enables callers to list blobs across all containers whose tags - * match a given search expression. Filter blobs searches across all containers within a - * storage account but can be scoped within the expression to a single container. - * - * @private - * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param {string} [marker] A string value that identifies the portion of - * the list of blobs to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all blobs remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to find blobs by tags. - * @returns {Promise} - * @memberof BlobServiceClient - */ - BlobServiceClient.prototype.findBlobsByTagsSegment = function (tagFilterSqlExpression, marker, options) { - if (options === void 0) { options = {}; } + return BatchRequestAssemblePolicy; +}(coreHttp.BaseRequestPolicy)); +var BatchRequestAssemblePolicyFactory = /** @class */ (function () { + function BatchRequestAssemblePolicyFactory(batchRequest) { + this.batchRequest = batchRequest; + } + BatchRequestAssemblePolicyFactory.prototype.create = function (nextPolicy, options) { + return new BatchRequestAssemblePolicy(this.batchRequest, nextPolicy, options); + }; + return BatchRequestAssemblePolicyFactory; +}()); +var BatchHeaderFilterPolicy = /** @class */ (function (_super) { + tslib.__extends(BatchHeaderFilterPolicy, _super); + function BatchHeaderFilterPolicy(nextPolicy, options) { + return _super.call(this, nextPolicy, options) || this; + } + BatchHeaderFilterPolicy.prototype.sendRequest = function (request) { return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_9; + var xMsHeaderName, _i, _a, header; return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-findBlobsByTagsSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.filterBlobs({ - abortSignal: options.abortSignal, - where: tagFilterSqlExpression, - marker: marker, - maxPageSize: options.maxPageSize, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_9 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_9.message - }); - throw e_9; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + xMsHeaderName = ""; + for (_i = 0, _a = request.headers.headersArray(); _i < _a.length; _i++) { + header = _a[_i]; + if (iEqual(header.name, HeaderConstants.X_MS_VERSION)) { + xMsHeaderName = header.name; + } + } + if (xMsHeaderName !== "") { + request.headers.remove(xMsHeaderName); // The subrequests should not have the x-ms-version header. } + return [2 /*return*/, this._nextPolicy.sendRequest(request)]; }); }); }; + return BatchHeaderFilterPolicy; +}(coreHttp.BaseRequestPolicy)); +var BatchHeaderFilterPolicyFactory = /** @class */ (function () { + function BatchHeaderFilterPolicyFactory() { + } + BatchHeaderFilterPolicyFactory.prototype.create = function (nextPolicy, options) { + return new BatchHeaderFilterPolicy(nextPolicy, options); + }; + return BatchHeaderFilterPolicyFactory; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * A BlobBatchClient allows you to make batched requests to the Azure Storage Blob service. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch + */ +var BlobBatchClient = /** @class */ (function () { + function BlobBatchClient(url, credentialOrPipeline, options) { + var pipeline; + if (credentialOrPipeline instanceof Pipeline) { + pipeline = credentialOrPipeline; + } + else if (!credentialOrPipeline) { + // no credential provided + pipeline = newPipeline(new AnonymousCredential(), options); + } + else { + pipeline = newPipeline(credentialOrPipeline, options); + } + var storageClientContext = new StorageClientContext(url, pipeline.toServiceClientOptions()); + this._serviceContext = new Service(storageClientContext); + } /** - * Returns an AsyncIterableIterator for ServiceFindBlobsByTagsSegmentResponse. - * - * @private - * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param {string} [marker] A string value that identifies the portion of - * the list of blobs to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all blobs remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to find blobs by tags. - * @returns {AsyncIterableIterator} - * @memberof BlobServiceClient + * Creates a {@link BlobBatch}. + * A BlobBatch represents an aggregated set of operations on blobs. */ - BlobServiceClient.prototype.findBlobsByTagsSegments = function (tagFilterSqlExpression, marker, options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function findBlobsByTagsSegments_1() { - var response; + BlobBatchClient.prototype.createBatch = function () { + return new BlobBatch(); + }; + BlobBatchClient.prototype.deleteBlobs = function (urlsOrBlobClients, credentialOrOptions, options) { + return tslib.__awaiter(this, void 0, void 0, function () { + var batch, _i, urlsOrBlobClients_1, urlOrBlobClient; return tslib.__generator(this, function (_a) { switch (_a.label) { case 0: - if (!(!!marker || marker === undefined)) return [3 /*break*/, 6]; + batch = new BlobBatch(); + _i = 0, urlsOrBlobClients_1 = urlsOrBlobClients; _a.label = 1; - case 1: return [4 /*yield*/, tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker, options))]; + case 1: + if (!(_i < urlsOrBlobClients_1.length)) return [3 /*break*/, 6]; + urlOrBlobClient = urlsOrBlobClients_1[_i]; + if (!(typeof urlOrBlobClient === "string")) return [3 /*break*/, 3]; + return [4 /*yield*/, batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options)]; case 2: - response = _a.sent(); - response.blobs = response.blobs || []; - marker = response.continuationToken; - return [4 /*yield*/, tslib.__await(response)]; - case 3: return [4 /*yield*/, _a.sent()]; + _a.sent(); + return [3 /*break*/, 5]; + case 3: return [4 /*yield*/, batch.deleteBlob(urlOrBlobClient, credentialOrOptions)]; case 4: _a.sent(); _a.label = 5; case 5: - if (marker) return [3 /*break*/, 1]; - _a.label = 6; - case 6: return [2 /*return*/]; - } - }); - }); - }; - /** - * Returns an AsyncIterableIterator for blobs. - * - * @private - * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to findBlobsByTagsItems. - * @returns {AsyncIterableIterator} - * @memberof BlobServiceClient - */ - BlobServiceClient.prototype.findBlobsByTagsItems = function (tagFilterSqlExpression, options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function findBlobsByTagsItems_1() { - var marker, _a, _b, segment, e_10_1; - var e_10, _c; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _d.trys.push([0, 7, 8, 13]); - _a = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker, options)); - _d.label = 1; - case 1: return [4 /*yield*/, tslib.__await(_a.next())]; - case 2: - if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; - segment = _b.value; - return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs)))]; - case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; - case 4: - _d.sent(); - _d.label = 5; - case 5: return [3 /*break*/, 1]; - case 6: return [3 /*break*/, 13]; - case 7: - e_10_1 = _d.sent(); - e_10 = { error: e_10_1 }; - return [3 /*break*/, 13]; - case 8: - _d.trys.push([8, , 11, 12]); - if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; - return [4 /*yield*/, tslib.__await(_c.call(_a))]; - case 9: - _d.sent(); - _d.label = 10; - case 10: return [3 /*break*/, 12]; - case 11: - if (e_10) throw e_10.error; - return [7 /*endfinally*/]; - case 12: return [7 /*endfinally*/]; - case 13: return [2 /*return*/]; + _i++; + return [3 /*break*/, 1]; + case 6: return [2 /*return*/, this.submitBatch(batch)]; } }); }); }; - /** - * Returns an async iterable iterator to find all blobs with specified tag - * under the specified account. - * - * .byPage() returns an async iterable iterator to list the blobs in pages. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties - * - * Example using `for await` syntax: - * - * ```js - * let i = 1; - * for await (const blob of blobServiceClient.findBlobsByTags("tagkey='tagvalue'")) { - * console.log(`Blob ${i++}: ${container.name}`); - * } - * ``` - * - * Example using `iter.next()`: - * - * ```js - * let i = 1; - * const iter = blobServiceClient.findBlobsByTags("tagkey='tagvalue'"); - * let blobItem = await iter.next(); - * while (!blobItem.done) { - * console.log(`Blob ${i++}: ${blobItem.value.name}`); - * blobItem = await iter.next(); - * } - * ``` - * - * Example using `byPage()`: - * - * ```js - * // passing optional maxPageSize in the page settings - * let i = 1; - * for await (const response of blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { - * if (response.blobs) { - * for (const blob of response.blobs) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } - * } - * ``` - * - * Example using paging with a marker: - * - * ```js - * let i = 1; - * let iterator = blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); - * let response = (await iterator.next()).value; - * - * // Prints 2 blob names - * if (response.blobs) { - * for (const blob of response.blobs) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } - * - * // Gets next marker - * let marker = response.continuationToken; - * // Passing next marker as continuationToken - * iterator = blobServiceClient - * .findBlobsByTags("tagkey='tagvalue'") - * .byPage({ continuationToken: marker, maxPageSize: 10 }); - * response = (await iterator.next()).value; - * - * // Prints blob names - * if (response.blobs) { - * for (const blob of response.blobs) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } - * ``` - * - * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param {ServiceFindBlobByTagsOptions} [options={}] Options to find blobs by tags. - * @returns {PagedAsyncIterableIterator} - * @memberof BlobServiceClient - */ - BlobServiceClient.prototype.findBlobsByTags = function (tagFilterSqlExpression, options) { - var _a; - var _this = this; - if (options === void 0) { options = {}; } - // AsyncIterableIterator to iterate over blobs - var listSegmentOptions = tslib.__assign({}, options); - var iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); - return _a = { - /** - * @member {Promise} [next] The next method, part of the iteration protocol - */ - next: function () { - return iter.next(); - } - }, - /** - * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol - */ - _a[Symbol.asyncIterator] = function () { - return this; - }, - /** - * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time - */ - _a.byPage = function (settings) { - if (settings === void 0) { settings = {}; } - return _this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); - }, - _a; - }; - /** - * Returns an AsyncIterableIterator for ServiceListContainersSegmentResponses - * - * @private - * @param {string} [marker] A string value that identifies the portion of - * the list of containers to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all containers remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param {ServiceListContainersSegmentOptions} [options] Options to list containers operation. - * @returns {AsyncIterableIterator} - * @memberof BlobServiceClient - */ - BlobServiceClient.prototype.listSegments = function (marker, options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listSegments_1() { - var listContainersSegmentResponse; + BlobBatchClient.prototype.setBlobsAccessTier = function (urlsOrBlobClients, credentialOrTier, tierOrOptions, options) { + return tslib.__awaiter(this, void 0, void 0, function () { + var batch, _i, urlsOrBlobClients_2, urlOrBlobClient; return tslib.__generator(this, function (_a) { switch (_a.label) { case 0: - if (!(!!marker || marker === undefined)) return [3 /*break*/, 7]; + batch = new BlobBatch(); + _i = 0, urlsOrBlobClients_2 = urlsOrBlobClients; _a.label = 1; - case 1: return [4 /*yield*/, tslib.__await(this.listContainersSegment(marker, options))]; + case 1: + if (!(_i < urlsOrBlobClients_2.length)) return [3 /*break*/, 6]; + urlOrBlobClient = urlsOrBlobClients_2[_i]; + if (!(typeof urlOrBlobClient === "string")) return [3 /*break*/, 3]; + return [4 /*yield*/, batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options)]; case 2: - listContainersSegmentResponse = _a.sent(); - listContainersSegmentResponse.containerItems = - listContainersSegmentResponse.containerItems || []; - marker = listContainersSegmentResponse.continuationToken; - return [4 /*yield*/, tslib.__await(listContainersSegmentResponse)]; - case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_a.sent()])]; - case 4: return [4 /*yield*/, _a.sent()]; - case 5: _a.sent(); - _a.label = 6; - case 6: - if (marker) return [3 /*break*/, 1]; - _a.label = 7; - case 7: return [2 /*return*/]; - } - }); - }); - }; - /** - * Returns an AsyncIterableIterator for Container Items - * - * @private - * @param {ServiceListContainersSegmentOptions} [options] Options to list containers operation. - * @returns {AsyncIterableIterator} - * @memberof BlobServiceClient - */ - BlobServiceClient.prototype.listItems = function (options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listItems_1() { - var marker, _a, _b, segment, e_11_1; - var e_11, _c; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _d.trys.push([0, 7, 8, 13]); - _a = tslib.__asyncValues(this.listSegments(marker, options)); - _d.label = 1; - case 1: return [4 /*yield*/, tslib.__await(_a.next())]; - case 2: - if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; - segment = _b.value; - return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(segment.containerItems)))]; - case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; + return [3 /*break*/, 5]; + case 3: return [4 /*yield*/, batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions)]; case 4: - _d.sent(); - _d.label = 5; - case 5: return [3 /*break*/, 1]; - case 6: return [3 /*break*/, 13]; - case 7: - e_11_1 = _d.sent(); - e_11 = { error: e_11_1 }; - return [3 /*break*/, 13]; - case 8: - _d.trys.push([8, , 11, 12]); - if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; - return [4 /*yield*/, tslib.__await(_c.call(_a))]; - case 9: - _d.sent(); - _d.label = 10; - case 10: return [3 /*break*/, 12]; - case 11: - if (e_11) throw e_11.error; - return [7 /*endfinally*/]; - case 12: return [7 /*endfinally*/]; - case 13: return [2 /*return*/]; + _a.sent(); + _a.label = 5; + case 5: + _i++; + return [3 /*break*/, 1]; + case 6: return [2 /*return*/, this.submitBatch(batch)]; } }); }); }; /** - * Returns an async iterable iterator to list all the containers - * under the specified account. - * - * .byPage() returns an async iterable iterator to list the containers in pages. - * - * Example using `for await` syntax: - * - * ```js - * let i = 1; - * for await (const container of blobServiceClient.listContainers()) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * ``` - * - * Example using `iter.next()`: + * Submit batch request which consists of multiple subrequests. * - * ```js - * let i = 1; - * const iter = blobServiceClient.listContainers(); - * let containerItem = await iter.next(); - * while (!containerItem.done) { - * console.log(`Container ${i++}: ${containerItem.value.name}`); - * containerItem = await iter.next(); - * } - * ``` + * Get `blobBatchClient` and other details before running the snippets. + * `blobServiceClient.getBlobBatchClient()` gives the `blobBatchClient` * - * Example using `byPage()`: + * Example usage: * * ```js - * // passing optional maxPageSize in the page settings - * let i = 1; - * for await (const response of blobServiceClient.listContainers().byPage({ maxPageSize: 20 })) { - * if (response.containerItems) { - * for (const container of response.containerItems) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * } - * } + * let batchRequest = new BlobBatch(); + * await batchRequest.deleteBlob(urlInString0, credential0); + * await batchRequest.deleteBlob(urlInString1, credential1, { + * deleteSnapshots: "include" + * }); + * const batchResp = await blobBatchClient.submitBatch(batchRequest); + * console.log(batchResp.subResponsesSucceededCount); * ``` * - * Example using paging with a marker: + * Example using a lease: * * ```js - * let i = 1; - * let iterator = blobServiceClient.listContainers().byPage({ maxPageSize: 2 }); - * let response = (await iterator.next()).value; - * - * // Prints 2 container names - * if (response.containerItems) { - * for (const container of response.containerItems) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * } - * - * // Gets next marker - * let marker = response.continuationToken; - * // Passing next marker as continuationToken - * iterator = blobServiceClient - * .listContainers() - * .byPage({ continuationToken: marker, maxPageSize: 10 }); - * response = (await iterator.next()).value; - * - * // Prints 10 container names - * if (response.containerItems) { - * for (const container of response.containerItems) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * } + * let batchRequest = new BlobBatch(); + * await batchRequest.setBlobAccessTier(blockBlobClient0, "Cool"); + * await batchRequest.setBlobAccessTier(blockBlobClient1, "Cool", { + * conditions: { leaseId: leaseId } + * }); + * const batchResp = await blobBatchClient.submitBatch(batchRequest); + * console.log(batchResp.subResponsesSucceededCount); * ``` * - * @param {ServiceListContainersOptions} [options={}] Options to list containers. - * @returns {PagedAsyncIterableIterator} An asyncIterableIterator that supports paging. - * @memberof BlobServiceClient - */ - BlobServiceClient.prototype.listContainers = function (options) { - var _a; - var _this = this; - if (options === void 0) { options = {}; } - if (options.prefix === "") { - options.prefix = undefined; - } - var include = []; - if (options.includeDeleted) { - include.push("deleted"); - } - if (options.includeMetadata) { - include.push("metadata"); - } - // AsyncIterableIterator to iterate over containers - var listSegmentOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); - var iter = this.listItems(listSegmentOptions); - return _a = { - /** - * @member {Promise} [next] The next method, part of the iteration protocol - */ - next: function () { - return iter.next(); - } - }, - /** - * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol - */ - _a[Symbol.asyncIterator] = function () { - return this; - }, - /** - * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time - */ - _a.byPage = function (settings) { - if (settings === void 0) { settings = {}; } - return _this.listSegments(settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); - }, - _a; - }; - /** - * ONLY AVAILABLE WHEN USING BEARER TOKEN AUTHENTICATION (TokenCredential). - * - * Retrieves a user delegation key for the Blob service. This is only a valid operation when using - * bearer token authentication. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-user-delegation-key + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch * - * @param {Date} startsOn The start time for the user delegation SAS. Must be within 7 days of the current time - * @param {Date} expiresOn The end time for the user delegation SAS. Must be within 7 days of the current time - * @returns {Promise} - * @memberof BlobServiceClient + * @param {BlobBatch} batchRequest A set of Delete or SetTier operations. + * @param {BlobBatchSubmitBatchOptionalParams} [options] + * @returns {Promise} + * @memberof BlobBatchClient */ - BlobServiceClient.prototype.getUserDelegationKey = function (startsOn, expiresOn, options) { + BlobBatchClient.prototype.submitBatch = function (batchRequest, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, response, userDelegationKey, res, e_12; + var _a, span, spanOptions, batchRequestBody, rawBatchResponse, batchResponseParser, responseSummary, res, e_1; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("BlobServiceClient-getUserDelegationKey", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + if (!batchRequest || batchRequest.getSubRequests().size == 0) { + throw new RangeError("Batch request should contain one or more sub requests."); + } + _a = createSpan("BlobBatchClient-submitBatch", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getUserDelegationKey({ - startsOn: truncatedISO8061Date(startsOn, false), - expiresOn: truncatedISO8061Date(expiresOn, false) - }, { - abortSignal: options.abortSignal, - spanOptions: spanOptions - })]; + _b.trys.push([1, 4, 5, 6]); + batchRequestBody = batchRequest.getHttpRequestBody(); + return [4 /*yield*/, this._serviceContext.submitBatch(batchRequestBody, utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), tslib.__assign(tslib.__assign({}, options), { spanOptions: spanOptions }))]; case 2: - response = _b.sent(); - userDelegationKey = { - signedObjectId: response.signedObjectId, - signedTenantId: response.signedTenantId, - signedStartsOn: new Date(response.signedStartsOn), - signedExpiresOn: new Date(response.signedExpiresOn), - signedService: response.signedService, - signedVersion: response.signedVersion, - value: response.value + rawBatchResponse = _b.sent(); + batchResponseParser = new BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests()); + return [4 /*yield*/, batchResponseParser.parseBatchResponse()]; + case 3: + responseSummary = _b.sent(); + res = { + _response: rawBatchResponse._response, + contentType: rawBatchResponse.contentType, + errorCode: rawBatchResponse.errorCode, + requestId: rawBatchResponse.requestId, + clientRequestId: rawBatchResponse.clientRequestId, + version: rawBatchResponse.version, + subResponses: responseSummary.subResponses, + subResponsesSucceededCount: responseSummary.subResponsesSucceededCount, + subResponsesFailedCount: responseSummary.subResponsesFailedCount }; - res = tslib.__assign({ _response: response._response, requestId: response.requestId, clientRequestId: response.clientRequestId, version: response.version, date: response.date, errorCode: response.errorCode }, userDelegationKey); return [2 /*return*/, res]; - case 3: - e_12 = _b.sent(); + case 4: + e_1 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_12.message + message: e_1.message }); - throw e_12; - case 4: + throw e_1; + case 5: span.end(); return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + case 6: return [2 /*return*/]; } }); }); }; - /** - * Creates a BlobBatchClient object to conduct batch operations. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch - * - * @returns {BlobBatchClient} A new BlobBatchClient object for this service. - * @memberof BlobServiceClient - */ - BlobServiceClient.prototype.getBlobBatchClient = function () { - return new BlobBatchClient(this.url, this.pipeline); - }; - return BlobServiceClient; -}(StorageClient)); + return BlobBatchClient; +}()); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. @@ -34596,6 +35043,52 @@ var AccountSASPermissions = /** @class */ (function () { } return accountSASPermissions; }; + /** + * Creates a {@link AccountSASPermissions} from a raw object which contains same keys as it + * and boolean values for them. + * + * @static + * @param {AccountSASPermissionsLike} permissionLike + * @returns {AccountSASPermissions} + * @memberof AccountSASPermissions + */ + AccountSASPermissions.from = function (permissionLike) { + var accountSASPermissions = new AccountSASPermissions(); + if (permissionLike.read) { + accountSASPermissions.read = true; + } + if (permissionLike.write) { + accountSASPermissions.write = true; + } + if (permissionLike.delete) { + accountSASPermissions.delete = true; + } + if (permissionLike.deleteVersion) { + accountSASPermissions.deleteVersion = true; + } + if (permissionLike.filter) { + accountSASPermissions.filter = true; + } + if (permissionLike.tag) { + accountSASPermissions.tag = true; + } + if (permissionLike.list) { + accountSASPermissions.list = true; + } + if (permissionLike.add) { + accountSASPermissions.add = true; + } + if (permissionLike.create) { + accountSASPermissions.create = true; + } + if (permissionLike.update) { + accountSASPermissions.update = true; + } + if (permissionLike.process) { + accountSASPermissions.process = true; + } + return accountSASPermissions; + }; /** * Produces the SAS permissions string for an Azure Storage account. * Call this method to set AccountSASSignatureValues Permissions field. @@ -34845,1072 +35338,1053 @@ var AccountSASServices = /** @class */ (function () { }()); // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. /** - * Generate SasIPRange format string. For example: + * ONLY AVAILABLE IN NODE.JS RUNTIME. * - * "8.8.8.8" or "1.1.1.1-255.255.255.255" + * Generates a {@link SASQueryParameters} object which contains all SAS query parameters needed to make an actual + * REST request. * - * @export - * @param {SasIPRange} ipRange - * @returns {string} + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas + * + * @param {AccountSASSignatureValues} accountSASSignatureValues + * @param {StorageSharedKeyCredential} sharedKeyCredential + * @returns {SASQueryParameters} + * @memberof AccountSASSignatureValues */ -function ipRangeToString(ipRange) { - return ipRange.end ? ipRange.start + "-" + ipRange.end : ipRange.start; +function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { + var version = accountSASSignatureValues.version + ? accountSASSignatureValues.version + : SERVICE_VERSION; + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.deleteVersion && + version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); + } + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.tag && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); + } + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.filter && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 'f' permission."); + } + var parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); + var parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); + var parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); + var stringToSign = [ + sharedKeyCredential.accountName, + parsedPermissions, + parsedServices, + parsedResourceTypes, + accountSASSignatureValues.startsOn + ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) + : "", + truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), + accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", + accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", + version, + "" // Account SAS requires an additional newline character + ].join("\n"); + var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(version, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange); } -// Copyright (c) Microsoft Corporation. All rights reserved. -(function (SASProtocol) { +/** + * A BlobServiceClient represents a Client to the Azure Storage Blob service allowing you + * to manipulate blob containers. + * + * @export + * @class BlobServiceClient + */ +var BlobServiceClient = /** @class */ (function (_super) { + tslib.__extends(BlobServiceClient, _super); + function BlobServiceClient(url, credentialOrPipeline, options) { + var _this = this; + var pipeline; + if (credentialOrPipeline instanceof Pipeline) { + pipeline = credentialOrPipeline; + } + else if ((coreHttp.isNode && credentialOrPipeline instanceof StorageSharedKeyCredential) || + credentialOrPipeline instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrPipeline)) { + pipeline = newPipeline(credentialOrPipeline, options); + } + else { + // The second parameter is undefined. Use anonymous credential + pipeline = newPipeline(new AnonymousCredential(), options); + } + _this = _super.call(this, url, pipeline) || this; + _this.serviceContext = new Service(_this.storageClientContext); + return _this; + } /** - * Protocol that allows HTTPS only + * + * Creates an instance of BlobServiceClient from connection string. + * + * @param {string} connectionString Account connection string or a SAS connection string of an Azure storage account. + * [ Note - Account connection string can only be used in NODE.JS runtime. ] + * Account connection string example - + * `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net` + * SAS connection string example - + * `BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString` + * @param {StoragePipelineOptions} [options] Optional. Options to configure the HTTP pipeline. + * @memberof BlobServiceClient */ - SASProtocol["Https"] = "https"; + BlobServiceClient.fromConnectionString = function (connectionString, options) { + options = options || {}; + var extractedCreds = extractConnectionStringParts(connectionString); + if (extractedCreds.kind === "AccountConnString") { + { + var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); + var pipeline = newPipeline(sharedKeyCredential, options); + return new BlobServiceClient(extractedCreds.url, pipeline); + } + } + else if (extractedCreds.kind === "SASConnString") { + var pipeline = newPipeline(new AnonymousCredential(), options); + return new BlobServiceClient(extractedCreds.url + "?" + extractedCreds.accountSas, pipeline); + } + else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + }; + /** + * Creates a {@link ContainerClient} object + * + * @param {string} containerName A container name + * @returns {ContainerClient} A new ContainerClient object for the given container name. + * @memberof BlobServiceClient + * + * Example usage: + * + * ```js + * const containerClient = blobServiceClient.getContainerClient(""); + * ``` + */ + BlobServiceClient.prototype.getContainerClient = function (containerName) { + return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline); + }; + /** + * Create a Blob container. + * + * @param {string} containerName Name of the container to create. + * @param {ContainerCreateOptions} [options] Options to configure Container Create operation. + * @returns {Promise<{ containerClient: ContainerClient; containerCreateResponse: ContainerCreateResponse }>} Container creation response and the corresponding container client. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.createContainer = function (containerName, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, containerClient, containerCreateResponse, e_1; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-createContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + containerClient = this.getContainerClient(containerName); + return [4 /*yield*/, containerClient.create(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: + containerCreateResponse = _b.sent(); + return [2 /*return*/, { + containerClient: containerClient, + containerCreateResponse: containerCreateResponse + }]; + case 3: + e_1 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_1.message + }); + throw e_1; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Deletes a Blob container. + * + * @param {string} containerName Name of the container to delete. + * @param {ContainerDeleteMethodOptions} [options] Options to configure Container Delete operation. + * @returns {Promise} Container deletion response. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.deleteContainer = function (containerName, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, containerClient, e_2; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-deleteContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + containerClient = this.getContainerClient(containerName); + return [4 /*yield*/, containerClient.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_2 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_2.message + }); + throw e_2; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Restore a previously deleted Blob container. + * This API is only functional if Container Soft Delete is enabled for the storage account associated with the container. + * + * @param {string} deletedContainerName Name of the previously deleted container. + * @param {string} deletedContainerVersion Version of the previously deleted container, used to uniquely identify the deleted container. + * @returns {Promise} Container deletion response. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.undeleteContainer = function (deletedContainerName, deletedContainerVersion, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, containerClient, containerContext, containerUndeleteResponse, e_3; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-undeleteContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + containerClient = this.getContainerClient(options.destinationContainerName || deletedContainerName); + containerContext = new Container(containerClient["storageClientContext"]); + return [4 /*yield*/, containerContext.restore(tslib.__assign(tslib.__assign({ deletedContainerName: deletedContainerName, + deletedContainerVersion: deletedContainerVersion }, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: + containerUndeleteResponse = _b.sent(); + return [2 /*return*/, { containerClient: containerClient, containerUndeleteResponse: containerUndeleteResponse }]; + case 3: + e_3 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_3.message + }); + throw e_3; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Gets the properties of a storage account’s Blob service, including properties + * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties + * + * @param {ServiceGetPropertiesOptions} [options] Options to the Service Get Properties operation. + * @returns {Promise} Response data for the Service Get Properties operation. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.getProperties = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_4; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-getProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.getProperties({ + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_4 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_4.message + }); + throw e_4; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Sets properties for a storage account’s Blob service endpoint, including properties + * for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules and soft delete settings. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties} + * + * @param {BlobServiceProperties} properties + * @param {ServiceSetPropertiesOptions} [options] Options to the Service Set Properties operation. + * @returns {Promise} Response data for the Service Set Properties operation. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.setProperties = function (properties, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_5; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-setProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.setProperties(properties, { + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_5 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_5.message + }); + throw e_5; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Retrieves statistics related to replication for the Blob service. It is only + * available on the secondary location endpoint when read-access geo-redundant + * replication is enabled for the storage account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-stats} + * + * @param {ServiceGetStatisticsOptions} [options] Options to the Service Get Statistics operation. + * @returns {Promise} Response data for the Service Get Statistics operation. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.getStatistics = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_6; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-getStatistics", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.getStatistics({ + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_6 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_6.message + }); + throw e_6; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * The Get Account Information operation returns the sku name and account kind + * for the specified account. + * The Get Account Information operation is available on service versions beginning + * with version 2018-03-28. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information + * + * @param {ServiceGetAccountInfoOptions} [options] Options to the Service Get Account Info operation. + * @returns {Promise} Response data for the Service Get Account Info operation. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.getAccountInfo = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_7; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-getAccountInfo", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.getAccountInfo({ + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_7 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_7.message + }); + throw e_7; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns a list of the containers under the specified account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/list-containers2 + * + * @param {string} [marker] A string value that identifies the portion of + * the list of containers to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all containers remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ServiceListContainersSegmentOptions} [options] Options to the Service List Container Segment operation. + * @returns {Promise} Response data for the Service List Container Segment operation. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.listContainersSegment = function (marker, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_8; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-listContainersSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.listContainersSegment(tslib.__assign(tslib.__assign({ abortSignal: options.abortSignal, marker: marker }, options), { include: typeof options.include === "string" ? [options.include] : options.include, spanOptions: spanOptions }))]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_8 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_8.message + }); + throw e_8; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; /** - * Protocol that allows both HTTPS and HTTP + * The Filter Blobs operation enables callers to list blobs across all containers whose tags + * match a given search expression. Filter blobs searches across all containers within a + * storage account but can be scoped within the expression to a single container. + * + * @private + * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param {string} [marker] A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to find blobs by tags. + * @returns {Promise} + * @memberof BlobServiceClient */ - SASProtocol["HttpsAndHttp"] = "https,http"; -})(exports.SASProtocol || (exports.SASProtocol = {})); -/** - * Represents the components that make up an Azure Storage SAS' query parameters. This type is not constructed directly - * by the user; it is only generated by the {@link AccountSASSignatureValues} and {@link BlobSASSignatureValues} - * types. Once generated, it can be encoded into a {@code String} and appended to a URL directly (though caution should - * be taken here in case there are existing query parameters, which might affect the appropriate means of appending - * these query parameters). - * - * NOTE: Instances of this class are immutable. - * - * @export - * @class SASQueryParameters - */ -var SASQueryParameters = /** @class */ (function () { - function SASQueryParameters(version, signature, permissionsOrOptions, services, resourceTypes, protocol, startsOn, expiresOn, ipRange, identifier, resource, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType, userDelegationKey, preauthorizedAgentObjectId, correlationId) { - this.version = version; - this.signature = signature; - if (permissionsOrOptions !== undefined && typeof permissionsOrOptions !== "string") { - // SASQueryParametersOptions - this.permissions = permissionsOrOptions.permissions; - this.services = permissionsOrOptions.services; - this.resourceTypes = permissionsOrOptions.resourceTypes; - this.protocol = permissionsOrOptions.protocol; - this.startsOn = permissionsOrOptions.startsOn; - this.expiresOn = permissionsOrOptions.expiresOn; - this.ipRangeInner = permissionsOrOptions.ipRange; - this.identifier = permissionsOrOptions.identifier; - this.resource = permissionsOrOptions.resource; - this.cacheControl = permissionsOrOptions.cacheControl; - this.contentDisposition = permissionsOrOptions.contentDisposition; - this.contentEncoding = permissionsOrOptions.contentEncoding; - this.contentLanguage = permissionsOrOptions.contentLanguage; - this.contentType = permissionsOrOptions.contentType; - if (permissionsOrOptions.userDelegationKey) { - this.signedOid = permissionsOrOptions.userDelegationKey.signedObjectId; - this.signedTenantId = permissionsOrOptions.userDelegationKey.signedTenantId; - this.signedStartsOn = permissionsOrOptions.userDelegationKey.signedStartsOn; - this.signedExpiresOn = permissionsOrOptions.userDelegationKey.signedExpiresOn; - this.signedService = permissionsOrOptions.userDelegationKey.signedService; - this.signedVersion = permissionsOrOptions.userDelegationKey.signedVersion; - this.preauthorizedAgentObjectId = permissionsOrOptions.preauthorizedAgentObjectId; - this.correlationId = permissionsOrOptions.correlationId; - } - } - else { - this.services = services; - this.resourceTypes = resourceTypes; - this.expiresOn = expiresOn; - this.permissions = permissionsOrOptions; - this.protocol = protocol; - this.startsOn = startsOn; - this.ipRangeInner = ipRange; - this.identifier = identifier; - this.resource = resource; - this.cacheControl = cacheControl; - this.contentDisposition = contentDisposition; - this.contentEncoding = contentEncoding; - this.contentLanguage = contentLanguage; - this.contentType = contentType; - if (userDelegationKey) { - this.signedOid = userDelegationKey.signedObjectId; - this.signedTenantId = userDelegationKey.signedTenantId; - this.signedStartsOn = userDelegationKey.signedStartsOn; - this.signedExpiresOn = userDelegationKey.signedExpiresOn; - this.signedService = userDelegationKey.signedService; - this.signedVersion = userDelegationKey.signedVersion; - this.preauthorizedAgentObjectId = preauthorizedAgentObjectId; - this.correlationId = correlationId; - } - } - } - Object.defineProperty(SASQueryParameters.prototype, "ipRange", { - /** - * Optional. IP range allowed for this SAS. - * - * @readonly - * @type {(SasIPRange | undefined)} - * @memberof SASQueryParameters - */ - get: function () { - if (this.ipRangeInner) { - return { - end: this.ipRangeInner.end, - start: this.ipRangeInner.start - }; - } - return undefined; - }, - enumerable: false, - configurable: true - }); + BlobServiceClient.prototype.findBlobsByTagsSegment = function (tagFilterSqlExpression, marker, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, response, wrappedResponse, e_9; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-findBlobsByTagsSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.filterBlobs({ + abortSignal: options.abortSignal, + where: tagFilterSqlExpression, + marker: marker, + maxPageSize: options.maxPageSize, + spanOptions: spanOptions + })]; + case 2: + response = _b.sent(); + wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, blobs: response.blobs.map(function (blob) { + var _a; + var tagValue = ""; + if (((_a = blob.tags) === null || _a === void 0 ? void 0 : _a.blobTagSet.length) === 1) { + tagValue = blob.tags.blobTagSet[0].value; + } + return tslib.__assign(tslib.__assign({}, blob), { tags: toTags(blob.tags), tagValue: tagValue }); + }) }); + return [2 /*return*/, wrappedResponse]; + case 3: + e_9 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_9.message + }); + throw e_9; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; /** - * Encodes all SAS query parameters into a string that can be appended to a URL. + * Returns an AsyncIterableIterator for ServiceFindBlobsByTagsSegmentResponse. * - * @returns {string} - * @memberof SASQueryParameters + * @private + * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param {string} [marker] A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to find blobs by tags. + * @returns {AsyncIterableIterator} + * @memberof BlobServiceClient */ - SASQueryParameters.prototype.toString = function () { - var params = [ - "sv", - "ss", - "srt", - "spr", - "st", - "se", - "sip", - "si", - "skoid", - "sktid", - "skt", - "ske", - "sks", - "skv", - "sr", - "sp", - "sig", - "rscc", - "rscd", - "rsce", - "rscl", - "rsct", - "saoid", - "scid" - ]; - var queries = []; - for (var _i = 0, params_1 = params; _i < params_1.length; _i++) { - var param = params_1[_i]; - switch (param) { - case "sv": - this.tryAppendQueryParameter(queries, param, this.version); - break; - case "ss": - this.tryAppendQueryParameter(queries, param, this.services); - break; - case "srt": - this.tryAppendQueryParameter(queries, param, this.resourceTypes); - break; - case "spr": - this.tryAppendQueryParameter(queries, param, this.protocol); - break; - case "st": - this.tryAppendQueryParameter(queries, param, this.startsOn ? truncatedISO8061Date(this.startsOn, false) : undefined); - break; - case "se": - this.tryAppendQueryParameter(queries, param, this.expiresOn ? truncatedISO8061Date(this.expiresOn, false) : undefined); - break; - case "sip": - this.tryAppendQueryParameter(queries, param, this.ipRange ? ipRangeToString(this.ipRange) : undefined); - break; - case "si": - this.tryAppendQueryParameter(queries, param, this.identifier); - break; - case "skoid": // Signed object ID - this.tryAppendQueryParameter(queries, param, this.signedOid); - break; - case "sktid": // Signed tenant ID - this.tryAppendQueryParameter(queries, param, this.signedTenantId); - break; - case "skt": // Signed key start time - this.tryAppendQueryParameter(queries, param, this.signedStartsOn ? truncatedISO8061Date(this.signedStartsOn, false) : undefined); - break; - case "ske": // Signed key expiry time - this.tryAppendQueryParameter(queries, param, this.signedExpiresOn ? truncatedISO8061Date(this.signedExpiresOn, false) : undefined); - break; - case "sks": // Signed key service - this.tryAppendQueryParameter(queries, param, this.signedService); - break; - case "skv": // Signed key version - this.tryAppendQueryParameter(queries, param, this.signedVersion); - break; - case "sr": - this.tryAppendQueryParameter(queries, param, this.resource); - break; - case "sp": - this.tryAppendQueryParameter(queries, param, this.permissions); - break; - case "sig": - this.tryAppendQueryParameter(queries, param, this.signature); - break; - case "rscc": - this.tryAppendQueryParameter(queries, param, this.cacheControl); - break; - case "rscd": - this.tryAppendQueryParameter(queries, param, this.contentDisposition); - break; - case "rsce": - this.tryAppendQueryParameter(queries, param, this.contentEncoding); - break; - case "rscl": - this.tryAppendQueryParameter(queries, param, this.contentLanguage); - break; - case "rsct": - this.tryAppendQueryParameter(queries, param, this.contentType); - break; - case "saoid": - this.tryAppendQueryParameter(queries, param, this.preauthorizedAgentObjectId); - break; - case "scid": - this.tryAppendQueryParameter(queries, param, this.correlationId); - break; - } - } - return queries.join("&"); + BlobServiceClient.prototype.findBlobsByTagsSegments = function (tagFilterSqlExpression, marker, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function findBlobsByTagsSegments_1() { + var response; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!(!!marker || marker === undefined)) return [3 /*break*/, 6]; + _a.label = 1; + case 1: return [4 /*yield*/, tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker, options))]; + case 2: + response = _a.sent(); + response.blobs = response.blobs || []; + marker = response.continuationToken; + return [4 /*yield*/, tslib.__await(response)]; + case 3: return [4 /*yield*/, _a.sent()]; + case 4: + _a.sent(); + _a.label = 5; + case 5: + if (marker) return [3 /*break*/, 1]; + _a.label = 6; + case 6: return [2 /*return*/]; + } + }); + }); }; /** - * A private helper method used to filter and append query key/value pairs into an array. + * Returns an AsyncIterableIterator for blobs. * * @private - * @param {string[]} queries - * @param {string} key - * @param {string} [value] - * @returns {void} - * @memberof SASQueryParameters + * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to findBlobsByTagsItems. + * @returns {AsyncIterableIterator} + * @memberof BlobServiceClient */ - SASQueryParameters.prototype.tryAppendQueryParameter = function (queries, key, value) { - if (!value) { - return; - } - key = encodeURIComponent(key); - value = encodeURIComponent(value); - if (key.length > 0 && value.length > 0) { - queries.push(key + "=" + value); - } + BlobServiceClient.prototype.findBlobsByTagsItems = function (tagFilterSqlExpression, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function findBlobsByTagsItems_1() { + var marker, _a, _b, segment, e_10_1; + var e_10, _c; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _d.trys.push([0, 7, 8, 13]); + _a = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker, options)); + _d.label = 1; + case 1: return [4 /*yield*/, tslib.__await(_a.next())]; + case 2: + if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; + segment = _b.value; + return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs)))]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; + case 4: + _d.sent(); + _d.label = 5; + case 5: return [3 /*break*/, 1]; + case 6: return [3 /*break*/, 13]; + case 7: + e_10_1 = _d.sent(); + e_10 = { error: e_10_1 }; + return [3 /*break*/, 13]; + case 8: + _d.trys.push([8, , 11, 12]); + if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; + return [4 /*yield*/, tslib.__await(_c.call(_a))]; + case 9: + _d.sent(); + _d.label = 10; + case 10: return [3 /*break*/, 12]; + case 11: + if (e_10) throw e_10.error; + return [7 /*endfinally*/]; + case 12: return [7 /*endfinally*/]; + case 13: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an async iterable iterator to find all blobs with specified tag + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the blobs in pages. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties + * + * Example using `for await` syntax: + * + * ```js + * let i = 1; + * for await (const blob of blobServiceClient.findBlobsByTags("tagkey='tagvalue'")) { + * console.log(`Blob ${i++}: ${container.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * const iter = blobServiceClient.findBlobsByTags("tagkey='tagvalue'"); + * let blobItem = await iter.next(); + * while (!blobItem.done) { + * console.log(`Blob ${i++}: ${blobItem.value.name}`); + * blobItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 blob names + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * // Passing next marker as continuationToken + * iterator = blobServiceClient + * .findBlobsByTags("tagkey='tagvalue'") + * .byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints blob names + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * ``` + * + * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param {ServiceFindBlobByTagsOptions} [options={}] Options to find blobs by tags. + * @returns {PagedAsyncIterableIterator} + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.findBlobsByTags = function (tagFilterSqlExpression, options) { + var _a; + var _this = this; + if (options === void 0) { options = {}; } + // AsyncIterableIterator to iterate over blobs + var listSegmentOptions = tslib.__assign({}, options); + var iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); + return _a = { + /** + * @member {Promise} [next] The next method, part of the iteration protocol + */ + next: function () { + return iter.next(); + } + }, + /** + * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol + */ + _a[Symbol.asyncIterator] = function () { + return this; + }, + /** + * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time + */ + _a.byPage = function (settings) { + if (settings === void 0) { settings = {}; } + return _this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + }, + _a; }; - return SASQueryParameters; -}()); - -// Copyright (c) Microsoft Corporation. All rights reserved. -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * Generates a {@link SASQueryParameters} object which contains all SAS query parameters needed to make an actual - * REST request. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas - * - * @param {AccountSASSignatureValues} accountSASSignatureValues - * @param {StorageSharedKeyCredential} sharedKeyCredential - * @returns {SASQueryParameters} - * @memberof AccountSASSignatureValues - */ -function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { - var version = accountSASSignatureValues.version - ? accountSASSignatureValues.version - : SERVICE_VERSION; - if (accountSASSignatureValues.permissions && - accountSASSignatureValues.permissions.deleteVersion && - version < "2019-10-10") { - throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); - } - if (accountSASSignatureValues.permissions && - accountSASSignatureValues.permissions.tag && - version < "2019-12-12") { - throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); - } - if (accountSASSignatureValues.permissions && - accountSASSignatureValues.permissions.filter && - version < "2019-12-12") { - throw RangeError("'version' must be >= '2019-12-12' when provided 'f' permission."); - } - var parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); - var parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); - var parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); - var stringToSign = [ - sharedKeyCredential.accountName, - parsedPermissions, - parsedServices, - parsedResourceTypes, - accountSASSignatureValues.startsOn - ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) - : "", - truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), - accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", - accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", - version, - "" // Account SAS requires an additional newline character - ].join("\n"); - var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(version, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange); -} - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a blob. Setting - * a value to true means that any SAS which uses these permissions will grant permissions for that operation. Once all - * the values are set, this should be serialized with toString and set as the permissions field on a - * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but - * the order of the permissions is particular and this class guarantees correctness. - * - * @export - * @class BlobSASPermissions - */ -var BlobSASPermissions = /** @class */ (function () { - function BlobSASPermissions() { - /** - * Specifies Read access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.read = false; - /** - * Specifies Add access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.add = false; - /** - * Specifies Create access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.create = false; - /** - * Specifies Write access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.write = false; - /** - * Specifies Delete access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.delete = false; - /** - * Specifies Delete version access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.deleteVersion = false; - /** - * Specfies Tag access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.tag = false; - /** - * Specifies Move access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.move = false; - /** - * Specifies Execute access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.execute = false; - } /** - * Creates a {@link BlobSASPermissions} from the specified permissions string. This method will throw an - * Error if it encounters a character that does not correspond to a valid permission. + * Returns an AsyncIterableIterator for ServiceListContainersSegmentResponses * - * @static - * @param {string} permissions - * @returns {BlobSASPermissions} - * @memberof BlobSASPermissions + * @private + * @param {string} [marker] A string value that identifies the portion of + * the list of containers to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all containers remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ServiceListContainersSegmentOptions} [options] Options to list containers operation. + * @returns {AsyncIterableIterator} + * @memberof BlobServiceClient */ - BlobSASPermissions.parse = function (permissions) { - var blobSASPermissions = new BlobSASPermissions(); - for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { - var char = permissions_1[_i]; - switch (char) { - case "r": - blobSASPermissions.read = true; - break; - case "a": - blobSASPermissions.add = true; - break; - case "c": - blobSASPermissions.create = true; - break; - case "w": - blobSASPermissions.write = true; - break; - case "d": - blobSASPermissions.delete = true; - break; - case "x": - blobSASPermissions.deleteVersion = true; - break; - case "t": - blobSASPermissions.tag = true; - break; - case "m": - blobSASPermissions.move = true; - break; - case "e": - blobSASPermissions.execute = true; - break; - default: - throw new RangeError("Invalid permission: " + char); - } - } - return blobSASPermissions; + BlobServiceClient.prototype.listSegments = function (marker, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listSegments_1() { + var listContainersSegmentResponse; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!(!!marker || marker === undefined)) return [3 /*break*/, 7]; + _a.label = 1; + case 1: return [4 /*yield*/, tslib.__await(this.listContainersSegment(marker, options))]; + case 2: + listContainersSegmentResponse = _a.sent(); + listContainersSegmentResponse.containerItems = + listContainersSegmentResponse.containerItems || []; + marker = listContainersSegmentResponse.continuationToken; + return [4 /*yield*/, tslib.__await(listContainersSegmentResponse)]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_a.sent()])]; + case 4: return [4 /*yield*/, _a.sent()]; + case 5: + _a.sent(); + _a.label = 6; + case 6: + if (marker) return [3 /*break*/, 1]; + _a.label = 7; + case 7: return [2 /*return*/]; + } + }); + }); }; /** - * Converts the given permissions to a string. Using this method will guarantee the permissions are in an - * order accepted by the service. + * Returns an AsyncIterableIterator for Container Items * - * @returns {string} A string which represents the BlobSASPermissions - * @memberof BlobSASPermissions + * @private + * @param {ServiceListContainersSegmentOptions} [options] Options to list containers operation. + * @returns {AsyncIterableIterator} + * @memberof BlobServiceClient */ - BlobSASPermissions.prototype.toString = function () { - var permissions = []; - if (this.read) { - permissions.push("r"); - } - if (this.add) { - permissions.push("a"); - } - if (this.create) { - permissions.push("c"); - } - if (this.write) { - permissions.push("w"); - } - if (this.delete) { - permissions.push("d"); - } - if (this.deleteVersion) { - permissions.push("x"); - } - if (this.tag) { - permissions.push("t"); - } - if (this.move) { - permissions.push("m"); - } - if (this.execute) { - permissions.push("e"); - } - return permissions.join(""); + BlobServiceClient.prototype.listItems = function (options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listItems_1() { + var marker, _a, _b, segment, e_11_1; + var e_11, _c; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _d.trys.push([0, 7, 8, 13]); + _a = tslib.__asyncValues(this.listSegments(marker, options)); + _d.label = 1; + case 1: return [4 /*yield*/, tslib.__await(_a.next())]; + case 2: + if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; + segment = _b.value; + return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(segment.containerItems)))]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; + case 4: + _d.sent(); + _d.label = 5; + case 5: return [3 /*break*/, 1]; + case 6: return [3 /*break*/, 13]; + case 7: + e_11_1 = _d.sent(); + e_11 = { error: e_11_1 }; + return [3 /*break*/, 13]; + case 8: + _d.trys.push([8, , 11, 12]); + if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; + return [4 /*yield*/, tslib.__await(_c.call(_a))]; + case 9: + _d.sent(); + _d.label = 10; + case 10: return [3 /*break*/, 12]; + case 11: + if (e_11) throw e_11.error; + return [7 /*endfinally*/]; + case 12: return [7 /*endfinally*/]; + case 13: return [2 /*return*/]; + } + }); + }); }; - return BlobSASPermissions; -}()); - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -/** - * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a container. - * Setting a value to true means that any SAS which uses these permissions will grant permissions for that operation. - * Once all the values are set, this should be serialized with toString and set as the permissions field on a - * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but - * the order of the permissions is particular and this class guarantees correctness. - * - * @export - * @class ContainerSASPermissions - */ -var ContainerSASPermissions = /** @class */ (function () { - function ContainerSASPermissions() { - /** - * Specifies Read access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.read = false; - /** - * Specifies Add access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.add = false; - /** - * Specifies Create access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.create = false; - /** - * Specifies Write access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.write = false; - /** - * Specifies Delete access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.delete = false; - /** - * Specifies Delete version access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.deleteVersion = false; - /** - * Specifies List access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.list = false; - /** - * Specfies Tag access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.tag = false; - /** - * Specifies Move access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.move = false; - /** - * Specifies Execute access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.execute = false; - } /** - * Creates an {@link ContainerSASPermissions} from the specified permissions string. This method will throw an - * Error if it encounters a character that does not correspond to a valid permission. + * Returns an async iterable iterator to list all the containers + * under the specified account. * - * @static - * @param {string} permissions - * @returns {ContainerSASPermissions} - * @memberof ContainerSASPermissions + * .byPage() returns an async iterable iterator to list the containers in pages. + * + * Example using `for await` syntax: + * + * ```js + * let i = 1; + * for await (const container of blobServiceClient.listContainers()) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * const iter = blobServiceClient.listContainers(); + * let containerItem = await iter.next(); + * while (!containerItem.done) { + * console.log(`Container ${i++}: ${containerItem.value.name}`); + * containerItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of blobServiceClient.listContainers().byPage({ maxPageSize: 20 })) { + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = blobServiceClient.listContainers().byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 container names + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * // Passing next marker as continuationToken + * iterator = blobServiceClient + * .listContainers() + * .byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints 10 container names + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * ``` + * + * @param {ServiceListContainersOptions} [options={}] Options to list containers. + * @returns {PagedAsyncIterableIterator} An asyncIterableIterator that supports paging. + * @memberof BlobServiceClient */ - ContainerSASPermissions.parse = function (permissions) { - var containerSASPermissions = new ContainerSASPermissions(); - for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { - var char = permissions_1[_i]; - switch (char) { - case "r": - containerSASPermissions.read = true; - break; - case "a": - containerSASPermissions.add = true; - break; - case "c": - containerSASPermissions.create = true; - break; - case "w": - containerSASPermissions.write = true; - break; - case "d": - containerSASPermissions.delete = true; - break; - case "l": - containerSASPermissions.list = true; - break; - case "t": - containerSASPermissions.tag = true; - break; - case "x": - containerSASPermissions.deleteVersion = true; - break; - case "m": - containerSASPermissions.move = true; - break; - case "e": - containerSASPermissions.execute = true; - break; - default: - throw new RangeError("Invalid permission " + char); - } + BlobServiceClient.prototype.listContainers = function (options) { + var _a; + var _this = this; + if (options === void 0) { options = {}; } + if (options.prefix === "") { + options.prefix = undefined; } - return containerSASPermissions; + var include = []; + if (options.includeDeleted) { + include.push("deleted"); + } + if (options.includeMetadata) { + include.push("metadata"); + } + // AsyncIterableIterator to iterate over containers + var listSegmentOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); + var iter = this.listItems(listSegmentOptions); + return _a = { + /** + * @member {Promise} [next] The next method, part of the iteration protocol + */ + next: function () { + return iter.next(); + } + }, + /** + * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol + */ + _a[Symbol.asyncIterator] = function () { + return this; + }, + /** + * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time + */ + _a.byPage = function (settings) { + if (settings === void 0) { settings = {}; } + return _this.listSegments(settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + }, + _a; }; /** - * Converts the given permissions to a string. Using this method will guarantee the permissions are in an - * order accepted by the service. + * ONLY AVAILABLE WHEN USING BEARER TOKEN AUTHENTICATION (TokenCredential). * - * The order of the characters should be as specified here to ensure correctness. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas + * Retrieves a user delegation key for the Blob service. This is only a valid operation when using + * bearer token authentication. * - * @returns {string} - * @memberof ContainerSASPermissions + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-user-delegation-key + * + * @param {Date} startsOn The start time for the user delegation SAS. Must be within 7 days of the current time + * @param {Date} expiresOn The end time for the user delegation SAS. Must be within 7 days of the current time + * @returns {Promise} + * @memberof BlobServiceClient */ - ContainerSASPermissions.prototype.toString = function () { - var permissions = []; - if (this.read) { - permissions.push("r"); - } - if (this.add) { - permissions.push("a"); - } - if (this.create) { - permissions.push("c"); - } - if (this.write) { - permissions.push("w"); - } - if (this.delete) { - permissions.push("d"); - } - if (this.deleteVersion) { - permissions.push("x"); - } - if (this.list) { - permissions.push("l"); - } - if (this.tag) { - permissions.push("t"); - } - if (this.move) { - permissions.push("m"); - } - if (this.execute) { - permissions.push("e"); - } - return permissions.join(""); + BlobServiceClient.prototype.getUserDelegationKey = function (startsOn, expiresOn, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, response, userDelegationKey, res, e_12; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-getUserDelegationKey", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.getUserDelegationKey({ + startsOn: truncatedISO8061Date(startsOn, false), + expiresOn: truncatedISO8061Date(expiresOn, false) + }, { + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: + response = _b.sent(); + userDelegationKey = { + signedObjectId: response.signedObjectId, + signedTenantId: response.signedTenantId, + signedStartsOn: new Date(response.signedStartsOn), + signedExpiresOn: new Date(response.signedExpiresOn), + signedService: response.signedService, + signedVersion: response.signedVersion, + value: response.value + }; + res = tslib.__assign({ _response: response._response, requestId: response.requestId, clientRequestId: response.clientRequestId, version: response.version, date: response.date, errorCode: response.errorCode }, userDelegationKey); + return [2 /*return*/, res]; + case 3: + e_12 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_12.message + }); + throw e_12; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; - return ContainerSASPermissions; -}()); - -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * UserDelegationKeyCredential is only used for generation of user delegation SAS. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas - * - * @export - * @class UserDelegationKeyCredential - */ -var UserDelegationKeyCredential = /** @class */ (function () { /** - * Creates an instance of UserDelegationKeyCredential. - * @param {string} accountName - * @param {UserDelegationKey} userDelegationKey - * @memberof UserDelegationKeyCredential + * Creates a BlobBatchClient object to conduct batch operations. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch + * + * @returns {BlobBatchClient} A new BlobBatchClient object for this service. + * @memberof BlobServiceClient */ - function UserDelegationKeyCredential(accountName, userDelegationKey) { - this.accountName = accountName; - this.userDelegationKey = userDelegationKey; - this.key = Buffer.from(userDelegationKey.value, "base64"); - } + BlobServiceClient.prototype.getBlobBatchClient = function () { + return new BlobBatchClient(this.url, this.pipeline); + }; /** - * Generates a hash signature for an HTTP request or for a SAS. + * Only available for BlobServiceClient constructed with a shared key credential. * - * @param {string} stringToSign - * @returns {string} - * @memberof UserDelegationKeyCredential + * Generates a Blob account Shared Access Signature (SAS) URI based on the client properties + * and parameters passed in. The SAS is signed by the shared key credential of the client. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-account-sas + * + * @param {Date} expiresOn Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not provided. + * @param {AccountSASPermissions} [permissions=AccountSASPermissions.parse("r")] Specifies the list of permissions to be associated with the SAS. + * @param {string} [resourceTypes="sco"] Specifies the resource types associated with the shared access signature. + * @param {ServiceGenerateAccountSasUrlOptions} [options={}] Optional parameters. + * @returns {string} An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + * @memberof BlobServiceClient */ - UserDelegationKeyCredential.prototype.computeHMACSHA256 = function (stringToSign) { - // console.log(`stringToSign: ${JSON.stringify(stringToSign)}`); - return crypto.createHmac("sha256", this.key) - .update(stringToSign, "utf8") - .digest("base64"); - }; - return UserDelegationKeyCredential; -}()); - -// Copyright (c) Microsoft Corporation. All rights reserved. -function generateBlobSASQueryParameters(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { - var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; - var sharedKeyCredential = sharedKeyCredentialOrUserDelegationKey instanceof StorageSharedKeyCredential - ? sharedKeyCredentialOrUserDelegationKey - : undefined; - var userDelegationKeyCredential; - if (sharedKeyCredential === undefined && accountName !== undefined) { - userDelegationKeyCredential = new UserDelegationKeyCredential(accountName, sharedKeyCredentialOrUserDelegationKey); - } - if (sharedKeyCredential === undefined && userDelegationKeyCredential === undefined) { - throw TypeError("Invalid sharedKeyCredential, userDelegationKey or accountName."); - } - // Version 2019-12-12 adds support for the blob tags permission. - // Version 2018-11-09 adds support for the signed resource and signed blob snapshot time fields. - // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas#constructing-the-signature-string - if (version >= "2018-11-09") { - if (sharedKeyCredential !== undefined) { - return generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential); - } - else { - // Version 2020-02-10 delegation SAS signature construction includes preauthorizedAgentObjectId, agentObjectId, correlationId. - if (version >= "2020-02-10") { - return generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userDelegationKeyCredential); - } - else { - return generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential); - } - } - } - if (version >= "2015-04-05") { - if (sharedKeyCredential !== undefined) { - return generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential); - } - else { - throw new RangeError("'version' must be >= '2018-11-09' when generating user delegation SAS using user delegation key."); - } - } - throw new RangeError("'version' must be >= '2015-04-05'."); -} -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * IMPLEMENTATION FOR API VERSION FROM 2015-04-05 AND BEFORE 2018-11-09. - * - * Creates an instance of SASQueryParameters. - * - * Only accepts required settings needed to create a SAS. For optional settings please - * set corresponding properties directly, such as permissions, startsOn and identifier. - * - * WARNING: When identifier is not provided, permissions and expiresOn are required. - * You MUST assign value to identifier or expiresOn & permissions manually if you initial with - * this constructor. - * - * @param {BlobSASSignatureValues} blobSASSignatureValues - * @param {StorageSharedKeyCredential} sharedKeyCredential - * @returns {SASQueryParameters} - */ -function generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential) { - blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); - if (!blobSASSignatureValues.identifier && - !blobSASSignatureValues.permissions && - !blobSASSignatureValues.expiresOn) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); - } - var resource = "c"; - if (blobSASSignatureValues.blobName) { - resource = "b"; - } - // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; - if (blobSASSignatureValues.permissions) { - if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - else { - verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - } - // Signature is generated on the un-url-encoded values. - var stringToSign = [ - verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn - ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) - : "", - blobSASSignatureValues.expiresOn - ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) - : "", - getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), - blobSASSignatureValues.identifier, - blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", - blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", - blobSASSignatureValues.version, - blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", - blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", - blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", - blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", - blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" - ].join("\n"); - var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); -} -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. - * - * Creates an instance of SASQueryParameters. - * - * Only accepts required settings needed to create a SAS. For optional settings please - * set corresponding properties directly, such as permissions, startsOn and identifier. - * - * WARNING: When identifier is not provided, permissions and expiresOn are required. - * You MUST assign value to identifier or expiresOn & permissions manually if you initial with - * this constructor. - * - * @param {BlobSASSignatureValues} blobSASSignatureValues - * @param {StorageSharedKeyCredential} sharedKeyCredential - * @returns {SASQueryParameters} - */ -function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential) { - blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); - if (!blobSASSignatureValues.identifier && - !blobSASSignatureValues.permissions && - !blobSASSignatureValues.expiresOn) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); - } - var resource = "c"; - var timestamp = blobSASSignatureValues.snapshotTime; - if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; - } - else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; - } - } - // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; - if (blobSASSignatureValues.permissions) { - if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - else { - verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - } - // Signature is generated on the un-url-encoded values. - var stringToSign = [ - verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn - ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) - : "", - blobSASSignatureValues.expiresOn - ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) - : "", - getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), - blobSASSignatureValues.identifier, - blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", - blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", - blobSASSignatureValues.version, - resource, - timestamp, - blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", - blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", - blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", - blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", - blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" - ].join("\n"); - var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); -} -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. - * - * Creates an instance of SASQueryParameters. - * - * Only accepts required settings needed to create a SAS. For optional settings please - * set corresponding properties directly, such as permissions, startsOn. - * - * WARNING: identifier will be ignored, permissions and expiresOn are required. - * - * @param {BlobSASSignatureValues} blobSASSignatureValues - * @param {UserDelegationKeyCredential} userDelegationKeyCredential - * @returns {SASQueryParameters} - */ -function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential) { - blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); - // Stored access policies are not supported for a user delegation SAS. - if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); - } - var resource = "c"; - var timestamp = blobSASSignatureValues.snapshotTime; - if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; - } - else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; - } - } - // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; - if (blobSASSignatureValues.permissions) { - if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - else { - verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - } - // Signature is generated on the un-url-encoded values. - var stringToSign = [ - verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn - ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) - : "", - blobSASSignatureValues.expiresOn - ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) - : "", - getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), - userDelegationKeyCredential.userDelegationKey.signedObjectId, - userDelegationKeyCredential.userDelegationKey.signedTenantId, - userDelegationKeyCredential.userDelegationKey.signedStartsOn - ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) - : "", - userDelegationKeyCredential.userDelegationKey.signedExpiresOn - ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) - : "", - userDelegationKeyCredential.userDelegationKey.signedService, - userDelegationKeyCredential.userDelegationKey.signedVersion, - blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", - blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", - blobSASSignatureValues.version, - resource, - timestamp, - blobSASSignatureValues.cacheControl, - blobSASSignatureValues.contentDisposition, - blobSASSignatureValues.contentEncoding, - blobSASSignatureValues.contentLanguage, - blobSASSignatureValues.contentType - ].join("\n"); - var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey); -} -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * IMPLEMENTATION FOR API VERSION FROM 2020-02-10. - * - * Creates an instance of SASQueryParameters. - * - * Only accepts required settings needed to create a SAS. For optional settings please - * set corresponding properties directly, such as permissions, startsOn. - * - * WARNING: identifier will be ignored, permissions and expiresOn are required. - * - * @param {BlobSASSignatureValues} blobSASSignatureValues - * @param {UserDelegationKeyCredential} userDelegationKeyCredential - * @returns {SASQueryParameters} - */ -function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userDelegationKeyCredential) { - blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); - // Stored access policies are not supported for a user delegation SAS. - if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); - } - var resource = "c"; - var timestamp = blobSASSignatureValues.snapshotTime; - if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; - } - else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; - } - } - // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; - if (blobSASSignatureValues.permissions) { - if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + BlobServiceClient.prototype.generateAccountSasUrl = function (expiresOn, permissions, resourceTypes, options) { + if (permissions === void 0) { permissions = AccountSASPermissions.parse("r"); } + if (resourceTypes === void 0) { resourceTypes = "sco"; } + if (options === void 0) { options = {}; } + if (!(this.credential instanceof StorageSharedKeyCredential)) { + throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); } - else { - verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + if (expiresOn === undefined) { + var now = new Date(); + expiresOn = new Date(now.getTime() + 3600 * 1000); } - } - // Signature is generated on the un-url-encoded values. - var stringToSign = [ - verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn - ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) - : "", - blobSASSignatureValues.expiresOn - ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) - : "", - getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), - userDelegationKeyCredential.userDelegationKey.signedObjectId, - userDelegationKeyCredential.userDelegationKey.signedTenantId, - userDelegationKeyCredential.userDelegationKey.signedStartsOn - ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) - : "", - userDelegationKeyCredential.userDelegationKey.signedExpiresOn - ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) - : "", - userDelegationKeyCredential.userDelegationKey.signedService, - userDelegationKeyCredential.userDelegationKey.signedVersion, - blobSASSignatureValues.preauthorizedAgentObjectId, - undefined, - blobSASSignatureValues.correlationId, - blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", - blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", - blobSASSignatureValues.version, - resource, - timestamp, - blobSASSignatureValues.cacheControl, - blobSASSignatureValues.contentDisposition, - blobSASSignatureValues.contentEncoding, - blobSASSignatureValues.contentLanguage, - blobSASSignatureValues.contentType - ].join("\n"); - var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId); -} -function getCanonicalName(accountName, containerName, blobName) { - // Container: "/blob/account/containerName" - // Blob: "/blob/account/containerName/blobName" - var elements = ["/blob/" + accountName + "/" + containerName]; - if (blobName) { - elements.push("/" + blobName); - } - return elements.join(""); -} -function SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues) { - var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; - if (blobSASSignatureValues.snapshotTime && version < "2018-11-09") { - throw RangeError("'version' must be >= '2018-11-09' when providing 'snapshotTime'."); - } - if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.snapshotTime) { - throw RangeError("Must provide 'blobName' when providing 'snapshotTime'."); - } - if (blobSASSignatureValues.versionId && version < "2019-10-10") { - throw RangeError("'version' must be >= '2019-10-10' when providing 'versionId'."); - } - if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.versionId) { - throw RangeError("Must provide 'blobName' when providing 'versionId'."); - } - if (blobSASSignatureValues.permissions && - blobSASSignatureValues.permissions.deleteVersion && - version < "2019-10-10") { - throw RangeError("'version' must be >= '2019-10-10' when providing 'x' permission."); - } - if (blobSASSignatureValues.permissions && - blobSASSignatureValues.permissions.tag && - version < "2019-12-12") { - throw RangeError("'version' must be >= '2019-12-12' when providing 't' permission."); - } - if (version < "2020-02-10" && - blobSASSignatureValues.permissions && - (blobSASSignatureValues.permissions.move || blobSASSignatureValues.permissions.execute)) { - throw RangeError("'version' must be >= '2020-02-10' when providing the 'm' or 'e' permission."); - } - if (version < "2020-02-10" && - (blobSASSignatureValues.preauthorizedAgentObjectId || blobSASSignatureValues.correlationId)) { - throw RangeError("'version' must be >= '2020-02-10' when providing 'preauthorizedAgentObjectId' or 'correlationId'."); - } - blobSASSignatureValues.version = version; - return blobSASSignatureValues; -} + var sas = generateAccountSASQueryParameters(tslib.__assign({ permissions: permissions, + expiresOn: expiresOn, + resourceTypes: resourceTypes, services: AccountSASServices.parse("b").toString() }, options), this.credential).toString(); + return appendToURLQuery(this.url, sas); + }; + return BlobServiceClient; +}(StorageClient)); Object.defineProperty(exports, 'BaseRequestPolicy', { enumerable: true, @@ -39004,288 +39478,7 @@ module.exports = require("crypto"); /* 419 */, /* 420 */, /* 421 */, -/* 422 */ -/***/ (function(module) { - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ -/* global global, define, System, Reflect, Promise */ -var __extends; -var __assign; -var __rest; -var __decorate; -var __param; -var __metadata; -var __awaiter; -var __generator; -var __exportStar; -var __values; -var __read; -var __spread; -var __spreadArrays; -var __await; -var __asyncGenerator; -var __asyncDelegator; -var __asyncValues; -var __makeTemplateObject; -var __importStar; -var __importDefault; -var __classPrivateFieldGet; -var __classPrivateFieldSet; -(function (factory) { - var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; - if (typeof define === "function" && define.amd) { - define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); - } - else if ( true && typeof module.exports === "object") { - factory(createExporter(root, createExporter(module.exports))); - } - else { - factory(createExporter(root)); - } - function createExporter(exports, previous) { - if (exports !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports, "__esModule", { value: true }); - } - else { - exports.__esModule = true; - } - } - return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; - } -}) -(function (exporter) { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - - __extends = function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - - __assign = Object.assign || function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - - __rest = function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; - - __decorate = function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - - __param = function (paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - }; - - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - }; - - __awaiter = function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - - __generator = function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - - __exportStar = function (m, exports) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; - }; - - __values = function (o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - - __read = function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - - __spread = function () { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - }; - - __spreadArrays = function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; - }; - - __await = function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - - __asyncGenerator = function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - }; - - __asyncDelegator = function (o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } - }; - - __asyncValues = function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } - }; - - __makeTemplateObject = function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - }; - - __importStar = function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; - }; - - __importDefault = function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - - __classPrivateFieldGet = function (receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - return privateMap.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - privateMap.set(receiver, value); - return value; - } - - exporter("__extends", __extends); - exporter("__assign", __assign); - exporter("__rest", __rest); - exporter("__decorate", __decorate); - exporter("__param", __param); - exporter("__metadata", __metadata); - exporter("__awaiter", __awaiter); - exporter("__generator", __generator); - exporter("__exportStar", __exportStar); - exporter("__values", __values); - exporter("__read", __read); - exporter("__spread", __spread); - exporter("__spreadArrays", __spreadArrays); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); - exporter("__asyncDelegator", __asyncDelegator); - exporter("__asyncValues", __asyncValues); - exporter("__makeTemplateObject", __makeTemplateObject); - exporter("__importStar", __importStar); - exporter("__importDefault", __importDefault); - exporter("__classPrivateFieldGet", __classPrivateFieldGet); - exporter("__classPrivateFieldSet", __classPrivateFieldSet); -}); - - -/***/ }), +/* 422 */, /* 423 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -39866,130 +40059,167 @@ function escapeProperty(s) { /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const exec_1 = __webpack_require__(986); -const io = __importStar(__webpack_require__(1)); -const fs_1 = __webpack_require__(747); -const path = __importStar(__webpack_require__(622)); -const utils = __importStar(__webpack_require__(15)); -const constants_1 = __webpack_require__(931); -function getTarPath(args, compressionMethod) { - return __awaiter(this, void 0, void 0, function* () { - const IS_WINDOWS = process.platform === 'win32'; - if (IS_WINDOWS) { - const systemTar = `${process.env['windir']}\\System32\\tar.exe`; - if (compressionMethod !== constants_1.CompressionMethod.Gzip) { - // We only use zstandard compression on windows when gnu tar is installed due to - // a bug with compressing large files with bsdtar + zstd - args.push('--force-local'); - } - else if (fs_1.existsSync(systemTar)) { - return systemTar; - } - else if (yield utils.isGnuTarInstalled()) { - args.push('--force-local'); - } - } - return yield io.which('tar', true); - }); -} -function execTar(args, compressionMethod, cwd) { - return __awaiter(this, void 0, void 0, function* () { - try { - yield exec_1.exec(`"${yield getTarPath(args, compressionMethod)}"`, args, { cwd }); - } - catch (error) { - throw new Error(`Tar failed with error: ${error === null || error === void 0 ? void 0 : error.message}`); - } - }); -} -function getWorkingDirectory() { - var _a; - return (_a = process.env['GITHUB_WORKSPACE']) !== null && _a !== void 0 ? _a : process.cwd(); -} -function extractTar(archivePath, compressionMethod) { - return __awaiter(this, void 0, void 0, function* () { - // Create directory to extract tar into - const workingDirectory = getWorkingDirectory(); - yield io.mkdirP(workingDirectory); - // --d: Decompress. - // --long=#: Enables long distance matching with # bits. Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit. - // Using 30 here because we also support 32-bit self-hosted runners. - function getCompressionProgram() { - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return ['--use-compress-program', 'zstd -d --long=30']; - case constants_1.CompressionMethod.ZstdWithoutLong: - return ['--use-compress-program', 'zstd -d']; - default: - return ['-z']; - } - } - const args = [ - ...getCompressionProgram(), - '-xf', - archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), - '-P', - '-C', - workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/') - ]; - yield execTar(args, compressionMethod); - }); -} -exports.extractTar = extractTar; -function createTar(archiveFolder, sourceDirectories, compressionMethod) { - return __awaiter(this, void 0, void 0, function* () { - // Write source directories to manifest.txt to avoid command length limits - const manifestFilename = 'manifest.txt'; - const cacheFileName = utils.getCacheFileName(compressionMethod); - fs_1.writeFileSync(path.join(archiveFolder, manifestFilename), sourceDirectories.join('\n')); - const workingDirectory = getWorkingDirectory(); - // -T#: Compress using # working thread. If # is 0, attempt to detect and use the number of physical CPU cores. - // --long=#: Enables long distance matching with # bits. Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit. - // Using 30 here because we also support 32-bit self-hosted runners. - // Long range mode is added to zstd in v1.3.2 release, so we will not use --long in older version of zstd. - function getCompressionProgram() { - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return ['--use-compress-program', 'zstd -T0 --long=30']; - case constants_1.CompressionMethod.ZstdWithoutLong: - return ['--use-compress-program', 'zstd -T0']; - default: - return ['-z']; - } - } - const args = [ - '--posix', - ...getCompressionProgram(), - '-cf', - cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), - '-P', - '-C', - workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), - '--files-from', - manifestFilename - ]; - yield execTar(args, compressionMethod, archiveFolder); - }); -} -exports.createTar = createTar; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const exec_1 = __webpack_require__(986); +const io = __importStar(__webpack_require__(1)); +const fs_1 = __webpack_require__(747); +const path = __importStar(__webpack_require__(622)); +const utils = __importStar(__webpack_require__(15)); +const constants_1 = __webpack_require__(931); +function getTarPath(args, compressionMethod) { + return __awaiter(this, void 0, void 0, function* () { + switch (process.platform) { + case 'win32': { + const systemTar = `${process.env['windir']}\\System32\\tar.exe`; + if (compressionMethod !== constants_1.CompressionMethod.Gzip) { + // We only use zstandard compression on windows when gnu tar is installed due to + // a bug with compressing large files with bsdtar + zstd + args.push('--force-local'); + } + else if (fs_1.existsSync(systemTar)) { + return systemTar; + } + else if (yield utils.isGnuTarInstalled()) { + args.push('--force-local'); + } + break; + } + case 'darwin': { + const gnuTar = yield io.which('gtar', false); + if (gnuTar) { + return gnuTar; + } + break; + } + default: + break; + } + return yield io.which('tar', true); + }); +} +function execTar(args, compressionMethod, cwd) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield exec_1.exec(`"${yield getTarPath(args, compressionMethod)}"`, args, { cwd }); + } + catch (error) { + throw new Error(`Tar failed with error: ${error === null || error === void 0 ? void 0 : error.message}`); + } + }); +} +function getWorkingDirectory() { + var _a; + return (_a = process.env['GITHUB_WORKSPACE']) !== null && _a !== void 0 ? _a : process.cwd(); +} +function extractTar(archivePath, compressionMethod) { + return __awaiter(this, void 0, void 0, function* () { + // Create directory to extract tar into + const workingDirectory = getWorkingDirectory(); + yield io.mkdirP(workingDirectory); + // --d: Decompress. + // --long=#: Enables long distance matching with # bits. Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit. + // Using 30 here because we also support 32-bit self-hosted runners. + function getCompressionProgram() { + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return ['--use-compress-program', 'zstd -d --long=30']; + case constants_1.CompressionMethod.ZstdWithoutLong: + return ['--use-compress-program', 'zstd -d']; + default: + return ['-z']; + } + } + const args = [ + ...getCompressionProgram(), + '-xf', + archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), + '-P', + '-C', + workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/') + ]; + yield execTar(args, compressionMethod); + }); +} +exports.extractTar = extractTar; +function createTar(archiveFolder, sourceDirectories, compressionMethod) { + return __awaiter(this, void 0, void 0, function* () { + // Write source directories to manifest.txt to avoid command length limits + const manifestFilename = 'manifest.txt'; + const cacheFileName = utils.getCacheFileName(compressionMethod); + fs_1.writeFileSync(path.join(archiveFolder, manifestFilename), sourceDirectories.join('\n')); + const workingDirectory = getWorkingDirectory(); + // -T#: Compress using # working thread. If # is 0, attempt to detect and use the number of physical CPU cores. + // --long=#: Enables long distance matching with # bits. Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit. + // Using 30 here because we also support 32-bit self-hosted runners. + // Long range mode is added to zstd in v1.3.2 release, so we will not use --long in older version of zstd. + function getCompressionProgram() { + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return ['--use-compress-program', 'zstd -T0 --long=30']; + case constants_1.CompressionMethod.ZstdWithoutLong: + return ['--use-compress-program', 'zstd -T0']; + default: + return ['-z']; + } + } + const args = [ + '--posix', + ...getCompressionProgram(), + '-cf', + cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), + '-P', + '-C', + workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), + '--files-from', + manifestFilename + ]; + yield execTar(args, compressionMethod, archiveFolder); + }); +} +exports.createTar = createTar; +function listTar(archivePath, compressionMethod) { + return __awaiter(this, void 0, void 0, function* () { + // --d: Decompress. + // --long=#: Enables long distance matching with # bits. + // Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit. + // Using 30 here because we also support 32-bit self-hosted runners. + function getCompressionProgram() { + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return ['--use-compress-program', 'zstd -d --long=30']; + case constants_1.CompressionMethod.ZstdWithoutLong: + return ['--use-compress-program', 'zstd -d']; + default: + return ['-z']; + } + } + const args = [ + ...getCompressionProgram(), + '-tf', + archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), + '-P' + ]; + yield execTar(args, compressionMethod); + }); +} +exports.listTar = listTar; //# sourceMappingURL=tar.js.map /***/ }), @@ -40067,7 +40297,7 @@ __exportStar(__webpack_require__(975), exports); __exportStar(__webpack_require__(70), exports); __exportStar(__webpack_require__(694), exports); __exportStar(__webpack_require__(695), exports); -var context_base_1 = __webpack_require__(231); +var context_base_1 = __webpack_require__(459); Object.defineProperty(exports, "Context", { enumerable: true, get: function () { return context_base_1.Context; } }); var context_1 = __webpack_require__(492); /** Entrypoint for context API */ @@ -42289,7 +42519,35 @@ exports.FetchError = FetchError; /***/ }), -/* 459 */, +/* 459 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +/*! + * Copyright 2019, OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(__webpack_require__(560)); +__export(__webpack_require__(53)); +//# sourceMappingURL=index.js.map + +/***/ }), /* 460 */ /***/ (function(module) { @@ -42882,7 +43140,7 @@ exports.getState = getState; */ Object.defineProperty(exports, "__esModule", { value: true }); exports.ContextAPI = void 0; -var context_base_1 = __webpack_require__(231); +var context_base_1 = __webpack_require__(459); var global_utils_1 = __webpack_require__(976); var NOOP_CONTEXT_MANAGER = new context_base_1.NoopContextManager(); /** @@ -44046,67 +44304,67 @@ function _unique(values) { /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(__webpack_require__(470)); -/** - * Returns a copy of the upload options with defaults filled in. - * - * @param copy the original upload options - */ -function getUploadOptions(copy) { - const result = { - uploadConcurrency: 4, - uploadChunkSize: 32 * 1024 * 1024 - }; - if (copy) { - if (typeof copy.uploadConcurrency === 'number') { - result.uploadConcurrency = copy.uploadConcurrency; - } - if (typeof copy.uploadChunkSize === 'number') { - result.uploadChunkSize = copy.uploadChunkSize; - } - } - core.debug(`Upload concurrency: ${result.uploadConcurrency}`); - core.debug(`Upload chunk size: ${result.uploadChunkSize}`); - return result; -} -exports.getUploadOptions = getUploadOptions; -/** - * Returns a copy of the download options with defaults filled in. - * - * @param copy the original download options - */ -function getDownloadOptions(copy) { - const result = { - useAzureSdk: true, - downloadConcurrency: 8, - timeoutInMs: 30000 - }; - if (copy) { - if (typeof copy.useAzureSdk === 'boolean') { - result.useAzureSdk = copy.useAzureSdk; - } - if (typeof copy.downloadConcurrency === 'number') { - result.downloadConcurrency = copy.downloadConcurrency; - } - if (typeof copy.timeoutInMs === 'number') { - result.timeoutInMs = copy.timeoutInMs; - } - } - core.debug(`Use Azure SDK: ${result.useAzureSdk}`); - core.debug(`Download concurrency: ${result.downloadConcurrency}`); - core.debug(`Request timeout (ms): ${result.timeoutInMs}`); - return result; -} -exports.getDownloadOptions = getDownloadOptions; + +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __importStar(__webpack_require__(470)); +/** + * Returns a copy of the upload options with defaults filled in. + * + * @param copy the original upload options + */ +function getUploadOptions(copy) { + const result = { + uploadConcurrency: 4, + uploadChunkSize: 32 * 1024 * 1024 + }; + if (copy) { + if (typeof copy.uploadConcurrency === 'number') { + result.uploadConcurrency = copy.uploadConcurrency; + } + if (typeof copy.uploadChunkSize === 'number') { + result.uploadChunkSize = copy.uploadChunkSize; + } + } + core.debug(`Upload concurrency: ${result.uploadConcurrency}`); + core.debug(`Upload chunk size: ${result.uploadChunkSize}`); + return result; +} +exports.getUploadOptions = getUploadOptions; +/** + * Returns a copy of the download options with defaults filled in. + * + * @param copy the original download options + */ +function getDownloadOptions(copy) { + const result = { + useAzureSdk: true, + downloadConcurrency: 8, + timeoutInMs: 30000 + }; + if (copy) { + if (typeof copy.useAzureSdk === 'boolean') { + result.useAzureSdk = copy.useAzureSdk; + } + if (typeof copy.downloadConcurrency === 'number') { + result.downloadConcurrency = copy.downloadConcurrency; + } + if (typeof copy.timeoutInMs === 'number') { + result.timeoutInMs = copy.timeoutInMs; + } + } + core.debug(`Use Azure SDK: ${result.useAzureSdk}`); + core.debug(`Download concurrency: ${result.downloadConcurrency}`); + core.debug(`Request timeout (ms): ${result.timeoutInMs}`); + return result; +} +exports.getDownloadOptions = getDownloadOptions; //# sourceMappingURL=options.js.map /***/ }), @@ -45233,7 +45491,90 @@ exports.defaultSetter = defaultSetter; /***/ }), -/* 560 */, +/* 560 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +/*! + * Copyright 2020, OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Class which stores and manages current context values. All methods which + * update context such as get and delete do not modify an existing context, + * but create a new one with updated values. + */ +class Context { + /** + * Construct a new context which inherits values from an optional parent context. + * + * @param parentContext a context from which to inherit values + */ + constructor(parentContext) { + this._currentContext = parentContext ? new Map(parentContext) : new Map(); + } + /** Get a key to uniquely identify a context value */ + static createKey(description) { + return Symbol(description); + } + /** + * Get a value from the context. + * + * @param key key which identifies a context value + */ + getValue(key) { + return this._currentContext.get(key); + } + /** + * Create a new context which inherits from this context and has + * the given key set to the given value. + * + * @param key context key for which to set the value + * @param value value to set for the given key + */ + setValue(key, value) { + const context = new Context(this._currentContext); + context._currentContext.set(key, value); + return context; + } + /** + * Return a new context which inherits from this context but does + * not contain a value for the given key. + * + * @param key context key for which to clear a value + */ + deleteValue(key) { + const context = new Context(this._currentContext); + context._currentContext.delete(key); + return context; + } +} +exports.Context = Context; +/** The root context is used as the default parent context when there is no active context */ +Context.ROOT_CONTEXT = new Context(); +/** + * This is another identifier to the root context which allows developers to easily search the + * codebase for direct uses of context which need to be removed in later PRs. + * + * It's existence is temporary and it should be removed when all references are fixed. + */ +Context.TODO = Context.ROOT_CONTEXT; +//# sourceMappingURL=context.js.map + +/***/ }), /* 561 */, /* 562 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { @@ -46649,152 +46990,159 @@ exports.makeSemver = makeSemver; /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(__webpack_require__(470)); -const path = __importStar(__webpack_require__(622)); -const utils = __importStar(__webpack_require__(15)); -const cacheHttpClient = __importStar(__webpack_require__(114)); -const tar_1 = __webpack_require__(434); -class ValidationError extends Error { - constructor(message) { - super(message); - this.name = 'ValidationError'; - Object.setPrototypeOf(this, ValidationError.prototype); - } -} -exports.ValidationError = ValidationError; -class ReserveCacheError extends Error { - constructor(message) { - super(message); - this.name = 'ReserveCacheError'; - Object.setPrototypeOf(this, ReserveCacheError.prototype); - } -} -exports.ReserveCacheError = ReserveCacheError; -function checkPaths(paths) { - if (!paths || paths.length === 0) { - throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); - } -} -function checkKey(key) { - if (key.length > 512) { - throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); - } - const regex = /^[^,]*$/; - if (!regex.test(key)) { - throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); - } -} -/** - * Restores cache from keys - * - * @param paths a list of file paths to restore from the cache - * @param primaryKey an explicit key for restoring the cache - * @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for key - * @param downloadOptions cache download options - * @returns string returns the key for the cache hit, otherwise returns undefined - */ -function restoreCache(paths, primaryKey, restoreKeys, options) { - return __awaiter(this, void 0, void 0, function* () { - checkPaths(paths); - restoreKeys = restoreKeys || []; - const keys = [primaryKey, ...restoreKeys]; - core.debug('Resolved Keys:'); - core.debug(JSON.stringify(keys)); - if (keys.length > 10) { - throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); - } - for (const key of keys) { - checkKey(key); - } - const compressionMethod = yield utils.getCompressionMethod(); - // path are needed to compute version - const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { - compressionMethod - }); - if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { - // Cache not found - return undefined; - } - const archivePath = path.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); - core.debug(`Archive Path: ${archivePath}`); - try { - // Download the cache from the cache entry - yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); - const archiveFileSize = utils.getArchiveFileSizeIsBytes(archivePath); - core.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); - yield tar_1.extractTar(archivePath, compressionMethod); - } - finally { - // Try to delete the archive to save space - try { - yield utils.unlinkFile(archivePath); - } - catch (error) { - core.debug(`Failed to delete archive: ${error}`); - } - } - return cacheEntry.cacheKey; - }); -} -exports.restoreCache = restoreCache; -/** - * Saves a list of files with the specified key - * - * @param paths a list of file paths to be cached - * @param key an explicit key for restoring the cache - * @param options cache upload options - * @returns number returns cacheId if the cache was saved successfully and throws an error if save fails - */ -function saveCache(paths, key, options) { - return __awaiter(this, void 0, void 0, function* () { - checkPaths(paths); - checkKey(key); - const compressionMethod = yield utils.getCompressionMethod(); - core.debug('Reserving Cache'); - const cacheId = yield cacheHttpClient.reserveCache(key, paths, { - compressionMethod - }); - if (cacheId === -1) { - throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); - } - core.debug(`Cache ID: ${cacheId}`); - const cachePaths = yield utils.resolvePaths(paths); - core.debug('Cache Paths:'); - core.debug(`${JSON.stringify(cachePaths)}`); - const archiveFolder = yield utils.createTempDirectory(); - const archivePath = path.join(archiveFolder, utils.getCacheFileName(compressionMethod)); - core.debug(`Archive Path: ${archivePath}`); - yield tar_1.createTar(archiveFolder, cachePaths, compressionMethod); - const fileSizeLimit = 5 * 1024 * 1024 * 1024; // 5GB per repo limit - const archiveFileSize = utils.getArchiveFileSizeIsBytes(archivePath); - core.debug(`File Size: ${archiveFileSize}`); - if (archiveFileSize > fileSizeLimit) { - throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 5GB limit, not saving cache.`); - } - core.debug(`Saving Cache (ID: ${cacheId})`); - yield cacheHttpClient.saveCache(cacheId, archivePath, options); - return cacheId; - }); -} -exports.saveCache = saveCache; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __importStar(__webpack_require__(470)); +const path = __importStar(__webpack_require__(622)); +const utils = __importStar(__webpack_require__(15)); +const cacheHttpClient = __importStar(__webpack_require__(114)); +const tar_1 = __webpack_require__(434); +class ValidationError extends Error { + constructor(message) { + super(message); + this.name = 'ValidationError'; + Object.setPrototypeOf(this, ValidationError.prototype); + } +} +exports.ValidationError = ValidationError; +class ReserveCacheError extends Error { + constructor(message) { + super(message); + this.name = 'ReserveCacheError'; + Object.setPrototypeOf(this, ReserveCacheError.prototype); + } +} +exports.ReserveCacheError = ReserveCacheError; +function checkPaths(paths) { + if (!paths || paths.length === 0) { + throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); + } +} +function checkKey(key) { + if (key.length > 512) { + throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); + } + const regex = /^[^,]*$/; + if (!regex.test(key)) { + throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); + } +} +/** + * Restores cache from keys + * + * @param paths a list of file paths to restore from the cache + * @param primaryKey an explicit key for restoring the cache + * @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for key + * @param downloadOptions cache download options + * @returns string returns the key for the cache hit, otherwise returns undefined + */ +function restoreCache(paths, primaryKey, restoreKeys, options) { + return __awaiter(this, void 0, void 0, function* () { + checkPaths(paths); + restoreKeys = restoreKeys || []; + const keys = [primaryKey, ...restoreKeys]; + core.debug('Resolved Keys:'); + core.debug(JSON.stringify(keys)); + if (keys.length > 10) { + throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + } + for (const key of keys) { + checkKey(key); + } + const compressionMethod = yield utils.getCompressionMethod(); + // path are needed to compute version + const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { + compressionMethod + }); + if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { + // Cache not found + return undefined; + } + const archivePath = path.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + core.debug(`Archive Path: ${archivePath}`); + try { + // Download the cache from the cache entry + yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); + if (core.isDebug()) { + yield tar_1.listTar(archivePath, compressionMethod); + } + const archiveFileSize = utils.getArchiveFileSizeIsBytes(archivePath); + core.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + yield tar_1.extractTar(archivePath, compressionMethod); + core.info('Cache restored successfully'); + } + finally { + // Try to delete the archive to save space + try { + yield utils.unlinkFile(archivePath); + } + catch (error) { + core.debug(`Failed to delete archive: ${error}`); + } + } + return cacheEntry.cacheKey; + }); +} +exports.restoreCache = restoreCache; +/** + * Saves a list of files with the specified key + * + * @param paths a list of file paths to be cached + * @param key an explicit key for restoring the cache + * @param options cache upload options + * @returns number returns cacheId if the cache was saved successfully and throws an error if save fails + */ +function saveCache(paths, key, options) { + return __awaiter(this, void 0, void 0, function* () { + checkPaths(paths); + checkKey(key); + const compressionMethod = yield utils.getCompressionMethod(); + core.debug('Reserving Cache'); + const cacheId = yield cacheHttpClient.reserveCache(key, paths, { + compressionMethod + }); + if (cacheId === -1) { + throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); + } + core.debug(`Cache ID: ${cacheId}`); + const cachePaths = yield utils.resolvePaths(paths); + core.debug('Cache Paths:'); + core.debug(`${JSON.stringify(cachePaths)}`); + const archiveFolder = yield utils.createTempDirectory(); + const archivePath = path.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + core.debug(`Archive Path: ${archivePath}`); + yield tar_1.createTar(archiveFolder, cachePaths, compressionMethod); + if (core.isDebug()) { + yield tar_1.listTar(archivePath, compressionMethod); + } + const fileSizeLimit = 5 * 1024 * 1024 * 1024; // 5GB per repo limit + const archiveFileSize = utils.getArchiveFileSizeIsBytes(archivePath); + core.debug(`File Size: ${archiveFileSize}`); + if (archiveFileSize > fileSizeLimit) { + throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 5GB limit, not saving cache.`); + } + core.debug(`Saving Cache (ID: ${cacheId})`); + yield cacheHttpClient.saveCache(cacheId, archivePath, options); + return cacheId; + }); +} +exports.saveCache = saveCache; //# sourceMappingURL=cache.js.map /***/ }), @@ -46883,7 +47231,316 @@ exports.saveCache = saveCache; /***/ }), -/* 640 */, +/* 640 */ +/***/ (function(module) { + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global global, define, System, Reflect, Promise */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __spreadArray; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __createBinding; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if ( true && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + + __extends = function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __exportStar = function(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); + }; + + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + }) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + /** @deprecated */ + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + /** @deprecated */ + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __spreadArray = function (to, from) { + for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) + to[j] = from[i]; + return to; + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, privateMap) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return privateMap.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, privateMap, value) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to set private field on non-instance"); + } + privateMap.set(receiver, value); + return value; + }; + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__spreadArray", __spreadArray); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); +}); + + +/***/ }), /* 641 */, /* 642 */, /* 643 */, @@ -49855,87 +50512,7 @@ __webpack_require__(71); /***/ }), /* 713 */, /* 714 */, -/* 715 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Context = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var Context = /** @class */ (function () { - /** - * Construct a new context which inherits values from an optional parent context. - * - * @param parentContext a context from which to inherit values - */ - function Context(parentContext) { - this._currentContext = parentContext ? new Map(parentContext) : new Map(); - } - /** Get a key to uniquely identify a context value */ - Context.createKey = function (description) { - return Symbol(description); - }; - /** - * Get a value from the context. - * - * @param key key which identifies a context value - */ - Context.prototype.getValue = function (key) { - return this._currentContext.get(key); - }; - /** - * Create a new context which inherits from this context and has - * the given key set to the given value. - * - * @param key context key for which to set the value - * @param value value to set for the given key - */ - Context.prototype.setValue = function (key, value) { - var context = new Context(this._currentContext); - context._currentContext.set(key, value); - return context; - }; - /** - * Return a new context which inherits from this context but does - * not contain a value for the given key. - * - * @param key context key for which to clear a value - */ - Context.prototype.deleteValue = function (key) { - var context = new Context(this._currentContext); - context._currentContext.delete(key); - return context; - }; - /** The root context is used as the default parent context when there is no active context */ - Context.ROOT_CONTEXT = new Context(); - /** - * This is another identifier to the root context which allows developers to easily search the - * codebase for direct uses of context which need to be removed in later PRs. - * - * It's existence is temporary and it should be removed when all references are fixed. - */ - Context.TODO = Context.ROOT_CONTEXT; - return Context; -}()); -exports.Context = Context; -//# sourceMappingURL=context.js.map - -/***/ }), +/* 715 */, /* 716 */, /* 717 */, /* 718 */, @@ -50146,7 +50723,316 @@ exports.saveCache = saveCache; /***/ }), -/* 725 */, +/* 725 */ +/***/ (function(module) { + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global global, define, System, Reflect, Promise */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __spreadArray; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __createBinding; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if ( true && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + + __extends = function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __exportStar = function(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); + }; + + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + }) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + /** @deprecated */ + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + /** @deprecated */ + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __spreadArray = function (to, from) { + for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) + to[j] = from[i]; + return to; + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, privateMap) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return privateMap.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, privateMap, value) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to set private field on non-instance"); + } + privateMap.set(receiver, value); + return value; + }; + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__spreadArray", __spreadArray); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); +}); + + +/***/ }), /* 726 */, /* 727 */ /***/ (function(__unusedmodule, exports) { @@ -57197,7 +58083,7 @@ exports.TraceAPI = TraceAPI; Object.defineProperty(exports, '__esModule', { value: true }); -var tslib = __webpack_require__(422); +var tslib = __webpack_require__(725); // Copyright (c) Microsoft Corporation. /** @@ -57867,124 +58753,124 @@ exports.withCustomRequest = withCustomRequest; /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(__webpack_require__(470)); -const http_client_1 = __webpack_require__(22); -const constants_1 = __webpack_require__(931); -function isSuccessStatusCode(statusCode) { - if (!statusCode) { - return false; - } - return statusCode >= 200 && statusCode < 300; -} -exports.isSuccessStatusCode = isSuccessStatusCode; -function isServerErrorStatusCode(statusCode) { - if (!statusCode) { - return true; - } - return statusCode >= 500; -} -exports.isServerErrorStatusCode = isServerErrorStatusCode; -function isRetryableStatusCode(statusCode) { - if (!statusCode) { - return false; - } - const retryableStatusCodes = [ - http_client_1.HttpCodes.BadGateway, - http_client_1.HttpCodes.ServiceUnavailable, - http_client_1.HttpCodes.GatewayTimeout - ]; - return retryableStatusCodes.includes(statusCode); -} -exports.isRetryableStatusCode = isRetryableStatusCode; -function sleep(milliseconds) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise(resolve => setTimeout(resolve, milliseconds)); - }); -} -function retry(name, method, getStatusCode, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay, onError = undefined) { - return __awaiter(this, void 0, void 0, function* () { - let errorMessage = ''; - let attempt = 1; - while (attempt <= maxAttempts) { - let response = undefined; - let statusCode = undefined; - let isRetryable = false; - try { - response = yield method(); - } - catch (error) { - if (onError) { - response = onError(error); - } - isRetryable = true; - errorMessage = error.message; - } - if (response) { - statusCode = getStatusCode(response); - if (!isServerErrorStatusCode(statusCode)) { - return response; - } - } - if (statusCode) { - isRetryable = isRetryableStatusCode(statusCode); - errorMessage = `Cache service responded with ${statusCode}`; - } - core.debug(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`); - if (!isRetryable) { - core.debug(`${name} - Error is not retryable`); - break; - } - yield sleep(delay); - attempt++; - } - throw Error(`${name} failed: ${errorMessage}`); - }); -} -exports.retry = retry; -function retryTypedResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) { - return __awaiter(this, void 0, void 0, function* () { - return yield retry(name, method, (response) => response.statusCode, maxAttempts, delay, - // If the error object contains the statusCode property, extract it and return - // an ITypedResponse so it can be processed by the retry logic. - (error) => { - if (error instanceof http_client_1.HttpClientError) { - return { - statusCode: error.statusCode, - result: null, - headers: {} - }; - } - else { - return undefined; - } - }); - }); -} -exports.retryTypedResponse = retryTypedResponse; -function retryHttpClientResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) { - return __awaiter(this, void 0, void 0, function* () { - return yield retry(name, method, (response) => response.message.statusCode, maxAttempts, delay); - }); -} -exports.retryHttpClientResponse = retryHttpClientResponse; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __importStar(__webpack_require__(470)); +const http_client_1 = __webpack_require__(22); +const constants_1 = __webpack_require__(931); +function isSuccessStatusCode(statusCode) { + if (!statusCode) { + return false; + } + return statusCode >= 200 && statusCode < 300; +} +exports.isSuccessStatusCode = isSuccessStatusCode; +function isServerErrorStatusCode(statusCode) { + if (!statusCode) { + return true; + } + return statusCode >= 500; +} +exports.isServerErrorStatusCode = isServerErrorStatusCode; +function isRetryableStatusCode(statusCode) { + if (!statusCode) { + return false; + } + const retryableStatusCodes = [ + http_client_1.HttpCodes.BadGateway, + http_client_1.HttpCodes.ServiceUnavailable, + http_client_1.HttpCodes.GatewayTimeout + ]; + return retryableStatusCodes.includes(statusCode); +} +exports.isRetryableStatusCode = isRetryableStatusCode; +function sleep(milliseconds) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise(resolve => setTimeout(resolve, milliseconds)); + }); +} +function retry(name, method, getStatusCode, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay, onError = undefined) { + return __awaiter(this, void 0, void 0, function* () { + let errorMessage = ''; + let attempt = 1; + while (attempt <= maxAttempts) { + let response = undefined; + let statusCode = undefined; + let isRetryable = false; + try { + response = yield method(); + } + catch (error) { + if (onError) { + response = onError(error); + } + isRetryable = true; + errorMessage = error.message; + } + if (response) { + statusCode = getStatusCode(response); + if (!isServerErrorStatusCode(statusCode)) { + return response; + } + } + if (statusCode) { + isRetryable = isRetryableStatusCode(statusCode); + errorMessage = `Cache service responded with ${statusCode}`; + } + core.debug(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`); + if (!isRetryable) { + core.debug(`${name} - Error is not retryable`); + break; + } + yield sleep(delay); + attempt++; + } + throw Error(`${name} failed: ${errorMessage}`); + }); +} +exports.retry = retry; +function retryTypedResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) { + return __awaiter(this, void 0, void 0, function* () { + return yield retry(name, method, (response) => response.statusCode, maxAttempts, delay, + // If the error object contains the statusCode property, extract it and return + // an ITypedResponse so it can be processed by the retry logic. + (error) => { + if (error instanceof http_client_1.HttpClientError) { + return { + statusCode: error.statusCode, + result: null, + headers: {} + }; + } + else { + return undefined; + } + }); + }); +} +exports.retryTypedResponse = retryTypedResponse; +function retryHttpClientResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) { + return __awaiter(this, void 0, void 0, function* () { + return yield retry(name, method, (response) => response.message.statusCode, maxAttempts, delay); + }); +} +exports.retryHttpClientResponse = retryHttpClientResponse; //# sourceMappingURL=requestUtils.js.map /***/ }), @@ -58383,53 +59269,7 @@ exports.Pattern = Pattern; //# sourceMappingURL=internal-pattern.js.map /***/ }), -/* 924 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.NoopContextManager = void 0; -var context_1 = __webpack_require__(715); -var NoopContextManager = /** @class */ (function () { - function NoopContextManager() { - } - NoopContextManager.prototype.active = function () { - return context_1.Context.ROOT_CONTEXT; - }; - NoopContextManager.prototype.with = function (context, fn) { - return fn(); - }; - NoopContextManager.prototype.bind = function (target, context) { - return target; - }; - NoopContextManager.prototype.enable = function () { - return this; - }; - NoopContextManager.prototype.disable = function () { - return this; - }; - return NoopContextManager; -}()); -exports.NoopContextManager = NoopContextManager; -//# sourceMappingURL=NoopContextManager.js.map - -/***/ }), +/* 924 */, /* 925 */, /* 926 */, /* 927 */, @@ -58443,7 +59283,7 @@ Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var tslib = __webpack_require__(422); +var tslib = __webpack_require__(966); var util = _interopDefault(__webpack_require__(669)); var os = __webpack_require__(87); @@ -58739,29 +59579,29 @@ module.exports = uuid; /***/ (function(__unusedmodule, exports) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var CacheFilename; -(function (CacheFilename) { - CacheFilename["Gzip"] = "cache.tgz"; - CacheFilename["Zstd"] = "cache.tzst"; -})(CacheFilename = exports.CacheFilename || (exports.CacheFilename = {})); -var CompressionMethod; -(function (CompressionMethod) { - CompressionMethod["Gzip"] = "gzip"; - // Long range mode was added to zstd in v1.3.2. - // This enum is for earlier version of zstd that does not have --long support - CompressionMethod["ZstdWithoutLong"] = "zstd-without-long"; - CompressionMethod["Zstd"] = "zstd"; -})(CompressionMethod = exports.CompressionMethod || (exports.CompressionMethod = {})); -// The default number of retry attempts. -exports.DefaultRetryAttempts = 2; -// The default delay in milliseconds between retry attempts. -exports.DefaultRetryDelay = 5000; -// Socket timeout in milliseconds during download. If no traffic is received -// over the socket during this period, the socket is destroyed and the download -// is aborted. -exports.SocketTimeout = 5000; + +Object.defineProperty(exports, "__esModule", { value: true }); +var CacheFilename; +(function (CacheFilename) { + CacheFilename["Gzip"] = "cache.tgz"; + CacheFilename["Zstd"] = "cache.tzst"; +})(CacheFilename = exports.CacheFilename || (exports.CacheFilename = {})); +var CompressionMethod; +(function (CompressionMethod) { + CompressionMethod["Gzip"] = "gzip"; + // Long range mode was added to zstd in v1.3.2. + // This enum is for earlier version of zstd that does not have --long support + CompressionMethod["ZstdWithoutLong"] = "zstd-without-long"; + CompressionMethod["Zstd"] = "zstd"; +})(CompressionMethod = exports.CompressionMethod || (exports.CompressionMethod = {})); +// The default number of retry attempts. +exports.DefaultRetryAttempts = 2; +// The default delay in milliseconds between retry attempts. +exports.DefaultRetryDelay = 5000; +// Socket timeout in milliseconds during download. If no traffic is received +// over the socket during this period, the socket is destroyed and the download +// is aborted. +exports.SocketTimeout = 5000; //# sourceMappingURL=constants.js.map /***/ }), @@ -59108,7 +59948,316 @@ exports.checkBypass = checkBypass; /* 963 */, /* 964 */, /* 965 */, -/* 966 */, +/* 966 */ +/***/ (function(module) { + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global global, define, System, Reflect, Promise */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __spreadArray; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __createBinding; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if ( true && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + + __extends = function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __exportStar = function(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); + }; + + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + }) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + /** @deprecated */ + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + /** @deprecated */ + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __spreadArray = function (to, from) { + for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) + to[j] = from[i]; + return to; + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, privateMap) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return privateMap.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, privateMap, value) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to set private field on non-instance"); + } + privateMap.set(receiver, value); + return value; + }; + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__spreadArray", __spreadArray); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); +}); + + +/***/ }), /* 967 */, /* 968 */, /* 969 */, @@ -59603,9 +60752,9 @@ var FormData = _interopDefault(__webpack_require__(790)); var util = __webpack_require__(669); var url = __webpack_require__(835); var stream = __webpack_require__(794); +var logger$1 = __webpack_require__(928); var tunnel = __webpack_require__(413); var coreAuth = __webpack_require__(229); -var logger$1 = __webpack_require__(928); var xml2js = __webpack_require__(992); var os = __webpack_require__(87); var coreTracing = __webpack_require__(263); @@ -59620,20 +60769,20 @@ function getHeaderKey(headerName) { return headerName.toLowerCase(); } function isHttpHeadersLike(object) { - if (!object || typeof object !== "object") { - return false; - } - if (typeof object.rawHeaders === "function" && - typeof object.clone === "function" && - typeof object.get === "function" && - typeof object.set === "function" && - typeof object.contains === "function" && - typeof object.remove === "function" && - typeof object.headersArray === "function" && - typeof object.headerValues === "function" && - typeof object.headerNames === "function" && - typeof object.toJson === "function") { - return true; + if (object && typeof object === "object") { + var castObject = object; + if (typeof castObject.rawHeaders === "function" && + typeof castObject.clone === "function" && + typeof castObject.get === "function" && + typeof castObject.set === "function" && + typeof castObject.contains === "function" && + typeof castObject.remove === "function" && + typeof castObject.headersArray === "function" && + typeof castObject.headerValues === "function" && + typeof castObject.headerNames === "function" && + typeof castObject.toJson === "function") { + return true; + } } return false; } @@ -59652,8 +60801,8 @@ var HttpHeaders = /** @class */ (function () { /** * Set a header in this collection with the provided name and value. The name is * case-insensitive. - * @param headerName The name of the header to set. This value is case-insensitive. - * @param headerValue The value of the header to set. + * @param headerName - The name of the header to set. This value is case-insensitive. + * @param headerValue - The value of the header to set. */ HttpHeaders.prototype.set = function (headerName, headerValue) { this._headersMap[getHeaderKey(headerName)] = { @@ -59664,7 +60813,7 @@ var HttpHeaders = /** @class */ (function () { /** * Get the header value for the provided header name, or undefined if no header exists in this * collection with the provided name. - * @param headerName The name of the header. + * @param headerName - The name of the header. */ HttpHeaders.prototype.get = function (headerName) { var header = this._headersMap[getHeaderKey(headerName)]; @@ -59679,7 +60828,7 @@ var HttpHeaders = /** @class */ (function () { /** * Remove the header with the provided headerName. Return whether or not the header existed and * was removed. - * @param headerName The name of the header to remove. + * @param headerName - The name of the header to remove. */ HttpHeaders.prototype.remove = function (headerName) { var result = this.contains(headerName); @@ -59754,14 +60903,14 @@ var HttpHeaders = /** @class */ (function () { // Licensed under the MIT license. /** * Encodes a string in base64 format. - * @param value the string to encode + * @param value - The string to encode */ function encodeString(value) { return Buffer.from(value).toString("base64"); } /** * Encodes a byte array in base64 format. - * @param value the Uint8Aray to encode + * @param value - The Uint8Aray to encode */ function encodeByteArray(value) { // Buffer.from accepts | -- the TypeScript definition is off here @@ -59771,7 +60920,7 @@ function encodeByteArray(value) { } /** * Decodes a base64 string into a byte array. - * @param value the base64 string to decode + * @param value - The base64 string to decode */ function decodeString(value) { return Buffer.from(value, "base64"); @@ -59782,58 +60931,35 @@ function decodeString(value) { var Constants = { /** * The core-http version - * @const - * @type {string} */ - coreHttpVersion: "1.2.1", + coreHttpVersion: "1.2.3", /** * Specifies HTTP. - * - * @const - * @type {string} */ HTTP: "http:", /** * Specifies HTTPS. - * - * @const - * @type {string} */ HTTPS: "https:", /** * Specifies HTTP Proxy. - * - * @const - * @type {string} */ HTTP_PROXY: "HTTP_PROXY", /** * Specifies HTTPS Proxy. - * - * @const - * @type {string} */ HTTPS_PROXY: "HTTPS_PROXY", /** * Specifies NO Proxy. - * - * @const - * @type {string} */ NO_PROXY: "NO_PROXY", /** * Specifies ALL Proxy. - * - * @const - * @type {string} */ ALL_PROXY: "ALL_PROXY", HttpConstants: { /** * Http Verbs - * - * @const - * @enum {string} */ HttpVerbs: { PUT: "PUT", @@ -59854,9 +60980,6 @@ var Constants = { HeaderConstants: { /** * The Authorization header. - * - * @const - * @type {string} */ AUTHORIZATION: "authorization", AUTHORIZATION_SCHEME: "Bearer", @@ -59864,16 +60987,10 @@ var Constants = { * The Retry-After response-header field can be used with a 503 (Service * Unavailable) or 349 (Too Many Requests) responses to indicate how long * the service is expected to be unavailable to the requesting client. - * - * @const - * @type {string} */ RETRY_AFTER: "Retry-After", /** * The UserAgent header. - * - * @const - * @type {string} */ USER_AGENT: "User-Agent" } @@ -59902,8 +61019,8 @@ var isNode = typeof process !== "undefined" && /** * Encodes an URI. * - * @param {string} uri The URI to be encoded. - * @return {string} The encoded URI. + * @param uri - The URI to be encoded. + * @returns The encoded URI. */ function encodeUri(uri) { return encodeURIComponent(uri) @@ -59917,9 +61034,8 @@ function encodeUri(uri) { * Returns a stripped version of the Http Response which only contains body, * headers and the status. * - * @param {HttpOperationResponse} response The Http Response - * - * @return {object} The stripped version of Http Response. + * @param response - The Http Response + * @returns The stripped version of Http Response. */ function stripResponse(response) { var strippedResponse = {}; @@ -59932,9 +61048,8 @@ function stripResponse(response) { * Returns a stripped version of the Http Request that does not contain the * Authorization header. * - * @param {WebResourceLike} request The Http Request object - * - * @return {WebResourceLike} The stripped version of Http Request. + * @param request - The Http Request object + * @returns The stripped version of Http Request. */ function stripRequest(request) { var strippedRequest = request.clone(); @@ -59946,9 +61061,8 @@ function stripRequest(request) { /** * Validates the given uuid as a string * - * @param {string} uuid The uuid as a string that needs to be validated - * - * @return {boolean} True if the uuid is valid; false otherwise. + * @param uuid - The uuid as a string that needs to be validated + * @returns True if the uuid is valid; false otherwise. */ function isValidUuid(uuid) { return validUuidRegex.test(uuid); @@ -59956,7 +61070,7 @@ function isValidUuid(uuid) { /** * Generated UUID * - * @return {string} RFC4122 v4 UUID. + * @returns RFC4122 v4 UUID. */ function generateUuid() { return uuid.v4(); @@ -59965,12 +61079,10 @@ function generateUuid() { * Executes an array of promises sequentially. Inspiration of this method is here: * https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html. An awesome blog on promises! * - * @param {Array} promiseFactories An array of promise factories(A function that return a promise) - * - * @param {any} [kickstart] Input to the first promise that is used to kickstart the promise chain. + * @param promiseFactories - An array of promise factories(A function that return a promise) + * @param kickstart - Input to the first promise that is used to kickstart the promise chain. * If not provided then the promise chain starts with undefined. - * - * @return A chain of resolved or rejected promises + * @returns A chain of resolved or rejected promises */ function executePromisesSequentially(promiseFactories, kickstart) { var result = Promise.resolve(kickstart); @@ -59981,23 +61093,25 @@ function executePromisesSequentially(promiseFactories, kickstart) { } /** * A wrapper for setTimeout that resolves a promise after t milliseconds. - * @param {number} t The number of milliseconds to be delayed. - * @param {T} value The value to be resolved with after a timeout of t milliseconds. - * @returns {Promise} Resolved promise + * @param t - The number of milliseconds to be delayed. + * @param value - The value to be resolved with after a timeout of t milliseconds. + * @returns Resolved promise */ function delay(t, value) { return new Promise(function (resolve) { return setTimeout(function () { return resolve(value); }, t); }); } /** * Converts a Promise to a callback. - * @param {Promise} promise The Promise to be converted to a callback - * @returns {Function} A function that takes the callback (cb: Function): void + * @param promise - The Promise to be converted to a callback + * @returns A function that takes the callback `(cb: Function) => void` * @deprecated generated code should instead depend on responseToBody */ +// eslint-disable-next-line @typescript-eslint/ban-types function promiseToCallback(promise) { if (typeof promise.then !== "function") { throw new Error("The provided input is not a Promise."); } + // eslint-disable-next-line @typescript-eslint/ban-types return function (cb) { promise .then(function (data) { @@ -60012,8 +61126,8 @@ function promiseToCallback(promise) { } /** * Converts a Promise to a service callback. - * @param {Promise} promise - The Promise of HttpOperationResponse to be converted to a service callback - * @returns {Function} A function that takes the service callback (cb: ServiceCallback): void + * @param promise - The Promise of HttpOperationResponse to be converted to a service callback + * @returns A function that takes the service callback (cb: ServiceCallback): void */ function promiseToServiceCallback(promise) { if (typeof promise.then !== "function") { @@ -60043,31 +61157,32 @@ function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) { } /** * Applies the properties on the prototype of sourceCtors to the prototype of targetCtor - * @param {object} targetCtor The target object on which the properties need to be applied. - * @param {Array} sourceCtors An array of source objects from which the properties need to be taken. + * @param targetCtor - The target object on which the properties need to be applied. + * @param sourceCtors - An array of source objects from which the properties need to be taken. */ -function applyMixins(targetCtor, sourceCtors) { - sourceCtors.forEach(function (sourceCtors) { - Object.getOwnPropertyNames(sourceCtors.prototype).forEach(function (name) { - targetCtor.prototype[name] = sourceCtors.prototype[name]; +function applyMixins(targetCtorParam, sourceCtors) { + var castTargetCtorParam = targetCtorParam; + sourceCtors.forEach(function (sourceCtor) { + Object.getOwnPropertyNames(sourceCtor.prototype).forEach(function (name) { + castTargetCtorParam.prototype[name] = sourceCtor.prototype[name]; }); }); } var validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; /** * Indicates whether the given string is in ISO 8601 format. - * @param {string} value The value to be validated for ISO 8601 duration format. - * @return {boolean} `true` if valid, `false` otherwise. + * @param value - The value to be validated for ISO 8601 duration format. + * @returns `true` if valid, `false` otherwise. */ function isDuration(value) { return validateISODuration.test(value); } /** * Replace all of the instances of searchValue in value with the provided replaceValue. - * @param {string | undefined} value The value to search and replace in. - * @param {string} searchValue The value to search for in the value argument. - * @param {string} replaceValue The value to replace searchValue with in the value argument. - * @returns {string | undefined} The value where each instance of searchValue was replaced with replacedValue. + * @param value - The value to search and replace in. + * @param searchValue - The value to search for in the value argument. + * @param replaceValue - The value to replace searchValue with in the value argument. + * @returns The value where each instance of searchValue was replaced with replacedValue. */ function replaceAll(value, searchValue, replaceValue) { return !value || !searchValue ? value : value.split(searchValue).join(replaceValue || ""); @@ -60075,8 +61190,8 @@ function replaceAll(value, searchValue, replaceValue) { /** * Determines whether the given entity is a basic/primitive type * (string, number, boolean, null, undefined). - * @param {any} value Any entity - * @return {boolean} - true is it is primitive type, false otherwise. + * @param value - Any entity + * @returns true is it is primitive type, false otherwise. */ function isPrimitiveType(value) { return (typeof value !== "object" && typeof value !== "function") || value === null; @@ -60103,32 +61218,34 @@ var Serializer = /** @class */ (function () { throw new Error("\"" + objectName + "\" with value \"" + value + "\" should satisfy the constraint \"" + constraintName + "\": " + constraintValue + "."); }; if (mapper.constraints && value != undefined) { + var valueAsNumber = value; var _a = mapper.constraints, ExclusiveMaximum = _a.ExclusiveMaximum, ExclusiveMinimum = _a.ExclusiveMinimum, InclusiveMaximum = _a.InclusiveMaximum, InclusiveMinimum = _a.InclusiveMinimum, MaxItems = _a.MaxItems, MaxLength = _a.MaxLength, MinItems = _a.MinItems, MinLength = _a.MinLength, MultipleOf = _a.MultipleOf, Pattern = _a.Pattern, UniqueItems = _a.UniqueItems; - if (ExclusiveMaximum != undefined && value >= ExclusiveMaximum) { + if (ExclusiveMaximum != undefined && valueAsNumber >= ExclusiveMaximum) { failValidation("ExclusiveMaximum", ExclusiveMaximum); } - if (ExclusiveMinimum != undefined && value <= ExclusiveMinimum) { + if (ExclusiveMinimum != undefined && valueAsNumber <= ExclusiveMinimum) { failValidation("ExclusiveMinimum", ExclusiveMinimum); } - if (InclusiveMaximum != undefined && value > InclusiveMaximum) { + if (InclusiveMaximum != undefined && valueAsNumber > InclusiveMaximum) { failValidation("InclusiveMaximum", InclusiveMaximum); } - if (InclusiveMinimum != undefined && value < InclusiveMinimum) { + if (InclusiveMinimum != undefined && valueAsNumber < InclusiveMinimum) { failValidation("InclusiveMinimum", InclusiveMinimum); } - if (MaxItems != undefined && value.length > MaxItems) { + var valueAsArray = value; + if (MaxItems != undefined && valueAsArray.length > MaxItems) { failValidation("MaxItems", MaxItems); } - if (MaxLength != undefined && value.length > MaxLength) { + if (MaxLength != undefined && valueAsArray.length > MaxLength) { failValidation("MaxLength", MaxLength); } - if (MinItems != undefined && value.length < MinItems) { + if (MinItems != undefined && valueAsArray.length < MinItems) { failValidation("MinItems", MinItems); } - if (MinLength != undefined && value.length < MinLength) { + if (MinLength != undefined && valueAsArray.length < MinLength) { failValidation("MinLength", MinLength); } - if (MultipleOf != undefined && value % MultipleOf !== 0) { + if (MultipleOf != undefined && valueAsNumber % MultipleOf !== 0) { failValidation("MultipleOf", MultipleOf); } if (Pattern) { @@ -60138,7 +61255,7 @@ var Serializer = /** @class */ (function () { } } if (UniqueItems && - value.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) { + valueAsArray.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) { failValidation("UniqueItems", UniqueItems); } } @@ -60146,15 +61263,11 @@ var Serializer = /** @class */ (function () { /** * Serialize the given object based on its metadata defined in the mapper * - * @param {Mapper} mapper The mapper which defines the metadata of the serializable object - * - * @param {object|string|Array|number|boolean|Date|stream} object A valid Javascript object to be serialized - * - * @param {string} objectName Name of the serialized object - * - * @param {options} options additional options to deserialization - * - * @returns {object|string|Array|number|boolean|Date|stream} A valid serialized Javascript object + * @param mapper - The mapper which defines the metadata of the serializable object + * @param object - A valid Javascript object to be serialized + * @param objectName - Name of the serialized object + * @param options - additional options to deserialization + * @returns A valid serialized Javascript object */ Serializer.prototype.serialize = function (mapper, object, objectName, options) { var _a, _b, _c; @@ -60234,15 +61347,11 @@ var Serializer = /** @class */ (function () { /** * Deserialize the given object based on its metadata defined in the mapper * - * @param {object} mapper The mapper which defines the metadata of the serializable object - * - * @param {object|string|Array|number|boolean|Date|stream} responseBody A valid Javascript entity to be deserialized - * - * @param {string} objectName Name of the deserialized object - * - * @param options Controls behavior of XML parser and builder. - * - * @returns {object|string|Array|number|boolean|Date|stream} A valid deserialized Javascript object + * @param mapper - The mapper which defines the metadata of the serializable object + * @param responseBody - A valid Javascript entity to be deserialized + * @param objectName - Name of the deserialized object + * @param options - Controls behavior of XML parser and builder. + * @returns A valid deserialized Javascript object */ Serializer.prototype.deserialize = function (mapper, responseBody, objectName, options) { var _a, _b, _c; @@ -60276,13 +61385,15 @@ var Serializer = /** @class */ (function () { else { if (this.isXML) { var xmlCharKey = updatedOptions.xmlCharKey; + var castResponseBody = responseBody; /** * If the mapper specifies this as a non-composite type value but the responseBody contains * both header ("$" i.e., XML_ATTRKEY) and body ("#" i.e., XML_CHARKEY) properties, * then just reduce the responseBody value to the body ("#" i.e., XML_CHARKEY) property. */ - if (responseBody[XML_ATTRKEY] != undefined && responseBody[xmlCharKey] != undefined) { - responseBody = responseBody[xmlCharKey]; + if (castResponseBody[XML_ATTRKEY] != undefined && + castResponseBody[xmlCharKey] != undefined) { + responseBody = castResponseBody[xmlCharKey]; } } if (mapperType.match(/^Number$/i) !== null) { @@ -60571,9 +61682,9 @@ function serializeDictionaryType(serializer, mapper, object, objectName, isXml, } /** * Resolves the additionalProperties property from a referenced mapper - * @param serializer the serializer containing the entire set of mappers - * @param mapper the composite mapper to resolve - * @param objectName name of the object being serialized + * @param serializer - The serializer containing the entire set of mappers + * @param mapper - The composite mapper to resolve + * @param objectName - Name of the object being serialized */ function resolveAdditionalProperties(serializer, mapper, objectName) { var additionalProperties = mapper.type.additionalProperties; @@ -60585,9 +61696,9 @@ function resolveAdditionalProperties(serializer, mapper, objectName) { } /** * Finds the mapper referenced by className - * @param serializer the serializer containing the entire set of mappers - * @param mapper the composite mapper to resolve - * @param objectName name of the object being serialized + * @param serializer - The serializer containing the entire set of mappers + * @param mapper - The composite mapper to resolve + * @param objectName - Name of the object being serialized */ function resolveReferencedMapper(serializer, mapper, objectName) { var className = mapper.type.className; @@ -60598,8 +61709,8 @@ function resolveReferencedMapper(serializer, mapper, objectName) { } /** * Resolves a composite mapper's modelProperties. - * @param serializer the serializer containing the entire set of mappers - * @param mapper the composite mapper to resolve + * @param serializer - The serializer containing the entire set of mappers + * @param mapper - The composite mapper to resolve */ function resolveModelProperties(serializer, mapper, objectName) { var modelProps = mapper.type.modelProperties; @@ -60929,6 +62040,7 @@ function getPolymorphicDiscriminatorSafely(serializer, typeName) { } // TODO: why is this here? function serializeObject(toSerialize) { + var castToSerialize = toSerialize; if (toSerialize == undefined) return undefined; if (toSerialize instanceof Uint8Array) { @@ -60948,7 +62060,7 @@ function serializeObject(toSerialize) { else if (typeof toSerialize === "object") { var dictionary = {}; for (var property in toSerialize) { - dictionary[property] = serializeObject(toSerialize[property]); + dictionary[property] = serializeObject(castToSerialize[property]); } return dictionary; } @@ -60965,6 +62077,7 @@ function strEnum(o) { } return result; } +// eslint-disable-next-line @typescript-eslint/no-redeclare var MapperType = strEnum([ "Base64Url", "Boolean", @@ -60986,17 +62099,17 @@ var MapperType = strEnum([ // Copyright (c) Microsoft Corporation. function isWebResourceLike(object) { - if (typeof object !== "object") { - return false; - } - if (typeof object.url === "string" && - typeof object.method === "string" && - typeof object.headers === "object" && - isHttpHeadersLike(object.headers) && - typeof object.validateRequestProperties === "function" && - typeof object.prepare === "function" && - typeof object.clone === "function") { - return true; + if (object && typeof object === "object") { + var castObject = object; + if (typeof castObject.url === "string" && + typeof castObject.method === "string" && + typeof castObject.headers === "object" && + isHttpHeadersLike(castObject.headers) && + typeof castObject.validateRequestProperties === "function" && + typeof castObject.prepare === "function" && + typeof castObject.clone === "function") { + return true; + } } return false; } @@ -61005,12 +62118,11 @@ function isWebResourceLike(object) { * * This class provides an abstraction over a REST call by being library / implementation agnostic and wrapping the necessary * properties to initiate a request. - * - * @constructor */ var WebResource = /** @class */ (function () { - function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, decompressResponse) { + function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, decompressResponse, streamResponseStatusCodes) { this.streamResponseBody = streamResponseBody; + this.streamResponseStatusCodes = streamResponseStatusCodes; this.url = url || ""; this.method = method || "GET"; this.headers = isHttpHeadersLike(headers) ? headers : new HttpHeaders(headers); @@ -61042,8 +62154,8 @@ var WebResource = /** @class */ (function () { }; /** * Prepares the request. - * @param {RequestPrepareOptions} options Options to provide for preparing the request. - * @returns {WebResource} Returns the prepared WebResource (HTTP Request) object that needs to be given to the request pipeline. + * @param options - Options to provide for preparing the request. + * @returns Returns the prepared WebResource (HTTP Request) object that needs to be given to the request pipeline. */ WebResource.prototype.prepare = function (options) { if (!options) { @@ -61223,10 +62335,10 @@ var WebResource = /** @class */ (function () { }; /** * Clone this WebResource HTTP request object. - * @returns {WebResource} The clone of this WebResource HTTP request object. + * @returns The clone of this WebResource HTTP request object. */ WebResource.prototype.clone = function () { - var result = new WebResource(this.url, this.method, this.body, this.query, this.headers && this.headers.clone(), this.streamResponseBody, this.withCredentials, this.abortSignal, this.timeout, this.onUploadProgress, this.onDownloadProgress, this.proxySettings, this.keepAlive, this.decompressResponse); + var result = new WebResource(this.url, this.method, this.body, this.query, this.headers && this.headers.clone(), this.streamResponseBody, this.withCredentials, this.abortSignal, this.timeout, this.onUploadProgress, this.onDownloadProgress, this.proxySettings, this.keepAlive, this.decompressResponse, this.streamResponseStatusCodes); if (this.formData) { result.formData = this.formData; } @@ -61273,9 +62385,12 @@ var URLQuery = /** @class */ (function () { * parameterName. */ URLQuery.prototype.set = function (parameterName, parameterValue) { + var caseParameterValue = parameterValue; if (parameterName) { - if (parameterValue !== undefined && parameterValue !== null) { - var newValue = Array.isArray(parameterValue) ? parameterValue : parameterValue.toString(); + if (caseParameterValue !== undefined && caseParameterValue !== null) { + var newValue = Array.isArray(caseParameterValue) + ? caseParameterValue + : caseParameterValue.toString(); this._rawQuery[parameterName] = newValue; } else { @@ -61852,6 +62967,7 @@ var defaultAllowedHeaderNames = [ "x-ms-correlation-request-id", "x-ms-request-id", "client-request-id", + "ms-cv", "return-client-request-id", "traceparent", "Access-Control-Allow-Credentials", @@ -61997,6 +63113,9 @@ var RestError = /** @class */ (function (_super) { return RestError; }(Error)); +// Copyright (c) Microsoft Corporation. +var logger = logger$1.createClientLogger("core-http"); + // Copyright (c) Microsoft Corporation. var ReportTransform = /** @class */ (function (_super) { tslib.__extends(ReportTransform, _super); @@ -62018,10 +63137,12 @@ var FetchHttpClient = /** @class */ (function () { function FetchHttpClient() { } FetchHttpClient.prototype.sendRequest = function (httpRequest) { + var _a; return tslib.__awaiter(this, void 0, void 0, function () { - var abortController$1, abortListener, formData, requestForm_1, appendFormValue, _i, _a, formKey, formValue, j, contentType, body, onUploadProgress, uploadReportStream, platformSpecificRequestInit, requestInit, response, headers, operationResponse, _b, _c, onDownloadProgress, responseBody, downloadReportStream, length_1, error_1, fetchError; - return tslib.__generator(this, function (_d) { - switch (_d.label) { + var abortController$1, abortListener, formData, requestForm_1, appendFormValue, _i, _b, formKey, formValue, j, contentType, body, onUploadProgress, uploadReportStream, platformSpecificRequestInit, requestInit, operationResponse, response, headers, streaming, _c, onDownloadProgress, responseBody, downloadReportStream, length_1, error_1, fetchError, uploadStreamDone, downloadStreamDone; + var _d; + return tslib.__generator(this, function (_e) { + switch (_e.label) { case 0: if (!httpRequest && typeof httpRequest !== "object") { throw new Error("'httpRequest' (WebResourceLike) cannot be null or undefined and must be of type object."); @@ -62060,8 +63181,8 @@ var FetchHttpClient = /** @class */ (function () { requestForm_1.append(key, value); } }; - for (_i = 0, _a = Object.keys(formData); _i < _a.length; _i++) { - formKey = _a[_i]; + for (_i = 0, _b = Object.keys(formData); _i < _b.length; _i++) { + formKey = _b[_i]; formValue = formData[formKey]; if (Array.isArray(formValue)) { for (j = 0; j < formValue.length; j++) { @@ -62103,34 +63224,36 @@ var FetchHttpClient = /** @class */ (function () { } return [4 /*yield*/, this.prepareRequest(httpRequest)]; case 1: - platformSpecificRequestInit = _d.sent(); + platformSpecificRequestInit = _e.sent(); requestInit = tslib.__assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, signal: abortController$1.signal, redirect: "manual" }, platformSpecificRequestInit); - _d.label = 2; + _e.label = 2; case 2: - _d.trys.push([2, 8, 9, 10]); + _e.trys.push([2, 8, 9, 10]); return [4 /*yield*/, this.fetch(httpRequest.url, requestInit)]; case 3: - response = _d.sent(); + response = _e.sent(); headers = parseHeaders(response.headers); - _b = { + streaming = ((_a = httpRequest.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(response.status)) || + httpRequest.streamResponseBody; + _d = { headers: headers, request: httpRequest, status: response.status, - readableStreamBody: httpRequest.streamResponseBody + readableStreamBody: streaming ? response.body : undefined }; - if (!!httpRequest.streamResponseBody) return [3 /*break*/, 5]; + if (!!streaming) return [3 /*break*/, 5]; return [4 /*yield*/, response.text()]; case 4: - _c = _d.sent(); + _c = _e.sent(); return [3 /*break*/, 6]; case 5: _c = undefined; - _d.label = 6; + _e.label = 6; case 6: - operationResponse = (_b.bodyAsText = _c, - _b); + operationResponse = (_d.bodyAsText = _c, + _d); onDownloadProgress = httpRequest.onDownloadProgress; if (onDownloadProgress) { responseBody = response.body || undefined; @@ -62149,10 +63272,10 @@ var FetchHttpClient = /** @class */ (function () { } return [4 /*yield*/, this.processRequest(operationResponse)]; case 7: - _d.sent(); + _e.sent(); return [2 /*return*/, operationResponse]; case 8: - error_1 = _d.sent(); + error_1 = _e.sent(); fetchError = error_1; if (fetchError.code === "ENOTFOUND") { throw new RestError(fetchError.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest); @@ -62164,7 +63287,23 @@ var FetchHttpClient = /** @class */ (function () { case 9: // clean up event listener if (httpRequest.abortSignal && abortListener) { - httpRequest.abortSignal.removeEventListener("abort", abortListener); + uploadStreamDone = Promise.resolve(); + if (isReadableStream(body)) { + uploadStreamDone = isStreamComplete(body); + } + downloadStreamDone = Promise.resolve(); + if (isReadableStream(operationResponse === null || operationResponse === void 0 ? void 0 : operationResponse.readableStreamBody)) { + downloadStreamDone = isStreamComplete(operationResponse.readableStreamBody); + } + Promise.all([uploadStreamDone, downloadStreamDone]) + .then(function () { + var _a; + (_a = httpRequest.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener); + return; + }) + .catch(function (e) { + logger.warning("Error when cleaning up abortListener on httpRequest", e); + }); } return [7 /*endfinally*/]; case 10: return [2 /*return*/]; @@ -62177,6 +63316,13 @@ var FetchHttpClient = /** @class */ (function () { function isReadableStream(body) { return body && typeof body.pipe === "function"; } +function isStreamComplete(stream) { + return new Promise(function (resolve) { + stream.on("close", resolve); + stream.on("end", resolve); + stream.on("error", resolve); + }); +} function parseHeaders(headers) { var httpHeaders = new HttpHeaders(); headers.forEach(function (value, key) { @@ -62383,7 +63529,7 @@ var NodeFetchHttpClient = /** @class */ (function (_super) { /** * Converts an OperationOptions to a RequestOptionsBase * - * @param opts OperationOptions object to convert to RequestOptionsBase + * @param opts - OperationOptions object to convert to RequestOptionsBase */ function operationOptionsToRequestOptionsBase(opts) { var requestOptions = opts.requestOptions, tracingOptions = opts.tracingOptions, additionalOptions = tslib.__rest(opts, ["requestOptions", "tracingOptions"]); @@ -62405,7 +63551,7 @@ var BaseRequestPolicy = /** @class */ (function () { } /** * Get whether or not a log with the provided log level should be logged. - * @param logLevel The log level of the log that will be logged. + * @param logLevel - The log level of the log that will be logged. * @returns Whether or not a log with the provided log level should be logged. */ BaseRequestPolicy.prototype.shouldLog = function (logLevel) { @@ -62414,8 +63560,8 @@ var BaseRequestPolicy = /** @class */ (function () { /** * Attempt to log the provided message to the provided logger. If no logger was provided or if * the log level does not meat the logger's threshold, then nothing will be logged. - * @param logLevel The log level of this log. - * @param message The message of this log. + * @param logLevel - The log level of this log. + * @param message - The message of this log. */ BaseRequestPolicy.prototype.log = function (logLevel, message) { this._options.log(logLevel, message); @@ -62431,7 +63577,7 @@ var RequestPolicyOptions = /** @class */ (function () { } /** * Get whether or not a log with the provided log level should be logged. - * @param logLevel The log level of the log that will be logged. + * @param logLevel - The log level of the log that will be logged. * @returns Whether or not a log with the provided log level should be logged. */ RequestPolicyOptions.prototype.shouldLog = function (logLevel) { @@ -62442,8 +63588,8 @@ var RequestPolicyOptions = /** @class */ (function () { /** * Attempt to log the provided message to the provided logger. If no logger was provided or if * the log level does not meet the logger's threshold, then nothing will be logged. - * @param logLevel The log level of this log. - * @param message The message of this log. + * @param logLevel - The log level of this log. + * @param message - The message of this log. */ RequestPolicyOptions.prototype.log = function (logLevel, message) { if (this._logger && this.shouldLog(logLevel)) { @@ -62453,9 +63599,6 @@ var RequestPolicyOptions = /** @class */ (function () { return RequestPolicyOptions; }()); -// Copyright (c) Microsoft Corporation. -var logger = logger$1.createClientLogger("core-http"); - // Copyright (c) Microsoft Corporation. function logPolicy(loggingOptions) { if (loggingOptions === void 0) { loggingOptions = {}; } @@ -62540,7 +63683,7 @@ var LogPolicy = /** @class */ (function (_super) { // Licensed under the MIT license. /** * Get the path to this parameter's value as a dotted string (a.b.c). - * @param parameter The parameter to get the path string for. + * @param parameter - The parameter to get the path string for. * @returns The path to this parameter's value as a dotted string. */ function getPathStringFromParameter(parameter) { @@ -62561,14 +63704,17 @@ function getPathStringFromParameterPath(parameterPath, mapper) { } // Copyright (c) Microsoft Corporation. -function isStreamOperation(operationSpec) { - var result = false; +/** + * Gets the list of status codes for streaming responses. + * @internal @hidden + */ +function getStreamResponseStatusCodes(operationSpec) { + var result = new Set(); for (var statusCode in operationSpec.responses) { var operationResponse = operationSpec.responses[statusCode]; if (operationResponse.bodyMapper && operationResponse.bodyMapper.type.name === MapperType.Stream) { - result = true; - break; + result.add(Number(statusCode)); } } return result; @@ -62630,9 +63776,8 @@ xml2jsBuilderSettings.renderOpts = { }; /** * Converts given JSON object to XML string - * @param obj JSON object to be converted into XML string - * @param opts Options that govern the parsing of given JSON object - * `rootName` indicates the name of the root element in the resulting XML + * @param obj - JSON object to be converted into XML string + * @param opts - Options that govern the parsing of given JSON object */ function stringifyXML(obj, opts) { var _a; @@ -62644,9 +63789,8 @@ function stringifyXML(obj, opts) { } /** * Converts given XML string into JSON - * @param str String containing the XML content to be parsed into JSON - * @param opts Options that govern the parsing of given xml string - * `includeRoot` indicates whether the root element is to be included or not in the output + * @param str - String containing the XML content to be parsed into JSON + * @param opts - Options that govern the parsing of given xml string */ function parseXML(str, opts) { var _a; @@ -62789,8 +63933,8 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, op try { parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options); } - catch (error) { - var restError = new RestError("Error " + error + " occurred in deserializing the responseBody - " + parsedResponse.bodyAsText, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); + catch (innerError) { + var restError = new RestError("Error " + innerError + " occurred in deserializing the responseBody - " + parsedResponse.bodyAsText, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); throw restError; } } @@ -62811,6 +63955,7 @@ function isOperationSpecEmpty(operationSpec) { (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default")); } function handleErrorResponse(parsedResponse, operationSpec, responseSpec) { + var _a; var isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300; var isExpectedStatusCode = isOperationSpecEmpty(operationSpec) ? isSuccessByStatus @@ -62826,7 +63971,9 @@ function handleErrorResponse(parsedResponse, operationSpec, responseSpec) { } } var errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default; - var initialErrorMessage = isStreamOperation(operationSpec) + var streaming = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status)) || + parsedResponse.request.streamResponseBody; + var initialErrorMessage = streaming ? "Unexpected status code: " + parsedResponse.status : parsedResponse.bodyAsText; var error = new RestError(initialErrorMessage, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); @@ -62871,13 +64018,16 @@ function handleErrorResponse(parsedResponse, operationSpec, responseSpec) { return { error: error, shouldReturnResponse: false }; } function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts) { + var _a; var errorHandler = function (err) { var msg = "Error \"" + err + "\" occurred while parsing the response body - " + operationResponse.bodyAsText + "."; var errCode = err.code || RestError.PARSE_ERROR; var e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse); return Promise.reject(e); }; - if (!operationResponse.request.streamResponseBody && operationResponse.bodyAsText) { + var streaming = ((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) || + operationResponse.request.streamResponseBody; + if (!streaming && operationResponse.bodyAsText) { var text_1 = operationResponse.bodyAsText; var contentType = operationResponse.headers.get("Content-Type") || ""; var contentComponents = !contentType @@ -62916,10 +64066,10 @@ function isNumber(n) { * @internal * Determines if the operation should be retried. * - * @param {number} retryLimit Specifies the max number of retries. - * @param {(response?: HttpOperationResponse, error?: RetryError) => boolean} predicate Initial chekck on whether to retry based on given responses or errors - * @param {RetryData} retryData The retry data. - * @return {boolean} True if the operation qualifies for a retry; false otherwise. + * @param retryLimit - Specifies the max number of retries. + * @param predicate - Initial chekck on whether to retry based on given responses or errors + * @param retryData - The retry data. + * @returns True if the operation qualifies for a retry; false otherwise. */ function shouldRetry(retryLimit, predicate, retryData, response, error) { if (!predicate(response, error)) { @@ -62931,9 +64081,9 @@ function shouldRetry(retryLimit, predicate, retryData, response, error) { * @internal * Updates the retry data for the next attempt. * - * @param {RetryPolicyOptions} retryOptions specifies retry interval, and its lower bound and upper bound. - * @param {RetryData} [retryData] The retry data. - * @param {RetryError} [err] The operation"s error, if any. + * @param retryOptions - specifies retry interval, and its lower bound and upper bound. + * @param retryData - The retry data. + * @param err - The operation"s error, if any. */ function updateRetryData(retryOptions, retryData, err) { if (retryData === void 0) { retryData = { retryCount: 0, retryInterval: 0 }; } @@ -62971,19 +64121,17 @@ var DefaultRetryOptions = { maxRetryDelayInMs: DEFAULT_CLIENT_MAX_RETRY_INTERVAL }; /** - * @class * Instantiates a new "ExponentialRetryPolicyFilter" instance. */ var ExponentialRetryPolicy = /** @class */ (function (_super) { tslib.__extends(ExponentialRetryPolicy, _super); /** - * @constructor - * @param {RequestPolicy} nextPolicy The next RequestPolicy in the pipeline chain. - * @param {RequestPolicyOptions} options The options for this RequestPolicy. - * @param {number} [retryCount] The client retry count. - * @param {number} [retryInterval] The client retry interval, in milliseconds. - * @param {number} [minRetryInterval] The minimum retry interval, in milliseconds. - * @param {number} [maxRetryInterval] The maximum retry interval, in milliseconds. + * @param nextPolicy - The next RequestPolicy in the pipeline chain. + * @param options - The options for this RequestPolicy. + * @param retryCount - The client retry count. + * @param retryInterval - The client retry interval, in milliseconds. + * @param minRetryInterval - The minimum retry interval, in milliseconds. + * @param maxRetryInterval - The maximum retry interval, in milliseconds. */ function ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, maxRetryInterval) { var _this = _super.call(this, nextPolicy, options) || this; @@ -63005,8 +64153,8 @@ var ExponentialRetryPolicy = /** @class */ (function (_super) { }(BaseRequestPolicy)); function retry(policy, request, response, retryData, requestError) { return tslib.__awaiter(this, void 0, void 0, function () { - function shouldPolicyRetry(response) { - var statusCode = response === null || response === void 0 ? void 0 : response.status; + function shouldPolicyRetry(responseParam) { + var statusCode = responseParam === null || responseParam === void 0 ? void 0 : responseParam.status; if (statusCode === undefined || (statusCode < 500 && statusCode !== 408) || statusCode === 501 || @@ -63269,9 +64417,9 @@ function registerIfNeeded(policy, request, response) { } /** * Reuses the headers of the original request and url (if specified). - * @param {WebResourceLike} originalRequest The original request - * @param {boolean} reuseUrlToo Should the url from the original request be reused as well. Default false. - * @returns {object} A new request object with desired headers. + * @param originalRequest - The original request + * @param reuseUrlToo - Should the url from the original request be reused as well. Default false. + * @returns A new request object with desired headers. */ function getRequestEssentials(originalRequest, reuseUrlToo) { if (reuseUrlToo === void 0) { reuseUrlToo = false; } @@ -63289,8 +64437,8 @@ function getRequestEssentials(originalRequest, reuseUrlToo) { /** * Validates the error code and message associated with 409 response status code. If it matches to that of * RP not registered then it returns the name of the RP else returns undefined. - * @param {string} body The response body received after making the original request. - * @returns {string} The name of the RP if condition is satisfied else undefined. + * @param body - The response body received after making the original request. + * @returns The name of the RP if condition is satisfied else undefined. */ function checkRPNotRegisteredError(body) { var result, responseBody; @@ -63317,8 +64465,8 @@ function checkRPNotRegisteredError(body) { /** * Extracts the first part of the URL, just after subscription: * https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ - * @param {string} url The original request url - * @returns {string} The url prefix as explained above. + * @param url - The original request url + * @returns The url prefix as explained above. */ function extractSubscriptionUrl(url) { var result; @@ -63333,12 +64481,12 @@ function extractSubscriptionUrl(url) { } /** * Registers the given provider. - * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against. - * @param {string} urlPrefix https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ - * @param {string} provider The provider name to be registered. - * @param {WebResourceLike} originalRequest The original request sent by the user that returned a 409 response + * @param policy - The RPRegistrationPolicy this function is being called against. + * @param urlPrefix - https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ + * @param provider - The provider name to be registered. + * @param originalRequest - The original request sent by the user that returned a 409 response * with a message that the provider is not registered. - * @param {registrationCallback} callback The callback that handles the RP registration + * @param callback - The callback that handles the RP registration */ function registerRP(policy, urlPrefix, provider, originalRequest) { var postUrl = urlPrefix + "providers/" + provider + "/register?api-version=2016-02-01"; @@ -63356,11 +64504,11 @@ function registerRP(policy, urlPrefix, provider, originalRequest) { /** * Polls the registration status of the provider that was registered. Polling happens at an interval of 30 seconds. * Polling will happen till the registrationState property of the response body is "Registered". - * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against. - * @param {string} url The request url for polling - * @param {WebResourceLike} originalRequest The original request sent by the user that returned a 409 response + * @param policy - The RPRegistrationPolicy this function is being called against. + * @param url - The request url for polling + * @param originalRequest - The original request sent by the user that returned a 409 response * with a message that the provider is not registered. - * @returns {Promise} True if RP Registration is successful. + * @returns True if RP Registration is successful. */ function getRegistrationStatus(policy, url, originalRequest) { var reqOptions = getRequestEssentials(originalRequest); @@ -63427,8 +64575,6 @@ var AccessTokenRefresher = /** @class */ (function () { /** * Returns true if the required milliseconds(defaulted to 30000) have been passed signifying * that we are ready for a new refresh. - * - * @returns {boolean} */ AccessTokenRefresher.prototype.isReady = function () { // We're only ready for a new refresh if the required milliseconds have passed. @@ -63439,7 +64585,6 @@ var AccessTokenRefresher = /** @class */ (function () { * then requests a new token, * then sets this.promise to undefined, * then returns the token. - * @param options getToken options */ AccessTokenRefresher.prototype.getToken = function (options) { return tslib.__awaiter(this, void 0, void 0, function () { @@ -63460,7 +64605,6 @@ var AccessTokenRefresher = /** @class */ (function () { /** * Requests a new token if we're not currently waiting for a new token. * Returns null if the required time between each call hasn't been reached. - * @param options getToken options */ AccessTokenRefresher.prototype.refresh = function (options) { if (!this.promise) { @@ -63481,8 +64625,8 @@ var timeBetweenRefreshAttemptsInMs = 30000; /** * Creates a new BearerTokenAuthenticationPolicy factory. * - * @param credential The TokenCredential implementation that can supply the bearer token. - * @param scopes The scopes for which the bearer token applies. + * @param credential - The TokenCredential implementation that can supply the bearer token. + * @param scopes - The scopes for which the bearer token applies. */ function bearerTokenAuthenticationPolicy(credential, scopes) { var tokenCache = new ExpiringAccessTokenCache(); @@ -63505,11 +64649,11 @@ var BearerTokenAuthenticationPolicy = /** @class */ (function (_super) { /** * Creates a new BearerTokenAuthenticationPolicy object. * - * @param nextPolicy The next RequestPolicy in the request pipeline. - * @param options Options for this RequestPolicy. - * @param credential The TokenCredential implementation that can supply the bearer token. - * @param scopes The scopes for which the bearer token applies. - * @param tokenCache The cache for the most recent AccessToken returned from the TokenCredential. + * @param nextPolicy - The next RequestPolicy in the request pipeline. + * @param options - Options for this RequestPolicy. + * @param credential - The TokenCredential implementation that can supply the bearer token. + * @param scopes - The scopes for which the bearer token applies. + * @param tokenCache - The cache for the most recent AccessToken returned from the TokenCredential. */ function BearerTokenAuthenticationPolicy(nextPolicy, options, tokenCache, tokenRefresher) { var _this = _super.call(this, nextPolicy, options) || this; @@ -63519,7 +64663,6 @@ var BearerTokenAuthenticationPolicy = /** @class */ (function (_super) { } /** * Applies the Bearer token to the request through the Authorization header. - * @param webResource */ BearerTokenAuthenticationPolicy.prototype.sendRequest = function (webResource) { return tslib.__awaiter(this, void 0, void 0, function () { @@ -63601,14 +64744,10 @@ function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, max }; } /** - * @class - * Instantiates a new "ExponentialRetryPolicyFilter" instance. - * - * @constructor - * @param {number} retryCount The client retry count. - * @param {number} retryInterval The client retry interval, in milliseconds. - * @param {number} minRetryInterval The minimum retry interval, in milliseconds. - * @param {number} maxRetryInterval The maximum retry interval, in milliseconds. + * @param retryCount - The client retry count. + * @param retryInterval - The client retry interval, in milliseconds. + * @param minRetryInterval - The minimum retry interval, in milliseconds. + * @param maxRetryInterval - The maximum retry interval, in milliseconds. */ var SystemErrorRetryPolicy = /** @class */ (function (_super) { tslib.__extends(SystemErrorRetryPolicy, _super); @@ -63646,7 +64785,7 @@ function retry$1(policy, request, operationResponse, err, retryData) { } return false; } - var err_1; + var nestedErr_1; return tslib.__generator(this, function (_a) { switch (_a.label) { case 0: @@ -63660,8 +64799,8 @@ function retry$1(policy, request, operationResponse, err, retryData) { _a.sent(); return [2 /*return*/, policy._nextPolicy.sendRequest(request.clone())]; case 3: - err_1 = _a.sent(); - return [2 /*return*/, retry$1(policy, request, operationResponse, err_1, retryData)]; + nestedErr_1 = _a.sent(); + return [2 /*return*/, retry$1(policy, request, operationResponse, nestedErr_1, retryData)]; case 4: return [3 /*break*/, 6]; case 5: if (err) { @@ -63685,8 +64824,10 @@ function retry$1(policy, request, operationResponse, err, retryData) { })(exports.QueryCollectionFormat || (exports.QueryCollectionFormat = {})); // Copyright (c) Microsoft Corporation. -var noProxyList = []; -var isNoProxyInitalized = false; +/** + * @internal + */ +var noProxyList = loadNoProxy(); var byPassedList = new Map(); function loadEnvironmentProxyValue() { if (!process) { @@ -63697,45 +64838,53 @@ function loadEnvironmentProxyValue() { var httpProxy = getEnvironmentValue(Constants.HTTP_PROXY); return httpsProxy || allProxy || httpProxy; } -// Check whether the given `uri` matches the noProxyList. If it matches, any request sent to that same `uri` won't set the proxy settings. +// Check whether the host of a given `uri` is in the noProxyList. +// If there's a match, any request sent to the same host won't have the proxy settings set. +// This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210 function isBypassed(uri) { - if (byPassedList.has(uri)) { - return byPassedList.get(uri); + if (noProxyList.length === 0) { + return false; } - loadNoProxy(); - var isBypassed = false; var host = URLBuilder.parse(uri).getHost(); + if (byPassedList.has(host)) { + return byPassedList.get(host); + } + var isBypassedFlag = false; for (var _i = 0, noProxyList_1 = noProxyList; _i < noProxyList_1.length; _i++) { - var proxyString = noProxyList_1[_i]; - if (proxyString[0] === ".") { - if (uri.endsWith(proxyString)) { - isBypassed = true; + var pattern = noProxyList_1[_i]; + if (pattern[0] === ".") { + // This should match either domain it self or any subdomain or host + // .foo.com will match foo.com it self or *.foo.com + if (host.endsWith(pattern)) { + isBypassedFlag = true; } else { - if (host === proxyString.slice(1) && host.length === proxyString.length - 1) { - isBypassed = true; + if (host.length === pattern.length - 1 && host === pattern.slice(1)) { + isBypassedFlag = true; } } } else { - if (host === proxyString) { - isBypassed = true; + if (host === pattern) { + isBypassedFlag = true; } } } - byPassedList.set(uri, isBypassed); - return isBypassed; + byPassedList.set(host, isBypassedFlag); + return isBypassedFlag; } +/** + * @internal + */ function loadNoProxy() { - if (isNoProxyInitalized) { - return; - } var noProxy = getEnvironmentValue(Constants.NO_PROXY); if (noProxy) { - var list = noProxy.split(","); - noProxyList = list.map(function (item) { return item.trim(); }).filter(function (item) { return item.length; }); + return noProxy + .split(",") + .map(function (item) { return item.trim(); }) + .filter(function (item) { return item.length; }); } - isNoProxyInitalized = true; + return []; } function getDefaultProxySettings(proxyUrl) { if (!proxyUrl) { @@ -63921,9 +65070,9 @@ var KeepAlivePolicy = /** @class */ (function (_super) { /** * Creates an instance of KeepAlivePolicy. * - * @param {RequestPolicy} nextPolicy - * @param {RequestPolicyOptions} options - * @param {KeepAliveOptions} [keepAliveOptions] + * @param nextPolicy - + * @param options - + * @param keepAliveOptions - */ function KeepAlivePolicy(nextPolicy, options, keepAliveOptions) { var _this = _super.call(this, nextPolicy, options) || this; @@ -63933,9 +65082,8 @@ var KeepAlivePolicy = /** @class */ (function (_super) { /** * Sends out request. * - * @param {WebResourceLike} request - * @returns {Promise} - * @memberof KeepAlivePolicy + * @param request - + * @returns */ KeepAlivePolicy.prototype.sendRequest = function (request) { return tslib.__awaiter(this, void 0, void 0, function () { @@ -64041,8 +65189,8 @@ var DisableResponseDecompressionPolicy = /** @class */ (function (_super) { /** * Creates an instance of DisableResponseDecompressionPolicy. * - * @param {RequestPolicy} nextPolicy - * @param {RequestPolicyOptions} options + * @param nextPolicy - + * @param options - */ // The parent constructor is protected. /* eslint-disable-next-line @typescript-eslint/no-useless-constructor */ @@ -64052,8 +65200,8 @@ var DisableResponseDecompressionPolicy = /** @class */ (function (_super) { /** * Sends out request. * - * @param {WebResource} request - * @returns {Promise} + * @param request - + * @returns */ DisableResponseDecompressionPolicy.prototype.sendRequest = function (request) { return tslib.__awaiter(this, void 0, void 0, function () { @@ -64081,17 +65229,12 @@ var NdJsonPolicy = /** @class */ (function (_super) { tslib.__extends(NdJsonPolicy, _super); /** * Creates an instance of KeepAlivePolicy. - * - * @param nextPolicy - * @param options */ function NdJsonPolicy(nextPolicy, options) { return _super.call(this, nextPolicy, options) || this; } /** * Sends a request. - * - * @param request */ NdJsonPolicy.prototype.sendRequest = function (request) { return tslib.__awaiter(this, void 0, void 0, function () { @@ -64111,17 +65254,24 @@ var NdJsonPolicy = /** @class */ (function (_super) { return NdJsonPolicy; }(BaseRequestPolicy)); +// Copyright (c) Microsoft Corporation. +var cachedHttpClient; +function getCachedDefaultHttpClient() { + if (!cachedHttpClient) { + cachedHttpClient = new NodeFetchHttpClient(); + } + return cachedHttpClient; +} + // Copyright (c) Microsoft Corporation. /** - * @class - * Initializes a new instance of the ServiceClient. + * ServiceClient sends service requests and receives responses. */ var ServiceClient = /** @class */ (function () { /** * The ServiceClient constructor - * @constructor - * @param credentials The credentials used for authentication with the service. - * @param options The service client options that govern the behavior of the client. + * @param credentials - The credentials used for authentication with the service. + * @param options - The service client options that govern the behavior of the client. */ function ServiceClient(credentials, /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options */ @@ -64131,7 +65281,7 @@ var ServiceClient = /** @class */ (function () { options = {}; } this._withCredentials = options.withCredentials || false; - this._httpClient = options.httpClient || new NodeFetchHttpClient(); + this._httpClient = options.httpClient || getCachedDefaultHttpClient(); this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger); var requestPolicyFactories; if (Array.isArray(options.requestPolicyFactories)) { @@ -64154,7 +65304,7 @@ var ServiceClient = /** @class */ (function () { var serviceClient = _this; var serviceClientOptions = options; return { - create: function (nextPolicy, options) { + create: function (nextPolicy, createOptions) { var credentialScopes = getCredentialScopes(serviceClientOptions, serviceClient.baseUri); if (!credentialScopes) { throw new Error("When using credential, the ServiceClient must contain a baseUri or a credentialScopes in ServiceClientOptions. Unable to create a bearerTokenAuthenticationPolicy"); @@ -64162,7 +65312,7 @@ var ServiceClient = /** @class */ (function () { if (bearerTokenPolicyFactory === undefined || bearerTokenPolicyFactory === null) { bearerTokenPolicyFactory = bearerTokenAuthenticationPolicy(credentials, credentialScopes); } - return bearerTokenPolicyFactory.create(nextPolicy, options); + return bearerTokenPolicyFactory.create(nextPolicy, createOptions); } }; }; @@ -64219,9 +65369,9 @@ var ServiceClient = /** @class */ (function () { }; /** * Send an HTTP request that is populated using the provided OperationSpec. - * @param {OperationArguments} operationArguments The arguments that the HTTP request's templated values will be populated from. - * @param {OperationSpec} operationSpec The OperationSpec to use to populate the httpRequest. - * @param {ServiceCallback} callback The callback to call when the response is received. + * @param operationArguments - The arguments that the HTTP request's templated values will be populated from. + * @param operationSpec - The OperationSpec to use to populate the httpRequest. + * @param callback - The callback to call when the response is received. */ ServiceClient.prototype.sendOperationRequest = function (operationArguments, operationSpec, callback) { var _a; @@ -64312,7 +65462,7 @@ var ServiceClient = /** @class */ (function () { } httpRequest.url = requestUrl.toString(); contentType = operationSpec.contentType || this.requestContentType; - if (contentType) { + if (contentType && operationSpec.requestBody) { httpRequest.headers.set("Content-Type", contentType); } if (operationSpec.headerParameters) { @@ -64364,8 +65514,8 @@ var ServiceClient = /** @class */ (function () { } httpRequest.withCredentials = this._withCredentials; serializeRequestBody(this, httpRequest, operationArguments, operationSpec); - if (httpRequest.streamResponseBody === undefined || httpRequest.streamResponseBody === null) { - httpRequest.streamResponseBody = isStreamOperation(operationSpec); + if (httpRequest.streamResponseStatusCodes === undefined) { + httpRequest.streamResponseStatusCodes = getStreamResponseStatusCodes(operationSpec); } rawResponse = void 0; sendRequestError = void 0; @@ -64400,7 +65550,6 @@ var ServiceClient = /** @class */ (function () { cb = callback; if (cb) { result - // tslint:disable-next-line:no-null-keyword .then(function (res) { return cb(null, res._response.parsedBody, res._response.request, res._response); }) .catch(function (err) { return cb(err); }); } @@ -64702,9 +65851,9 @@ function getCredentialScopes(options, baseUri) { // Copyright (c) Microsoft Corporation. /** * Creates a function called createSpan to create spans using the global tracer. - * @ignore - * @param spanConfig The name of the operation being performed. - * @param tracingOptions The options for the underlying http request. + * @hidden + * @param spanConfig - The name of the operation being performed. + * @param tracingOptions - The options for the underlying http request. */ function createSpanFunction(_a) { var packagePrefix = _a.packagePrefix, namespace = _a.namespace; @@ -64734,10 +65883,9 @@ var BasicAuthenticationCredentials = /** @class */ (function () { /** * Creates a new BasicAuthenticationCredentials object. * - * @constructor - * @param {string} userName User name. - * @param {string} password Password. - * @param {string} [authorizationScheme] The authorization scheme. + * @param userName - User name. + * @param password - Password. + * @param authorizationScheme - The authorization scheme. */ function BasicAuthenticationCredentials(userName, password, authorizationScheme) { if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME; } @@ -64755,8 +65903,8 @@ var BasicAuthenticationCredentials = /** @class */ (function () { /** * Signs a request with the Authentication header. * - * @param {WebResourceLike} webResource The WebResourceLike to be signed. - * @returns {Promise} The signed request object. + * @param webResource - The WebResourceLike to be signed. + * @returns The signed request object. */ BasicAuthenticationCredentials.prototype.signRequest = function (webResource) { var credentials = this.userName + ":" + this.password; @@ -64775,8 +65923,7 @@ var BasicAuthenticationCredentials = /** @class */ (function () { */ var ApiKeyCredentials = /** @class */ (function () { /** - * @constructor - * @param {object} options Specifies the options to be provided for auth. Either header or query needs to be provided. + * @param options - Specifies the options to be provided for auth. Either header or query needs to be provided. */ function ApiKeyCredentials(options) { if (!options || (options && !options.inHeader && !options.inQuery)) { @@ -64788,8 +65935,8 @@ var ApiKeyCredentials = /** @class */ (function () { /** * Signs a request with the values provided in the inHeader and inQuery parameter. * - * @param {WebResourceLike} webResource The WebResourceLike to be signed. - * @returns {Promise} The signed request object. + * @param webResource - The WebResourceLike to be signed. + * @returns The signed request object. */ ApiKeyCredentials.prototype.signRequest = function (webResource) { if (!webResource) { @@ -64828,8 +65975,7 @@ var TopicCredentials = /** @class */ (function (_super) { /** * Creates a new EventGrid TopicCredentials object. * - * @constructor - * @param {string} topicKey The EventGrid topic key + * @param topicKey - The EventGrid topic key */ function TopicCredentials(topicKey) { var _this = this; diff --git a/package-lock.json b/package-lock.json index ac46a2c8c4..f5c3babb73 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,8 +1,2969 @@ { "name": "golanci-lint-action", "version": "2.0.0", - "lockfileVersion": 1, + "lockfileVersion": 2, "requires": true, + "packages": { + "": { + "name": "golanci-lint-action", + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "@actions/cache": "^1.0.6", + "@actions/core": "^1.2.6", + "@actions/exec": "^1.0.1", + "@actions/github": "^4.0.0", + "@actions/tool-cache": "^1.6.1", + "@types/semver": "^7.3.4", + "@types/tmp": "^0.2.0", + "setup-go": "git+https://github.com/actions/setup-go.git#v2.1.3", + "tmp": "^0.2.1" + }, + "devDependencies": { + "@types/node": "^14.14.25", + "@types/uuid": "^8.3.0", + "@typescript-eslint/eslint-plugin": "^2.34.0", + "@typescript-eslint/parser": "^2.34.0", + "@zeit/ncc": "^0.22.3", + "eslint": "^6.6.0", + "eslint-config-prettier": "^6.15.0", + "eslint-plugin-import": "^2.22.1", + "eslint-plugin-prettier": "^3.3.1", + "eslint-plugin-simple-import-sort": "^7.0.0", + "prettier": "^2.2.1", + "typescript": "^4.1.3" + } + }, + "node_modules/@actions/cache": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@actions/cache/-/cache-1.0.6.tgz", + "integrity": "sha512-c8CSJS6uCatX07VHazgvL4XPMpTdawOyyD+OCThRE0v486lqThYa4tayRqTyl6FSyD5LclQyB8/FQlZ5cxTNJA==", + "dependencies": { + "@actions/core": "^1.2.6", + "@actions/exec": "^1.0.1", + "@actions/glob": "^0.1.0", + "@actions/http-client": "^1.0.9", + "@actions/io": "^1.0.1", + "@azure/ms-rest-js": "^2.0.7", + "@azure/storage-blob": "^12.1.2", + "semver": "^6.1.0", + "uuid": "^3.3.3" + } + }, + "node_modules/@actions/cache/node_modules/@actions/http-client": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-1.0.9.tgz", + "integrity": "sha512-0O4SsJ7q+MK0ycvXPl2e6bMXV7dxAXOGjrXS1eTF9s2S401Tp6c/P3c3Joz04QefC1J6Gt942Wl2jbm3f4mLcg==", + "dependencies": { + "tunnel": "0.0.6" + } + }, + "node_modules/@actions/core": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.2.6.tgz", + "integrity": "sha512-ZQYitnqiyBc3D+k7LsgSBmMDVkOVidaagDG7j3fOym77jNunWRuYx7VSHa9GNfFZh+zh61xsCjRj4JxMZlDqTA==" + }, + "node_modules/@actions/exec": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@actions/exec/-/exec-1.0.4.tgz", + "integrity": "sha512-4DPChWow9yc9W3WqEbUj8Nr86xkpyE29ZzWjXucHItclLbEW6jr80Zx4nqv18QL6KK65+cifiQZXvnqgTV6oHw==", + "dependencies": { + "@actions/io": "^1.0.1" + } + }, + "node_modules/@actions/github": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@actions/github/-/github-4.0.0.tgz", + "integrity": "sha512-Ej/Y2E+VV6sR9X7pWL5F3VgEWrABaT292DRqRU6R4hnQjPtC/zD3nagxVdXWiRQvYDh8kHXo7IDmG42eJ/dOMA==", + "dependencies": { + "@actions/http-client": "^1.0.8", + "@octokit/core": "^3.0.0", + "@octokit/plugin-paginate-rest": "^2.2.3", + "@octokit/plugin-rest-endpoint-methods": "^4.0.0" + } + }, + "node_modules/@actions/glob": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@actions/glob/-/glob-0.1.1.tgz", + "integrity": "sha512-ikM4GVZOgSGDNTjv0ECJ8AOqmDqQwtO4K1M4P465C9iikRq34+FwCjUVSwzgOYDP85qtddyWpzBw5lTub/9Xmg==", + "dependencies": { + "@actions/core": "^1.2.6", + "minimatch": "^3.0.4" + } + }, + "node_modules/@actions/http-client": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-1.0.8.tgz", + "integrity": "sha512-G4JjJ6f9Hb3Zvejj+ewLLKLf99ZC+9v+yCxoYf9vSyH+WkzPLB2LuUtRMGNkooMqdugGBFStIKXOuvH1W+EctA==", + "dependencies": { + "tunnel": "0.0.6" + } + }, + "node_modules/@actions/io": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@actions/io/-/io-1.0.2.tgz", + "integrity": "sha512-J8KuFqVPr3p6U8W93DOXlXW6zFvrQAJANdS+vw0YhusLIq+bszW8zmK2Fh1C2kDPX8FMvwIl1OUcFgvJoXLbAg==" + }, + "node_modules/@actions/tool-cache": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/@actions/tool-cache/-/tool-cache-1.6.1.tgz", + "integrity": "sha512-F+vwEDwfqcHMKuSkj79pihOnsAMv23EkG76nMpc82UsnXwyQdyEsktGxrB0SNtm7pRqTXEIOoAPTgrSQclXYTg==", + "dependencies": { + "@actions/core": "^1.2.6", + "@actions/exec": "^1.0.0", + "@actions/http-client": "^1.0.8", + "@actions/io": "^1.0.1", + "semver": "^6.1.0", + "uuid": "^3.3.2" + } + }, + "node_modules/@azure/abort-controller": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-1.0.2.tgz", + "integrity": "sha512-XUyTo+bcyxHEf+jlN2MXA7YU9nxVehaubngHV1MIZZaqYmZqykkoeAz/JMMEeR7t3TcyDwbFa3Zw8BZywmIx4g==", + "dependencies": { + "tslib": "^2.0.0" + } + }, + "node_modules/@azure/abort-controller/node_modules/tslib": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.1.0.tgz", + "integrity": "sha512-hcVC3wYEziELGGmEEXue7D75zbwIIVUMWAVbHItGPx0ziyXxrOMQx4rQEVEV45Ut/1IotuEvwqPopzIOkDMf0A==" + }, + "node_modules/@azure/core-asynciterator-polyfill": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@azure/core-asynciterator-polyfill/-/core-asynciterator-polyfill-1.0.0.tgz", + "integrity": "sha512-kmv8CGrPfN9SwMwrkiBK9VTQYxdFQEGe0BmQk+M8io56P9KNzpAxcWE/1fxJj7uouwN4kXF0BHW8DNlgx+wtCg==" + }, + "node_modules/@azure/core-auth": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@azure/core-auth/-/core-auth-1.1.4.tgz", + "integrity": "sha512-+j1embyH1jqf04AIfJPdLafd5SC1y6z1Jz4i+USR1XkTp6KM8P5u4/AjmWMVoEQdM/M29PJcRDZcCEWjK9S1bw==", + "dependencies": { + "@azure/abort-controller": "^1.0.0", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@azure/core-auth/node_modules/tslib": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.1.0.tgz", + "integrity": "sha512-hcVC3wYEziELGGmEEXue7D75zbwIIVUMWAVbHItGPx0ziyXxrOMQx4rQEVEV45Ut/1IotuEvwqPopzIOkDMf0A==" + }, + "node_modules/@azure/core-http": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@azure/core-http/-/core-http-1.2.3.tgz", + "integrity": "sha512-g5C1zUJO5dehP2Riv+vy9iCYoS1UwKnZsBVCzanScz9A83LbnXKpZDa9wie26G9dfXUhQoFZoFT8LYWhPKmwcg==", + "dependencies": { + "@azure/abort-controller": "^1.0.0", + "@azure/core-auth": "^1.1.3", + "@azure/core-tracing": "1.0.0-preview.9", + "@azure/logger": "^1.0.0", + "@opentelemetry/api": "^0.10.2", + "@types/node-fetch": "^2.5.0", + "@types/tunnel": "^0.0.1", + "form-data": "^3.0.0", + "node-fetch": "^2.6.0", + "process": "^0.11.10", + "tough-cookie": "^4.0.0", + "tslib": "^2.0.0", + "tunnel": "^0.0.6", + "uuid": "^8.3.0", + "xml2js": "^0.4.19" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@azure/core-http/node_modules/form-data": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.0.tgz", + "integrity": "sha512-CKMFDglpbMi6PyN+brwB9Q/GOw0eAnsrEZDgcsH5Krhz5Od/haKHAX0NmQfha2zPPz0JpWzA7GJHGSnvCRLWsg==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/@azure/core-http/node_modules/tough-cookie": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.0.0.tgz", + "integrity": "sha512-tHdtEpQCMrc1YLrMaqXXcj6AxhYi/xgit6mZu1+EDWUn+qhUf8wMQoFIy9NXuq23zAwtcB0t/MjACGR18pcRbg==", + "dependencies": { + "psl": "^1.1.33", + "punycode": "^2.1.1", + "universalify": "^0.1.2" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@azure/core-http/node_modules/tslib": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.1.0.tgz", + "integrity": "sha512-hcVC3wYEziELGGmEEXue7D75zbwIIVUMWAVbHItGPx0ziyXxrOMQx4rQEVEV45Ut/1IotuEvwqPopzIOkDMf0A==" + }, + "node_modules/@azure/core-http/node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/@azure/core-lro": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@azure/core-lro/-/core-lro-1.0.3.tgz", + "integrity": "sha512-Py2crJ84qx1rXkzIwfKw5Ni4WJuzVU7KAF6i1yP3ce8fbynUeu8eEWS4JGtSQgU7xv02G55iPDROifmSDbxeHA==", + "dependencies": { + "@azure/abort-controller": "^1.0.0", + "@azure/core-http": "^1.2.0", + "events": "^3.0.0", + "tslib": "^2.0.0" + } + }, + "node_modules/@azure/core-lro/node_modules/tslib": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.1.0.tgz", + "integrity": "sha512-hcVC3wYEziELGGmEEXue7D75zbwIIVUMWAVbHItGPx0ziyXxrOMQx4rQEVEV45Ut/1IotuEvwqPopzIOkDMf0A==" + }, + "node_modules/@azure/core-paging": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@azure/core-paging/-/core-paging-1.1.3.tgz", + "integrity": "sha512-his7Ah40ThEYORSpIAwuh6B8wkGwO/zG7gqVtmSE4WAJ46e36zUDXTKReUCLBDc6HmjjApQQxxcRFy5FruG79A==", + "dependencies": { + "@azure/core-asynciterator-polyfill": "^1.0.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@azure/core-tracing": { + "version": "1.0.0-preview.9", + "resolved": "https://registry.npmjs.org/@azure/core-tracing/-/core-tracing-1.0.0-preview.9.tgz", + "integrity": "sha512-zczolCLJ5QG42AEPQ+Qg9SRYNUyB+yZ5dzof4YEc+dyWczO9G2sBqbAjLB7IqrsdHN2apkiB2oXeDKCsq48jug==", + "dependencies": { + "@opencensus/web-types": "0.0.7", + "@opentelemetry/api": "^0.10.2", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@azure/core-tracing/node_modules/tslib": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.1.0.tgz", + "integrity": "sha512-hcVC3wYEziELGGmEEXue7D75zbwIIVUMWAVbHItGPx0ziyXxrOMQx4rQEVEV45Ut/1IotuEvwqPopzIOkDMf0A==" + }, + "node_modules/@azure/logger": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@azure/logger/-/logger-1.0.1.tgz", + "integrity": "sha512-QYQeaJ+A5x6aMNu8BG5qdsVBnYBop9UMwgUvGihSjf1PdZZXB+c/oMdM2ajKwzobLBh9e9QuMQkN9iL+IxLBLA==", + "dependencies": { + "tslib": "^2.0.0" + } + }, + "node_modules/@azure/logger/node_modules/tslib": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.1.0.tgz", + "integrity": "sha512-hcVC3wYEziELGGmEEXue7D75zbwIIVUMWAVbHItGPx0ziyXxrOMQx4rQEVEV45Ut/1IotuEvwqPopzIOkDMf0A==" + }, + "node_modules/@azure/ms-rest-js": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@azure/ms-rest-js/-/ms-rest-js-2.2.1.tgz", + "integrity": "sha512-vd8SIsoC27u8gpxatDQQ1Z5+wcnkAVhOUxA2VXRDse/zKRN0RuYoj7jTRIiJlNEOyUX4a+oGFplSZNQEsLZVbg==", + "dependencies": { + "@azure/core-auth": "^1.1.4", + "@types/node-fetch": "^2.3.7", + "@types/tunnel": "0.0.1", + "abort-controller": "^3.0.0", + "form-data": "^2.5.0", + "node-fetch": "^2.6.0", + "tough-cookie": "^3.0.1", + "tslib": "^1.10.0", + "tunnel": "0.0.6", + "uuid": "^3.3.2", + "xml2js": "^0.4.19" + } + }, + "node_modules/@azure/storage-blob": { + "version": "12.4.1", + "resolved": "https://registry.npmjs.org/@azure/storage-blob/-/storage-blob-12.4.1.tgz", + "integrity": "sha512-RH6ru8LbnCC+m1rlVLon6mYUXdHsTcyUXFCJAWRQQM7p0XOwVKPS+UiVk2tZXfvMWd3q/qT/meOrEbHEcp/c4g==", + "dependencies": { + "@azure/abort-controller": "^1.0.0", + "@azure/core-http": "^1.2.0", + "@azure/core-lro": "^1.0.2", + "@azure/core-paging": "^1.1.1", + "@azure/core-tracing": "1.0.0-preview.9", + "@azure/logger": "^1.0.0", + "@opentelemetry/api": "^0.10.2", + "events": "^3.0.0", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@azure/storage-blob/node_modules/tslib": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.1.0.tgz", + "integrity": "sha512-hcVC3wYEziELGGmEEXue7D75zbwIIVUMWAVbHItGPx0ziyXxrOMQx4rQEVEV45Ut/1IotuEvwqPopzIOkDMf0A==" + }, + "node_modules/@babel/code-frame": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.8.3.tgz", + "integrity": "sha512-a9gxpmdXtZEInkCSHUJDLHZVBgb1QS0jhss4cPP93EW7s+uC5bikET2twEF3KV+7rDblJcmNvTR7VJejqd2C2g==", + "dev": true, + "dependencies": { + "@babel/highlight": "^7.8.3" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.9.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.9.5.tgz", + "integrity": "sha512-/8arLKUFq882w4tWGj9JYzRpAlZgiWUJ+dtteNTDqrRBz9Iguck9Rn3ykuBDoUwh2TO4tSAJlrxDUOXWklJe4g==", + "dev": true + }, + "node_modules/@babel/highlight": { + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.9.0.tgz", + "integrity": "sha512-lJZPilxX7Op3Nv/2cvFdnlepPXDxi29wxteT57Q965oc5R9v86ztx0jfxVrTcBk8C2kcPkkDa2Z4T3ZsPPVWsQ==", + "dev": true, + "dependencies": { + "@babel/helper-validator-identifier": "^7.9.0", + "chalk": "^2.0.0", + "js-tokens": "^4.0.0" + } + }, + "node_modules/@octokit/auth-token": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.4.2.tgz", + "integrity": "sha512-jE/lE/IKIz2v1+/P0u4fJqv0kYwXOTujKemJMFr6FeopsxlIK3+wKDCJGnysg81XID5TgZQbIfuJ5J0lnTiuyQ==", + "dependencies": { + "@octokit/types": "^5.0.0" + } + }, + "node_modules/@octokit/core": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@octokit/core/-/core-3.1.1.tgz", + "integrity": "sha512-cQ2HGrtyNJ1IBxpTP1U5m/FkMAJvgw7d2j1q3c9P0XUuYilEgF6e4naTpsgm4iVcQeOnccZlw7XHRIUBy0ymcg==", + "dependencies": { + "@octokit/auth-token": "^2.4.0", + "@octokit/graphql": "^4.3.1", + "@octokit/request": "^5.4.0", + "@octokit/types": "^5.0.0", + "before-after-hook": "^2.1.0", + "universal-user-agent": "^6.0.0" + } + }, + "node_modules/@octokit/endpoint": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.5.tgz", + "integrity": "sha512-70K5u6zd45ItOny6aHQAsea8HHQjlQq85yqOMe+Aj8dkhN2qSJ9T+Q3YjUjEYfPRBcuUWNgMn62DQnP/4LAIiQ==", + "dependencies": { + "@octokit/types": "^5.0.0", + "is-plain-object": "^4.0.0", + "universal-user-agent": "^6.0.0" + } + }, + "node_modules/@octokit/graphql": { + "version": "4.5.3", + "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.5.3.tgz", + "integrity": "sha512-JyYvi3j2tOb5ofASEpcg1Advs07H+Ag+I+ez7buuZfNVAmh1IYcDTuxd4gnYH8S2PSGu+f5IdDGxMmkK+5zsdA==", + "dependencies": { + "@octokit/request": "^5.3.0", + "@octokit/types": "^5.0.0", + "universal-user-agent": "^6.0.0" + } + }, + "node_modules/@octokit/plugin-paginate-rest": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.3.0.tgz", + "integrity": "sha512-Ye2ZJreP0ZlqJQz8fz+hXvrEAEYK4ay7br1eDpWzr6j76VXs/gKqxFcH8qRzkB3fo/2xh4Vy9VtGii4ZDc9qlA==", + "dependencies": { + "@octokit/types": "^5.2.0" + } + }, + "node_modules/@octokit/plugin-rest-endpoint-methods": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-4.1.2.tgz", + "integrity": "sha512-PTI7wpbGEZ2IR87TVh+TNWaLcgX/RsZQalFbQCq8XxYUrQ36RHyERrHSNXFy5gkWpspUAOYRSV707JJv6BhqJA==", + "dependencies": { + "@octokit/types": "^5.1.1", + "deprecation": "^2.3.1" + } + }, + "node_modules/@octokit/request": { + "version": "5.4.7", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.4.7.tgz", + "integrity": "sha512-FN22xUDP0i0uF38YMbOfx6TotpcENP5W8yJM1e/LieGXn6IoRxDMnBf7tx5RKSW4xuUZ/1P04NFZy5iY3Rax1A==", + "dependencies": { + "@octokit/endpoint": "^6.0.1", + "@octokit/request-error": "^2.0.0", + "@octokit/types": "^5.0.0", + "deprecation": "^2.0.0", + "is-plain-object": "^4.0.0", + "node-fetch": "^2.3.0", + "once": "^1.4.0", + "universal-user-agent": "^6.0.0" + } + }, + "node_modules/@octokit/request-error": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.0.2.tgz", + "integrity": "sha512-2BrmnvVSV1MXQvEkrb9zwzP0wXFNbPJij922kYBTLIlIafukrGOb+ABBT2+c6wZiuyWDH1K1zmjGQ0toN/wMWw==", + "dependencies": { + "@octokit/types": "^5.0.1", + "deprecation": "^2.0.0", + "once": "^1.4.0" + } + }, + "node_modules/@octokit/types": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-5.2.0.tgz", + "integrity": "sha512-XjOk9y4m8xTLIKPe1NFxNWBdzA2/z3PFFA/bwf4EoH6oS8hM0Y46mEa4Cb+KCyj/tFDznJFahzQ0Aj3o1FYq4A==", + "dependencies": { + "@types/node": ">= 8" + } + }, + "node_modules/@opencensus/web-types": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/@opencensus/web-types/-/web-types-0.0.7.tgz", + "integrity": "sha512-xB+w7ZDAu3YBzqH44rCmG9/RlrOmFuDPt/bpf17eJr8eZSrLt7nc7LnWdxM9Mmoj/YKMHpxRg28txu3TcpiL+g==", + "engines": { + "node": ">=6.0" + } + }, + "node_modules/@opentelemetry/api": { + "version": "0.10.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-0.10.2.tgz", + "integrity": "sha512-GtpMGd6vkzDMYcpu2t9LlhEgMy/SzBwRnz48EejlRArYqZzqSzAsKmegUK7zHgl+EOIaK9mKHhnRaQu3qw20cA==", + "dependencies": { + "@opentelemetry/context-base": "^0.10.2" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@opentelemetry/context-base": { + "version": "0.10.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/context-base/-/context-base-0.10.2.tgz", + "integrity": "sha512-hZNKjKOYsckoOEgBziGMnBcX0M7EtstnCmwz5jZUOUYwlZ+/xxX6z3jPu1XVO2Jivk0eLfuP9GP+vFD49CMetw==", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@types/color-name": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@types/color-name/-/color-name-1.1.1.tgz", + "integrity": "sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ==", + "dev": true + }, + "node_modules/@types/eslint-visitor-keys": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@types/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz", + "integrity": "sha512-OCutwjDZ4aFS6PB1UZ988C4YgwlBHJd6wCeQqaLdmadZ/7e+w79+hbMUFC1QXDNCmdyoRfAFdm0RypzwR+Qpag==", + "dev": true + }, + "node_modules/@types/json-schema": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.4.tgz", + "integrity": "sha512-8+KAKzEvSUdeo+kmqnKrqgeE+LcA0tjYWFY7RPProVYwnqDjukzO+3b6dLD56rYX5TdWejnEOLJYOIeh4CXKuA==", + "dev": true + }, + "node_modules/@types/json5": { + "version": "0.0.29", + "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz", + "integrity": "sha1-7ihweulOEdK4J7y+UnC86n8+ce4=", + "dev": true + }, + "node_modules/@types/node": { + "version": "14.14.25", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.14.25.tgz", + "integrity": "sha512-EPpXLOVqDvisVxtlbvzfyqSsFeQxltFbluZNRndIb8tr9KiBnYNLzrc1N3pyKUCww2RNrfHDViqDWWE1LCJQtQ==" + }, + "node_modules/@types/node-fetch": { + "version": "2.5.8", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.5.8.tgz", + "integrity": "sha512-fbjI6ja0N5ZA8TV53RUqzsKNkl9fv8Oj3T7zxW7FGv1GSH7gwJaNF8dzCjrqKaxKeUpTz4yT1DaJFq/omNpGfw==", + "dependencies": { + "@types/node": "*", + "form-data": "^3.0.0" + } + }, + "node_modules/@types/node-fetch/node_modules/form-data": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.0.tgz", + "integrity": "sha512-CKMFDglpbMi6PyN+brwB9Q/GOw0eAnsrEZDgcsH5Krhz5Od/haKHAX0NmQfha2zPPz0JpWzA7GJHGSnvCRLWsg==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/@types/semver": { + "version": "7.3.4", + "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.3.4.tgz", + "integrity": "sha512-+nVsLKlcUCeMzD2ufHEYuJ9a2ovstb6Dp52A5VsoKxDXgvE051XgHI/33I1EymwkRGQkwnA0LkhnUzituGs4EQ==" + }, + "node_modules/@types/tmp": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@types/tmp/-/tmp-0.2.0.tgz", + "integrity": "sha512-flgpHJjntpBAdJD43ShRosQvNC0ME97DCfGvZEDlAThQmnerRXrLbX6YgzRBQCZTthET9eAWFAMaYP0m0Y4HzQ==" + }, + "node_modules/@types/tunnel": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/@types/tunnel/-/tunnel-0.0.1.tgz", + "integrity": "sha512-AOqu6bQu5MSWwYvehMXLukFHnupHrpZ8nvgae5Ggie9UwzDR1CCwoXgSSWNZJuyOlCdfdsWMA5F2LlmvyoTv8A==", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/uuid": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-8.3.0.tgz", + "integrity": "sha512-eQ9qFW/fhfGJF8WKHGEHZEyVWfZxrT+6CLIJGBcZPfxUh/+BnEj+UCGYMlr9qZuX/2AltsvwrGqp0LhEW8D0zQ==", + "dev": true + }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "2.34.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-2.34.0.tgz", + "integrity": "sha512-4zY3Z88rEE99+CNvTbXSyovv2z9PNOVffTWD2W8QF5s2prBQtwN2zadqERcrHpcR7O/+KMI3fcTAmUUhK/iQcQ==", + "dev": true, + "dependencies": { + "@typescript-eslint/experimental-utils": "2.34.0", + "functional-red-black-tree": "^1.0.1", + "regexpp": "^3.0.0", + "tsutils": "^3.17.1" + }, + "engines": { + "node": "^8.10.0 || ^10.13.0 || >=11.10.1" + } + }, + "node_modules/@typescript-eslint/eslint-plugin/node_modules/@typescript-eslint/experimental-utils": { + "version": "2.34.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-2.34.0.tgz", + "integrity": "sha512-eS6FTkq+wuMJ+sgtuNTtcqavWXqsflWcfBnlYhg/nS4aZ1leewkXGbvBhaapn1q6qf4M71bsR1tez5JTRMuqwA==", + "dev": true, + "dependencies": { + "@types/json-schema": "^7.0.3", + "@typescript-eslint/typescript-estree": "2.34.0", + "eslint-scope": "^5.0.0", + "eslint-utils": "^2.0.0" + }, + "engines": { + "node": "^8.10.0 || ^10.13.0 || >=11.10.1" + } + }, + "node_modules/@typescript-eslint/eslint-plugin/node_modules/@typescript-eslint/typescript-estree": { + "version": "2.34.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-2.34.0.tgz", + "integrity": "sha512-OMAr+nJWKdlVM9LOqCqh3pQQPwxHAN7Du8DR6dmwCrAmxtiXQnhHJ6tBNtf+cggqfo51SG/FCwnKhXCIM7hnVg==", + "dev": true, + "dependencies": { + "debug": "^4.1.1", + "eslint-visitor-keys": "^1.1.0", + "glob": "^7.1.6", + "is-glob": "^4.0.1", + "lodash": "^4.17.15", + "semver": "^7.3.2", + "tsutils": "^3.17.1" + }, + "engines": { + "node": "^8.10.0 || ^10.13.0 || >=11.10.1" + } + }, + "node_modules/@typescript-eslint/eslint-plugin/node_modules/semver": { + "version": "7.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.2.tgz", + "integrity": "sha512-OrOb32TeeambH6UrhtShmF7CRDqhL6/5XpPNp2DuRH6+9QLw/orhp72j87v8Qa1ScDkvrrBNpZcDejAirJmfXQ==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@typescript-eslint/experimental-utils": { + "version": "2.34.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-2.34.0.tgz", + "integrity": "sha512-eS6FTkq+wuMJ+sgtuNTtcqavWXqsflWcfBnlYhg/nS4aZ1leewkXGbvBhaapn1q6qf4M71bsR1tez5JTRMuqwA==", + "dev": true, + "dependencies": { + "@types/json-schema": "^7.0.3", + "@typescript-eslint/typescript-estree": "2.34.0", + "eslint-scope": "^5.0.0", + "eslint-utils": "^2.0.0" + }, + "engines": { + "node": "^8.10.0 || ^10.13.0 || >=11.10.1" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "2.34.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-2.34.0.tgz", + "integrity": "sha512-03ilO0ucSD0EPTw2X4PntSIRFtDPWjrVq7C3/Z3VQHRC7+13YB55rcJI3Jt+YgeHbjUdJPcPa7b23rXCBokuyA==", + "dev": true, + "dependencies": { + "@types/eslint-visitor-keys": "^1.0.0", + "@typescript-eslint/experimental-utils": "2.34.0", + "@typescript-eslint/typescript-estree": "2.34.0", + "eslint-visitor-keys": "^1.1.0" + }, + "engines": { + "node": "^8.10.0 || ^10.13.0 || >=11.10.1" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "2.34.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-2.34.0.tgz", + "integrity": "sha512-OMAr+nJWKdlVM9LOqCqh3pQQPwxHAN7Du8DR6dmwCrAmxtiXQnhHJ6tBNtf+cggqfo51SG/FCwnKhXCIM7hnVg==", + "dev": true, + "dependencies": { + "debug": "^4.1.1", + "eslint-visitor-keys": "^1.1.0", + "glob": "^7.1.6", + "is-glob": "^4.0.1", + "lodash": "^4.17.15", + "semver": "^7.3.2", + "tsutils": "^3.17.1" + }, + "engines": { + "node": "^8.10.0 || ^10.13.0 || >=11.10.1" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { + "version": "7.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.2.tgz", + "integrity": "sha512-OrOb32TeeambH6UrhtShmF7CRDqhL6/5XpPNp2DuRH6+9QLw/orhp72j87v8Qa1ScDkvrrBNpZcDejAirJmfXQ==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@zeit/ncc": { + "version": "0.22.3", + "resolved": "https://registry.npmjs.org/@zeit/ncc/-/ncc-0.22.3.tgz", + "integrity": "sha512-jnCLpLXWuw/PAiJiVbLjA8WBC0IJQbFeUwF4I9M+23MvIxTxk5pD4Q8byQBSPmHQjz5aBoA7AKAElQxMpjrCLQ==", + "dev": true, + "bin": { + "ncc": "dist/ncc/cli.js" + } + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/acorn": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.1.1.tgz", + "integrity": "sha512-add7dgA5ppRPxCFJoAGfMDi7PIBXq1RtGo7BhbLaxwrXPOmw8gq48Y9ozT01hUKy9byMjlR20EJhu5zlkErEkg==", + "dev": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.2.0.tgz", + "integrity": "sha512-HiUX/+K2YpkpJ+SzBffkM/AQ2YE03S0U1kjTLVpoJdhZMOWy8qvXVN9JdLqv2QsaQ6MPYQIuNmwD8zOiYUofLQ==", + "dev": true + }, + "node_modules/ajv": { + "version": "6.12.2", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.2.tgz", + "integrity": "sha512-k+V+hzjm5q/Mr8ef/1Y9goCmlsK4I6Sm74teeyGvFk1XrOsbsKLjEdrvny42CZ+a8sXbk8KWpY/bDwS+FLL2UQ==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + } + }, + "node_modules/ansi-escapes": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.1.tgz", + "integrity": "sha512-JWF7ocqNrp8u9oqpgV+wH5ftbt+cfvv+PTjOvKLT3AdYly/LmORARfEVT1iyjwN+4MqE5UmVKoAdIBqeoCHgLA==", + "dev": true, + "dependencies": { + "type-fest": "^0.11.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-escapes/node_modules/type-fest": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.11.0.tgz", + "integrity": "sha512-OdjXJxnCN1AvyLSzeKIgXTXxV+99ZuXl3Hpo9XpJAv9MBcHrrJOQ5kV7ypXOuQie+AmWG25hLbiKdwYTifzcfQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/array-includes": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.1.tgz", + "integrity": "sha512-c2VXaCHl7zPsvpkFsw4nxvFie4fh1ur9bpcgsVkIjqn0H/Xwdg+7fv3n2r/isyS8EBj5b06M9kHyZuIr4El6WQ==", + "dev": true, + "dependencies": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.0", + "is-string": "^1.0.5" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/array.prototype.flat": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.2.3.tgz", + "integrity": "sha512-gBlRZV0VSmfPIeWfuuy56XZMvbVfbEUnOXUvt3F/eUUUSyzlgLxhEX4YAEpxNAogRGehPSnfXyPtYyKAhkzQhQ==", + "dev": true, + "dependencies": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.0-next.1" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/astral-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-1.0.0.tgz", + "integrity": "sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=" + }, + "node_modules/balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" + }, + "node_modules/before-after-hook": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.1.0.tgz", + "integrity": "sha512-IWIbu7pMqyw3EAJHzzHbWa85b6oud/yfKYg5rqB5hNE8CeMi3nX+2C2sj0HswfblST86hpVEOAb9x34NZd6P7A==" + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/chardet": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", + "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", + "dev": true + }, + "node_modules/cli-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", + "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", + "dev": true, + "dependencies": { + "restore-cursor": "^3.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cli-width": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-2.2.1.tgz", + "integrity": "sha512-GRMWDxpOB6Dgk2E5Uo+3eEBvtOOlimMmpbFiKuLFnQzYDavtLFY3K5ona41jgN/WdRZtG7utuVSVTL4HbZHGkw==", + "dev": true + }, + "node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "dev": true + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" + }, + "node_modules/contains-path": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/contains-path/-/contains-path-0.1.0.tgz", + "integrity": "sha1-/ozxhP9mcLa67wGp1IYaXL7EEgo=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/cross-spawn": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", + "dev": true, + "dependencies": { + "nice-try": "^1.0.4", + "path-key": "^2.0.1", + "semver": "^5.5.0", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + }, + "engines": { + "node": ">=4.8" + } + }, + "node_modules/cross-spawn/node_modules/semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "dev": true, + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/deep-is": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", + "dev": true + }, + "node_modules/define-properties": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", + "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", + "dev": true, + "dependencies": { + "object-keys": "^1.0.12" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/deprecation": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz", + "integrity": "sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==" + }, + "node_modules/doctrine": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", + "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", + "dev": true, + "dependencies": { + "esutils": "^2.0.2" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "node_modules/error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dev": true, + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/es-abstract": { + "version": "1.17.7", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.17.7.tgz", + "integrity": "sha512-VBl/gnfcJ7OercKA9MVaegWsBHFjV492syMudcnQZvt/Dw8ezpcOHYZXa/J96O8vx+g4x65YKhxOwDUh63aS5g==", + "dev": true, + "dependencies": { + "es-to-primitive": "^1.2.1", + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1", + "is-callable": "^1.2.2", + "is-regex": "^1.1.1", + "object-inspect": "^1.8.0", + "object-keys": "^1.1.1", + "object.assign": "^4.1.1", + "string.prototype.trimend": "^1.0.1", + "string.prototype.trimstart": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-to-primitive": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", + "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", + "dev": true, + "dependencies": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/eslint": { + "version": "6.8.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-6.8.0.tgz", + "integrity": "sha512-K+Iayyo2LtyYhDSYwz5D5QdWw0hCacNzyq1Y821Xna2xSJj7cijoLLYmLxTQgcgZ9mC61nryMy9S7GRbYpI5Ig==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.0.0", + "ajv": "^6.10.0", + "chalk": "^2.1.0", + "cross-spawn": "^6.0.5", + "debug": "^4.0.1", + "doctrine": "^3.0.0", + "eslint-scope": "^5.0.0", + "eslint-utils": "^1.4.3", + "eslint-visitor-keys": "^1.1.0", + "espree": "^6.1.2", + "esquery": "^1.0.1", + "esutils": "^2.0.2", + "file-entry-cache": "^5.0.1", + "functional-red-black-tree": "^1.0.1", + "glob-parent": "^5.0.0", + "globals": "^12.1.0", + "ignore": "^4.0.6", + "import-fresh": "^3.0.0", + "imurmurhash": "^0.1.4", + "inquirer": "^7.0.0", + "is-glob": "^4.0.0", + "js-yaml": "^3.13.1", + "json-stable-stringify-without-jsonify": "^1.0.1", + "levn": "^0.3.0", + "lodash": "^4.17.14", + "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", + "natural-compare": "^1.4.0", + "optionator": "^0.8.3", + "progress": "^2.0.0", + "regexpp": "^2.0.1", + "semver": "^6.1.2", + "strip-ansi": "^5.2.0", + "strip-json-comments": "^3.0.1", + "table": "^5.2.3", + "text-table": "^0.2.0", + "v8-compile-cache": "^2.0.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^8.10.0 || ^10.13.0 || >=11.10.1" + } + }, + "node_modules/eslint-config-prettier": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-6.15.0.tgz", + "integrity": "sha512-a1+kOYLR8wMGustcgAjdydMsQ2A/2ipRPwRKUmfYaSxc9ZPcrku080Ctl6zrZzZNs/U82MjSv+qKREkoq3bJaw==", + "dev": true, + "dependencies": { + "get-stdin": "^6.0.0" + }, + "bin": { + "eslint-config-prettier-check": "bin/cli.js" + } + }, + "node_modules/eslint-import-resolver-node": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.4.tgz", + "integrity": "sha512-ogtf+5AB/O+nM6DIeBUNr2fuT7ot9Qg/1harBfBtaP13ekEWFQEEMP94BCB7zaNW3gyY+8SHYF00rnqYwXKWOA==", + "dev": true, + "dependencies": { + "debug": "^2.6.9", + "resolve": "^1.13.1" + } + }, + "node_modules/eslint-import-resolver-node/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/eslint-import-resolver-node/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "node_modules/eslint-module-utils": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.6.0.tgz", + "integrity": "sha512-6j9xxegbqe8/kZY8cYpcp0xhbK0EgJlg3g9mib3/miLaExuuwc3n5UEfSnU6hWMbT0FAYVvDbL9RrRgpUeQIvA==", + "dev": true, + "dependencies": { + "debug": "^2.6.9", + "pkg-dir": "^2.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/eslint-module-utils/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/eslint-module-utils/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "node_modules/eslint-plugin-import": { + "version": "2.22.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.22.1.tgz", + "integrity": "sha512-8K7JjINHOpH64ozkAhpT3sd+FswIZTfMZTjdx052pnWrgRCVfp8op9tbjpAk3DdUeI/Ba4C8OjdC0r90erHEOw==", + "dev": true, + "dependencies": { + "array-includes": "^3.1.1", + "array.prototype.flat": "^1.2.3", + "contains-path": "^0.1.0", + "debug": "^2.6.9", + "doctrine": "1.5.0", + "eslint-import-resolver-node": "^0.3.4", + "eslint-module-utils": "^2.6.0", + "has": "^1.0.3", + "minimatch": "^3.0.4", + "object.values": "^1.1.1", + "read-pkg-up": "^2.0.0", + "resolve": "^1.17.0", + "tsconfig-paths": "^3.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/eslint-plugin-import/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/eslint-plugin-import/node_modules/doctrine": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-1.5.0.tgz", + "integrity": "sha1-N53Ocw9hZvds76TmcHoVmwLFpvo=", + "dev": true, + "dependencies": { + "esutils": "^2.0.2", + "isarray": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/eslint-plugin-import/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "node_modules/eslint-plugin-prettier": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-3.3.1.tgz", + "integrity": "sha512-Rq3jkcFY8RYeQLgk2cCwuc0P7SEFwDravPhsJZOQ5N4YI4DSg50NyqJ/9gdZHzQlHf8MvafSesbNJCcP/FF6pQ==", + "dev": true, + "dependencies": { + "prettier-linter-helpers": "^1.0.0" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/eslint-plugin-simple-import-sort": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-simple-import-sort/-/eslint-plugin-simple-import-sort-7.0.0.tgz", + "integrity": "sha512-U3vEDB5zhYPNfxT5TYR7u01dboFZp+HNpnGhkDB2g/2E4wZ/g1Q9Ton8UwCLfRV9yAKyYqDh62oHOamvkFxsvw==", + "dev": true + }, + "node_modules/eslint-scope": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.0.0.tgz", + "integrity": "sha512-oYrhJW7S0bxAFDvWqzvMPRm6pcgcnWc4QnofCAqRTRfQC0JcwenzGglTtsLyIuuWFfkqDG9vz67cnttSd53djw==", + "dev": true, + "dependencies": { + "esrecurse": "^4.1.0", + "estraverse": "^4.1.1" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/eslint-utils": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-2.0.0.tgz", + "integrity": "sha512-0HCPuJv+7Wv1bACm8y5/ECVfYdfsAm9xmVb7saeFlxjPYALefjhbYoCkBjPdPzGH8wWyTpAez82Fh3VKYEZ8OA==", + "dev": true, + "dependencies": { + "eslint-visitor-keys": "^1.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.1.0.tgz", + "integrity": "sha512-8y9YjtM1JBJU/A9Kc+SbaOV4y29sSWckBwMHa+FGtVj5gN/sbnKDf6xJUl+8g7FAij9LVaP8C24DUiH/f/2Z9A==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/eslint/node_modules/eslint-utils": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-1.4.3.tgz", + "integrity": "sha512-fbBN5W2xdY45KulGXmLHZ3c3FHfVYmKg0IrAKGOkT/464PQsx2UeIzfz1RmEci+KLm1bBaAzZAh8+/E+XAeZ8Q==", + "dev": true, + "dependencies": { + "eslint-visitor-keys": "^1.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/eslint/node_modules/regexpp": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-2.0.1.tgz", + "integrity": "sha512-lv0M6+TkDVniA3aD1Eg0DVpfU/booSu7Eev3TDO/mZKHBfVjgCGTV4t4buppESEYDtkArYFOxTJWv6S5C+iaNw==", + "dev": true, + "engines": { + "node": ">=6.5.0" + } + }, + "node_modules/espree": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-6.2.1.tgz", + "integrity": "sha512-ysCxRQY3WaXJz9tdbWOwuWr5Y/XrPTGX9Kiz3yoUXwW0VZ4w30HTkQLaGx/+ttFjF8i+ACbArnB4ce68a9m5hw==", + "dev": true, + "dependencies": { + "acorn": "^7.1.1", + "acorn-jsx": "^5.2.0", + "eslint-visitor-keys": "^1.1.0" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true, + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/esquery": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.3.1.tgz", + "integrity": "sha512-olpvt9QG0vniUBZspVRN6lwB7hOZoTRtT+jzR+tS4ffYx2mzbw+z0XCOk44aaLYKApNX5nMm+E+P6o25ip/DHQ==", + "dev": true, + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esquery/node_modules/estraverse": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.1.0.tgz", + "integrity": "sha512-FyohXK+R0vE+y1nHLoBM7ZTyqRpqAlhdZHCWIWEviFLiGB8b04H6bQs8G+XTthacvT8VuwvteiP7RJSxMs8UEw==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esrecurse": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.1.tgz", + "integrity": "sha512-64RBB++fIOAXPw3P9cy89qfMlvZEXZkqqJkjqqXIvzP5ezRZjW+lPWjw35UX/3EhUPFYbg5ER4JYgDw4007/DQ==", + "dev": true, + "dependencies": { + "estraverse": "^4.1.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "engines": { + "node": ">=6" + } + }, + "node_modules/events": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.2.0.tgz", + "integrity": "sha512-/46HWwbfCX2xTawVfkKLGxMifJYQBWMwY1mjywRtb4c9x8l5NP3KoJtnIOiL1hfdRkIuYhETxQlo62IF8tcnlg==", + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/external-editor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz", + "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==", + "dev": true, + "dependencies": { + "chardet": "^0.7.0", + "iconv-lite": "^0.4.24", + "tmp": "^0.0.33" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/external-editor/node_modules/tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "dev": true, + "dependencies": { + "os-tmpdir": "~1.0.2" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.1.tgz", + "integrity": "sha512-8UEa58QDLauDNfpbrX55Q9jrGHThw2ZMdOky5Gl1CDtVeJDPVrG4Jxx1N8jw2gkWaff5UUuX1KJd+9zGe2B+ZA==", + "dev": true + }, + "node_modules/fast-diff": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.2.0.tgz", + "integrity": "sha512-xJuoT5+L99XlZ8twedaRf6Ax2TgQVxvgZOYoPKqZufmJib0tL2tegPBOZb1pVNgIhlqDlA0eO0c3wBvQcmzx4w==", + "dev": true + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "dev": true + }, + "node_modules/figures": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", + "integrity": "sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==", + "dev": true, + "dependencies": { + "escape-string-regexp": "^1.0.5" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/file-entry-cache": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-5.0.1.tgz", + "integrity": "sha512-bCg29ictuBaKUwwArK4ouCaqDgLZcysCFLmM/Yn/FDoqndh/9vNuQfXRDvTuXKLxfD/JtZQGKFT8MGcJBK644g==", + "dev": true, + "dependencies": { + "flat-cache": "^2.0.1" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/find-up": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", + "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", + "dev": true, + "dependencies": { + "locate-path": "^2.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/flat-cache": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-2.0.1.tgz", + "integrity": "sha512-LoQe6yDuUMDzQAEH8sgmh4Md6oZnc/7PjtwjNFSzveXqSHt6ka9fPBuso7IGf9Rz4uqnSnWiFH2B/zj24a5ReA==", + "dev": true, + "dependencies": { + "flatted": "^2.0.0", + "rimraf": "2.6.3", + "write": "1.0.3" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/flatted": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-2.0.2.tgz", + "integrity": "sha512-r5wGx7YeOwNWNlCA0wQ86zKyDLMQr+/RB8xy74M4hTphfmjlijTSSXGuH8rnvKZnfT9i+75zmd8jcKdMR4O6jA==", + "dev": true + }, + "node_modules/form-data": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.5.1.tgz", + "integrity": "sha512-m21N3WOmEEURgk6B9GLOE4RuWOFf28Lhh9qGYeNlGq4VDXUlJy2th2slBNU8Gp8EzloYZOibZJ7t5ecIrFSjVA==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.6", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 0.12" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" + }, + "node_modules/function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "dev": true + }, + "node_modules/functional-red-black-tree": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", + "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=", + "dev": true + }, + "node_modules/get-stdin": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-6.0.0.tgz", + "integrity": "sha512-jp4tHawyV7+fkkSKyvjuLZswblUtz+SQKzSWnBbii16BuZksJlU1wuBYXY75r+duh/llF1ur6oNwi+2ZzjKZ7g==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/glob": { + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", + "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + } + }, + "node_modules/glob-parent": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.1.tgz", + "integrity": "sha512-FnI+VGOpnlGHWZxthPGR+QhR78fuiK0sNLkHQv+bL9fQi57lNNdquIbna/WrfROrolq8GK5Ek6BiMwqL/voRYQ==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/globals": { + "version": "12.4.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-12.4.0.tgz", + "integrity": "sha512-BWICuzzDvDoH54NHKCseDanAhE3CeDorgDL5MT6LMXXj2WCnd9UC2szdk4AWLfjdgNBCXLUanXYcpBBKOSWGwg==", + "dev": true, + "dependencies": { + "type-fest": "^0.8.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.4.tgz", + "integrity": "sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw==", + "dev": true + }, + "node_modules/has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/has-symbols": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz", + "integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hosted-git-info": { + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.8.tgz", + "integrity": "sha512-f/wzC2QaWBs7t9IYqB4T3sR1xviIViXJRJTWBlx2Gf3g0Xi5vI7Yy4koXQ1c9OYDGHN9sBy1DQ2AB8fqZBWhUg==", + "dev": true + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dev": true, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ignore": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", + "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.2.1.tgz", + "integrity": "sha512-6e1q1cnWP2RXD9/keSkxHScg508CdXqXWgWBaETNhyuBFz+kUZlKboh+ISK+bU++DmbHimVBrOz/zzPe0sZ3sQ==", + "dev": true, + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", + "dev": true, + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/inquirer": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-7.1.0.tgz", + "integrity": "sha512-5fJMWEmikSYu0nv/flMc475MhGbB7TSPd/2IpFV4I4rMklboCH2rQjYY5kKiYGHqUF9gvaambupcJFFG9dvReg==", + "dev": true, + "dependencies": { + "ansi-escapes": "^4.2.1", + "chalk": "^3.0.0", + "cli-cursor": "^3.1.0", + "cli-width": "^2.0.0", + "external-editor": "^3.0.3", + "figures": "^3.0.0", + "lodash": "^4.17.15", + "mute-stream": "0.0.8", + "run-async": "^2.4.0", + "rxjs": "^6.5.3", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0", + "through": "^2.3.6" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/inquirer/node_modules/ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "dependencies": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/inquirer/node_modules/chalk": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-3.0.0.tgz", + "integrity": "sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/inquirer/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/inquirer/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "node_modules/inquirer/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/inquirer/node_modules/strip-ansi": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/inquirer/node_modules/supports-color": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", + "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ip-regex": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/ip-regex/-/ip-regex-2.1.0.tgz", + "integrity": "sha1-+ni/XS5pE8kRzp+BnuUUa7bYROk=", + "engines": { + "node": ">=4" + } + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", + "dev": true + }, + "node_modules/is-callable": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.2.tgz", + "integrity": "sha512-dnMqspv5nU3LoewK2N/y7KLtxtakvTuaCsU9FU50/QDmdbHNy/4/JuRtMHqRU22o3q+W89YQndQEeCVwK+3qrA==", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-date-object": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.2.tgz", + "integrity": "sha512-USlDT524woQ08aoZFzh3/Z6ch9Y/EWXEHQ/AaRN0SkKq4t2Jw2R2339tSXmwuVoY7LLlBCbOIlx2myP/L5zk0g==", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-glob": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", + "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", + "dev": true, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-negative-zero": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.0.tgz", + "integrity": "sha1-lVOxIbD6wohp2p7UWeIMdUN4hGE=", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-plain-object": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-4.1.1.tgz", + "integrity": "sha512-5Aw8LLVsDlZsETVMhoMXzqsXwQqr/0vlnBYzIXJbYo2F4yYlhLHs+Ez7Bod7IIQKWkJbJfxrWD7pA1Dw1TKrwA==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-regex": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.1.tgz", + "integrity": "sha512-1+QkEcxiLlB7VEyFtyBg94e08OAsvq7FUBgApTq/w2ymCLyKJgDPsybBENVtA7XCQEgEXxKPonG+mvYRxh/LIg==", + "dev": true, + "dependencies": { + "has-symbols": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-string": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.5.tgz", + "integrity": "sha512-buY6VNRjhQMiF1qWDouloZlQbRhDPCebwxSjxMjxgemYT46YMd2NR0/H+fBhEfWX4A/w9TBJ+ol+okqJKFE6vQ==", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-symbol": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.3.tgz", + "integrity": "sha512-OwijhaRSgqvhm/0ZdAcXNZt9lYdKFpcRDT5ULUuYXPoT794UNOdU+gpT6Rzo7b4V2HUl/op6GqY894AZwv9faQ==", + "dev": true, + "dependencies": { + "has-symbols": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "dev": true + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", + "dev": true + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true + }, + "node_modules/js-yaml": { + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", + "dev": true, + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=", + "dev": true + }, + "node_modules/json5": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", + "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", + "dev": true, + "dependencies": { + "minimist": "^1.2.0" + }, + "bin": { + "json5": "lib/cli.js" + } + }, + "node_modules/levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "dev": true, + "dependencies": { + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/load-json-file": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-2.0.0.tgz", + "integrity": "sha1-eUfkIUmvgNaWy/eXvKq8/h/inKg=", + "dev": true, + "dependencies": { + "graceful-fs": "^4.1.2", + "parse-json": "^2.2.0", + "pify": "^2.0.0", + "strip-bom": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/locate-path": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", + "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", + "dev": true, + "dependencies": { + "p-locate": "^2.0.0", + "path-exists": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/lodash": { + "version": "4.17.19", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.19.tgz", + "integrity": "sha512-JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ==", + "dev": true + }, + "node_modules/mime-db": { + "version": "1.45.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.45.0.tgz", + "integrity": "sha512-CkqLUxUk15hofLoLyljJSrukZi8mAtgd+yE5uO4tqRZsdsAJKv0O+rFMhVDRJgozy+yG6md5KwuXhD4ocIoP+w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.28", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.28.tgz", + "integrity": "sha512-0TO2yJ5YHYr7M2zzT7gDU1tbwHxEUWBCLt0lscSNpcdAfFyJOVEpRYNS7EXVcTLNj/25QO8gulHC5JtTzSE2UQ==", + "dependencies": { + "mime-db": "1.45.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", + "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", + "dev": true + }, + "node_modules/mkdirp": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", + "integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", + "dev": true, + "dependencies": { + "minimist": "^1.2.5" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "node_modules/mute-stream": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", + "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==", + "dev": true + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", + "dev": true + }, + "node_modules/nice-try": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", + "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", + "dev": true + }, + "node_modules/node-fetch": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz", + "integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==", + "engines": { + "node": "4.x || >=6.0.0" + } + }, + "node_modules/normalize-package-data": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", + "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", + "dev": true, + "dependencies": { + "hosted-git-info": "^2.1.4", + "resolve": "^1.10.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" + } + }, + "node_modules/normalize-package-data/node_modules/semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "dev": true, + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/object-inspect": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.8.0.tgz", + "integrity": "sha512-jLdtEOB112fORuypAyl/50VRVIBIdVQOSUUGQHzJ4xBSbit81zRarz7GThkEFZy1RceYrWYcPcBFPQwHyAc1gA==", + "dev": true + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.1.tgz", + "integrity": "sha512-VT/cxmx5yaoHSOTSyrCygIDFco+RsibY2NM0a4RdEeY/4KgqezwFtK1yr3U67xYhqJSlASm2pKhLVzPj2lr4bA==", + "dev": true, + "dependencies": { + "define-properties": "^1.1.3", + "es-abstract": "^1.18.0-next.0", + "has-symbols": "^1.0.1", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.assign/node_modules/es-abstract": { + "version": "1.18.0-next.1", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.1.tgz", + "integrity": "sha512-I4UGspA0wpZXWENrdA0uHbnhte683t3qT/1VFH9aX2dA5PPSf6QW5HHXf5HImaqPmjXaVeVk4RGWnaylmV7uAA==", + "dev": true, + "dependencies": { + "es-to-primitive": "^1.2.1", + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1", + "is-callable": "^1.2.2", + "is-negative-zero": "^2.0.0", + "is-regex": "^1.1.1", + "object-inspect": "^1.8.0", + "object-keys": "^1.1.1", + "object.assign": "^4.1.1", + "string.prototype.trimend": "^1.0.1", + "string.prototype.trimstart": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.values": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.1.tgz", + "integrity": "sha512-WTa54g2K8iu0kmS/us18jEmdv1a4Wi//BZ/DTVYEcH0XhLM5NYdpDHja3gt57VrZLcNAO2WGA+KpWsDBaHt6eA==", + "dev": true, + "dependencies": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.0-next.1", + "function-bind": "^1.1.1", + "has": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onetime": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.0.tgz", + "integrity": "sha512-5NcSkPHhwTVFIQN+TUqXoS5+dlElHXdpAWu9I0HP20YOtIi+aZ0Ct82jdlILDxjLEAWwvm+qj1m6aEtsDVmm6Q==", + "dev": true, + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/optionator": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz", + "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", + "dev": true, + "dependencies": { + "deep-is": "~0.1.3", + "fast-levenshtein": "~2.0.6", + "levn": "~0.3.0", + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2", + "word-wrap": "~1.2.3" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/p-limit": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", + "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", + "dev": true, + "dependencies": { + "p-try": "^1.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/p-locate": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", + "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", + "dev": true, + "dependencies": { + "p-limit": "^1.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/p-try": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", + "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parse-json": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-2.2.0.tgz", + "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", + "dev": true, + "dependencies": { + "error-ex": "^1.2.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-exists": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", + "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/path-parse": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", + "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==", + "dev": true + }, + "node_modules/path-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-2.0.0.tgz", + "integrity": "sha1-8BLMuEFbcJb8LaoQVMPXI4lZTHM=", + "dev": true, + "dependencies": { + "pify": "^2.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pkg-dir": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-2.0.0.tgz", + "integrity": "sha1-9tXREJ4Z1j7fQo4L1X4Sd3YVM0s=", + "dev": true, + "dependencies": { + "find-up": "^2.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "dev": true, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/prettier": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.2.1.tgz", + "integrity": "sha512-PqyhM2yCjg/oKkFPtTGUojv7gnZAoG80ttl45O6x2Ug/rMJw4wcc9k6aaf2hibP7BGVCCM33gZoGjyvt9mm16Q==", + "dev": true, + "bin": { + "prettier": "bin-prettier.js" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/prettier-linter-helpers": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz", + "integrity": "sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w==", + "dev": true, + "dependencies": { + "fast-diff": "^1.1.2" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/process": { + "version": "0.11.10", + "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", + "integrity": "sha1-czIwDoQBYb2j5podHZGn1LwW8YI=", + "engines": { + "node": ">= 0.6.0" + } + }, + "node_modules/progress": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", + "dev": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/psl": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.8.0.tgz", + "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==" + }, + "node_modules/punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "engines": { + "node": ">=6" + } + }, + "node_modules/read-pkg": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-2.0.0.tgz", + "integrity": "sha1-jvHAYjxqbbDcZxPEv6xGMysjaPg=", + "dev": true, + "dependencies": { + "load-json-file": "^2.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^2.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/read-pkg-up": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-2.0.0.tgz", + "integrity": "sha1-a3KoBImE4MQeeVEP1en6mbO1Sb4=", + "dev": true, + "dependencies": { + "find-up": "^2.0.0", + "read-pkg": "^2.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/regexpp": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.1.0.tgz", + "integrity": "sha512-ZOIzd8yVsQQA7j8GCSlPGXwg5PfmA1mrq0JP4nGhh54LaKN3xdai/vHUDu74pKwV8OxseMS65u2NImosQcSD0Q==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve": { + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.17.0.tgz", + "integrity": "sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w==", + "dev": true, + "dependencies": { + "path-parse": "^1.0.6" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/restore-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", + "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "dev": true, + "dependencies": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/rimraf": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", + "dev": true, + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + } + }, + "node_modules/run-async": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz", + "integrity": "sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==", + "dev": true, + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/rxjs": { + "version": "6.5.5", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.5.tgz", + "integrity": "sha512-WfQI+1gohdf0Dai/Bbmk5L5ItH5tYqm3ki2c5GdWhKjalzjg93N3avFjVStyZZz+A2Em+ZxKH5bNghw9UeylGQ==", + "dev": true, + "dependencies": { + "tslib": "^1.9.0" + }, + "engines": { + "npm": ">=2.0.0" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true + }, + "node_modules/sax": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", + "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==" + }, + "node_modules/semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/setup-go": { + "resolved": "git+ssh://git@github.com/actions/setup-go.git#37335c7bb261b353407cff977110895fa0b4f7d8", + "dependencies": { + "@actions/core": "^1.2.6", + "@actions/http-client": "^1.0.6", + "@actions/io": "^1.0.2", + "@actions/tool-cache": "^1.5.5", + "semver": "^6.1.1" + } + }, + "node_modules/shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "dev": true, + "dependencies": { + "shebang-regex": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/signal-exit": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz", + "integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==", + "dev": true + }, + "node_modules/slice-ansi": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-2.1.0.tgz", + "integrity": "sha512-Qu+VC3EwYLldKa1fCxuuvULvSJOKEgk9pi8dZeCVK7TqBfUNTH4sFkk4joj8afVSfAYgJoSOetjx9QWOJ5mYoQ==", + "dev": true, + "dependencies": { + "ansi-styles": "^3.2.0", + "astral-regex": "^1.0.0", + "is-fullwidth-code-point": "^2.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/slice-ansi/node_modules/is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/spdx-correct": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.1.tgz", + "integrity": "sha512-cOYcUWwhCuHCXi49RhFRCyJEK3iPj1Ziz9DpViV3tbZOwXD49QzIN3MpOLJNxh2qwq2lJJZaKMVw9qNi4jTC0w==", + "dev": true, + "dependencies": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/spdx-exceptions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz", + "integrity": "sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A==", + "dev": true + }, + "node_modules/spdx-expression-parse": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", + "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", + "dev": true, + "dependencies": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/spdx-license-ids": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.6.tgz", + "integrity": "sha512-+orQK83kyMva3WyPf59k1+Y525csj5JejicWut55zeTWANuN17qSiSLUXWtzHeNWORSvT7GLDJ/E/XiIWoXBTw==", + "dev": true + }, + "node_modules/sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", + "dev": true + }, + "node_modules/string-width": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz", + "integrity": "sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==", + "dev": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width/node_modules/strip-ansi": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string.prototype.trimend": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.1.tgz", + "integrity": "sha512-LRPxFUaTtpqYsTeNKaFOw3R4bxIzWOnbQ837QfBylo8jIxtcbK/A/sMV7Q+OAV/vWo+7s25pOE10KYSjaSO06g==", + "dev": true, + "dependencies": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.5" + } + }, + "node_modules/string.prototype.trimstart": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.1.tgz", + "integrity": "sha512-XxZn+QpvrBI1FOcg6dIpxUPgWCPuNXvMD72aaRaUQv1eD4e/Qy8i/hFTe0BUmD60p/QA6bh1avmuPTfNjqVWRw==", + "dev": true, + "dependencies": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.5" + } + }, + "node_modules/strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dev": true, + "dependencies": { + "ansi-regex": "^4.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/strip-ansi/node_modules/ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.0.tgz", + "integrity": "sha512-e6/d0eBu7gHtdCqFt0xJr642LdToM5/cN4Qb9DbHjVx1CP5RyeM+zH7pbecEmDv/lBqb0QH+6Uqq75rxFPkM0w==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/table": { + "version": "5.4.6", + "resolved": "https://registry.npmjs.org/table/-/table-5.4.6.tgz", + "integrity": "sha512-wmEc8m4fjnob4gt5riFRtTu/6+4rSe12TpAELNSqHMfF3IqnA+CH37USM6/YR3qRZv7e56kAEAtd6nKZaxe0Ug==", + "dev": true, + "dependencies": { + "ajv": "^6.10.2", + "lodash": "^4.17.14", + "slice-ansi": "^2.1.0", + "string-width": "^3.0.0" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/table/node_modules/emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", + "dev": true + }, + "node_modules/table/node_modules/is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/table/node_modules/string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dev": true, + "dependencies": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/text-table": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", + "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", + "dev": true + }, + "node_modules/through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=", + "dev": true + }, + "node_modules/tmp": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.1.tgz", + "integrity": "sha512-76SUhtfqR2Ijn+xllcI5P1oyannHNHByD80W1q447gU3mp9G9PSpGdWmjUOHRDPiHYacIk66W7ubDTuPF3BEtQ==", + "dependencies": { + "rimraf": "^3.0.0" + }, + "engines": { + "node": ">=8.17.0" + } + }, + "node_modules/tmp/node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + } + }, + "node_modules/tough-cookie": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-3.0.1.tgz", + "integrity": "sha512-yQyJ0u4pZsv9D4clxO69OEjLWYw+jbgspjTue4lTQZLfV0c5l1VmK2y1JK8E9ahdpltPOaAThPcp5nKPUgSnsg==", + "dependencies": { + "ip-regex": "^2.1.0", + "psl": "^1.1.28", + "punycode": "^2.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tsconfig-paths": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.9.0.tgz", + "integrity": "sha512-dRcuzokWhajtZWkQsDVKbWyY+jgcLC5sqJhg2PSgf4ZkH2aHPvaOY8YWGhmjb68b5qqTfasSsDO9k7RUiEmZAw==", + "dev": true, + "dependencies": { + "@types/json5": "^0.0.29", + "json5": "^1.0.1", + "minimist": "^1.2.0", + "strip-bom": "^3.0.0" + } + }, + "node_modules/tslib": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.11.1.tgz", + "integrity": "sha512-aZW88SY8kQbU7gpV19lN24LtXh/yD4ZZg6qieAJDDg+YBsJcSmLGK9QpnUjAKVG/xefmvJGd1WUmfpT/g6AJGA==" + }, + "node_modules/tsutils": { + "version": "3.17.1", + "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.17.1.tgz", + "integrity": "sha512-kzeQ5B8H3w60nFY2g8cJIuH7JDpsALXySGtwGJ0p2LSjLgay3NdIpqq5SoOBe46bKDW2iq25irHCr8wjomUS2g==", + "dev": true, + "dependencies": { + "tslib": "^1.8.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/tunnel": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/tunnel/-/tunnel-0.0.6.tgz", + "integrity": "sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==", + "engines": { + "node": ">=0.6.11 <=0.7.0 || >=0.7.3" + } + }, + "node_modules/type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "dev": true, + "dependencies": { + "prelude-ls": "~1.1.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/type-fest": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.8.1.tgz", + "integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/typescript": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.1.3.tgz", + "integrity": "sha512-B3ZIOf1IKeH2ixgHhj6la6xdwR9QrLC5d1VKeCSY4tvkqhF2eqd9O7txNlS0PO3GrBAFIdr3L1ndNwteUbZLYg==", + "dev": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=4.2.0" + } + }, + "node_modules/universal-user-agent": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz", + "integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w==" + }, + "node_modules/universalify": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/uri-js": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.2.2.tgz", + "integrity": "sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ==", + "dev": true, + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/uuid": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", + "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", + "bin": { + "uuid": "bin/uuid" + } + }, + "node_modules/v8-compile-cache": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.1.0.tgz", + "integrity": "sha512-usZBT3PW+LOjM25wbqIlZwPeJV+3OSz3M1k1Ws8snlW39dZyYL9lOGC5FgPVHfk0jKmjiDV8Z0mIbVQPiwFs7g==", + "dev": true + }, + "node_modules/validate-npm-package-license": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", + "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", + "dev": true, + "dependencies": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "node_modules/which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "dev": true, + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "which": "bin/which" + } + }, + "node_modules/word-wrap": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz", + "integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + }, + "node_modules/write": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/write/-/write-1.0.3.tgz", + "integrity": "sha512-/lg70HAjtkUgWPVZhZcm+T4hkL8Zbtp1nFNOn3lRrxnlv50SRBv7cR7RqR+GMsd3hUXy9hWBo4CHTbFTcOYwig==", + "dev": true, + "dependencies": { + "mkdirp": "^0.5.1" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/xml2js": { + "version": "0.4.23", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.23.tgz", + "integrity": "sha512-ySPiMjM0+pLDftHgXY4By0uswI3SPKLDw/i3UXbnO8M/p28zqexCUoPmQFrYD+/1BzhGJSs2i1ERWKJAtiLrug==", + "dependencies": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/xmlbuilder": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz", + "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==", + "engines": { + "node": ">=4.0" + } + } + }, "dependencies": { "@actions/cache": { "version": "1.0.6",