/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 5116: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; 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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.saveCache = exports.restoreCache = exports.isFeatureAvailable = exports.ReserveCacheError = exports.ValidationError = void 0; const core = __importStar(__nccwpck_require__(37484)); const path = __importStar(__nccwpck_require__(16928)); const utils = __importStar(__nccwpck_require__(98299)); const cacheHttpClient = __importStar(__nccwpck_require__(73171)); const cacheTwirpClient = __importStar(__nccwpck_require__(96819)); const config_1 = __nccwpck_require__(17606); const tar_1 = __nccwpck_require__(95321); const constants_1 = __nccwpck_require__(58287); 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.`); } } /** * isFeatureAvailable to check the presence of Actions cache service * * @returns boolean return true if Actions cache service feature is available, otherwise false */ function isFeatureAvailable() { return !!process.env['ACTIONS_CACHE_URL']; } exports.isFeatureAvailable = isFeatureAvailable; /** * 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. Lookup is done with prefix matching. * @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for primaryKey * @param downloadOptions cache download options * @param enableCrossOsArchive an optional boolean enabled to restore on windows any cache created on any platform * @returns string returns the key for the cache hit, otherwise returns undefined */ function restoreCache(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { return __awaiter(this, void 0, void 0, function* () { const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); core.debug(`Cache service version: ${cacheServiceVersion}`); checkPaths(paths); switch (cacheServiceVersion) { case 'v2': return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); case 'v1': default: return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); } }); } exports.restoreCache = restoreCache; /** * Restores cache using the legacy Cache Service * * @param paths a list of file paths to restore from the cache * @param primaryKey an explicit key for restoring the cache. Lookup is done with prefix matching. * @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for primaryKey * @param options cache download options * @param enableCrossOsArchive an optional boolean enabled to restore on Windows any cache created on any platform * @returns string returns the key for the cache hit, otherwise returns undefined */ function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { return __awaiter(this, void 0, void 0, function* () { 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(); let archivePath = ''; try { // path are needed to compute version const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { compressionMethod, enableCrossOsArchive }); if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { // Cache not found return undefined; } if (options === null || options === void 0 ? void 0 : options.lookupOnly) { core.info('Lookup only - skipping download'); return cacheEntry.cacheKey; } archivePath = path.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); core.debug(`Archive Path: ${archivePath}`); // Download the cache from the cache entry yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); if (core.isDebug()) { yield (0, tar_1.listTar)(archivePath, compressionMethod); } const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); core.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); yield (0, tar_1.extractTar)(archivePath, compressionMethod); core.info('Cache restored successfully'); // PATCHED - Include size of restored entry return new CacheEntry(cacheEntry.cacheKey, archiveFileSize);; } // PATCHED - propagate errors // catch (error) { // const typedError = error; // if (typedError.name === ValidationError.name) { // throw error; // } // else { // // Supress all non-validation cache related errors because caching should be optional // core.warning(`Failed to restore: ${error.message}`); // } // } finally { // Try to delete the archive to save space try { yield utils.unlinkFile(archivePath); } catch (error) { core.debug(`Failed to delete archive: ${error}`); } } return undefined; }); } /** * Restores cache using Cache Service v2 * * @param paths a list of file paths to restore from the cache * @param primaryKey an explicit key for restoring the cache. Lookup is done with prefix matching * @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for primaryKey * @param downloadOptions cache download options * @param enableCrossOsArchive an optional boolean enabled to restore on windows any cache created on any platform * @returns string returns the key for the cache hit, otherwise returns undefined */ function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { return __awaiter(this, void 0, void 0, function* () { // Override UploadOptions to force the use of Azure options = Object.assign(Object.assign({}, options), { useAzureSdk: true }); 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); } let archivePath = ''; try { const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); const compressionMethod = yield utils.getCompressionMethod(); const request = { key: primaryKey, restoreKeys, version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive) }; const response = yield twirpClient.GetCacheEntryDownloadURL(request); if (!response.ok) { core.debug(`Cache not found for version ${request.version} of keys: ${keys.join(', ')}`); return undefined; } core.info(`Cache hit for: ${request.key}`); if (options === null || options === void 0 ? void 0 : options.lookupOnly) { core.info('Lookup only - skipping download'); return response.matchedKey; } archivePath = path.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); core.debug(`Archive path: ${archivePath}`); core.debug(`Starting download of archive to: ${archivePath}`); yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options); const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); core.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); if (core.isDebug()) { yield (0, tar_1.listTar)(archivePath, compressionMethod); } yield (0, tar_1.extractTar)(archivePath, compressionMethod); core.info('Cache restored successfully'); // PATCHED - Include size of restored entry return new CacheEntry(response.matchedKey, archiveFileSize);; } // PATCHED - propagate errors // catch (error) { // const typedError = error; // if (typedError.name === ValidationError.name) { // throw error; // } // else { // // Supress all non-validation cache related errors because caching should be optional // core.warning(`Failed to restore: ${error.message}`); // } // } finally { try { if (archivePath) { yield utils.unlinkFile(archivePath); } } catch (error) { core.debug(`Failed to delete archive: ${error}`); } } return undefined; }); } /** * 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 enableCrossOsArchive an optional boolean enabled to save cache on windows which could be restored on any platform * @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, enableCrossOsArchive = false) { return __awaiter(this, void 0, void 0, function* () { const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); core.debug(`Cache service version: ${cacheServiceVersion}`); checkPaths(paths); checkKey(key); switch (cacheServiceVersion) { case 'v2': return yield saveCacheV2(paths, key, options, enableCrossOsArchive); case 'v1': default: return yield saveCacheV1(paths, key, options, enableCrossOsArchive); } }); } exports.saveCache = saveCache; /** * Save cache using the legacy Cache Service * * @param paths * @param key * @param options * @param enableCrossOsArchive * @returns */ function saveCacheV1(paths, key, options, enableCrossOsArchive = false) { var _a, _b, _c, _d, _e; return __awaiter(this, void 0, void 0, function* () { const compressionMethod = yield utils.getCompressionMethod(); let cacheId = -1; const cachePaths = yield utils.resolvePaths(paths); core.debug('Cache Paths:'); core.debug(`${JSON.stringify(cachePaths)}`); if (cachePaths.length === 0) { throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); } const archiveFolder = yield utils.createTempDirectory(); const archivePath = path.join(archiveFolder, utils.getCacheFileName(compressionMethod)); core.debug(`Archive Path: ${archivePath}`); try { yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); if (core.isDebug()) { yield (0, tar_1.listTar)(archivePath, compressionMethod); } const fileSizeLimit = 10 * 1024 * 1024 * 1024; // 10GB per repo limit const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); core.debug(`File Size: ${archiveFileSize}`); // For GHES, this check will take place in ReserveCache API with enterprise file size limit if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) { throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); } core.debug('Reserving Cache'); const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, { compressionMethod, enableCrossOsArchive, cacheSize: archiveFileSize }); if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) { cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId; } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) { throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`); } else { throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`); } core.debug(`Saving Cache (ID: ${cacheId})`); yield cacheHttpClient.saveCache(cacheId, archivePath, '', options); // PATCHED - Include size of saved entry return new CacheEntry(key, archiveFileSize); } // PATCHED - propagate errors // catch (error) { // const typedError = error; // if (typedError.name === ValidationError.name) { // throw error; // } // else if (typedError.name === ReserveCacheError.name) { // core.info(`Failed to save: ${typedError.message}`); // } // else { // core.warning(`Failed to save: ${typedError.message}`); // } // } finally { // Try to delete the archive to save space try { yield utils.unlinkFile(archivePath); } catch (error) { core.debug(`Failed to delete archive: ${error}`); } } return cacheId; }); } /** * Save cache using Cache Service v2 * * @param paths a list of file paths to restore from the cache * @param key an explicit key for restoring the cache * @param options cache upload options * @param enableCrossOsArchive an optional boolean enabled to save cache on windows which could be restored on any platform * @returns */ function saveCacheV2(paths, key, options, enableCrossOsArchive = false) { return __awaiter(this, void 0, void 0, function* () { // Override UploadOptions to force the use of Azure // ...options goes first because we want to override the default values // set in UploadOptions with these specific figures options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true }); const compressionMethod = yield utils.getCompressionMethod(); const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); let cacheId = -1; const cachePaths = yield utils.resolvePaths(paths); core.debug('Cache Paths:'); core.debug(`${JSON.stringify(cachePaths)}`); if (cachePaths.length === 0) { throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); } const archiveFolder = yield utils.createTempDirectory(); const archivePath = path.join(archiveFolder, utils.getCacheFileName(compressionMethod)); core.debug(`Archive Path: ${archivePath}`); try { yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); if (core.isDebug()) { yield (0, tar_1.listTar)(archivePath, compressionMethod); } const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); core.debug(`File Size: ${archiveFileSize}`); // For GHES, this check will take place in ReserveCache API with enterprise file size limit if (archiveFileSize > constants_1.CacheFileSizeLimit && !(0, config_1.isGhes)()) { throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); } // Set the archive size in the options, will be used to display the upload progress options.archiveSizeBytes = archiveFileSize; core.debug('Reserving Cache'); const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive); const request = { key, version }; let signedUploadUrl; try { const response = yield twirpClient.CreateCacheEntry(request); if (!response.ok) { throw new Error('Response was not ok'); } signedUploadUrl = response.signedUploadUrl; } catch (error) { core.debug(`Failed to reserve cache: ${error}`); throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); } core.debug(`Attempting to upload cache located at: ${archivePath}`); yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options); const finalizeRequest = { key, version, sizeBytes: `${archiveFileSize}` }; const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest); core.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`); if (!finalizeResponse.ok) { throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`); } cacheId = parseInt(finalizeResponse.entryId); // PATCHED - Include size of saved entry return new CacheEntry(key, archiveFileSize); } // PATCHED - propagate errors // catch (error) { // const typedError = error; // if (typedError.name === ValidationError.name) { // throw error; // } // else if (typedError.name === ReserveCacheError.name) { // core.info(`Failed to save: ${typedError.message}`); // } // else { // core.warning(`Failed to save: ${typedError.message}`); // } // } finally { // Try to delete the archive to save space try { yield utils.unlinkFile(archivePath); } catch (error) { core.debug(`Failed to delete archive: ${error}`); } } return cacheId; }); } // PATCHED - CacheEntry class class CacheEntry { constructor(key, size) { this.key = key; this.size = size; } } //# sourceMappingURL=cache.js.map /***/ }), /***/ 93156: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CacheService = exports.GetCacheEntryDownloadURLResponse = exports.GetCacheEntryDownloadURLRequest = exports.FinalizeCacheEntryUploadResponse = exports.FinalizeCacheEntryUploadRequest = exports.CreateCacheEntryResponse = exports.CreateCacheEntryRequest = void 0; // @generated by protobuf-ts 2.9.1 with parameter long_type_string,client_none,generate_dependencies // @generated from protobuf file "results/api/v1/cache.proto" (package "github.actions.results.api.v1", syntax proto3) // tslint:disable const runtime_rpc_1 = __nccwpck_require__(44420); const runtime_1 = __nccwpck_require__(68886); const runtime_2 = __nccwpck_require__(68886); const runtime_3 = __nccwpck_require__(68886); const runtime_4 = __nccwpck_require__(68886); const runtime_5 = __nccwpck_require__(68886); const cachemetadata_1 = __nccwpck_require__(89444); // @generated message type with reflection information, may provide speed optimized methods class CreateCacheEntryRequest$Type extends runtime_5.MessageType { constructor() { super("github.actions.results.api.v1.CreateCacheEntryRequest", [ { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, { no: 2, name: "key", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 3, name: "version", kind: "scalar", T: 9 /*ScalarType.STRING*/ } ]); } create(value) { const message = { key: "", version: "" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* github.actions.results.entities.v1.CacheMetadata metadata */ 1: message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); break; case /* string key */ 2: message.key = reader.string(); break; case /* string version */ 3: message.version = reader.string(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { /* github.actions.results.entities.v1.CacheMetadata metadata = 1; */ if (message.metadata) cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); /* string key = 2; */ if (message.key !== "") writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); /* string version = 3; */ if (message.version !== "") writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message github.actions.results.api.v1.CreateCacheEntryRequest */ exports.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type(); // @generated message type with reflection information, may provide speed optimized methods class CreateCacheEntryResponse$Type extends runtime_5.MessageType { constructor() { super("github.actions.results.api.v1.CreateCacheEntryResponse", [ { no: 1, name: "ok", kind: "scalar", T: 8 /*ScalarType.BOOL*/ }, { no: 2, name: "signed_upload_url", kind: "scalar", T: 9 /*ScalarType.STRING*/ } ]); } create(value) { const message = { ok: false, signedUploadUrl: "" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* bool ok */ 1: message.ok = reader.bool(); break; case /* string signed_upload_url */ 2: message.signedUploadUrl = reader.string(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { /* bool ok = 1; */ if (message.ok !== false) writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); /* string signed_upload_url = 2; */ if (message.signedUploadUrl !== "") writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message github.actions.results.api.v1.CreateCacheEntryResponse */ exports.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type(); // @generated message type with reflection information, may provide speed optimized methods class FinalizeCacheEntryUploadRequest$Type extends runtime_5.MessageType { constructor() { super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [ { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, { no: 2, name: "key", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 3, name: "size_bytes", kind: "scalar", T: 3 /*ScalarType.INT64*/ }, { no: 4, name: "version", kind: "scalar", T: 9 /*ScalarType.STRING*/ } ]); } create(value) { const message = { key: "", sizeBytes: "0", version: "" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* github.actions.results.entities.v1.CacheMetadata metadata */ 1: message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); break; case /* string key */ 2: message.key = reader.string(); break; case /* int64 size_bytes */ 3: message.sizeBytes = reader.int64().toString(); break; case /* string version */ 4: message.version = reader.string(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { /* github.actions.results.entities.v1.CacheMetadata metadata = 1; */ if (message.metadata) cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); /* string key = 2; */ if (message.key !== "") writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); /* int64 size_bytes = 3; */ if (message.sizeBytes !== "0") writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes); /* string version = 4; */ if (message.version !== "") writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message github.actions.results.api.v1.FinalizeCacheEntryUploadRequest */ exports.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type(); // @generated message type with reflection information, may provide speed optimized methods class FinalizeCacheEntryUploadResponse$Type extends runtime_5.MessageType { constructor() { super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [ { no: 1, name: "ok", kind: "scalar", T: 8 /*ScalarType.BOOL*/ }, { no: 2, name: "entry_id", kind: "scalar", T: 3 /*ScalarType.INT64*/ } ]); } create(value) { const message = { ok: false, entryId: "0" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* bool ok */ 1: message.ok = reader.bool(); break; case /* int64 entry_id */ 2: message.entryId = reader.int64().toString(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { /* bool ok = 1; */ if (message.ok !== false) writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); /* int64 entry_id = 2; */ if (message.entryId !== "0") writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message github.actions.results.api.v1.FinalizeCacheEntryUploadResponse */ exports.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type(); // @generated message type with reflection information, may provide speed optimized methods class GetCacheEntryDownloadURLRequest$Type extends runtime_5.MessageType { constructor() { super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [ { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, { no: 2, name: "key", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 3, name: "restore_keys", kind: "scalar", repeat: 2 /*RepeatType.UNPACKED*/, T: 9 /*ScalarType.STRING*/ }, { no: 4, name: "version", kind: "scalar", T: 9 /*ScalarType.STRING*/ } ]); } create(value) { const message = { key: "", restoreKeys: [], version: "" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* github.actions.results.entities.v1.CacheMetadata metadata */ 1: message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); break; case /* string key */ 2: message.key = reader.string(); break; case /* repeated string restore_keys */ 3: message.restoreKeys.push(reader.string()); break; case /* string version */ 4: message.version = reader.string(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { /* github.actions.results.entities.v1.CacheMetadata metadata = 1; */ if (message.metadata) cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); /* string key = 2; */ if (message.key !== "") writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); /* repeated string restore_keys = 3; */ for (let i = 0; i < message.restoreKeys.length; i++) writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]); /* string version = 4; */ if (message.version !== "") writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message github.actions.results.api.v1.GetCacheEntryDownloadURLRequest */ exports.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type(); // @generated message type with reflection information, may provide speed optimized methods class GetCacheEntryDownloadURLResponse$Type extends runtime_5.MessageType { constructor() { super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [ { no: 1, name: "ok", kind: "scalar", T: 8 /*ScalarType.BOOL*/ }, { no: 2, name: "signed_download_url", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 3, name: "matched_key", kind: "scalar", T: 9 /*ScalarType.STRING*/ } ]); } create(value) { const message = { ok: false, signedDownloadUrl: "", matchedKey: "" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* bool ok */ 1: message.ok = reader.bool(); break; case /* string signed_download_url */ 2: message.signedDownloadUrl = reader.string(); break; case /* string matched_key */ 3: message.matchedKey = reader.string(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { /* bool ok = 1; */ if (message.ok !== false) writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); /* string signed_download_url = 2; */ if (message.signedDownloadUrl !== "") writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl); /* string matched_key = 3; */ if (message.matchedKey !== "") writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message github.actions.results.api.v1.GetCacheEntryDownloadURLResponse */ exports.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type(); /** * @generated ServiceType for protobuf service github.actions.results.api.v1.CacheService */ exports.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [ { name: "CreateCacheEntry", options: {}, I: exports.CreateCacheEntryRequest, O: exports.CreateCacheEntryResponse }, { name: "FinalizeCacheEntryUpload", options: {}, I: exports.FinalizeCacheEntryUploadRequest, O: exports.FinalizeCacheEntryUploadResponse }, { name: "GetCacheEntryDownloadURL", options: {}, I: exports.GetCacheEntryDownloadURLRequest, O: exports.GetCacheEntryDownloadURLResponse } ]); //# sourceMappingURL=cache.js.map /***/ }), /***/ 11486: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CacheServiceClientProtobuf = exports.CacheServiceClientJSON = void 0; const cache_1 = __nccwpck_require__(93156); class CacheServiceClientJSON { constructor(rpc) { this.rpc = rpc; this.CreateCacheEntry.bind(this); this.FinalizeCacheEntryUpload.bind(this); this.GetCacheEntryDownloadURL.bind(this); } CreateCacheEntry(request) { const data = cache_1.CreateCacheEntryRequest.toJson(request, { useProtoFieldName: true, emitDefaultValues: false, }); const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data); return promise.then((data) => cache_1.CreateCacheEntryResponse.fromJson(data, { ignoreUnknownFields: true, })); } FinalizeCacheEntryUpload(request) { const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, { useProtoFieldName: true, emitDefaultValues: false, }); const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data); return promise.then((data) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data, { ignoreUnknownFields: true, })); } GetCacheEntryDownloadURL(request) { const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, { useProtoFieldName: true, emitDefaultValues: false, }); const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data); return promise.then((data) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data, { ignoreUnknownFields: true, })); } } exports.CacheServiceClientJSON = CacheServiceClientJSON; class CacheServiceClientProtobuf { constructor(rpc) { this.rpc = rpc; this.CreateCacheEntry.bind(this); this.FinalizeCacheEntryUpload.bind(this); this.GetCacheEntryDownloadURL.bind(this); } CreateCacheEntry(request) { const data = cache_1.CreateCacheEntryRequest.toBinary(request); const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data); return promise.then((data) => cache_1.CreateCacheEntryResponse.fromBinary(data)); } FinalizeCacheEntryUpload(request) { const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request); const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data); return promise.then((data) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data)); } GetCacheEntryDownloadURL(request) { const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request); const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data); return promise.then((data) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data)); } } exports.CacheServiceClientProtobuf = CacheServiceClientProtobuf; //# sourceMappingURL=cache.twirp-client.js.map /***/ }), /***/ 89444: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CacheMetadata = void 0; const runtime_1 = __nccwpck_require__(68886); const runtime_2 = __nccwpck_require__(68886); const runtime_3 = __nccwpck_require__(68886); const runtime_4 = __nccwpck_require__(68886); const runtime_5 = __nccwpck_require__(68886); const cachescope_1 = __nccwpck_require__(29425); // @generated message type with reflection information, may provide speed optimized methods class CacheMetadata$Type extends runtime_5.MessageType { constructor() { super("github.actions.results.entities.v1.CacheMetadata", [ { no: 1, name: "repository_id", kind: "scalar", T: 3 /*ScalarType.INT64*/ }, { no: 2, name: "scope", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => cachescope_1.CacheScope } ]); } create(value) { const message = { repositoryId: "0", scope: [] }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* int64 repository_id */ 1: message.repositoryId = reader.int64().toString(); break; case /* repeated github.actions.results.entities.v1.CacheScope scope */ 2: message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options)); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { /* int64 repository_id = 1; */ if (message.repositoryId !== "0") writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId); /* repeated github.actions.results.entities.v1.CacheScope scope = 2; */ for (let i = 0; i < message.scope.length; i++) cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message github.actions.results.entities.v1.CacheMetadata */ exports.CacheMetadata = new CacheMetadata$Type(); //# sourceMappingURL=cachemetadata.js.map /***/ }), /***/ 29425: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CacheScope = void 0; const runtime_1 = __nccwpck_require__(68886); const runtime_2 = __nccwpck_require__(68886); const runtime_3 = __nccwpck_require__(68886); const runtime_4 = __nccwpck_require__(68886); const runtime_5 = __nccwpck_require__(68886); // @generated message type with reflection information, may provide speed optimized methods class CacheScope$Type extends runtime_5.MessageType { constructor() { super("github.actions.results.entities.v1.CacheScope", [ { no: 1, name: "scope", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 2, name: "permission", kind: "scalar", T: 3 /*ScalarType.INT64*/ } ]); } create(value) { const message = { scope: "", permission: "0" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* string scope */ 1: message.scope = reader.string(); break; case /* int64 permission */ 2: message.permission = reader.int64().toString(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { /* string scope = 1; */ if (message.scope !== "") writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope); /* int64 permission = 2; */ if (message.permission !== "0") writer.tag(2, runtime_1.WireType.Varint).int64(message.permission); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message github.actions.results.entities.v1.CacheScope */ exports.CacheScope = new CacheScope$Type(); //# sourceMappingURL=cachescope.js.map /***/ }), /***/ 73171: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; 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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.saveCache = exports.reserveCache = exports.downloadCache = exports.getCacheEntry = void 0; const core = __importStar(__nccwpck_require__(37484)); const http_client_1 = __nccwpck_require__(54844); const auth_1 = __nccwpck_require__(44552); const fs = __importStar(__nccwpck_require__(79896)); const url_1 = __nccwpck_require__(87016); const utils = __importStar(__nccwpck_require__(98299)); const uploadUtils_1 = __nccwpck_require__(35268); const downloadUtils_1 = __nccwpck_require__(75067); const options_1 = __nccwpck_require__(98356); const requestUtils_1 = __nccwpck_require__(32846); const config_1 = __nccwpck_require__(17606); const user_agent_1 = __nccwpck_require__(41899); function getCacheApiUrl(resource) { const baseUrl = (0, config_1.getCacheServiceURL)(); 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((0, user_agent_1.getUserAgentString)(), [bearerCredentialHandler], getRequestOptions()); } function getCacheEntry(keys, paths, options) { return __awaiter(this, void 0, void 0, function* () { const httpClient = createHttpClient(); const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive); const resource = `cache?keys=${encodeURIComponent(keys.join(','))}&version=${version}`; const response = yield (0, requestUtils_1.retryTypedResponse)('getCacheEntry', () => __awaiter(this, void 0, void 0, function* () { return httpClient.getJson(getCacheApiUrl(resource)); })); // Cache not found if (response.statusCode === 204) { // List cache for primary key only if cache miss occurs if (core.isDebug()) { yield printCachesListForDiagnostics(keys[0], httpClient, version); } return null; } if (!(0, 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) { // Cache achiveLocation not found. This should never happen, and hence bail out. throw new Error('Cache not found.'); } core.setSecret(cacheDownloadUrl); core.debug(`Cache Result:`); core.debug(JSON.stringify(cacheResult)); return cacheResult; }); } exports.getCacheEntry = getCacheEntry; function printCachesListForDiagnostics(key, httpClient, version) { return __awaiter(this, void 0, void 0, function* () { const resource = `caches?key=${encodeURIComponent(key)}`; const response = yield (0, requestUtils_1.retryTypedResponse)('listCache', () => __awaiter(this, void 0, void 0, function* () { return httpClient.getJson(getCacheApiUrl(resource)); })); if (response.statusCode === 200) { const cacheListResult = response.result; const totalCount = cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.totalCount; if (totalCount && totalCount > 0) { core.debug(`No matching cache found for cache key '${key}', version '${version} and scope ${process.env['GITHUB_REF']}. There exist one or more cache(s) with similar key but they have different version or scope. See more info on cache matching here: https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#matching-a-cache-key \nOther caches with similar key:`); for (const cacheEntry of (cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.artifactCaches) || []) { core.debug(`Cache Key: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheKey}, Cache Version: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheVersion}, Cache Scope: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.scope}, Cache Created: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.creationTime}`); } } } }); } function downloadCache(archiveLocation, archivePath, options) { return __awaiter(this, void 0, void 0, function* () { const archiveUrl = new url_1.URL(archiveLocation); const downloadOptions = (0, options_1.getDownloadOptions)(options); if (archiveUrl.hostname.endsWith('.blob.core.windows.net')) { if (downloadOptions.useAzureSdk) { // Use Azure storage SDK to download caches hosted on Azure to improve speed and reliability. yield (0, downloadUtils_1.downloadCacheStorageSDK)(archiveLocation, archivePath, downloadOptions); } else if (downloadOptions.concurrentBlobDownloads) { // Use concurrent implementation with HttpClient to work around blob SDK issue yield (0, downloadUtils_1.downloadCacheHttpClientConcurrent)(archiveLocation, archivePath, downloadOptions); } else { // Otherwise, download using the Actions http-client. yield (0, downloadUtils_1.downloadCacheHttpClient)(archiveLocation, archivePath); } } else { yield (0, downloadUtils_1.downloadCacheHttpClient)(archiveLocation, archivePath); } }); } exports.downloadCache = downloadCache; // Reserve Cache function reserveCache(key, paths, options) { return __awaiter(this, void 0, void 0, function* () { const httpClient = createHttpClient(); const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive); const reserveCacheRequest = { key, version, cacheSize: options === null || options === void 0 ? void 0 : options.cacheSize }; const response = yield (0, requestUtils_1.retryTypedResponse)('reserveCache', () => __awaiter(this, void 0, void 0, function* () { return httpClient.postJson(getCacheApiUrl('caches'), reserveCacheRequest); })); return response; }); } 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 (0, requestUtils_1.retryHttpClientResponse)(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter(this, void 0, void 0, function* () { return httpClient.sendStream('PATCH', resourceUrl, openStream(), additionalHeaders); })); if (!(0, 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 = utils.getArchiveFileSizeInBytes(archivePath); const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`); const fd = fs.openSync(archivePath, 'r'); const uploadOptions = (0, 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 (0, requestUtils_1.retryTypedResponse)('commitCache', () => __awaiter(this, void 0, void 0, function* () { return httpClient.postJson(getCacheApiUrl(`caches/${cacheId.toString()}`), commitCacheRequest); })); }); } function saveCache(cacheId, archivePath, signedUploadURL, options) { return __awaiter(this, void 0, void 0, function* () { const uploadOptions = (0, options_1.getUploadOptions)(options); if (uploadOptions.useAzureSdk) { // Use Azure storage SDK to upload caches directly to Azure if (!signedUploadURL) { throw new Error('Azure Storage SDK can only be used when a signed URL is provided.'); } yield (0, uploadUtils_1.uploadCacheArchiveSDK)(signedUploadURL, archivePath, options); } else { const httpClient = createHttpClient(); core.debug('Upload cache'); yield uploadFile(httpClient, cacheId, archivePath, options); // Commit Cache core.debug('Commiting cache'); const cacheSize = utils.getArchiveFileSizeInBytes(archivePath); core.info(`Cache Size: ~${Math.round(cacheSize / (1024 * 1024))} MB (${cacheSize} B)`); const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize); if (!(0, 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 /***/ }), /***/ 98299: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; 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); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRuntimeToken = exports.getCacheVersion = exports.assertDefined = exports.getGnuTarPathOnWindows = exports.getCacheFileName = exports.getCompressionMethod = exports.unlinkFile = exports.resolvePaths = exports.getArchiveFileSizeInBytes = exports.createTempDirectory = void 0; const core = __importStar(__nccwpck_require__(37484)); const exec = __importStar(__nccwpck_require__(95236)); const glob = __importStar(__nccwpck_require__(39688)); const io = __importStar(__nccwpck_require__(94994)); const crypto = __importStar(__nccwpck_require__(76982)); const fs = __importStar(__nccwpck_require__(79896)); const path = __importStar(__nccwpck_require__(16928)); const semver = __importStar(__nccwpck_require__(53272)); const util = __importStar(__nccwpck_require__(39023)); const constants_1 = __nccwpck_require__(58287); const versionSalt = '1.0'; // 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, crypto.randomUUID()); yield io.mkdirP(dest); return dest; }); } exports.createTempDirectory = createTempDirectory; function getArchiveFileSizeInBytes(filePath) { return fs.statSync(filePath).size; } exports.getArchiveFileSizeInBytes = getArchiveFileSizeInBytes; function resolvePaths(patterns) { var _a, e_1, _b, _c; var _d; return __awaiter(this, void 0, void 0, function* () { const paths = []; const workspace = (_d = process.env['GITHUB_WORKSPACE']) !== null && _d !== void 0 ? _d : process.cwd(); const globber = yield glob.create(patterns.join('\n'), { implicitDescendants: false }); try { for (var _e = true, _f = __asyncValues(globber.globGenerator()), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) { _c = _g.value; _e = false; const file = _c; 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. if (relativeFile === '') { // path.relative returns empty string if workspace and file are equal paths.push('.'); } else { paths.push(`${relativeFile}`); } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (!_e && !_a && (_b = _f.return)) yield _b.call(_f); } 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, additionalArgs = []) { return __awaiter(this, void 0, void 0, function* () { let versionOutput = ''; additionalArgs.push('--version'); core.debug(`Checking ${app} ${additionalArgs.join(' ')}`); try { yield exec.exec(`${app}`, additionalArgs, { 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* () { const versionOutput = yield getVersion('zstd', ['--quiet']); const version = semver.clean(versionOutput); core.debug(`zstd version: ${version}`); if (versionOutput === '') { return constants_1.CompressionMethod.Gzip; } else { return constants_1.CompressionMethod.ZstdWithoutLong; } }); } exports.getCompressionMethod = getCompressionMethod; function getCacheFileName(compressionMethod) { return compressionMethod === constants_1.CompressionMethod.Gzip ? constants_1.CacheFilename.Gzip : constants_1.CacheFilename.Zstd; } exports.getCacheFileName = getCacheFileName; function getGnuTarPathOnWindows() { return __awaiter(this, void 0, void 0, function* () { if (fs.existsSync(constants_1.GnuTarPathOnWindows)) { return constants_1.GnuTarPathOnWindows; } const versionOutput = yield getVersion('tar'); return versionOutput.toLowerCase().includes('gnu tar') ? io.which('tar') : ''; }); } exports.getGnuTarPathOnWindows = getGnuTarPathOnWindows; function assertDefined(name, value) { if (value === undefined) { throw Error(`Expected ${name} but value was undefiend`); } return value; } exports.assertDefined = assertDefined; function getCacheVersion(paths, compressionMethod, enableCrossOsArchive = false) { // don't pass changes upstream const components = paths.slice(); // Add compression method to cache version to restore // compressed cache as per compression method if (compressionMethod) { components.push(compressionMethod); } // Only check for windows platforms if enableCrossOsArchive is false if (process.platform === 'win32' && !enableCrossOsArchive) { components.push('windows-only'); } // 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 getRuntimeToken() { const token = process.env['ACTIONS_RUNTIME_TOKEN']; if (!token) { throw new Error('Unable to get the ACTIONS_RUNTIME_TOKEN env variable'); } return token; } exports.getRuntimeToken = getRuntimeToken; //# sourceMappingURL=cacheUtils.js.map /***/ }), /***/ 17606: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getCacheServiceURL = exports.getCacheServiceVersion = exports.isGhes = void 0; function isGhes() { const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); const hostname = ghUrl.hostname.trimEnd().toUpperCase(); const isGitHubHost = hostname === 'GITHUB.COM'; const isGheHost = hostname.endsWith('.GHE.COM'); const isLocalHost = hostname.endsWith('.LOCALHOST'); return !isGitHubHost && !isGheHost && !isLocalHost; } exports.isGhes = isGhes; function getCacheServiceVersion() { // Cache service v2 is not supported on GHES. We will default to // cache service v1 even if the feature flag was enabled by user. if (isGhes()) return 'v1'; return process.env['ACTIONS_CACHE_SERVICE_V2'] ? 'v2' : 'v1'; } exports.getCacheServiceVersion = getCacheServiceVersion; function getCacheServiceURL() { const version = getCacheServiceVersion(); // Based on the version of the cache service, we will determine which // URL to use. switch (version) { case 'v1': return (process.env['ACTIONS_CACHE_URL'] || process.env['ACTIONS_RESULTS_URL'] || ''); case 'v2': return process.env['ACTIONS_RESULTS_URL'] || ''; default: throw new Error(`Unsupported cache service version: ${version}`); } } exports.getCacheServiceURL = getCacheServiceURL; //# sourceMappingURL=config.js.map /***/ }), /***/ 58287: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CacheFileSizeLimit = exports.ManifestFilename = exports.TarFilename = exports.SystemTarPathOnWindows = exports.GnuTarPathOnWindows = exports.SocketTimeout = exports.DefaultRetryDelay = exports.DefaultRetryAttempts = exports.ArchiveToolType = exports.CompressionMethod = exports.CacheFilename = void 0; var CacheFilename; (function (CacheFilename) { CacheFilename["Gzip"] = "cache.tgz"; CacheFilename["Zstd"] = "cache.tzst"; })(CacheFilename || (exports.CacheFilename = 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 = CompressionMethod = {})); var ArchiveToolType; (function (ArchiveToolType) { ArchiveToolType["GNU"] = "gnu"; ArchiveToolType["BSD"] = "bsd"; })(ArchiveToolType || (exports.ArchiveToolType = ArchiveToolType = {})); // 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; // The default path of GNUtar on hosted Windows runners exports.GnuTarPathOnWindows = `${process.env['PROGRAMFILES']}\\Git\\usr\\bin\\tar.exe`; // The default path of BSDtar on hosted Windows runners exports.SystemTarPathOnWindows = `${process.env['SYSTEMDRIVE']}\\Windows\\System32\\tar.exe`; exports.TarFilename = 'cache.tar'; exports.ManifestFilename = 'manifest.txt'; exports.CacheFileSizeLimit = 10 * Math.pow(1024, 3); // 10GiB per repository //# sourceMappingURL=constants.js.map /***/ }), /***/ 75067: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; 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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.downloadCacheStorageSDK = exports.downloadCacheHttpClientConcurrent = exports.downloadCacheHttpClient = exports.DownloadProgress = void 0; const core = __importStar(__nccwpck_require__(37484)); const http_client_1 = __nccwpck_require__(54844); const storage_blob_1 = __nccwpck_require__(1012); const buffer = __importStar(__nccwpck_require__(20181)); const fs = __importStar(__nccwpck_require__(79896)); const stream = __importStar(__nccwpck_require__(2203)); const util = __importStar(__nccwpck_require__(39023)); const utils = __importStar(__nccwpck_require__(98299)); const constants_1 = __nccwpck_require__(58287); const requestUtils_1 = __nccwpck_require__(32846); const abort_controller_1 = __nccwpck_require__(68110); /** * 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 (0, 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.getArchiveFileSizeInBytes(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 Actions toolkit http-client concurrently * * @param archiveLocation the URL for the cache * @param archivePath the local path where the cache is saved */ function downloadCacheHttpClientConcurrent(archiveLocation, archivePath, options) { var _a; return __awaiter(this, void 0, void 0, function* () { const archiveDescriptor = yield fs.promises.open(archivePath, 'w'); const httpClient = new http_client_1.HttpClient('actions/cache', undefined, { socketTimeout: options.timeoutInMs, keepAlive: true }); try { const res = yield (0, requestUtils_1.retryHttpClientResponse)('downloadCacheMetadata', () => __awaiter(this, void 0, void 0, function* () { return yield httpClient.request('HEAD', archiveLocation, null, {}); })); const lengthHeader = res.message.headers['content-length']; if (lengthHeader === undefined || lengthHeader === null) { throw new Error('Content-Length not found on blob response'); } const length = parseInt(lengthHeader); if (Number.isNaN(length)) { throw new Error(`Could not interpret Content-Length: ${length}`); } const downloads = []; const blockSize = 4 * 1024 * 1024; for (let offset = 0; offset < length; offset += blockSize) { const count = Math.min(blockSize, length - offset); downloads.push({ offset, promiseGetter: () => __awaiter(this, void 0, void 0, function* () { return yield downloadSegmentRetry(httpClient, archiveLocation, offset, count); }) }); } // reverse to use .pop instead of .shift downloads.reverse(); let actives = 0; let bytesDownloaded = 0; const progress = new DownloadProgress(length); progress.startDisplayTimer(); const progressFn = progress.onProgress(); const activeDownloads = []; let nextDownload; const waitAndWrite = () => __awaiter(this, void 0, void 0, function* () { const segment = yield Promise.race(Object.values(activeDownloads)); yield archiveDescriptor.write(segment.buffer, 0, segment.count, segment.offset); actives--; delete activeDownloads[segment.offset]; bytesDownloaded += segment.count; progressFn({ loadedBytes: bytesDownloaded }); }); while ((nextDownload = downloads.pop())) { activeDownloads[nextDownload.offset] = nextDownload.promiseGetter(); actives++; if (actives >= ((_a = options.downloadConcurrency) !== null && _a !== void 0 ? _a : 10)) { yield waitAndWrite(); } } while (actives > 0) { yield waitAndWrite(); } } finally { httpClient.dispose(); yield archiveDescriptor.close(); } }); } exports.downloadCacheHttpClientConcurrent = downloadCacheHttpClientConcurrent; function downloadSegmentRetry(httpClient, archiveLocation, offset, count) { return __awaiter(this, void 0, void 0, function* () { const retries = 5; let failures = 0; while (true) { try { const timeout = 30000; const result = yield promiseWithTimeout(timeout, downloadSegment(httpClient, archiveLocation, offset, count)); if (typeof result === 'string') { throw new Error('downloadSegmentRetry failed due to timeout'); } return result; } catch (err) { if (failures >= retries) { throw err; } failures++; } } }); } function downloadSegment(httpClient, archiveLocation, offset, count) { return __awaiter(this, void 0, void 0, function* () { const partRes = yield (0, requestUtils_1.retryHttpClientResponse)('downloadCachePart', () => __awaiter(this, void 0, void 0, function* () { return yield httpClient.get(archiveLocation, { Range: `bytes=${offset}-${offset + count - 1}` }); })); if (!partRes.readBodyBuffer) { throw new Error('Expected HttpClientResponse to implement readBodyBuffer'); } return { offset, count, buffer: yield partRes.readBodyBuffer() }; }); } /** * 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 // ~2 GB = 2147483647, beyond this, we start getting out of range error. So, capping it accordingly. // Updated segment size to 128MB = 134217728 bytes, to complete a segment faster and fail fast const maxSegmentSize = Math.min(134217728, buffer.constants.MAX_LENGTH); const downloadProgress = new DownloadProgress(contentLength); const fd = fs.openSync(archivePath, 'w'); try { downloadProgress.startDisplayTimer(); const controller = new abort_controller_1.AbortController(); const abortSignal = controller.signal; while (!downloadProgress.isDone()) { const segmentStart = downloadProgress.segmentOffset + downloadProgress.segmentSize; const segmentSize = Math.min(maxSegmentSize, contentLength - segmentStart); downloadProgress.nextSegment(segmentSize); const result = yield promiseWithTimeout(options.segmentTimeoutInMs || 3600000, client.downloadToBuffer(segmentStart, segmentSize, { abortSignal, concurrency: options.downloadConcurrency, onProgress: downloadProgress.onProgress() })); if (result === 'timeout') { controller.abort(); throw new Error('Aborting cache download as the download time exceeded the timeout.'); } else if (Buffer.isBuffer(result)) { fs.writeFileSync(fd, result); } } } finally { downloadProgress.stopDisplayTimer(); fs.closeSync(fd); } } }); } exports.downloadCacheStorageSDK = downloadCacheStorageSDK; const promiseWithTimeout = (timeoutMs, promise) => __awaiter(void 0, void 0, void 0, function* () { let timeoutHandle; const timeoutPromise = new Promise(resolve => { timeoutHandle = setTimeout(() => resolve('timeout'), timeoutMs); }); return Promise.race([promise, timeoutPromise]).then(result => { clearTimeout(timeoutHandle); return result; }); }); //# sourceMappingURL=downloadUtils.js.map /***/ }), /***/ 32846: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; 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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.retryHttpClientResponse = exports.retryTypedResponse = exports.retry = exports.isRetryableStatusCode = exports.isServerErrorStatusCode = exports.isSuccessStatusCode = void 0; const core = __importStar(__nccwpck_require__(37484)); const http_client_1 = __nccwpck_require__(54844); const constants_1 = __nccwpck_require__(58287); 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 TypedResponse so it can be processed by the retry logic. (error) => { if (error instanceof http_client_1.HttpClientError) { return { statusCode: error.statusCode, result: null, headers: {}, error }; } 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 /***/ }), /***/ 96819: /***/ (function(__unused_webpack_module, exports, __nccwpck_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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.internalCacheTwirpClient = void 0; const core_1 = __nccwpck_require__(37484); const user_agent_1 = __nccwpck_require__(41899); const errors_1 = __nccwpck_require__(50263); const config_1 = __nccwpck_require__(17606); const cacheUtils_1 = __nccwpck_require__(98299); const auth_1 = __nccwpck_require__(44552); const http_client_1 = __nccwpck_require__(54844); const cache_twirp_client_1 = __nccwpck_require__(11486); const util_1 = __nccwpck_require__(27564); /** * This class is a wrapper around the CacheServiceClientJSON class generated by Twirp. * * It adds retry logic to the request method, which is not present in the generated client. * * This class is used to interact with cache service v2. */ class CacheServiceClient { constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { this.maxAttempts = 5; this.baseRetryIntervalMilliseconds = 3000; this.retryMultiplier = 1.5; const token = (0, cacheUtils_1.getRuntimeToken)(); this.baseUrl = (0, config_1.getCacheServiceURL)(); if (maxAttempts) { this.maxAttempts = maxAttempts; } if (baseRetryIntervalMilliseconds) { this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds; } if (retryMultiplier) { this.retryMultiplier = retryMultiplier; } this.httpClient = new http_client_1.HttpClient(userAgent, [ new auth_1.BearerCredentialHandler(token) ]); } // This function satisfies the Rpc interface. It is compatible with the JSON // JSON generated client. request(service, method, contentType, data) { return __awaiter(this, void 0, void 0, function* () { const url = new URL(`/twirp/${service}/${method}`, this.baseUrl).href; (0, core_1.debug)(`[Request] ${method} ${url}`); const headers = { 'Content-Type': contentType }; try { const { body } = yield this.retryableRequest(() => __awaiter(this, void 0, void 0, function* () { return this.httpClient.post(url, JSON.stringify(data), headers); })); return body; } catch (error) { throw new Error(`Failed to ${method}: ${error.message}`); } }); } retryableRequest(operation) { return __awaiter(this, void 0, void 0, function* () { let attempt = 0; let errorMessage = ''; let rawBody = ''; while (attempt < this.maxAttempts) { let isRetryable = false; try { const response = yield operation(); const statusCode = response.message.statusCode; rawBody = yield response.readBody(); (0, core_1.debug)(`[Response] - ${response.message.statusCode}`); (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`); const body = JSON.parse(rawBody); (0, util_1.maskSecretUrls)(body); (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`); if (this.isSuccessStatusCode(statusCode)) { return { response, body }; } isRetryable = this.isRetryableHttpStatusCode(statusCode); errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`; if (body.msg) { if (errors_1.UsageError.isUsageErrorMessage(body.msg)) { throw new errors_1.UsageError(); } errorMessage = `${errorMessage}: ${body.msg}`; } } catch (error) { if (error instanceof SyntaxError) { (0, core_1.debug)(`Raw Body: ${rawBody}`); } if (error instanceof errors_1.UsageError) { throw error; } if (errors_1.NetworkError.isNetworkErrorCode(error === null || error === void 0 ? void 0 : error.code)) { throw new errors_1.NetworkError(error === null || error === void 0 ? void 0 : error.code); } isRetryable = true; errorMessage = error.message; } if (!isRetryable) { throw new Error(`Received non-retryable error: ${errorMessage}`); } if (attempt + 1 === this.maxAttempts) { throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`); } const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt); (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`); yield this.sleep(retryTimeMilliseconds); attempt++; } throw new Error(`Request failed`); }); } isSuccessStatusCode(statusCode) { if (!statusCode) return false; return statusCode >= 200 && statusCode < 300; } isRetryableHttpStatusCode(statusCode) { if (!statusCode) return false; const retryableStatusCodes = [ http_client_1.HttpCodes.BadGateway, http_client_1.HttpCodes.GatewayTimeout, http_client_1.HttpCodes.InternalServerError, http_client_1.HttpCodes.ServiceUnavailable, http_client_1.HttpCodes.TooManyRequests ]; return retryableStatusCodes.includes(statusCode); } sleep(milliseconds) { return __awaiter(this, void 0, void 0, function* () { return new Promise(resolve => setTimeout(resolve, milliseconds)); }); } getExponentialRetryTimeMilliseconds(attempt) { if (attempt < 0) { throw new Error('attempt should be a positive integer'); } if (attempt === 0) { return this.baseRetryIntervalMilliseconds; } const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt); const maxTime = minTime * this.retryMultiplier; // returns a random number between minTime and maxTime (exclusive) return Math.trunc(Math.random() * (maxTime - minTime) + minTime); } } function internalCacheTwirpClient(options) { const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier); return new cache_twirp_client_1.CacheServiceClientJSON(client); } exports.internalCacheTwirpClient = internalCacheTwirpClient; //# sourceMappingURL=cacheTwirpClient.js.map /***/ }), /***/ 50263: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UsageError = exports.NetworkError = exports.GHESNotSupportedError = exports.CacheNotFoundError = exports.InvalidResponseError = exports.FilesNotFoundError = void 0; class FilesNotFoundError extends Error { constructor(files = []) { let message = 'No files were found to upload'; if (files.length > 0) { message += `: ${files.join(', ')}`; } super(message); this.files = files; this.name = 'FilesNotFoundError'; } } exports.FilesNotFoundError = FilesNotFoundError; class InvalidResponseError extends Error { constructor(message) { super(message); this.name = 'InvalidResponseError'; } } exports.InvalidResponseError = InvalidResponseError; class CacheNotFoundError extends Error { constructor(message = 'Cache not found') { super(message); this.name = 'CacheNotFoundError'; } } exports.CacheNotFoundError = CacheNotFoundError; class GHESNotSupportedError extends Error { constructor(message = '@actions/cache v4.1.4+, actions/cache/save@v4+ and actions/cache/restore@v4+ are not currently supported on GHES.') { super(message); this.name = 'GHESNotSupportedError'; } } exports.GHESNotSupportedError = GHESNotSupportedError; class NetworkError extends Error { constructor(code) { const message = `Unable to make request: ${code}\nIf you are using self-hosted runners, please make sure your runner has access to all GitHub endpoints: https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/about-self-hosted-runners#communication-between-self-hosted-runners-and-github`; super(message); this.code = code; this.name = 'NetworkError'; } } exports.NetworkError = NetworkError; NetworkError.isNetworkErrorCode = (code) => { if (!code) return false; return [ 'ECONNRESET', 'ENOTFOUND', 'ETIMEDOUT', 'ECONNREFUSED', 'EHOSTUNREACH' ].includes(code); }; class UsageError extends Error { constructor() { const message = `Cache storage quota has been hit. Unable to upload any new cache entries. Usage is recalculated every 6-12 hours.\nMore info on storage limits: https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions#calculating-minute-and-storage-spending`; super(message); this.name = 'UsageError'; } } exports.UsageError = UsageError; UsageError.isUsageErrorMessage = (msg) => { if (!msg) return false; return msg.includes('insufficient usage'); }; //# sourceMappingURL=errors.js.map /***/ }), /***/ 41899: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getUserAgentString = void 0; // eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports const packageJson = __nccwpck_require__(64012); /** * Ensure that this User Agent String is used in all HTTP calls so that we can monitor telemetry between different versions of this package */ function getUserAgentString() { return `@actions/cache-${packageJson.version}`; } exports.getUserAgentString = getUserAgentString; //# sourceMappingURL=user-agent.js.map /***/ }), /***/ 27564: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.maskSecretUrls = exports.maskSigUrl = void 0; const core_1 = __nccwpck_require__(37484); /** * Masks the `sig` parameter in a URL and sets it as a secret. * * @param url - The URL containing the signature parameter to mask * @remarks * This function attempts to parse the provided URL and identify the 'sig' query parameter. * If found, it registers both the raw and URL-encoded signature values as secrets using * the Actions `setSecret` API, which prevents them from being displayed in logs. * * The function handles errors gracefully if URL parsing fails, logging them as debug messages. * * @example * ```typescript * // Mask a signature in an Azure SAS token URL * maskSigUrl('https://example.blob.core.windows.net/container/file.txt?sig=abc123&se=2023-01-01'); * ``` */ function maskSigUrl(url) { if (!url) return; try { const parsedUrl = new URL(url); const signature = parsedUrl.searchParams.get('sig'); if (signature) { (0, core_1.setSecret)(signature); (0, core_1.setSecret)(encodeURIComponent(signature)); } } catch (error) { (0, core_1.debug)(`Failed to parse URL: ${url} ${error instanceof Error ? error.message : String(error)}`); } } exports.maskSigUrl = maskSigUrl; /** * Masks sensitive information in URLs containing signature parameters. * Currently supports masking 'sig' parameters in the 'signed_upload_url' * and 'signed_download_url' properties of the provided object. * * @param body - The object should contain a signature * @remarks * This function extracts URLs from the object properties and calls maskSigUrl * on each one to redact sensitive signature information. The function doesn't * modify the original object; it only marks the signatures as secrets for * logging purposes. * * @example * ```typescript * const responseBody = { * signed_upload_url: 'https://blob.core.windows.net/?sig=abc123', * signed_download_url: 'https://blob.core/windows.net/?sig=def456' * }; * maskSecretUrls(responseBody); * ``` */ function maskSecretUrls(body) { if (typeof body !== 'object' || body === null) { (0, core_1.debug)('body is not an object or is null'); return; } if ('signed_upload_url' in body && typeof body.signed_upload_url === 'string') { maskSigUrl(body.signed_upload_url); } if ('signed_download_url' in body && typeof body.signed_download_url === 'string') { maskSigUrl(body.signed_download_url); } } exports.maskSecretUrls = maskSecretUrls; //# sourceMappingURL=util.js.map /***/ }), /***/ 95321: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; 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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createTar = exports.extractTar = exports.listTar = void 0; const exec_1 = __nccwpck_require__(95236); const io = __importStar(__nccwpck_require__(94994)); const fs_1 = __nccwpck_require__(79896); const path = __importStar(__nccwpck_require__(16928)); const utils = __importStar(__nccwpck_require__(98299)); const constants_1 = __nccwpck_require__(58287); const IS_WINDOWS = process.platform === 'win32'; // Returns tar path and type: BSD or GNU function getTarPath() { return __awaiter(this, void 0, void 0, function* () { switch (process.platform) { case 'win32': { const gnuTar = yield utils.getGnuTarPathOnWindows(); const systemTar = constants_1.SystemTarPathOnWindows; if (gnuTar) { // Use GNUtar as default on windows return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; } else if ((0, fs_1.existsSync)(systemTar)) { return { path: systemTar, type: constants_1.ArchiveToolType.BSD }; } break; } case 'darwin': { const gnuTar = yield io.which('gtar', false); if (gnuTar) { // fix permission denied errors when extracting BSD tar archive with GNU tar - https://github.com/actions/cache/issues/527 return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; } else { return { path: yield io.which('tar', true), type: constants_1.ArchiveToolType.BSD }; } } default: break; } // Default assumption is GNU tar is present in path return { path: yield io.which('tar', true), type: constants_1.ArchiveToolType.GNU }; }); } // Return arguments for tar as per tarPath, compressionMethod, method type and os function getTarArgs(tarPath, compressionMethod, type, archivePath = '') { return __awaiter(this, void 0, void 0, function* () { const args = [`"${tarPath.path}"`]; const cacheFileName = utils.getCacheFileName(compressionMethod); const tarFile = 'cache.tar'; const workingDirectory = getWorkingDirectory(); // Speficic args for BSD tar on windows for workaround const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; // Method specific args switch (type) { case 'create': args.push('--posix', '-cf', BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), '--exclude', BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), '-P', '-C', workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), '--files-from', constants_1.ManifestFilename); break; case 'extract': args.push('-xf', BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), '-P', '-C', workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/')); break; case 'list': args.push('-tf', BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), '-P'); break; } // Platform specific args if (tarPath.type === constants_1.ArchiveToolType.GNU) { switch (process.platform) { case 'win32': args.push('--force-local'); break; case 'darwin': args.push('--delay-directory-restore'); break; } } return args; }); } // Returns commands to run tar and compression program function getCommands(compressionMethod, type, archivePath = '') { return __awaiter(this, void 0, void 0, function* () { let args; const tarPath = yield getTarPath(); const tarArgs = yield getTarArgs(tarPath, compressionMethod, type, archivePath); const compressionArgs = type !== 'create' ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod); const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; if (BSD_TAR_ZSTD && type !== 'create') { args = [[...compressionArgs].join(' '), [...tarArgs].join(' ')]; } else { args = [[...tarArgs].join(' '), [...compressionArgs].join(' ')]; } if (BSD_TAR_ZSTD) { return args; } return [args.join(' ')]; }); } function getWorkingDirectory() { var _a; return (_a = process.env['GITHUB_WORKSPACE']) !== null && _a !== void 0 ? _a : process.cwd(); } // Common function for extractTar and listTar to get the compression method function getDecompressionProgram(tarPath, compressionMethod, archivePath) { return __awaiter(this, void 0, void 0, function* () { // -d: Decompress. // unzstd is equivalent to 'zstd -d' // --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. const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; switch (compressionMethod) { case constants_1.CompressionMethod.Zstd: return BSD_TAR_ZSTD ? [ 'zstd -d --long=30 --force -o', constants_1.TarFilename, archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/') ] : [ '--use-compress-program', IS_WINDOWS ? '"zstd -d --long=30"' : 'unzstd --long=30' ]; case constants_1.CompressionMethod.ZstdWithoutLong: return BSD_TAR_ZSTD ? [ 'zstd -d --force -o', constants_1.TarFilename, archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/') ] : ['--use-compress-program', IS_WINDOWS ? '"zstd -d"' : 'unzstd']; default: return ['-z']; } }); } // Used for creating the archive // -T#: Compress using # working thread. If # is 0, attempt to detect and use the number of physical CPU cores. // zstdmt is equivalent to 'zstd -T0' // --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(tarPath, compressionMethod) { return __awaiter(this, void 0, void 0, function* () { const cacheFileName = utils.getCacheFileName(compressionMethod); const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; switch (compressionMethod) { case constants_1.CompressionMethod.Zstd: return BSD_TAR_ZSTD ? [ 'zstd -T0 --long=30 --force -o', cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), constants_1.TarFilename ] : [ '--use-compress-program', IS_WINDOWS ? '"zstd -T0 --long=30"' : 'zstdmt --long=30' ]; case constants_1.CompressionMethod.ZstdWithoutLong: return BSD_TAR_ZSTD ? [ 'zstd -T0 --force -o', cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), constants_1.TarFilename ] : ['--use-compress-program', IS_WINDOWS ? '"zstd -T0"' : 'zstdmt']; default: return ['-z']; } }); } // Executes all commands as separate processes function execCommands(commands, cwd) { return __awaiter(this, void 0, void 0, function* () { for (const command of commands) { try { yield (0, exec_1.exec)(command, undefined, { cwd, env: Object.assign(Object.assign({}, process.env), { MSYS: 'winsymlinks:nativestrict' }) }); } catch (error) { throw new Error(`${command.split(' ')[0]} failed with error: ${error === null || error === void 0 ? void 0 : error.message}`); } } }); } // List the contents of a tar function listTar(archivePath, compressionMethod) { return __awaiter(this, void 0, void 0, function* () { const commands = yield getCommands(compressionMethod, 'list', archivePath); yield execCommands(commands); }); } exports.listTar = listTar; // Extract a tar 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); const commands = yield getCommands(compressionMethod, 'extract', archivePath); yield execCommands(commands); }); } exports.extractTar = extractTar; // Create a tar function createTar(archiveFolder, sourceDirectories, compressionMethod) { return __awaiter(this, void 0, void 0, function* () { // Write source directories to manifest.txt to avoid command length limits (0, fs_1.writeFileSync)(path.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join('\n')); const commands = yield getCommands(compressionMethod, 'create'); yield execCommands(commands, archiveFolder); }); } exports.createTar = createTar; //# sourceMappingURL=tar.js.map /***/ }), /***/ 35268: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; 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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.uploadCacheArchiveSDK = exports.UploadProgress = void 0; const core = __importStar(__nccwpck_require__(37484)); const storage_blob_1 = __nccwpck_require__(1012); const errors_1 = __nccwpck_require__(50263); /** * Class for tracking the upload state and displaying stats. */ class UploadProgress { constructor(contentLength) { this.contentLength = contentLength; this.sentBytes = 0; this.displayedComplete = false; this.startTime = Date.now(); } /** * Sets the number of bytes sent * * @param sentBytes the number of bytes sent */ setSentBytes(sentBytes) { this.sentBytes = sentBytes; } /** * Returns the total number of bytes transferred. */ getTransferredBytes() { return this.sentBytes; } /** * Returns true if the upload is complete. */ isDone() { return this.getTransferredBytes() === this.contentLength; } /** * Prints the current upload stats. Once the upload completes, this will print one * last line and then stop. */ display() { if (this.displayedComplete) { return; } const transferredBytes = this.sentBytes; const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); const elapsedTime = Date.now() - this.startTime; const uploadSpeed = (transferredBytes / (1024 * 1024) / (elapsedTime / 1000)).toFixed(1); core.info(`Sent ${transferredBytes} of ${this.contentLength} (${percentage}%), ${uploadSpeed} MBs/sec`); if (this.isDone()) { this.displayedComplete = true; } } /** * Returns a function used to handle TransferProgressEvents. */ onProgress() { return (progress) => { this.setSentBytes(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 upload * 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.UploadProgress = UploadProgress; /** * Uploads a cache archive directly to Azure Blob Storage using the Azure SDK. * This function will display progress information to the console. Concurrency of the * upload is determined by the calling functions. * * @param signedUploadURL * @param archivePath * @param options * @returns */ function uploadCacheArchiveSDK(signedUploadURL, archivePath, options) { var _a; return __awaiter(this, void 0, void 0, function* () { const blobClient = new storage_blob_1.BlobClient(signedUploadURL); const blockBlobClient = blobClient.getBlockBlobClient(); const uploadProgress = new UploadProgress((_a = options === null || options === void 0 ? void 0 : options.archiveSizeBytes) !== null && _a !== void 0 ? _a : 0); // Specify data transfer options const uploadOptions = { blockSize: options === null || options === void 0 ? void 0 : options.uploadChunkSize, concurrency: options === null || options === void 0 ? void 0 : options.uploadConcurrency, maxSingleShotSize: 128 * 1024 * 1024, onProgress: uploadProgress.onProgress() }; try { uploadProgress.startDisplayTimer(); core.debug(`BlobClient: ${blobClient.name}:${blobClient.accountName}:${blobClient.containerName}`); const response = yield blockBlobClient.uploadFile(archivePath, uploadOptions); // TODO: better management of non-retryable errors if (response._response.status >= 400) { throw new errors_1.InvalidResponseError(`uploadCacheArchiveSDK: upload failed with status code ${response._response.status}`); } return response; } catch (error) { core.warning(`uploadCacheArchiveSDK: internal error uploading cache archive: ${error.message}`); throw error; } finally { uploadProgress.stopDisplayTimer(); } }); } exports.uploadCacheArchiveSDK = uploadCacheArchiveSDK; //# sourceMappingURL=uploadUtils.js.map /***/ }), /***/ 98356: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getDownloadOptions = exports.getUploadOptions = void 0; const core = __importStar(__nccwpck_require__(37484)); /** * Returns a copy of the upload options with defaults filled in. * * @param copy the original upload options */ function getUploadOptions(copy) { // Defaults if not overriden const result = { useAzureSdk: false, uploadConcurrency: 4, uploadChunkSize: 32 * 1024 * 1024 }; if (copy) { if (typeof copy.useAzureSdk === 'boolean') { result.useAzureSdk = copy.useAzureSdk; } if (typeof copy.uploadConcurrency === 'number') { result.uploadConcurrency = copy.uploadConcurrency; } if (typeof copy.uploadChunkSize === 'number') { result.uploadChunkSize = copy.uploadChunkSize; } } /** * Add env var overrides */ // Cap the uploadConcurrency at 32 result.uploadConcurrency = !isNaN(Number(process.env['CACHE_UPLOAD_CONCURRENCY'])) ? Math.min(32, Number(process.env['CACHE_UPLOAD_CONCURRENCY'])) : result.uploadConcurrency; // Cap the uploadChunkSize at 128MiB result.uploadChunkSize = !isNaN(Number(process.env['CACHE_UPLOAD_CHUNK_SIZE'])) ? Math.min(128 * 1024 * 1024, Number(process.env['CACHE_UPLOAD_CHUNK_SIZE']) * 1024 * 1024) : result.uploadChunkSize; core.debug(`Use Azure SDK: ${result.useAzureSdk}`); 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: false, concurrentBlobDownloads: true, downloadConcurrency: 8, timeoutInMs: 30000, segmentTimeoutInMs: 600000, lookupOnly: false }; if (copy) { if (typeof copy.useAzureSdk === 'boolean') { result.useAzureSdk = copy.useAzureSdk; } if (typeof copy.concurrentBlobDownloads === 'boolean') { result.concurrentBlobDownloads = copy.concurrentBlobDownloads; } if (typeof copy.downloadConcurrency === 'number') { result.downloadConcurrency = copy.downloadConcurrency; } if (typeof copy.timeoutInMs === 'number') { result.timeoutInMs = copy.timeoutInMs; } if (typeof copy.segmentTimeoutInMs === 'number') { result.segmentTimeoutInMs = copy.segmentTimeoutInMs; } if (typeof copy.lookupOnly === 'boolean') { result.lookupOnly = copy.lookupOnly; } } const segmentDownloadTimeoutMins = process.env['SEGMENT_DOWNLOAD_TIMEOUT_MINS']; if (segmentDownloadTimeoutMins && !isNaN(Number(segmentDownloadTimeoutMins)) && isFinite(Number(segmentDownloadTimeoutMins))) { result.segmentTimeoutInMs = Number(segmentDownloadTimeoutMins) * 60 * 1000; } core.debug(`Use Azure SDK: ${result.useAzureSdk}`); core.debug(`Download concurrency: ${result.downloadConcurrency}`); core.debug(`Request timeout (ms): ${result.timeoutInMs}`); core.debug(`Cache segment download timeout mins env var: ${process.env['SEGMENT_DOWNLOAD_TIMEOUT_MINS']}`); core.debug(`Segment download timeout (ms): ${result.segmentTimeoutInMs}`); core.debug(`Lookup only: ${result.lookupOnly}`); return result; } exports.getDownloadOptions = getDownloadOptions; //# sourceMappingURL=options.js.map /***/ }), /***/ 39688: /***/ (function(__unused_webpack_module, exports, __nccwpck_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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.create = void 0; const internal_globber_1 = __nccwpck_require__(57698); /** * Constructs a globber * * @param patterns Patterns separated by newlines * @param options Glob options */ function create(patterns, options) { return __awaiter(this, void 0, void 0, function* () { return yield internal_globber_1.DefaultGlobber.create(patterns, options); }); } exports.create = create; //# sourceMappingURL=glob.js.map /***/ }), /***/ 48462: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; 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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getOptions = void 0; const core = __importStar(__nccwpck_require__(37484)); /** * Returns a copy with defaults filled in. */ function getOptions(copy) { const result = { followSymbolicLinks: true, implicitDescendants: true, omitBrokenSymbolicLinks: true }; if (copy) { if (typeof copy.followSymbolicLinks === 'boolean') { result.followSymbolicLinks = copy.followSymbolicLinks; core.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`); } if (typeof copy.implicitDescendants === 'boolean') { result.implicitDescendants = copy.implicitDescendants; core.debug(`implicitDescendants '${result.implicitDescendants}'`); } if (typeof copy.omitBrokenSymbolicLinks === 'boolean') { result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks; core.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`); } } return result; } exports.getOptions = getOptions; //# sourceMappingURL=internal-glob-options-helper.js.map /***/ }), /***/ 57698: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; 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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; 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 __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__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]); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DefaultGlobber = void 0; const core = __importStar(__nccwpck_require__(37484)); const fs = __importStar(__nccwpck_require__(79896)); const globOptionsHelper = __importStar(__nccwpck_require__(48462)); const path = __importStar(__nccwpck_require__(16928)); const patternHelper = __importStar(__nccwpck_require__(30637)); const internal_match_kind_1 = __nccwpck_require__(49222); const internal_pattern_1 = __nccwpck_require__(8188); const internal_search_state_1 = __nccwpck_require__(768); const IS_WINDOWS = process.platform === 'win32'; class DefaultGlobber { constructor(options) { this.patterns = []; this.searchPaths = []; this.options = globOptionsHelper.getOptions(options); } getSearchPaths() { // Return a copy return this.searchPaths.slice(); } glob() { var e_1, _a; return __awaiter(this, void 0, void 0, function* () { const result = []; try { for (var _b = __asyncValues(this.globGenerator()), _c; _c = yield _b.next(), !_c.done;) { const itemPath = _c.value; result.push(itemPath); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b); } finally { if (e_1) throw e_1.error; } } return result; }); } globGenerator() { return __asyncGenerator(this, arguments, function* globGenerator_1() { // Fill in defaults options const options = globOptionsHelper.getOptions(this.options); // Implicit descendants? const patterns = []; for (const pattern of this.patterns) { patterns.push(pattern); if (options.implicitDescendants && (pattern.trailingSeparator || pattern.segments[pattern.segments.length - 1] !== '**')) { patterns.push(new internal_pattern_1.Pattern(pattern.negate, true, pattern.segments.concat('**'))); } } // Push the search paths const stack = []; for (const searchPath of patternHelper.getSearchPaths(patterns)) { core.debug(`Search path '${searchPath}'`); // Exists? try { // Intentionally using lstat. Detection for broken symlink // will be performed later (if following symlinks). yield __await(fs.promises.lstat(searchPath)); } catch (err) { if (err.code === 'ENOENT') { continue; } throw err; } stack.unshift(new internal_search_state_1.SearchState(searchPath, 1)); } // Search const traversalChain = []; // used to detect cycles while (stack.length) { // Pop const item = stack.pop(); // Match? const match = patternHelper.match(patterns, item.path); const partialMatch = !!match || patternHelper.partialMatch(patterns, item.path); if (!match && !partialMatch) { continue; } // Stat const stats = yield __await(DefaultGlobber.stat(item, options, traversalChain) // Broken symlink, or symlink cycle detected, or no longer exists ); // Broken symlink, or symlink cycle detected, or no longer exists if (!stats) { continue; } // Directory if (stats.isDirectory()) { // Matched if (match & internal_match_kind_1.MatchKind.Directory) { yield yield __await(item.path); } // Descend? else if (!partialMatch) { continue; } // Push the child items in reverse const childLevel = item.level + 1; const childItems = (yield __await(fs.promises.readdir(item.path))).map(x => new internal_search_state_1.SearchState(path.join(item.path, x), childLevel)); stack.push(...childItems.reverse()); } // File else if (match & internal_match_kind_1.MatchKind.File) { yield yield __await(item.path); } } }); } /** * Constructs a DefaultGlobber */ static create(patterns, options) { return __awaiter(this, void 0, void 0, function* () { const result = new DefaultGlobber(options); if (IS_WINDOWS) { patterns = patterns.replace(/\r\n/g, '\n'); patterns = patterns.replace(/\r/g, '\n'); } const lines = patterns.split('\n').map(x => x.trim()); for (const line of lines) { // Empty or comment if (!line || line.startsWith('#')) { continue; } // Pattern else { result.patterns.push(new internal_pattern_1.Pattern(line)); } } result.searchPaths.push(...patternHelper.getSearchPaths(result.patterns)); return result; }); } static stat(item, options, traversalChain) { return __awaiter(this, void 0, void 0, function* () { // Note: // `stat` returns info about the target of a symlink (or symlink chain) // `lstat` returns info about a symlink itself let stats; if (options.followSymbolicLinks) { try { // Use `stat` (following symlinks) stats = yield fs.promises.stat(item.path); } catch (err) { if (err.code === 'ENOENT') { if (options.omitBrokenSymbolicLinks) { core.debug(`Broken symlink '${item.path}'`); return undefined; } throw new Error(`No information found for the path '${item.path}'. This may indicate a broken symbolic link.`); } throw err; } } else { // Use `lstat` (not following symlinks) stats = yield fs.promises.lstat(item.path); } // Note, isDirectory() returns false for the lstat of a symlink if (stats.isDirectory() && options.followSymbolicLinks) { // Get the realpath const realPath = yield fs.promises.realpath(item.path); // Fixup the traversal chain to match the item level while (traversalChain.length >= item.level) { traversalChain.pop(); } // Test for a cycle if (traversalChain.some((x) => x === realPath)) { core.debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`); return undefined; } // Update the traversal chain traversalChain.push(realPath); } return stats; }); } } exports.DefaultGlobber = DefaultGlobber; //# sourceMappingURL=internal-globber.js.map /***/ }), /***/ 49222: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MatchKind = void 0; /** * Indicates whether a pattern matches a path */ var MatchKind; (function (MatchKind) { /** Not matched */ MatchKind[MatchKind["None"] = 0] = "None"; /** Matched if the path is a directory */ MatchKind[MatchKind["Directory"] = 1] = "Directory"; /** Matched if the path is a regular file */ MatchKind[MatchKind["File"] = 2] = "File"; /** Matched */ MatchKind[MatchKind["All"] = 3] = "All"; })(MatchKind = exports.MatchKind || (exports.MatchKind = {})); //# sourceMappingURL=internal-match-kind.js.map /***/ }), /***/ 51256: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; 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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.safeTrimTrailingSeparator = exports.normalizeSeparators = exports.hasRoot = exports.hasAbsoluteRoot = exports.ensureAbsoluteRoot = exports.dirname = void 0; const path = __importStar(__nccwpck_require__(16928)); const assert_1 = __importDefault(__nccwpck_require__(42613)); const IS_WINDOWS = process.platform === 'win32'; /** * Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths. * * For example, on Linux/macOS: * - `/ => /` * - `/hello => /` * * For example, on Windows: * - `C:\ => C:\` * - `C:\hello => C:\` * - `C: => C:` * - `C:hello => C:` * - `\ => \` * - `\hello => \` * - `\\hello => \\hello` * - `\\hello\world => \\hello\world` */ function dirname(p) { // Normalize slashes and trim unnecessary trailing slash p = safeTrimTrailingSeparator(p); // Windows UNC root, e.g. \\hello or \\hello\world if (IS_WINDOWS && /^\\\\[^\\]+(\\[^\\]+)?$/.test(p)) { return p; } // Get dirname let result = path.dirname(p); // Trim trailing slash for Windows UNC root, e.g. \\hello\world\ if (IS_WINDOWS && /^\\\\[^\\]+\\[^\\]+\\$/.test(result)) { result = safeTrimTrailingSeparator(result); } return result; } exports.dirname = dirname; /** * Roots the path if not already rooted. On Windows, relative roots like `\` * or `C:` are expanded based on the current working directory. */ function ensureAbsoluteRoot(root, itemPath) { assert_1.default(root, `ensureAbsoluteRoot parameter 'root' must not be empty`); assert_1.default(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`); // Already rooted if (hasAbsoluteRoot(itemPath)) { return itemPath; } // Windows if (IS_WINDOWS) { // Check for itemPath like C: or C:foo if (itemPath.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)) { let cwd = process.cwd(); assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); // Drive letter matches cwd? Expand to cwd if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) { // Drive only, e.g. C: if (itemPath.length === 2) { // Preserve specified drive letter case (upper or lower) return `${itemPath[0]}:\\${cwd.substr(3)}`; } // Drive + path, e.g. C:foo else { if (!cwd.endsWith('\\')) { cwd += '\\'; } // Preserve specified drive letter case (upper or lower) return `${itemPath[0]}:\\${cwd.substr(3)}${itemPath.substr(2)}`; } } // Different drive else { return `${itemPath[0]}:\\${itemPath.substr(2)}`; } } // Check for itemPath like \ or \foo else if (normalizeSeparators(itemPath).match(/^\\$|^\\[^\\]/)) { const cwd = process.cwd(); assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); return `${cwd[0]}:\\${itemPath.substr(1)}`; } } assert_1.default(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`); // Otherwise ensure root ends with a separator if (root.endsWith('/') || (IS_WINDOWS && root.endsWith('\\'))) { // Intentionally empty } else { // Append separator root += path.sep; } return root + itemPath; } exports.ensureAbsoluteRoot = ensureAbsoluteRoot; /** * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: * `\\hello\share` and `C:\hello` (and using alternate separator). */ function hasAbsoluteRoot(itemPath) { assert_1.default(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`); // Normalize separators itemPath = normalizeSeparators(itemPath); // Windows if (IS_WINDOWS) { // E.g. \\hello\share or C:\hello return itemPath.startsWith('\\\\') || /^[A-Z]:\\/i.test(itemPath); } // E.g. /hello return itemPath.startsWith('/'); } exports.hasAbsoluteRoot = hasAbsoluteRoot; /** * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: * `\`, `\hello`, `\\hello\share`, `C:`, and `C:\hello` (and using alternate separator). */ function hasRoot(itemPath) { assert_1.default(itemPath, `isRooted parameter 'itemPath' must not be empty`); // Normalize separators itemPath = normalizeSeparators(itemPath); // Windows if (IS_WINDOWS) { // E.g. \ or \hello or \\hello // E.g. C: or C:\hello return itemPath.startsWith('\\') || /^[A-Z]:/i.test(itemPath); } // E.g. /hello return itemPath.startsWith('/'); } exports.hasRoot = hasRoot; /** * Removes redundant slashes and converts `/` to `\` on Windows */ function normalizeSeparators(p) { p = p || ''; // Windows if (IS_WINDOWS) { // Convert slashes on Windows p = p.replace(/\//g, '\\'); // Remove redundant slashes const isUnc = /^\\\\+[^\\]/.test(p); // e.g. \\hello return (isUnc ? '\\' : '') + p.replace(/\\\\+/g, '\\'); // preserve leading \\ for UNC } // Remove redundant slashes return p.replace(/\/\/+/g, '/'); } exports.normalizeSeparators = normalizeSeparators; /** * Normalizes the path separators and trims the trailing separator (when safe). * For example, `/foo/ => /foo` but `/ => /` */ function safeTrimTrailingSeparator(p) { // Short-circuit if empty if (!p) { return ''; } // Normalize separators p = normalizeSeparators(p); // No trailing slash if (!p.endsWith(path.sep)) { return p; } // Check '/' on Linux/macOS and '\' on Windows if (p === path.sep) { return p; } // On Windows check if drive root. E.g. C:\ if (IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) { return p; } // Otherwise trim trailing slash return p.substr(0, p.length - 1); } exports.safeTrimTrailingSeparator = safeTrimTrailingSeparator; //# sourceMappingURL=internal-path-helper.js.map /***/ }), /***/ 70279: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; 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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Path = void 0; const path = __importStar(__nccwpck_require__(16928)); const pathHelper = __importStar(__nccwpck_require__(51256)); const assert_1 = __importDefault(__nccwpck_require__(42613)); const IS_WINDOWS = process.platform === 'win32'; /** * Helper class for parsing paths into segments */ class Path { /** * Constructs a Path * @param itemPath Path or array of segments */ constructor(itemPath) { this.segments = []; // String if (typeof itemPath === 'string') { assert_1.default(itemPath, `Parameter 'itemPath' must not be empty`); // Normalize slashes and trim unnecessary trailing slash itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); // Not rooted if (!pathHelper.hasRoot(itemPath)) { this.segments = itemPath.split(path.sep); } // Rooted else { // Add all segments, while not at the root let remaining = itemPath; let dir = pathHelper.dirname(remaining); while (dir !== remaining) { // Add the segment const basename = path.basename(remaining); this.segments.unshift(basename); // Truncate the last segment remaining = dir; dir = pathHelper.dirname(remaining); } // Remainder is the root this.segments.unshift(remaining); } } // Array else { // Must not be empty assert_1.default(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); // Each segment for (let i = 0; i < itemPath.length; i++) { let segment = itemPath[i]; // Must not be empty assert_1.default(segment, `Parameter 'itemPath' must not contain any empty segments`); // Normalize slashes segment = pathHelper.normalizeSeparators(itemPath[i]); // Root segment if (i === 0 && pathHelper.hasRoot(segment)) { segment = pathHelper.safeTrimTrailingSeparator(segment); assert_1.default(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); this.segments.push(segment); } // All other segments else { // Must not contain slash assert_1.default(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); this.segments.push(segment); } } } } /** * Converts the path to it's string representation */ toString() { // First segment let result = this.segments[0]; // All others let skipSlash = result.endsWith(path.sep) || (IS_WINDOWS && /^[A-Z]:$/i.test(result)); for (let i = 1; i < this.segments.length; i++) { if (skipSlash) { skipSlash = false; } else { result += path.sep; } result += this.segments[i]; } return result; } } exports.Path = Path; //# sourceMappingURL=internal-path.js.map /***/ }), /***/ 30637: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; 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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.partialMatch = exports.match = exports.getSearchPaths = void 0; const pathHelper = __importStar(__nccwpck_require__(51256)); const internal_match_kind_1 = __nccwpck_require__(49222); const IS_WINDOWS = process.platform === 'win32'; /** * Given an array of patterns, returns an array of paths to search. * Duplicates and paths under other included paths are filtered out. */ function getSearchPaths(patterns) { // Ignore negate patterns patterns = patterns.filter(x => !x.negate); // Create a map of all search paths const searchPathMap = {}; for (const pattern of patterns) { const key = IS_WINDOWS ? pattern.searchPath.toUpperCase() : pattern.searchPath; searchPathMap[key] = 'candidate'; } const result = []; for (const pattern of patterns) { // Check if already included const key = IS_WINDOWS ? pattern.searchPath.toUpperCase() : pattern.searchPath; if (searchPathMap[key] === 'included') { continue; } // Check for an ancestor search path let foundAncestor = false; let tempKey = key; let parent = pathHelper.dirname(tempKey); while (parent !== tempKey) { if (searchPathMap[parent]) { foundAncestor = true; break; } tempKey = parent; parent = pathHelper.dirname(tempKey); } // Include the search pattern in the result if (!foundAncestor) { result.push(pattern.searchPath); searchPathMap[key] = 'included'; } } return result; } exports.getSearchPaths = getSearchPaths; /** * Matches the patterns against the path */ function match(patterns, itemPath) { let result = internal_match_kind_1.MatchKind.None; for (const pattern of patterns) { if (pattern.negate) { result &= ~pattern.match(itemPath); } else { result |= pattern.match(itemPath); } } return result; } exports.match = match; /** * Checks whether to descend further into the directory */ function partialMatch(patterns, itemPath) { return patterns.some(x => !x.negate && x.partialMatch(itemPath)); } exports.partialMatch = partialMatch; //# sourceMappingURL=internal-pattern-helper.js.map /***/ }), /***/ 8188: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; 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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Pattern = void 0; const os = __importStar(__nccwpck_require__(70857)); const path = __importStar(__nccwpck_require__(16928)); const pathHelper = __importStar(__nccwpck_require__(51256)); const assert_1 = __importDefault(__nccwpck_require__(42613)); const minimatch_1 = __nccwpck_require__(43772); const internal_match_kind_1 = __nccwpck_require__(49222); const internal_path_1 = __nccwpck_require__(70279); const IS_WINDOWS = process.platform === 'win32'; class Pattern { constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) { /** * Indicates whether matches should be excluded from the result set */ this.negate = false; // Pattern overload let pattern; if (typeof patternOrNegate === 'string') { pattern = patternOrNegate.trim(); } // Segments overload else { // Convert to pattern segments = segments || []; assert_1.default(segments.length, `Parameter 'segments' must not empty`); const root = Pattern.getLiteral(segments[0]); assert_1.default(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); pattern = new internal_path_1.Path(segments).toString().trim(); if (patternOrNegate) { pattern = `!${pattern}`; } } // Negate while (pattern.startsWith('!')) { this.negate = !this.negate; pattern = pattern.substr(1).trim(); } // Normalize slashes and ensures absolute root pattern = Pattern.fixupPattern(pattern, homedir); // Segments this.segments = new internal_path_1.Path(pattern).segments; // Trailing slash indicates the pattern should only match directories, not regular files this.trailingSeparator = pathHelper .normalizeSeparators(pattern) .endsWith(path.sep); pattern = pathHelper.safeTrimTrailingSeparator(pattern); // Search path (literal path prior to the first glob segment) let foundGlob = false; const searchSegments = this.segments .map(x => Pattern.getLiteral(x)) .filter(x => !foundGlob && !(foundGlob = x === '')); this.searchPath = new internal_path_1.Path(searchSegments).toString(); // Root RegExp (required when determining partial match) this.rootRegExp = new RegExp(Pattern.regExpEscape(searchSegments[0]), IS_WINDOWS ? 'i' : ''); this.isImplicitPattern = isImplicitPattern; // Create minimatch const minimatchOptions = { dot: true, nobrace: true, nocase: IS_WINDOWS, nocomment: true, noext: true, nonegate: true }; pattern = IS_WINDOWS ? pattern.replace(/\\/g, '/') : pattern; this.minimatch = new minimatch_1.Minimatch(pattern, minimatchOptions); } /** * Matches the pattern against the specified path */ match(itemPath) { // Last segment is globstar? if (this.segments[this.segments.length - 1] === '**') { // Normalize slashes itemPath = pathHelper.normalizeSeparators(itemPath); // Append a trailing slash. Otherwise Minimatch will not match the directory immediately // preceding the globstar. For example, given the pattern `/foo/**`, Minimatch returns // false for `/foo` but returns true for `/foo/`. Append a trailing slash to handle that quirk. if (!itemPath.endsWith(path.sep) && this.isImplicitPattern === false) { // Note, this is safe because the constructor ensures the pattern has an absolute root. // For example, formats like C: and C:foo on Windows are resolved to an absolute root. itemPath = `${itemPath}${path.sep}`; } } else { // Normalize slashes and trim unnecessary trailing slash itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); } // Match if (this.minimatch.match(itemPath)) { return this.trailingSeparator ? internal_match_kind_1.MatchKind.Directory : internal_match_kind_1.MatchKind.All; } return internal_match_kind_1.MatchKind.None; } /** * Indicates whether the pattern may match descendants of the specified path */ partialMatch(itemPath) { // Normalize slashes and trim unnecessary trailing slash itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); // matchOne does not handle root path correctly if (pathHelper.dirname(itemPath) === itemPath) { return this.rootRegExp.test(itemPath); } return this.minimatch.matchOne(itemPath.split(IS_WINDOWS ? /\\+/ : /\/+/), this.minimatch.set[0], true); } /** * Escapes glob patterns within a path */ static globEscape(s) { return (IS_WINDOWS ? s : s.replace(/\\/g, '\\\\')) // escape '\' on Linux/macOS .replace(/(\[)(?=[^/]+\])/g, '[[]') // escape '[' when ']' follows within the path segment .replace(/\?/g, '[?]') // escape '?' .replace(/\*/g, '[*]'); // escape '*' } /** * Normalizes slashes and ensures absolute root */ static fixupPattern(pattern, homedir) { // Empty assert_1.default(pattern, 'pattern cannot be empty'); // Must not contain `.` segment, unless first segment // Must not contain `..` segment const literalSegments = new internal_path_1.Path(pattern).segments.map(x => Pattern.getLiteral(x)); assert_1.default(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); // Must not contain globs in root, e.g. Windows UNC path \\foo\b*r assert_1.default(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); // Normalize slashes pattern = pathHelper.normalizeSeparators(pattern); // Replace leading `.` segment if (pattern === '.' || pattern.startsWith(`.${path.sep}`)) { pattern = Pattern.globEscape(process.cwd()) + pattern.substr(1); } // Replace leading `~` segment else if (pattern === '~' || pattern.startsWith(`~${path.sep}`)) { homedir = homedir || os.homedir(); assert_1.default(homedir, 'Unable to determine HOME directory'); assert_1.default(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`); pattern = Pattern.globEscape(homedir) + pattern.substr(1); } // Replace relative drive root, e.g. pattern is C: or C:foo else if (IS_WINDOWS && (pattern.match(/^[A-Z]:$/i) || pattern.match(/^[A-Z]:[^\\]/i))) { let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', pattern.substr(0, 2)); if (pattern.length > 2 && !root.endsWith('\\')) { root += '\\'; } pattern = Pattern.globEscape(root) + pattern.substr(2); } // Replace relative root, e.g. pattern is \ or \foo else if (IS_WINDOWS && (pattern === '\\' || pattern.match(/^\\[^\\]/))) { let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', '\\'); if (!root.endsWith('\\')) { root += '\\'; } pattern = Pattern.globEscape(root) + pattern.substr(1); } // Otherwise ensure absolute root else { pattern = pathHelper.ensureAbsoluteRoot(Pattern.globEscape(process.cwd()), pattern); } return pathHelper.normalizeSeparators(pattern); } /** * Attempts to unescape a pattern segment to create a literal path segment. * Otherwise returns empty string. */ static getLiteral(segment) { let literal = ''; for (let i = 0; i < segment.length; i++) { const c = segment[i]; // Escape if (c === '\\' && !IS_WINDOWS && i + 1 < segment.length) { literal += segment[++i]; continue; } // Wildcard else if (c === '*' || c === '?') { return ''; } // Character set else if (c === '[' && i + 1 < segment.length) { let set = ''; let closed = -1; for (let i2 = i + 1; i2 < segment.length; i2++) { const c2 = segment[i2]; // Escape if (c2 === '\\' && !IS_WINDOWS && i2 + 1 < segment.length) { set += segment[++i2]; continue; } // Closed else if (c2 === ']') { closed = i2; break; } // Otherwise else { set += c2; } } // Closed? if (closed >= 0) { // Cannot convert if (set.length > 1) { return ''; } // Convert to literal if (set) { literal += set; i = closed; continue; } } // Otherwise fall thru } // Append literal += c; } return literal; } /** * Escapes regexp special characters * https://javascript.info/regexp-escaping */ static regExpEscape(s) { return s.replace(/[[\\^$.|?*+()]/g, '\\$&'); } } exports.Pattern = Pattern; //# sourceMappingURL=internal-pattern.js.map /***/ }), /***/ 768: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SearchState = void 0; class SearchState { constructor(path, level) { this.path = path; this.level = level; } } exports.SearchState = SearchState; //# sourceMappingURL=internal-search-state.js.map /***/ }), /***/ 53272: /***/ ((module, exports) => { exports = module.exports = SemVer var debug /* istanbul ignore next */ if (typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) { debug = function () { var args = Array.prototype.slice.call(arguments, 0) args.unshift('SEMVER') console.log.apply(console, args) } } else { debug = function () {} } // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. exports.SEMVER_SPEC_VERSION = '2.0.0' var MAX_LENGTH = 256 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. var MAX_SAFE_COMPONENT_LENGTH = 16 var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 // The actual regexps go on exports.re var re = exports.re = [] var safeRe = exports.safeRe = [] var src = exports.src = [] var t = exports.tokens = {} var R = 0 function tok (n) { t[n] = R++ } var LETTERDASHNUMBER = '[a-zA-Z0-9-]' // Replace some greedy regex tokens to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. var safeRegexReplacements = [ ['\\s', 1], ['\\d', MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], ] function makeSafeRe (value) { for (var i = 0; i < safeRegexReplacements.length; i++) { var token = safeRegexReplacements[i][0] var max = safeRegexReplacements[i][1] value = value .split(token + '*').join(token + '{0,' + max + '}') .split(token + '+').join(token + '{1,' + max + '}') } return value } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. tok('NUMERICIDENTIFIER') src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*' tok('NUMERICIDENTIFIERLOOSE') src[t.NUMERICIDENTIFIERLOOSE] = '\\d+' // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. tok('NONNUMERICIDENTIFIER') src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-]' + LETTERDASHNUMBER + '*' // ## Main Version // Three dot-separated numeric identifiers. tok('MAINVERSION') src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + '(' + src[t.NUMERICIDENTIFIER] + ')' tok('MAINVERSIONLOOSE') src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')' // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. tok('PRERELEASEIDENTIFIER') src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] + '|' + src[t.NONNUMERICIDENTIFIER] + ')' tok('PRERELEASEIDENTIFIERLOOSE') src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] + '|' + src[t.NONNUMERICIDENTIFIER] + ')' // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. tok('PRERELEASE') src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] + '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))' tok('PRERELEASELOOSE') src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))' // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. tok('BUILDIDENTIFIER') src[t.BUILDIDENTIFIER] = LETTERDASHNUMBER + '+' // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. tok('BUILD') src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] + '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))' // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. tok('FULL') tok('FULLPLAIN') src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] + src[t.PRERELEASE] + '?' + src[t.BUILD] + '?' src[t.FULL] = '^' + src[t.FULLPLAIN] + '$' // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. tok('LOOSEPLAIN') src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] + src[t.PRERELEASELOOSE] + '?' + src[t.BUILD] + '?' tok('LOOSE') src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$' tok('GTLT') src[t.GTLT] = '((?:<|>)?=?)' // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. tok('XRANGEIDENTIFIERLOOSE') src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' tok('XRANGEIDENTIFIER') src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*' tok('XRANGEPLAIN') src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:' + src[t.PRERELEASE] + ')?' + src[t.BUILD] + '?' + ')?)?' tok('XRANGEPLAINLOOSE') src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[t.PRERELEASELOOSE] + ')?' + src[t.BUILD] + '?' + ')?)?' tok('XRANGE') src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$' tok('XRANGELOOSE') src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$' // Coercion. // Extract anything that could conceivably be a part of a valid semver tok('COERCE') src[t.COERCE] = '(^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])' tok('COERCERTL') re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g') safeRe[t.COERCERTL] = new RegExp(makeSafeRe(src[t.COERCE]), 'g') // Tilde ranges. // Meaning is "reasonably at or greater than" tok('LONETILDE') src[t.LONETILDE] = '(?:~>?)' tok('TILDETRIM') src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+' re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g') safeRe[t.TILDETRIM] = new RegExp(makeSafeRe(src[t.TILDETRIM]), 'g') var tildeTrimReplace = '$1~' tok('TILDE') src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$' tok('TILDELOOSE') src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$' // Caret ranges. // Meaning is "at least and backwards compatible with" tok('LONECARET') src[t.LONECARET] = '(?:\\^)' tok('CARETTRIM') src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+' re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g') safeRe[t.CARETTRIM] = new RegExp(makeSafeRe(src[t.CARETTRIM]), 'g') var caretTrimReplace = '$1^' tok('CARET') src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$' tok('CARETLOOSE') src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$' // A simple gt/lt/eq thing, or just "" to indicate "any version" tok('COMPARATORLOOSE') src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$' tok('COMPARATOR') src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$' // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` tok('COMPARATORTRIM') src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')' // this one has to use the /g flag re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g') safeRe[t.COMPARATORTRIM] = new RegExp(makeSafeRe(src[t.COMPARATORTRIM]), 'g') var comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. tok('HYPHENRANGE') src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[t.XRANGEPLAIN] + ')' + '\\s*$' tok('HYPHENRANGELOOSE') src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[t.XRANGEPLAINLOOSE] + ')' + '\\s*$' // Star ranges basically just allow anything at all. tok('STAR') src[t.STAR] = '(<|>)?=?\\s*\\*' // Compile to actual regexp objects. // All are flag-free, unless they were created above with a flag. for (var i = 0; i < R; i++) { debug(i, src[i]) if (!re[i]) { re[i] = new RegExp(src[i]) // Replace all greedy whitespace to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. safeRe[i] = new RegExp(makeSafeRe(src[i])) } } exports.parse = parse function parse (version, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (version instanceof SemVer) { return version } if (typeof version !== 'string') { return null } if (version.length > MAX_LENGTH) { return null } var r = options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL] if (!r.test(version)) { return null } try { return new SemVer(version, options) } catch (er) { return null } } exports.valid = valid function valid (version, options) { var v = parse(version, options) return v ? v.version : null } exports.clean = clean function clean (version, options) { var s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } exports.SemVer = SemVer function SemVer (version, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (version instanceof SemVer) { if (version.loose === options.loose) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError('Invalid Version: ' + version) } if (version.length > MAX_LENGTH) { throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') } if (!(this instanceof SemVer)) { return new SemVer(version, options) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose var m = version.trim().match(options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL]) if (!m) { throw new TypeError('Invalid Version: ' + version) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map(function (id) { if (/^[0-9]+$/.test(id)) { var num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } SemVer.prototype.format = function () { this.version = this.major + '.' + this.minor + '.' + this.patch if (this.prerelease.length) { this.version += '-' + this.prerelease.join('.') } return this.version } SemVer.prototype.toString = function () { return this.version } SemVer.prototype.compare = function (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return this.compareMain(other) || this.comparePre(other) } SemVer.prototype.compareMain = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) } SemVer.prototype.comparePre = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } var i = 0 do { var a = this.prerelease[i] var b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } SemVer.prototype.compareBuild = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } var i = 0 do { var a = this.build[i] var b = other.build[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. SemVer.prototype.inc = function (release, identifier) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier) this.inc('pre', identifier) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier) } this.inc('pre', identifier) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. case 'pre': if (this.prerelease.length === 0) { this.prerelease = [0] } else { var i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything this.prerelease.push(0) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 if (this.prerelease[0] === identifier) { if (isNaN(this.prerelease[1])) { this.prerelease = [identifier, 0] } } else { this.prerelease = [identifier, 0] } } break default: throw new Error('invalid increment argument: ' + release) } this.format() this.raw = this.version return this } exports.inc = inc function inc (version, release, loose, identifier) { if (typeof (loose) === 'string') { identifier = loose loose = undefined } try { return new SemVer(version, loose).inc(release, identifier).version } catch (er) { return null } } exports.diff = diff function diff (version1, version2) { if (eq(version1, version2)) { return null } else { var v1 = parse(version1) var v2 = parse(version2) var prefix = '' if (v1.prerelease.length || v2.prerelease.length) { prefix = 'pre' var defaultResult = 'prerelease' } for (var key in v1) { if (key === 'major' || key === 'minor' || key === 'patch') { if (v1[key] !== v2[key]) { return prefix + key } } } return defaultResult // may be undefined } } exports.compareIdentifiers = compareIdentifiers var numeric = /^[0-9]+$/ function compareIdentifiers (a, b) { var anum = numeric.test(a) var bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } exports.rcompareIdentifiers = rcompareIdentifiers function rcompareIdentifiers (a, b) { return compareIdentifiers(b, a) } exports.major = major function major (a, loose) { return new SemVer(a, loose).major } exports.minor = minor function minor (a, loose) { return new SemVer(a, loose).minor } exports.patch = patch function patch (a, loose) { return new SemVer(a, loose).patch } exports.compare = compare function compare (a, b, loose) { return new SemVer(a, loose).compare(new SemVer(b, loose)) } exports.compareLoose = compareLoose function compareLoose (a, b) { return compare(a, b, true) } exports.compareBuild = compareBuild function compareBuild (a, b, loose) { var versionA = new SemVer(a, loose) var versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } exports.rcompare = rcompare function rcompare (a, b, loose) { return compare(b, a, loose) } exports.sort = sort function sort (list, loose) { return list.sort(function (a, b) { return exports.compareBuild(a, b, loose) }) } exports.rsort = rsort function rsort (list, loose) { return list.sort(function (a, b) { return exports.compareBuild(b, a, loose) }) } exports.gt = gt function gt (a, b, loose) { return compare(a, b, loose) > 0 } exports.lt = lt function lt (a, b, loose) { return compare(a, b, loose) < 0 } exports.eq = eq function eq (a, b, loose) { return compare(a, b, loose) === 0 } exports.neq = neq function neq (a, b, loose) { return compare(a, b, loose) !== 0 } exports.gte = gte function gte (a, b, loose) { return compare(a, b, loose) >= 0 } exports.lte = lte function lte (a, b, loose) { return compare(a, b, loose) <= 0 } exports.cmp = cmp function cmp (a, op, b, loose) { switch (op) { case '===': if (typeof a === 'object') a = a.version if (typeof b === 'object') b = b.version return a === b case '!==': if (typeof a === 'object') a = a.version if (typeof b === 'object') b = b.version return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError('Invalid operator: ' + op) } } exports.Comparator = Comparator function Comparator (comp, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } if (!(this instanceof Comparator)) { return new Comparator(comp, options) } comp = comp.trim().split(/\s+/).join(' ') debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } var ANY = {} Comparator.prototype.parse = function (comp) { var r = this.options.loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR] var m = comp.match(r) if (!m) { throw new TypeError('Invalid comparator: ' + comp) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } Comparator.prototype.toString = function () { return this.value } Comparator.prototype.test = function (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } Comparator.prototype.intersects = function (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } var rangeTmp if (this.operator === '') { if (this.value === '') { return true } rangeTmp = new Range(comp.value, options) return satisfies(this.value, rangeTmp, options) } else if (comp.operator === '') { if (comp.value === '') { return true } rangeTmp = new Range(this.value, options) return satisfies(comp.semver, rangeTmp, options) } var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>') var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<') var sameSemVer = this.semver.version === comp.semver.version var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=') var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && ((this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<')) var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && ((this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>')) return sameDirectionIncreasing || sameDirectionDecreasing || (sameSemVer && differentDirectionsInclusive) || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan } exports.Range = Range function Range (range, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (range instanceof Range) { if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { return new Range(range.value, options) } if (!(this instanceof Range)) { return new Range(range, options) } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. this.raw = range .trim() .split(/\s+/) .join(' ') // First, split based on boolean or || this.set = this.raw.split('||').map(function (range) { return this.parseRange(range.trim()) }, this).filter(function (c) { // throw out any that are not relevant for whatever reason return c.length }) if (!this.set.length) { throw new TypeError('Invalid SemVer Range: ' + this.raw) } this.format() } Range.prototype.format = function () { this.range = this.set.map(function (comps) { return comps.join(' ').trim() }).join('||').trim() return this.range } Range.prototype.toString = function () { return this.range } Range.prototype.parseRange = function (range) { var loose = this.options.loose // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` var hr = loose ? safeRe[t.HYPHENRANGELOOSE] : safeRe[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(safeRe[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range, safeRe[t.COMPARATORTRIM]) // `~ 1.2.3` => `~1.2.3` range = range.replace(safeRe[t.TILDETRIM], tildeTrimReplace) // `^ 1.2.3` => `^1.2.3` range = range.replace(safeRe[t.CARETTRIM], caretTrimReplace) // normalize spaces range = range.split(/\s+/).join(' ') // At this point, the range is completely trimmed and // ready to be split into comparators. var compRe = loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR] var set = range.split(' ').map(function (comp) { return parseComparator(comp, this.options) }, this).join(' ').split(/\s+/) if (this.options.loose) { // in loose mode, throw out any that are not valid comparators set = set.filter(function (comp) { return !!comp.match(compRe) }) } set = set.map(function (comp) { return new Comparator(comp, this.options) }, this) return set } Range.prototype.intersects = function (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some(function (thisComparators) { return ( isSatisfiable(thisComparators, options) && range.set.some(function (rangeComparators) { return ( isSatisfiable(rangeComparators, options) && thisComparators.every(function (thisComparator) { return rangeComparators.every(function (rangeComparator) { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // take a set of comparators and determine whether there // exists a version which can satisfy it function isSatisfiable (comparators, options) { var result = true var remainingComparators = comparators.slice() var testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every(function (otherComparator) { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // Mostly just for testing and legacy API reasons exports.toComparators = toComparators function toComparators (range, options) { return new Range(range, options).set.map(function (comp) { return comp.map(function (c) { return c.value }).join(' ').trim().split(' ') }) } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. function parseComparator (comp, options) { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } function isX (id) { return !id || id.toLowerCase() === 'x' || id === '*' } // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 function replaceTildes (comp, options) { return comp.trim().split(/\s+/).map(function (comp) { return replaceTilde(comp, options) }).join(' ') } function replaceTilde (comp, options) { var r = options.loose ? safeRe[t.TILDELOOSE] : safeRe[t.TILDE] return comp.replace(r, function (_, M, m, p, pr) { debug('tilde', comp, _, M, m, p, pr) var ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } else if (pr) { debug('replaceTilde pr', pr) ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0' } else { // ~1.2.3 == >=1.2.3 <1.3.0 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0' } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 // ^1.2.3 --> >=1.2.3 <2.0.0 // ^1.2.0 --> >=1.2.0 <2.0.0 function replaceCarets (comp, options) { return comp.trim().split(/\s+/).map(function (comp) { return replaceCaret(comp, options) }).join(' ') } function replaceCaret (comp, options) { debug('caret', comp, options) var r = options.loose ? safeRe[t.CARETLOOSE] : safeRe[t.CARET] return comp.replace(r, function (_, M, m, p, pr) { debug('caret', comp, _, M, m, p, pr) var ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (isX(p)) { if (M === '0') { ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } else { ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + m + '.' + (+p + 1) } else { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0' } } else { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + (+M + 1) + '.0.0' } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1) } else { ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0' } } else { ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0' } } debug('caret return', ret) return ret }) } function replaceXRanges (comp, options) { debug('replaceXRanges', comp, options) return comp.split(/\s+/).map(function (comp) { return replaceXRange(comp, options) }).join(' ') } function replaceXRange (comp, options) { comp = comp.trim() var r = options.loose ? safeRe[t.XRANGELOOSE] : safeRe[t.XRANGE] return comp.replace(r, function (ret, gtlt, M, m, p, pr) { debug('xRange', comp, ret, gtlt, M, m, p, pr) var xM = isX(M) var xm = xM || isX(m) var xp = xm || isX(p) var anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 // >1.2.3 => >= 1.2.4 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } ret = gtlt + M + '.' + m + '.' + p + pr } else if (xm) { ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr } else if (xp) { ret = '>=' + M + '.' + m + '.0' + pr + ' <' + M + '.' + (+m + 1) + '.0' + pr } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. function replaceStars (comp, options) { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp.trim().replace(safeRe[t.STAR], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0 function hyphenReplace ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) { if (isX(fM)) { from = '' } else if (isX(fm)) { from = '>=' + fM + '.0.0' } else if (isX(fp)) { from = '>=' + fM + '.' + fm + '.0' } else { from = '>=' + from } if (isX(tM)) { to = '' } else if (isX(tm)) { to = '<' + (+tM + 1) + '.0.0' } else if (isX(tp)) { to = '<' + tM + '.' + (+tm + 1) + '.0' } else if (tpr) { to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr } else { to = '<=' + to } return (from + ' ' + to).trim() } // if ANY of the sets match ALL of its comparators, then pass Range.prototype.test = function (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (var i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } function testSet (set, version, options) { for (var i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === ANY) { continue } if (set[i].semver.prerelease.length > 0) { var allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } exports.satisfies = satisfies function satisfies (version, range, options) { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } exports.maxSatisfying = maxSatisfying function maxSatisfying (versions, range, options) { var max = null var maxSV = null try { var rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach(function (v) { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } exports.minSatisfying = minSatisfying function minSatisfying (versions, range, options) { var min = null var minSV = null try { var rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach(function (v) { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } exports.minVersion = minVersion function minVersion (range, loose) { range = new Range(range, loose) var minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (var i = 0; i < range.set.length; ++i) { var comparators = range.set[i] comparators.forEach(function (comparator) { // Clone to avoid manipulating the comparator's semver object. var compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!minver || gt(minver, compver)) { minver = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error('Unexpected operation: ' + comparator.operator) } }) } if (minver && range.test(minver)) { return minver } return null } exports.validRange = validRange function validRange (range, options) { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } // Determine if version is less than all the versions possible in the range exports.ltr = ltr function ltr (version, range, options) { return outside(version, range, '<', options) } // Determine if version is greater than all the versions possible in the range. exports.gtr = gtr function gtr (version, range, options) { return outside(version, range, '>', options) } exports.outside = outside function outside (version, range, hilo, options) { version = new SemVer(version, options) range = new Range(range, options) var gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisifes the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (var i = 0; i < range.set.length; ++i) { var comparators = range.set[i] var high = null var low = null comparators.forEach(function (comparator) { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } exports.prerelease = prerelease function prerelease (version, options) { var parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } exports.intersects = intersects function intersects (r1, r2, options) { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2) } exports.coerce = coerce function coerce (version, options) { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} var match = null if (!options.rtl) { match = version.match(safeRe[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. var next while ((next = safeRe[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } safeRe[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state safeRe[t.COERCERTL].lastIndex = -1 } if (match === null) { return null } return parse(match[2] + '.' + (match[3] || '0') + '.' + (match[4] || '0'), options) } /***/ }), /***/ 44914: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.issue = exports.issueCommand = void 0; const os = __importStar(__nccwpck_require__(70857)); const utils_1 = __nccwpck_require__(30302); /** * Commands * * Command Format: * ::name key=value,key=value::message * * Examples: * ::warning::This is the message * ::set-env name=MY_VAR::some value */ function issueCommand(command, properties, message) { const cmd = new Command(command, properties, message); process.stdout.write(cmd.toString() + os.EOL); } exports.issueCommand = issueCommand; function issue(name, message = '') { issueCommand(name, {}, message); } exports.issue = issue; const CMD_STRING = '::'; class Command { constructor(command, properties, message) { if (!command) { command = 'missing.command'; } this.command = command; this.properties = properties; this.message = message; } toString() { let cmdStr = CMD_STRING + this.command; if (this.properties && Object.keys(this.properties).length > 0) { cmdStr += ' '; let first = true; for (const key in this.properties) { if (this.properties.hasOwnProperty(key)) { const val = this.properties[key]; if (val) { if (first) { first = false; } else { cmdStr += ','; } cmdStr += `${key}=${escapeProperty(val)}`; } } } } cmdStr += `${CMD_STRING}${escapeData(this.message)}`; return cmdStr; } } function escapeData(s) { return (0, utils_1.toCommandValue)(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A'); } function escapeProperty(s) { return (0, utils_1.toCommandValue)(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A') .replace(/:/g, '%3A') .replace(/,/g, '%2C'); } //# sourceMappingURL=command.js.map /***/ }), /***/ 37484: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; 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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.platform = exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = exports.markdownSummary = exports.summary = exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; const command_1 = __nccwpck_require__(44914); const file_command_1 = __nccwpck_require__(24753); const utils_1 = __nccwpck_require__(30302); const os = __importStar(__nccwpck_require__(70857)); const path = __importStar(__nccwpck_require__(16928)); const oidc_utils_1 = __nccwpck_require__(35306); /** * The code to exit an action */ var ExitCode; (function (ExitCode) { /** * A code indicating that the action was successful */ ExitCode[ExitCode["Success"] = 0] = "Success"; /** * A code indicating that the action was a failure */ ExitCode[ExitCode["Failure"] = 1] = "Failure"; })(ExitCode || (exports.ExitCode = ExitCode = {})); //----------------------------------------------------------------------- // Variables //----------------------------------------------------------------------- /** * Sets env variable for this action and future actions in the job * @param name the name of the variable to set * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function exportVariable(name, val) { const convertedVal = (0, utils_1.toCommandValue)(val); process.env[name] = convertedVal; const filePath = process.env['GITHUB_ENV'] || ''; if (filePath) { return (0, file_command_1.issueFileCommand)('ENV', (0, file_command_1.prepareKeyValueMessage)(name, val)); } (0, command_1.issueCommand)('set-env', { name }, convertedVal); } exports.exportVariable = exportVariable; /** * Registers a secret which will get masked from logs * @param secret value of the secret */ function setSecret(secret) { (0, command_1.issueCommand)('add-mask', {}, secret); } exports.setSecret = setSecret; /** * Prepends inputPath to the PATH (for this action and future actions) * @param inputPath */ function addPath(inputPath) { const filePath = process.env['GITHUB_PATH'] || ''; if (filePath) { (0, file_command_1.issueFileCommand)('PATH', inputPath); } else { (0, command_1.issueCommand)('add-path', {}, inputPath); } process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; } exports.addPath = addPath; /** * Gets the value of an input. * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. * Returns an empty string if the value is not defined. * * @param name name of the input to get * @param options optional. See InputOptions. * @returns string */ function getInput(name, options) { const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; if (options && options.required && !val) { throw new Error(`Input required and not supplied: ${name}`); } if (options && options.trimWhitespace === false) { return val; } return val.trim(); } exports.getInput = getInput; /** * Gets the values of an multiline input. Each value is also trimmed. * * @param name name of the input to get * @param options optional. See InputOptions. * @returns string[] * */ function getMultilineInput(name, options) { const inputs = getInput(name, options) .split('\n') .filter(x => x !== ''); if (options && options.trimWhitespace === false) { return inputs; } return inputs.map(input => input.trim()); } exports.getMultilineInput = getMultilineInput; /** * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. * Support boolean input list: `true | True | TRUE | false | False | FALSE` . * The return value is also in boolean type. * ref: https://yaml.org/spec/1.2/spec.html#id2804923 * * @param name name of the input to get * @param options optional. See InputOptions. * @returns boolean */ function getBooleanInput(name, options) { const trueValue = ['true', 'True', 'TRUE']; const falseValue = ['false', 'False', 'FALSE']; const val = getInput(name, options); if (trueValue.includes(val)) return true; if (falseValue.includes(val)) return false; throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); } exports.getBooleanInput = getBooleanInput; /** * Sets the value of an output. * * @param name name of the output to set * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function setOutput(name, value) { const filePath = process.env['GITHUB_OUTPUT'] || ''; if (filePath) { return (0, file_command_1.issueFileCommand)('OUTPUT', (0, file_command_1.prepareKeyValueMessage)(name, value)); } process.stdout.write(os.EOL); (0, command_1.issueCommand)('set-output', { name }, (0, utils_1.toCommandValue)(value)); } exports.setOutput = setOutput; /** * Enables or disables the echoing of commands into stdout for the rest of the step. * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. * */ function setCommandEcho(enabled) { (0, command_1.issue)('echo', enabled ? 'on' : 'off'); } exports.setCommandEcho = setCommandEcho; //----------------------------------------------------------------------- // Results //----------------------------------------------------------------------- /** * Sets the action status to failed. * When the action exits it will be with an exit code of 1 * @param message add error issue message */ function setFailed(message) { process.exitCode = ExitCode.Failure; error(message); } exports.setFailed = setFailed; //----------------------------------------------------------------------- // Logging Commands //----------------------------------------------------------------------- /** * Gets whether Actions Step Debug is on or not */ function isDebug() { return process.env['RUNNER_DEBUG'] === '1'; } exports.isDebug = isDebug; /** * Writes debug message to user log * @param message debug message */ function debug(message) { (0, command_1.issueCommand)('debug', {}, message); } exports.debug = debug; /** * Adds an error issue * @param message error issue message. Errors will be converted to string via toString() * @param properties optional properties to add to the annotation. */ function error(message, properties = {}) { (0, command_1.issueCommand)('error', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } exports.error = error; /** * Adds a warning issue * @param message warning issue message. Errors will be converted to string via toString() * @param properties optional properties to add to the annotation. */ function warning(message, properties = {}) { (0, command_1.issueCommand)('warning', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } exports.warning = warning; /** * Adds a notice issue * @param message notice issue message. Errors will be converted to string via toString() * @param properties optional properties to add to the annotation. */ function notice(message, properties = {}) { (0, command_1.issueCommand)('notice', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } exports.notice = notice; /** * Writes info to log with console.log. * @param message info message */ function info(message) { process.stdout.write(message + os.EOL); } exports.info = info; /** * Begin an output group. * * Output until the next `groupEnd` will be foldable in this group * * @param name The name of the output group */ function startGroup(name) { (0, command_1.issue)('group', name); } exports.startGroup = startGroup; /** * End an output group. */ function endGroup() { (0, command_1.issue)('endgroup'); } exports.endGroup = endGroup; /** * Wrap an asynchronous function call in a group. * * Returns the same type as the function itself. * * @param name The name of the group * @param fn The function to wrap in the group */ function group(name, fn) { return __awaiter(this, void 0, void 0, function* () { startGroup(name); let result; try { result = yield fn(); } finally { endGroup(); } return result; }); } exports.group = group; //----------------------------------------------------------------------- // Wrapper action state //----------------------------------------------------------------------- /** * Saves state for current action, the state can only be retrieved by this action's post job execution. * * @param name name of the state to store * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function saveState(name, value) { const filePath = process.env['GITHUB_STATE'] || ''; if (filePath) { return (0, file_command_1.issueFileCommand)('STATE', (0, file_command_1.prepareKeyValueMessage)(name, value)); } (0, command_1.issueCommand)('save-state', { name }, (0, utils_1.toCommandValue)(value)); } exports.saveState = saveState; /** * Gets the value of an state set by this action's main execution. * * @param name name of the state to get * @returns string */ function getState(name) { return process.env[`STATE_${name}`] || ''; } exports.getState = getState; function getIDToken(aud) { return __awaiter(this, void 0, void 0, function* () { return yield oidc_utils_1.OidcClient.getIDToken(aud); }); } exports.getIDToken = getIDToken; /** * Summary exports */ var summary_1 = __nccwpck_require__(71847); Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); /** * @deprecated use core.summary */ var summary_2 = __nccwpck_require__(71847); Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); /** * Path exports */ var path_utils_1 = __nccwpck_require__(31976); Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); /** * Platform utilities exports */ exports.platform = __importStar(__nccwpck_require__(18968)); //# sourceMappingURL=core.js.map /***/ }), /***/ 24753: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // For internal use, subject to change. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ const crypto = __importStar(__nccwpck_require__(76982)); const fs = __importStar(__nccwpck_require__(79896)); const os = __importStar(__nccwpck_require__(70857)); const utils_1 = __nccwpck_require__(30302); function issueFileCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; if (!filePath) { throw new Error(`Unable to find environment variable for file command ${command}`); } if (!fs.existsSync(filePath)) { throw new Error(`Missing file at path: ${filePath}`); } fs.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, { encoding: 'utf8' }); } exports.issueFileCommand = issueFileCommand; function prepareKeyValueMessage(key, value) { const delimiter = `ghadelimiter_${crypto.randomUUID()}`; const convertedValue = (0, utils_1.toCommandValue)(value); // These should realistically never happen, but just in case someone finds a // way to exploit uuid generation let's not allow keys or values that contain // the delimiter. if (key.includes(delimiter)) { throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); } if (convertedValue.includes(delimiter)) { throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); } return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; } exports.prepareKeyValueMessage = prepareKeyValueMessage; //# sourceMappingURL=file-command.js.map /***/ }), /***/ 35306: /***/ (function(__unused_webpack_module, exports, __nccwpck_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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OidcClient = void 0; const http_client_1 = __nccwpck_require__(54844); const auth_1 = __nccwpck_require__(44552); const core_1 = __nccwpck_require__(37484); class OidcClient { static createHttpClient(allowRetry = true, maxRetry = 10) { const requestOptions = { allowRetries: allowRetry, maxRetries: maxRetry }; return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); } static getRequestToken() { const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; if (!token) { throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); } return token; } static getIDTokenUrl() { const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; if (!runtimeUrl) { throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); } return runtimeUrl; } static getCall(id_token_url) { var _a; return __awaiter(this, void 0, void 0, function* () { const httpclient = OidcClient.createHttpClient(); const res = yield httpclient .getJson(id_token_url) .catch(error => { throw new Error(`Failed to get ID Token. \n Error Code : ${error.statusCode}\n Error Message: ${error.message}`); }); const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; if (!id_token) { throw new Error('Response json body do not have ID Token field'); } return id_token; }); } static getIDToken(audience) { return __awaiter(this, void 0, void 0, function* () { try { // New ID Token is requested from action service let id_token_url = OidcClient.getIDTokenUrl(); if (audience) { const encodedAudience = encodeURIComponent(audience); id_token_url = `${id_token_url}&audience=${encodedAudience}`; } (0, core_1.debug)(`ID token url is ${id_token_url}`); const id_token = yield OidcClient.getCall(id_token_url); (0, core_1.setSecret)(id_token); return id_token; } catch (error) { throw new Error(`Error message: ${error.message}`); } }); } } exports.OidcClient = OidcClient; //# sourceMappingURL=oidc-utils.js.map /***/ }), /***/ 31976: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; const path = __importStar(__nccwpck_require__(16928)); /** * toPosixPath converts the given path to the posix form. On Windows, \\ will be * replaced with /. * * @param pth. Path to transform. * @return string Posix path. */ function toPosixPath(pth) { return pth.replace(/[\\]/g, '/'); } exports.toPosixPath = toPosixPath; /** * toWin32Path converts the given path to the win32 form. On Linux, / will be * replaced with \\. * * @param pth. Path to transform. * @return string Win32 path. */ function toWin32Path(pth) { return pth.replace(/[/]/g, '\\'); } exports.toWin32Path = toWin32Path; /** * toPlatformPath converts the given path to a platform-specific path. It does * this by replacing instances of / and \ with the platform-specific path * separator. * * @param pth The path to platformize. * @return string The platform-specific path. */ function toPlatformPath(pth) { return pth.replace(/[/\\]/g, path.sep); } exports.toPlatformPath = toPlatformPath; //# sourceMappingURL=path-utils.js.map /***/ }), /***/ 18968: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; 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 __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getDetails = exports.isLinux = exports.isMacOS = exports.isWindows = exports.arch = exports.platform = void 0; const os_1 = __importDefault(__nccwpck_require__(70857)); const exec = __importStar(__nccwpck_require__(95236)); const getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () { const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, { silent: true }); const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', undefined, { silent: true }); return { name: name.trim(), version: version.trim() }; }); const getMacOsInfo = () => __awaiter(void 0, void 0, void 0, function* () { var _a, _b, _c, _d; const { stdout } = yield exec.getExecOutput('sw_vers', undefined, { silent: true }); const version = (_b = (_a = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : ''; const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : ''; return { name, version }; }); const getLinuxInfo = () => __awaiter(void 0, void 0, void 0, function* () { const { stdout } = yield exec.getExecOutput('lsb_release', ['-i', '-r', '-s'], { silent: true }); const [name, version] = stdout.trim().split('\n'); return { name, version }; }); exports.platform = os_1.default.platform(); exports.arch = os_1.default.arch(); exports.isWindows = exports.platform === 'win32'; exports.isMacOS = exports.platform === 'darwin'; exports.isLinux = exports.platform === 'linux'; function getDetails() { return __awaiter(this, void 0, void 0, function* () { return Object.assign(Object.assign({}, (yield (exports.isWindows ? getWindowsInfo() : exports.isMacOS ? getMacOsInfo() : getLinuxInfo()))), { platform: exports.platform, arch: exports.arch, isWindows: exports.isWindows, isMacOS: exports.isMacOS, isLinux: exports.isLinux }); }); } exports.getDetails = getDetails; //# sourceMappingURL=platform.js.map /***/ }), /***/ 71847: /***/ (function(__unused_webpack_module, exports, __nccwpck_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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; const os_1 = __nccwpck_require__(70857); const fs_1 = __nccwpck_require__(79896); const { access, appendFile, writeFile } = fs_1.promises; exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; class Summary { constructor() { this._buffer = ''; } /** * Finds the summary file path from the environment, rejects if env var is not found or file does not exist * Also checks r/w permissions. * * @returns step summary file path */ filePath() { return __awaiter(this, void 0, void 0, function* () { if (this._filePath) { return this._filePath; } const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; if (!pathFromEnv) { throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); } try { yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); } catch (_a) { throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); } this._filePath = pathFromEnv; return this._filePath; }); } /** * Wraps content in an HTML tag, adding any HTML attributes * * @param {string} tag HTML tag to wrap * @param {string | null} content content within the tag * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add * * @returns {string} content wrapped in HTML element */ wrap(tag, content, attrs = {}) { const htmlAttrs = Object.entries(attrs) .map(([key, value]) => ` ${key}="${value}"`) .join(''); if (!content) { return `<${tag}${htmlAttrs}>`; } return `<${tag}${htmlAttrs}>${content}`; } /** * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. * * @param {SummaryWriteOptions} [options] (optional) options for write operation * * @returns {Promise} summary instance */ write(options) { return __awaiter(this, void 0, void 0, function* () { const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); const filePath = yield this.filePath(); const writeFunc = overwrite ? writeFile : appendFile; yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); return this.emptyBuffer(); }); } /** * Clears the summary buffer and wipes the summary file * * @returns {Summary} summary instance */ clear() { return __awaiter(this, void 0, void 0, function* () { return this.emptyBuffer().write({ overwrite: true }); }); } /** * Returns the current summary buffer as a string * * @returns {string} string of summary buffer */ stringify() { return this._buffer; } /** * If the summary buffer is empty * * @returns {boolen} true if the buffer is empty */ isEmptyBuffer() { return this._buffer.length === 0; } /** * Resets the summary buffer without writing to summary file * * @returns {Summary} summary instance */ emptyBuffer() { this._buffer = ''; return this; } /** * Adds raw text to the summary buffer * * @param {string} text content to add * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) * * @returns {Summary} summary instance */ addRaw(text, addEOL = false) { this._buffer += text; return addEOL ? this.addEOL() : this; } /** * Adds the operating system-specific end-of-line marker to the buffer * * @returns {Summary} summary instance */ addEOL() { return this.addRaw(os_1.EOL); } /** * Adds an HTML codeblock to the summary buffer * * @param {string} code content to render within fenced code block * @param {string} lang (optional) language to syntax highlight code * * @returns {Summary} summary instance */ addCodeBlock(code, lang) { const attrs = Object.assign({}, (lang && { lang })); const element = this.wrap('pre', this.wrap('code', code), attrs); return this.addRaw(element).addEOL(); } /** * Adds an HTML list to the summary buffer * * @param {string[]} items list of items to render * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) * * @returns {Summary} summary instance */ addList(items, ordered = false) { const tag = ordered ? 'ol' : 'ul'; const listItems = items.map(item => this.wrap('li', item)).join(''); const element = this.wrap(tag, listItems); return this.addRaw(element).addEOL(); } /** * Adds an HTML table to the summary buffer * * @param {SummaryTableCell[]} rows table rows * * @returns {Summary} summary instance */ addTable(rows) { const tableBody = rows .map(row => { const cells = row .map(cell => { if (typeof cell === 'string') { return this.wrap('td', cell); } const { header, data, colspan, rowspan } = cell; const tag = header ? 'th' : 'td'; const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); return this.wrap(tag, data, attrs); }) .join(''); return this.wrap('tr', cells); }) .join(''); const element = this.wrap('table', tableBody); return this.addRaw(element).addEOL(); } /** * Adds a collapsable HTML details element to the summary buffer * * @param {string} label text for the closed state * @param {string} content collapsable content * * @returns {Summary} summary instance */ addDetails(label, content) { const element = this.wrap('details', this.wrap('summary', label) + content); return this.addRaw(element).addEOL(); } /** * Adds an HTML image tag to the summary buffer * * @param {string} src path to the image you to embed * @param {string} alt text description of the image * @param {SummaryImageOptions} options (optional) addition image attributes * * @returns {Summary} summary instance */ addImage(src, alt, options) { const { width, height } = options || {}; const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); return this.addRaw(element).addEOL(); } /** * Adds an HTML section heading element * * @param {string} text heading text * @param {number | string} [level=1] (optional) the heading level, default: 1 * * @returns {Summary} summary instance */ addHeading(text, level) { const tag = `h${level}`; const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) ? tag : 'h1'; const element = this.wrap(allowedTag, text); return this.addRaw(element).addEOL(); } /** * Adds an HTML thematic break (
) to the summary buffer * * @returns {Summary} summary instance */ addSeparator() { const element = this.wrap('hr', null); return this.addRaw(element).addEOL(); } /** * Adds an HTML line break (
) to the summary buffer * * @returns {Summary} summary instance */ addBreak() { const element = this.wrap('br', null); return this.addRaw(element).addEOL(); } /** * Adds an HTML blockquote to the summary buffer * * @param {string} text quote text * @param {string} cite (optional) citation url * * @returns {Summary} summary instance */ addQuote(text, cite) { const attrs = Object.assign({}, (cite && { cite })); const element = this.wrap('blockquote', text, attrs); return this.addRaw(element).addEOL(); } /** * Adds an HTML anchor tag to the summary buffer * * @param {string} text link text/content * @param {string} href hyperlink * * @returns {Summary} summary instance */ addLink(text, href) { const element = this.wrap('a', text, { href }); return this.addRaw(element).addEOL(); } } const _summary = new Summary(); /** * @deprecated use `core.summary` */ exports.markdownSummary = _summary; exports.summary = _summary; //# sourceMappingURL=summary.js.map /***/ }), /***/ 30302: /***/ ((__unused_webpack_module, exports) => { "use strict"; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toCommandProperties = exports.toCommandValue = void 0; /** * Sanitizes an input into a string so it can be passed into issueCommand safely * @param input input to sanitize into a string */ function toCommandValue(input) { if (input === null || input === undefined) { return ''; } else if (typeof input === 'string' || input instanceof String) { return input; } return JSON.stringify(input); } exports.toCommandValue = toCommandValue; /** * * @param annotationProperties * @returns The command properties to send with the actual annotation command * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 */ function toCommandProperties(annotationProperties) { if (!Object.keys(annotationProperties).length) { return {}; } return { title: annotationProperties.title, file: annotationProperties.file, line: annotationProperties.startLine, endLine: annotationProperties.endLine, col: annotationProperties.startColumn, endColumn: annotationProperties.endColumn }; } exports.toCommandProperties = toCommandProperties; //# sourceMappingURL=utils.js.map /***/ }), /***/ 95236: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; 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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; 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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getExecOutput = exports.exec = void 0; const string_decoder_1 = __nccwpck_require__(13193); const tr = __importStar(__nccwpck_require__(6665)); /** * Exec a command. * Output will be streamed to the live console. * Returns promise with return code * * @param commandLine command to execute (can include additional args). Must be correctly escaped. * @param args optional arguments for tool. Escaping is handled by the lib. * @param options optional exec options. See ExecOptions * @returns Promise exit code */ function exec(commandLine, args, options) { return __awaiter(this, void 0, void 0, function* () { const commandArgs = tr.argStringToArray(commandLine); if (commandArgs.length === 0) { throw new Error(`Parameter 'commandLine' cannot be null or empty.`); } // Path to tool to execute should be first arg const toolPath = commandArgs[0]; args = commandArgs.slice(1).concat(args || []); const runner = new tr.ToolRunner(toolPath, args, options); return runner.exec(); }); } exports.exec = exec; /** * Exec a command and get the output. * Output will be streamed to the live console. * Returns promise with the exit code and collected stdout and stderr * * @param commandLine command to execute (can include additional args). Must be correctly escaped. * @param args optional arguments for tool. Escaping is handled by the lib. * @param options optional exec options. See ExecOptions * @returns Promise exit code, stdout, and stderr */ function getExecOutput(commandLine, args, options) { var _a, _b; return __awaiter(this, void 0, void 0, function* () { let stdout = ''; let stderr = ''; //Using string decoder covers the case where a mult-byte character is split const stdoutDecoder = new string_decoder_1.StringDecoder('utf8'); const stderrDecoder = new string_decoder_1.StringDecoder('utf8'); const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout; const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; const stdErrListener = (data) => { stderr += stderrDecoder.write(data); if (originalStdErrListener) { originalStdErrListener(data); } }; const stdOutListener = (data) => { stdout += stdoutDecoder.write(data); if (originalStdoutListener) { originalStdoutListener(data); } }; const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); //flush any remaining characters stdout += stdoutDecoder.end(); stderr += stderrDecoder.end(); return { exitCode, stdout, stderr }; }); } exports.getExecOutput = getExecOutput; //# sourceMappingURL=exec.js.map /***/ }), /***/ 6665: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; 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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; 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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.argStringToArray = exports.ToolRunner = void 0; const os = __importStar(__nccwpck_require__(70857)); const events = __importStar(__nccwpck_require__(24434)); const child = __importStar(__nccwpck_require__(35317)); const path = __importStar(__nccwpck_require__(16928)); const io = __importStar(__nccwpck_require__(94994)); const ioUtil = __importStar(__nccwpck_require__(75207)); const timers_1 = __nccwpck_require__(53557); /* eslint-disable @typescript-eslint/unbound-method */ const IS_WINDOWS = process.platform === 'win32'; /* * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. */ class ToolRunner extends events.EventEmitter { constructor(toolPath, args, options) { super(); if (!toolPath) { throw new Error("Parameter 'toolPath' cannot be null or empty."); } this.toolPath = toolPath; this.args = args || []; this.options = options || {}; } _debug(message) { if (this.options.listeners && this.options.listeners.debug) { this.options.listeners.debug(message); } } _getCommandString(options, noPrefix) { const toolPath = this._getSpawnFileName(); const args = this._getSpawnArgs(options); let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool if (IS_WINDOWS) { // Windows + cmd file if (this._isCmdFile()) { cmd += toolPath; for (const a of args) { cmd += ` ${a}`; } } // Windows + verbatim else if (options.windowsVerbatimArguments) { cmd += `"${toolPath}"`; for (const a of args) { cmd += ` ${a}`; } } // Windows (regular) else { cmd += this._windowsQuoteCmdArg(toolPath); for (const a of args) { cmd += ` ${this._windowsQuoteCmdArg(a)}`; } } } else { // OSX/Linux - this can likely be improved with some form of quoting. // creating processes on Unix is fundamentally different than Windows. // on Unix, execvp() takes an arg array. cmd += toolPath; for (const a of args) { cmd += ` ${a}`; } } return cmd; } _processLineBuffer(data, strBuffer, onLine) { try { let s = strBuffer + data.toString(); let n = s.indexOf(os.EOL); while (n > -1) { const line = s.substring(0, n); onLine(line); // the rest of the string ... s = s.substring(n + os.EOL.length); n = s.indexOf(os.EOL); } return s; } catch (err) { // streaming lines to console is best effort. Don't fail a build. this._debug(`error processing line. Failed with error ${err}`); return ''; } } _getSpawnFileName() { if (IS_WINDOWS) { if (this._isCmdFile()) { return process.env['COMSPEC'] || 'cmd.exe'; } } return this.toolPath; } _getSpawnArgs(options) { if (IS_WINDOWS) { if (this._isCmdFile()) { let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; for (const a of this.args) { argline += ' '; argline += options.windowsVerbatimArguments ? a : this._windowsQuoteCmdArg(a); } argline += '"'; return [argline]; } } return this.args; } _endsWith(str, end) { return str.endsWith(end); } _isCmdFile() { const upperToolPath = this.toolPath.toUpperCase(); return (this._endsWith(upperToolPath, '.CMD') || this._endsWith(upperToolPath, '.BAT')); } _windowsQuoteCmdArg(arg) { // for .exe, apply the normal quoting rules that libuv applies if (!this._isCmdFile()) { return this._uvQuoteCmdArg(arg); } // otherwise apply quoting rules specific to the cmd.exe command line parser. // the libuv rules are generic and are not designed specifically for cmd.exe // command line parser. // // for a detailed description of the cmd.exe command line parser, refer to // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 // need quotes for empty arg if (!arg) { return '""'; } // determine whether the arg needs to be quoted const cmdSpecialChars = [ ' ', '\t', '&', '(', ')', '[', ']', '{', '}', '^', '=', ';', '!', "'", '+', ',', '`', '~', '|', '<', '>', '"' ]; let needsQuotes = false; for (const char of arg) { if (cmdSpecialChars.some(x => x === char)) { needsQuotes = true; break; } } // short-circuit if quotes not needed if (!needsQuotes) { return arg; } // the following quoting rules are very similar to the rules that by libuv applies. // // 1) wrap the string in quotes // // 2) double-up quotes - i.e. " => "" // // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately // doesn't work well with a cmd.exe command line. // // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. // for example, the command line: // foo.exe "myarg:""my val""" // is parsed by a .NET console app into an arg array: // [ "myarg:\"my val\"" ] // which is the same end result when applying libuv quoting rules. although the actual // command line from libuv quoting rules would look like: // foo.exe "myarg:\"my val\"" // // 3) double-up slashes that precede a quote, // e.g. hello \world => "hello \world" // hello\"world => "hello\\""world" // hello\\"world => "hello\\\\""world" // hello world\ => "hello world\\" // // technically this is not required for a cmd.exe command line, or the batch argument parser. // the reasons for including this as a .cmd quoting rule are: // // a) this is optimized for the scenario where the argument is passed from the .cmd file to an // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. // // b) it's what we've been doing previously (by deferring to node default behavior) and we // haven't heard any complaints about that aspect. // // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be // escaped when used on the command line directly - even though within a .cmd file % can be escaped // by using %%. // // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. // // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args // to an external program. // // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. // % can be escaped within a .cmd file. let reverse = '"'; let quoteHit = true; for (let i = arg.length; i > 0; i--) { // walk the string in reverse reverse += arg[i - 1]; if (quoteHit && arg[i - 1] === '\\') { reverse += '\\'; // double the slash } else if (arg[i - 1] === '"') { quoteHit = true; reverse += '"'; // double the quote } else { quoteHit = false; } } reverse += '"'; return reverse .split('') .reverse() .join(''); } _uvQuoteCmdArg(arg) { // Tool runner wraps child_process.spawn() and needs to apply the same quoting as // Node in certain cases where the undocumented spawn option windowsVerbatimArguments // is used. // // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), // pasting copyright notice from Node within this function: // // Copyright Joyent, Inc. and other Node contributors. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. if (!arg) { // Need double quotation for empty argument return '""'; } if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { // No quotation needed return arg; } if (!arg.includes('"') && !arg.includes('\\')) { // No embedded double quotes or backslashes, so I can just wrap // quote marks around the whole thing. return `"${arg}"`; } // Expected input/output: // input : hello"world // output: "hello\"world" // input : hello""world // output: "hello\"\"world" // input : hello\world // output: hello\world // input : hello\\world // output: hello\\world // input : hello\"world // output: "hello\\\"world" // input : hello\\"world // output: "hello\\\\\"world" // input : hello world\ // output: "hello world\\" - note the comment in libuv actually reads "hello world\" // but it appears the comment is wrong, it should be "hello world\\" let reverse = '"'; let quoteHit = true; for (let i = arg.length; i > 0; i--) { // walk the string in reverse reverse += arg[i - 1]; if (quoteHit && arg[i - 1] === '\\') { reverse += '\\'; } else if (arg[i - 1] === '"') { quoteHit = true; reverse += '\\'; } else { quoteHit = false; } } reverse += '"'; return reverse .split('') .reverse() .join(''); } _cloneExecOptions(options) { options = options || {}; const result = { cwd: options.cwd || process.cwd(), env: options.env || process.env, silent: options.silent || false, windowsVerbatimArguments: options.windowsVerbatimArguments || false, failOnStdErr: options.failOnStdErr || false, ignoreReturnCode: options.ignoreReturnCode || false, delay: options.delay || 10000 }; result.outStream = options.outStream || process.stdout; result.errStream = options.errStream || process.stderr; return result; } _getSpawnOptions(options, toolPath) { options = options || {}; const result = {}; result.cwd = options.cwd; result.env = options.env; result['windowsVerbatimArguments'] = options.windowsVerbatimArguments || this._isCmdFile(); if (options.windowsVerbatimArguments) { result.argv0 = `"${toolPath}"`; } return result; } /** * Exec a tool. * Output will be streamed to the live console. * Returns promise with return code * * @param tool path to tool to exec * @param options optional exec options. See ExecOptions * @returns number */ exec() { return __awaiter(this, void 0, void 0, function* () { // root the tool path if it is unrooted and contains relative pathing if (!ioUtil.isRooted(this.toolPath) && (this.toolPath.includes('/') || (IS_WINDOWS && this.toolPath.includes('\\')))) { // prefer options.cwd if it is specified, however options.cwd may also need to be rooted this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); } // if the tool is only a file name, then resolve it from the PATH // otherwise verify it exists (add extension on Windows if necessary) this.toolPath = yield io.which(this.toolPath, true); return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { this._debug(`exec tool: ${this.toolPath}`); this._debug('arguments:'); for (const arg of this.args) { this._debug(` ${arg}`); } const optionsNonNull = this._cloneExecOptions(this.options); if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); } const state = new ExecState(optionsNonNull, this.toolPath); state.on('debug', (message) => { this._debug(message); }); if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) { return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); } const fileName = this._getSpawnFileName(); const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); let stdbuffer = ''; if (cp.stdout) { cp.stdout.on('data', (data) => { if (this.options.listeners && this.options.listeners.stdout) { this.options.listeners.stdout(data); } if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(data); } stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { if (this.options.listeners && this.options.listeners.stdline) { this.options.listeners.stdline(line); } }); }); } let errbuffer = ''; if (cp.stderr) { cp.stderr.on('data', (data) => { state.processStderr = true; if (this.options.listeners && this.options.listeners.stderr) { this.options.listeners.stderr(data); } if (!optionsNonNull.silent && optionsNonNull.errStream && optionsNonNull.outStream) { const s = optionsNonNull.failOnStdErr ? optionsNonNull.errStream : optionsNonNull.outStream; s.write(data); } errbuffer = this._processLineBuffer(data, errbuffer, (line) => { if (this.options.listeners && this.options.listeners.errline) { this.options.listeners.errline(line); } }); }); } cp.on('error', (err) => { state.processError = err.message; state.processExited = true; state.processClosed = true; state.CheckComplete(); }); cp.on('exit', (code) => { state.processExitCode = code; state.processExited = true; this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); state.CheckComplete(); }); cp.on('close', (code) => { state.processExitCode = code; state.processExited = true; state.processClosed = true; this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); state.CheckComplete(); }); state.on('done', (error, exitCode) => { if (stdbuffer.length > 0) { this.emit('stdline', stdbuffer); } if (errbuffer.length > 0) { this.emit('errline', errbuffer); } cp.removeAllListeners(); if (error) { reject(error); } else { resolve(exitCode); } }); if (this.options.input) { if (!cp.stdin) { throw new Error('child process missing stdin'); } cp.stdin.end(this.options.input); } })); }); } } exports.ToolRunner = ToolRunner; /** * Convert an arg string to an array of args. Handles escaping * * @param argString string of arguments * @returns string[] array of arguments */ function argStringToArray(argString) { const args = []; let inQuotes = false; let escaped = false; let arg = ''; function append(c) { // we only escape double quotes. if (escaped && c !== '"') { arg += '\\'; } arg += c; escaped = false; } for (let i = 0; i < argString.length; i++) { const c = argString.charAt(i); if (c === '"') { if (!escaped) { inQuotes = !inQuotes; } else { append(c); } continue; } if (c === '\\' && escaped) { append(c); continue; } if (c === '\\' && inQuotes) { escaped = true; continue; } if (c === ' ' && !inQuotes) { if (arg.length > 0) { args.push(arg); arg = ''; } continue; } append(c); } if (arg.length > 0) { args.push(arg.trim()); } return args; } exports.argStringToArray = argStringToArray; class ExecState extends events.EventEmitter { constructor(options, toolPath) { super(); this.processClosed = false; // tracks whether the process has exited and stdio is closed this.processError = ''; this.processExitCode = 0; this.processExited = false; // tracks whether the process has exited this.processStderr = false; // tracks whether stderr was written to this.delay = 10000; // 10 seconds this.done = false; this.timeout = null; if (!toolPath) { throw new Error('toolPath must not be empty'); } this.options = options; this.toolPath = toolPath; if (options.delay) { this.delay = options.delay; } } CheckComplete() { if (this.done) { return; } if (this.processClosed) { this._setResult(); } else if (this.processExited) { this.timeout = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this); } } _debug(message) { this.emit('debug', message); } _setResult() { // determine whether there is an error let error; if (this.processExited) { if (this.processError) { error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); } else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); } else if (this.processStderr && this.options.failOnStdErr) { error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); } } // clear the timeout if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } this.done = true; this.emit('done', error, this.processExitCode); } static HandleTimeout(state) { if (state.done) { return; } if (!state.processClosed && state.processExited) { const message = `The STDIO streams did not close within ${state.delay / 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; state._debug(message); } state._setResult(); } } //# sourceMappingURL=toolrunner.js.map /***/ }), /***/ 51648: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Context = void 0; const fs_1 = __nccwpck_require__(79896); const os_1 = __nccwpck_require__(70857); class Context { /** * Hydrate the context from the environment */ constructor() { var _a, _b, _c; this.payload = {}; if (process.env.GITHUB_EVENT_PATH) { if ((0, fs_1.existsSync)(process.env.GITHUB_EVENT_PATH)) { this.payload = JSON.parse((0, fs_1.readFileSync)(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })); } else { const path = process.env.GITHUB_EVENT_PATH; process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`); } } this.eventName = process.env.GITHUB_EVENT_NAME; this.sha = process.env.GITHUB_SHA; this.ref = process.env.GITHUB_REF; this.workflow = process.env.GITHUB_WORKFLOW; this.action = process.env.GITHUB_ACTION; this.actor = process.env.GITHUB_ACTOR; this.job = process.env.GITHUB_JOB; this.runAttempt = parseInt(process.env.GITHUB_RUN_ATTEMPT, 10); this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; this.graphqlUrl = (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; } get issue() { const payload = this.payload; return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); } get repo() { if (process.env.GITHUB_REPOSITORY) { const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); return { owner, repo }; } if (this.payload.repository) { return { owner: this.payload.repository.owner.login, repo: this.payload.repository.name }; } throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); } } exports.Context = Context; //# sourceMappingURL=context.js.map /***/ }), /***/ 93228: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getOctokit = exports.context = void 0; const Context = __importStar(__nccwpck_require__(51648)); const utils_1 = __nccwpck_require__(38006); exports.context = new Context.Context(); /** * Returns a hydrated octokit ready to use for GitHub Actions * * @param token the repo PAT or GITHUB_TOKEN * @param options other options to set */ function getOctokit(token, options, ...additionalPlugins) { const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins); return new GitHubWithPlugins((0, utils_1.getOctokitOptions)(token, options)); } exports.getOctokit = getOctokit; //# sourceMappingURL=github.js.map /***/ }), /***/ 65156: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; 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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getApiBaseUrl = exports.getProxyFetch = exports.getProxyAgentDispatcher = exports.getProxyAgent = exports.getAuthString = void 0; const httpClient = __importStar(__nccwpck_require__(54844)); const undici_1 = __nccwpck_require__(46752); function getAuthString(token, options) { if (!token && !options.auth) { throw new Error('Parameter token or opts.auth is required'); } else if (token && options.auth) { throw new Error('Parameters token and opts.auth may not both be specified'); } return typeof options.auth === 'string' ? options.auth : `token ${token}`; } exports.getAuthString = getAuthString; function getProxyAgent(destinationUrl) { const hc = new httpClient.HttpClient(); return hc.getAgent(destinationUrl); } exports.getProxyAgent = getProxyAgent; function getProxyAgentDispatcher(destinationUrl) { const hc = new httpClient.HttpClient(); return hc.getAgentDispatcher(destinationUrl); } exports.getProxyAgentDispatcher = getProxyAgentDispatcher; function getProxyFetch(destinationUrl) { const httpDispatcher = getProxyAgentDispatcher(destinationUrl); const proxyFetch = (url, opts) => __awaiter(this, void 0, void 0, function* () { return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); }); return proxyFetch; } exports.getProxyFetch = getProxyFetch; function getApiBaseUrl() { return process.env['GITHUB_API_URL'] || 'https://api.github.com'; } exports.getApiBaseUrl = getApiBaseUrl; //# sourceMappingURL=utils.js.map /***/ }), /***/ 38006: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getOctokitOptions = exports.GitHub = exports.defaults = exports.context = void 0; const Context = __importStar(__nccwpck_require__(51648)); const Utils = __importStar(__nccwpck_require__(65156)); // octokit + plugins const core_1 = __nccwpck_require__(61897); const plugin_rest_endpoint_methods_1 = __nccwpck_require__(75726); const plugin_paginate_rest_1 = __nccwpck_require__(38082); exports.context = new Context.Context(); const baseUrl = Utils.getApiBaseUrl(); exports.defaults = { baseUrl, request: { agent: Utils.getProxyAgent(baseUrl), fetch: Utils.getProxyFetch(baseUrl) } }; exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports.defaults); /** * Convience function to correctly format Octokit Options to pass into the constructor. * * @param token the repo PAT or GITHUB_TOKEN * @param options other options to set */ function getOctokitOptions(token, options) { const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller // Auth const auth = Utils.getAuthString(token, opts); if (auth) { opts.auth = auth; } return opts; } exports.getOctokitOptions = getOctokitOptions; //# sourceMappingURL=utils.js.map /***/ }), /***/ 75726: /***/ ((module) => { "use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // pkg/dist-src/index.js var dist_src_exports = {}; __export(dist_src_exports, { legacyRestEndpointMethods: () => legacyRestEndpointMethods, restEndpointMethods: () => restEndpointMethods }); module.exports = __toCommonJS(dist_src_exports); // pkg/dist-src/version.js var VERSION = "10.4.1"; // pkg/dist-src/generated/endpoints.js var Endpoints = { actions: { addCustomLabelsToSelfHostedRunnerForOrg: [ "POST /orgs/{org}/actions/runners/{runner_id}/labels" ], addCustomLabelsToSelfHostedRunnerForRepo: [ "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" ], addSelectedRepoToOrgSecret: [ "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" ], addSelectedRepoToOrgVariable: [ "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" ], approveWorkflowRun: [ "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" ], cancelWorkflowRun: [ "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" ], createEnvironmentVariable: [ "POST /repositories/{repository_id}/environments/{environment_name}/variables" ], createOrUpdateEnvironmentSecret: [ "PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" ], createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], createOrUpdateRepoSecret: [ "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" ], createOrgVariable: ["POST /orgs/{org}/actions/variables"], createRegistrationTokenForOrg: [ "POST /orgs/{org}/actions/runners/registration-token" ], createRegistrationTokenForRepo: [ "POST /repos/{owner}/{repo}/actions/runners/registration-token" ], createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], createRemoveTokenForRepo: [ "POST /repos/{owner}/{repo}/actions/runners/remove-token" ], createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], createWorkflowDispatch: [ "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" ], deleteActionsCacheById: [ "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" ], deleteActionsCacheByKey: [ "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" ], deleteArtifact: [ "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" ], deleteEnvironmentSecret: [ "DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" ], deleteEnvironmentVariable: [ "DELETE /repositories/{repository_id}/environments/{environment_name}/variables/{name}" ], deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], deleteRepoSecret: [ "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" ], deleteRepoVariable: [ "DELETE /repos/{owner}/{repo}/actions/variables/{name}" ], deleteSelfHostedRunnerFromOrg: [ "DELETE /orgs/{org}/actions/runners/{runner_id}" ], deleteSelfHostedRunnerFromRepo: [ "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" ], deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], deleteWorkflowRunLogs: [ "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" ], disableSelectedRepositoryGithubActionsOrganization: [ "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" ], disableWorkflow: [ "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" ], downloadArtifact: [ "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" ], downloadJobLogsForWorkflowRun: [ "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" ], downloadWorkflowRunAttemptLogs: [ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" ], downloadWorkflowRunLogs: [ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" ], enableSelectedRepositoryGithubActionsOrganization: [ "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" ], enableWorkflow: [ "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" ], forceCancelWorkflowRun: [ "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" ], generateRunnerJitconfigForOrg: [ "POST /orgs/{org}/actions/runners/generate-jitconfig" ], generateRunnerJitconfigForRepo: [ "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" ], getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], getActionsCacheUsageByRepoForOrg: [ "GET /orgs/{org}/actions/cache/usage-by-repository" ], getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], getAllowedActionsOrganization: [ "GET /orgs/{org}/actions/permissions/selected-actions" ], getAllowedActionsRepository: [ "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" ], getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], getCustomOidcSubClaimForRepo: [ "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" ], getEnvironmentPublicKey: [ "GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key" ], getEnvironmentSecret: [ "GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" ], getEnvironmentVariable: [ "GET /repositories/{repository_id}/environments/{environment_name}/variables/{name}" ], getGithubActionsDefaultWorkflowPermissionsOrganization: [ "GET /orgs/{org}/actions/permissions/workflow" ], getGithubActionsDefaultWorkflowPermissionsRepository: [ "GET /repos/{owner}/{repo}/actions/permissions/workflow" ], getGithubActionsPermissionsOrganization: [ "GET /orgs/{org}/actions/permissions" ], getGithubActionsPermissionsRepository: [ "GET /repos/{owner}/{repo}/actions/permissions" ], getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], getPendingDeploymentsForRun: [ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" ], getRepoPermissions: [ "GET /repos/{owner}/{repo}/actions/permissions", {}, { renamed: ["actions", "getGithubActionsPermissionsRepository"] } ], getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], getReviewsForRun: [ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" ], getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], getSelfHostedRunnerForRepo: [ "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" ], getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], getWorkflowAccessToRepository: [ "GET /repos/{owner}/{repo}/actions/permissions/access" ], getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], getWorkflowRunAttempt: [ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" ], getWorkflowRunUsage: [ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" ], getWorkflowUsage: [ "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" ], listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], listEnvironmentSecrets: [ "GET /repositories/{repository_id}/environments/{environment_name}/secrets" ], listEnvironmentVariables: [ "GET /repositories/{repository_id}/environments/{environment_name}/variables" ], listJobsForWorkflowRun: [ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" ], listJobsForWorkflowRunAttempt: [ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" ], listLabelsForSelfHostedRunnerForOrg: [ "GET /orgs/{org}/actions/runners/{runner_id}/labels" ], listLabelsForSelfHostedRunnerForRepo: [ "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" ], listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], listOrgVariables: ["GET /orgs/{org}/actions/variables"], listRepoOrganizationSecrets: [ "GET /repos/{owner}/{repo}/actions/organization-secrets" ], listRepoOrganizationVariables: [ "GET /repos/{owner}/{repo}/actions/organization-variables" ], listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], listRunnerApplicationsForRepo: [ "GET /repos/{owner}/{repo}/actions/runners/downloads" ], listSelectedReposForOrgSecret: [ "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" ], listSelectedReposForOrgVariable: [ "GET /orgs/{org}/actions/variables/{name}/repositories" ], listSelectedRepositoriesEnabledGithubActionsOrganization: [ "GET /orgs/{org}/actions/permissions/repositories" ], listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], listWorkflowRunArtifacts: [ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" ], listWorkflowRuns: [ "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" ], listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], reRunJobForWorkflowRun: [ "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" ], reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], reRunWorkflowFailedJobs: [ "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" ], removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" ], removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" ], removeCustomLabelFromSelfHostedRunnerForOrg: [ "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" ], removeCustomLabelFromSelfHostedRunnerForRepo: [ "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" ], removeSelectedRepoFromOrgSecret: [ "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" ], removeSelectedRepoFromOrgVariable: [ "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" ], reviewCustomGatesForRun: [ "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" ], reviewPendingDeploymentsForRun: [ "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" ], setAllowedActionsOrganization: [ "PUT /orgs/{org}/actions/permissions/selected-actions" ], setAllowedActionsRepository: [ "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" ], setCustomLabelsForSelfHostedRunnerForOrg: [ "PUT /orgs/{org}/actions/runners/{runner_id}/labels" ], setCustomLabelsForSelfHostedRunnerForRepo: [ "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" ], setCustomOidcSubClaimForRepo: [ "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" ], setGithubActionsDefaultWorkflowPermissionsOrganization: [ "PUT /orgs/{org}/actions/permissions/workflow" ], setGithubActionsDefaultWorkflowPermissionsRepository: [ "PUT /repos/{owner}/{repo}/actions/permissions/workflow" ], setGithubActionsPermissionsOrganization: [ "PUT /orgs/{org}/actions/permissions" ], setGithubActionsPermissionsRepository: [ "PUT /repos/{owner}/{repo}/actions/permissions" ], setSelectedReposForOrgSecret: [ "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" ], setSelectedReposForOrgVariable: [ "PUT /orgs/{org}/actions/variables/{name}/repositories" ], setSelectedRepositoriesEnabledGithubActionsOrganization: [ "PUT /orgs/{org}/actions/permissions/repositories" ], setWorkflowAccessToRepository: [ "PUT /repos/{owner}/{repo}/actions/permissions/access" ], updateEnvironmentVariable: [ "PATCH /repositories/{repository_id}/environments/{environment_name}/variables/{name}" ], updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], updateRepoVariable: [ "PATCH /repos/{owner}/{repo}/actions/variables/{name}" ] }, activity: { checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], deleteThreadSubscription: [ "DELETE /notifications/threads/{thread_id}/subscription" ], getFeeds: ["GET /feeds"], getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], getThread: ["GET /notifications/threads/{thread_id}"], getThreadSubscriptionForAuthenticatedUser: [ "GET /notifications/threads/{thread_id}/subscription" ], listEventsForAuthenticatedUser: ["GET /users/{username}/events"], listNotificationsForAuthenticatedUser: ["GET /notifications"], listOrgEventsForAuthenticatedUser: [ "GET /users/{username}/events/orgs/{org}" ], listPublicEvents: ["GET /events"], listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], listPublicEventsForUser: ["GET /users/{username}/events/public"], listPublicOrgEvents: ["GET /orgs/{org}/events"], listReceivedEventsForUser: ["GET /users/{username}/received_events"], listReceivedPublicEventsForUser: [ "GET /users/{username}/received_events/public" ], listRepoEvents: ["GET /repos/{owner}/{repo}/events"], listRepoNotificationsForAuthenticatedUser: [ "GET /repos/{owner}/{repo}/notifications" ], listReposStarredByAuthenticatedUser: ["GET /user/starred"], listReposStarredByUser: ["GET /users/{username}/starred"], listReposWatchedByUser: ["GET /users/{username}/subscriptions"], listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], markNotificationsAsRead: ["PUT /notifications"], markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], markThreadAsDone: ["DELETE /notifications/threads/{thread_id}"], markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], setThreadSubscription: [ "PUT /notifications/threads/{thread_id}/subscription" ], starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] }, apps: { addRepoToInstallation: [ "PUT /user/installations/{installation_id}/repositories/{repository_id}", {}, { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } ], addRepoToInstallationForAuthenticatedUser: [ "PUT /user/installations/{installation_id}/repositories/{repository_id}" ], checkToken: ["POST /applications/{client_id}/token"], createFromManifest: ["POST /app-manifests/{code}/conversions"], createInstallationAccessToken: [ "POST /app/installations/{installation_id}/access_tokens" ], deleteAuthorization: ["DELETE /applications/{client_id}/grant"], deleteInstallation: ["DELETE /app/installations/{installation_id}"], deleteToken: ["DELETE /applications/{client_id}/token"], getAuthenticated: ["GET /app"], getBySlug: ["GET /apps/{app_slug}"], getInstallation: ["GET /app/installations/{installation_id}"], getOrgInstallation: ["GET /orgs/{org}/installation"], getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], getSubscriptionPlanForAccount: [ "GET /marketplace_listing/accounts/{account_id}" ], getSubscriptionPlanForAccountStubbed: [ "GET /marketplace_listing/stubbed/accounts/{account_id}" ], getUserInstallation: ["GET /users/{username}/installation"], getWebhookConfigForApp: ["GET /app/hook/config"], getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], listAccountsForPlanStubbed: [ "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" ], listInstallationReposForAuthenticatedUser: [ "GET /user/installations/{installation_id}/repositories" ], listInstallationRequestsForAuthenticatedApp: [ "GET /app/installation-requests" ], listInstallations: ["GET /app/installations"], listInstallationsForAuthenticatedUser: ["GET /user/installations"], listPlans: ["GET /marketplace_listing/plans"], listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], listReposAccessibleToInstallation: ["GET /installation/repositories"], listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], listSubscriptionsForAuthenticatedUserStubbed: [ "GET /user/marketplace_purchases/stubbed" ], listWebhookDeliveries: ["GET /app/hook/deliveries"], redeliverWebhookDelivery: [ "POST /app/hook/deliveries/{delivery_id}/attempts" ], removeRepoFromInstallation: [ "DELETE /user/installations/{installation_id}/repositories/{repository_id}", {}, { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } ], removeRepoFromInstallationForAuthenticatedUser: [ "DELETE /user/installations/{installation_id}/repositories/{repository_id}" ], resetToken: ["PATCH /applications/{client_id}/token"], revokeInstallationAccessToken: ["DELETE /installation/token"], scopeToken: ["POST /applications/{client_id}/token/scoped"], suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], unsuspendInstallation: [ "DELETE /app/installations/{installation_id}/suspended" ], updateWebhookConfigForApp: ["PATCH /app/hook/config"] }, billing: { getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], getGithubActionsBillingUser: [ "GET /users/{username}/settings/billing/actions" ], getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], getGithubPackagesBillingUser: [ "GET /users/{username}/settings/billing/packages" ], getSharedStorageBillingOrg: [ "GET /orgs/{org}/settings/billing/shared-storage" ], getSharedStorageBillingUser: [ "GET /users/{username}/settings/billing/shared-storage" ] }, checks: { create: ["POST /repos/{owner}/{repo}/check-runs"], createSuite: ["POST /repos/{owner}/{repo}/check-suites"], get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], listAnnotations: [ "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" ], listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], listForSuite: [ "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" ], listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], rerequestRun: [ "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" ], rerequestSuite: [ "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" ], setSuitesPreferences: [ "PATCH /repos/{owner}/{repo}/check-suites/preferences" ], update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] }, codeScanning: { deleteAnalysis: [ "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" ], getAlert: [ "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", {}, { renamedParameters: { alert_id: "alert_number" } } ], getAnalysis: [ "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" ], getCodeqlDatabase: [ "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" ], getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], listAlertInstances: [ "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" ], listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], listAlertsInstances: [ "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", {}, { renamed: ["codeScanning", "listAlertInstances"] } ], listCodeqlDatabases: [ "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" ], listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], updateAlert: [ "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" ], updateDefaultSetup: [ "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" ], uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] }, codesOfConduct: { getAllCodesOfConduct: ["GET /codes_of_conduct"], getConductCode: ["GET /codes_of_conduct/{key}"] }, codespaces: { addRepositoryForSecretForAuthenticatedUser: [ "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" ], addSelectedRepoToOrgSecret: [ "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" ], checkPermissionsForDevcontainer: [ "GET /repos/{owner}/{repo}/codespaces/permissions_check" ], codespaceMachinesForAuthenticatedUser: [ "GET /user/codespaces/{codespace_name}/machines" ], createForAuthenticatedUser: ["POST /user/codespaces"], createOrUpdateOrgSecret: [ "PUT /orgs/{org}/codespaces/secrets/{secret_name}" ], createOrUpdateRepoSecret: [ "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" ], createOrUpdateSecretForAuthenticatedUser: [ "PUT /user/codespaces/secrets/{secret_name}" ], createWithPrForAuthenticatedUser: [ "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" ], createWithRepoForAuthenticatedUser: [ "POST /repos/{owner}/{repo}/codespaces" ], deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], deleteFromOrganization: [ "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" ], deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], deleteRepoSecret: [ "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" ], deleteSecretForAuthenticatedUser: [ "DELETE /user/codespaces/secrets/{secret_name}" ], exportForAuthenticatedUser: [ "POST /user/codespaces/{codespace_name}/exports" ], getCodespacesForUserInOrg: [ "GET /orgs/{org}/members/{username}/codespaces" ], getExportDetailsForAuthenticatedUser: [ "GET /user/codespaces/{codespace_name}/exports/{export_id}" ], getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], getPublicKeyForAuthenticatedUser: [ "GET /user/codespaces/secrets/public-key" ], getRepoPublicKey: [ "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" ], getRepoSecret: [ "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" ], getSecretForAuthenticatedUser: [ "GET /user/codespaces/secrets/{secret_name}" ], listDevcontainersInRepositoryForAuthenticatedUser: [ "GET /repos/{owner}/{repo}/codespaces/devcontainers" ], listForAuthenticatedUser: ["GET /user/codespaces"], listInOrganization: [ "GET /orgs/{org}/codespaces", {}, { renamedParameters: { org_id: "org" } } ], listInRepositoryForAuthenticatedUser: [ "GET /repos/{owner}/{repo}/codespaces" ], listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], listRepositoriesForSecretForAuthenticatedUser: [ "GET /user/codespaces/secrets/{secret_name}/repositories" ], listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], listSelectedReposForOrgSecret: [ "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" ], preFlightWithRepoForAuthenticatedUser: [ "GET /repos/{owner}/{repo}/codespaces/new" ], publishForAuthenticatedUser: [ "POST /user/codespaces/{codespace_name}/publish" ], removeRepositoryForSecretForAuthenticatedUser: [ "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" ], removeSelectedRepoFromOrgSecret: [ "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" ], repoMachinesForAuthenticatedUser: [ "GET /repos/{owner}/{repo}/codespaces/machines" ], setRepositoriesForSecretForAuthenticatedUser: [ "PUT /user/codespaces/secrets/{secret_name}/repositories" ], setSelectedReposForOrgSecret: [ "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" ], startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], stopInOrganization: [ "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" ], updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] }, copilot: { addCopilotSeatsForTeams: [ "POST /orgs/{org}/copilot/billing/selected_teams" ], addCopilotSeatsForUsers: [ "POST /orgs/{org}/copilot/billing/selected_users" ], cancelCopilotSeatAssignmentForTeams: [ "DELETE /orgs/{org}/copilot/billing/selected_teams" ], cancelCopilotSeatAssignmentForUsers: [ "DELETE /orgs/{org}/copilot/billing/selected_users" ], getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], getCopilotSeatDetailsForUser: [ "GET /orgs/{org}/members/{username}/copilot" ], listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] }, dependabot: { addSelectedRepoToOrgSecret: [ "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" ], createOrUpdateOrgSecret: [ "PUT /orgs/{org}/dependabot/secrets/{secret_name}" ], createOrUpdateRepoSecret: [ "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" ], deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], deleteRepoSecret: [ "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" ], getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], getRepoPublicKey: [ "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" ], getRepoSecret: [ "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" ], listAlertsForEnterprise: [ "GET /enterprises/{enterprise}/dependabot/alerts" ], listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], listSelectedReposForOrgSecret: [ "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" ], removeSelectedRepoFromOrgSecret: [ "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" ], setSelectedReposForOrgSecret: [ "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" ], updateAlert: [ "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" ] }, dependencyGraph: { createRepositorySnapshot: [ "POST /repos/{owner}/{repo}/dependency-graph/snapshots" ], diffRange: [ "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" ], exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] }, emojis: { get: ["GET /emojis"] }, gists: { checkIsStarred: ["GET /gists/{gist_id}/star"], create: ["POST /gists"], createComment: ["POST /gists/{gist_id}/comments"], delete: ["DELETE /gists/{gist_id}"], deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], fork: ["POST /gists/{gist_id}/forks"], get: ["GET /gists/{gist_id}"], getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], getRevision: ["GET /gists/{gist_id}/{sha}"], list: ["GET /gists"], listComments: ["GET /gists/{gist_id}/comments"], listCommits: ["GET /gists/{gist_id}/commits"], listForUser: ["GET /users/{username}/gists"], listForks: ["GET /gists/{gist_id}/forks"], listPublic: ["GET /gists/public"], listStarred: ["GET /gists/starred"], star: ["PUT /gists/{gist_id}/star"], unstar: ["DELETE /gists/{gist_id}/star"], update: ["PATCH /gists/{gist_id}"], updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] }, git: { createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], createCommit: ["POST /repos/{owner}/{repo}/git/commits"], createRef: ["POST /repos/{owner}/{repo}/git/refs"], createTag: ["POST /repos/{owner}/{repo}/git/tags"], createTree: ["POST /repos/{owner}/{repo}/git/trees"], deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] }, gitignore: { getAllTemplates: ["GET /gitignore/templates"], getTemplate: ["GET /gitignore/templates/{name}"] }, interactions: { getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], getRestrictionsForYourPublicRepos: [ "GET /user/interaction-limits", {}, { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } ], removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], removeRestrictionsForRepo: [ "DELETE /repos/{owner}/{repo}/interaction-limits" ], removeRestrictionsForYourPublicRepos: [ "DELETE /user/interaction-limits", {}, { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } ], setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], setRestrictionsForYourPublicRepos: [ "PUT /user/interaction-limits", {}, { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } ] }, issues: { addAssignees: [ "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" ], addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], checkUserCanBeAssignedToIssue: [ "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" ], create: ["POST /repos/{owner}/{repo}/issues"], createComment: [ "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" ], createLabel: ["POST /repos/{owner}/{repo}/labels"], createMilestone: ["POST /repos/{owner}/{repo}/milestones"], deleteComment: [ "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" ], deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], deleteMilestone: [ "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" ], get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], list: ["GET /issues"], listAssignees: ["GET /repos/{owner}/{repo}/assignees"], listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], listEventsForTimeline: [ "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" ], listForAuthenticatedUser: ["GET /user/issues"], listForOrg: ["GET /orgs/{org}/issues"], listForRepo: ["GET /repos/{owner}/{repo}/issues"], listLabelsForMilestone: [ "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" ], listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], listLabelsOnIssue: [ "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" ], listMilestones: ["GET /repos/{owner}/{repo}/milestones"], lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], removeAllLabels: [ "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" ], removeAssignees: [ "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" ], removeLabel: [ "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" ], setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], updateMilestone: [ "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" ] }, licenses: { get: ["GET /licenses/{license}"], getAllCommonlyUsed: ["GET /licenses"], getForRepo: ["GET /repos/{owner}/{repo}/license"] }, markdown: { render: ["POST /markdown"], renderRaw: [ "POST /markdown/raw", { headers: { "content-type": "text/plain; charset=utf-8" } } ] }, meta: { get: ["GET /meta"], getAllVersions: ["GET /versions"], getOctocat: ["GET /octocat"], getZen: ["GET /zen"], root: ["GET /"] }, migrations: { cancelImport: [ "DELETE /repos/{owner}/{repo}/import", {}, { deprecated: "octokit.rest.migrations.cancelImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#cancel-an-import" } ], deleteArchiveForAuthenticatedUser: [ "DELETE /user/migrations/{migration_id}/archive" ], deleteArchiveForOrg: [ "DELETE /orgs/{org}/migrations/{migration_id}/archive" ], downloadArchiveForOrg: [ "GET /orgs/{org}/migrations/{migration_id}/archive" ], getArchiveForAuthenticatedUser: [ "GET /user/migrations/{migration_id}/archive" ], getCommitAuthors: [ "GET /repos/{owner}/{repo}/import/authors", {}, { deprecated: "octokit.rest.migrations.getCommitAuthors() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-commit-authors" } ], getImportStatus: [ "GET /repos/{owner}/{repo}/import", {}, { deprecated: "octokit.rest.migrations.getImportStatus() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-an-import-status" } ], getLargeFiles: [ "GET /repos/{owner}/{repo}/import/large_files", {}, { deprecated: "octokit.rest.migrations.getLargeFiles() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-large-files" } ], getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], listForAuthenticatedUser: ["GET /user/migrations"], listForOrg: ["GET /orgs/{org}/migrations"], listReposForAuthenticatedUser: [ "GET /user/migrations/{migration_id}/repositories" ], listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], listReposForUser: [ "GET /user/migrations/{migration_id}/repositories", {}, { renamed: ["migrations", "listReposForAuthenticatedUser"] } ], mapCommitAuthor: [ "PATCH /repos/{owner}/{repo}/import/authors/{author_id}", {}, { deprecated: "octokit.rest.migrations.mapCommitAuthor() is deprecated, see https://docs.github.com/rest/migrations/source-imports#map-a-commit-author" } ], setLfsPreference: [ "PATCH /repos/{owner}/{repo}/import/lfs", {}, { deprecated: "octokit.rest.migrations.setLfsPreference() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-git-lfs-preference" } ], startForAuthenticatedUser: ["POST /user/migrations"], startForOrg: ["POST /orgs/{org}/migrations"], startImport: [ "PUT /repos/{owner}/{repo}/import", {}, { deprecated: "octokit.rest.migrations.startImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#start-an-import" } ], unlockRepoForAuthenticatedUser: [ "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" ], unlockRepoForOrg: [ "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" ], updateImport: [ "PATCH /repos/{owner}/{repo}/import", {}, { deprecated: "octokit.rest.migrations.updateImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-an-import" } ] }, oidc: { getOidcCustomSubTemplateForOrg: [ "GET /orgs/{org}/actions/oidc/customization/sub" ], updateOidcCustomSubTemplateForOrg: [ "PUT /orgs/{org}/actions/oidc/customization/sub" ] }, orgs: { addSecurityManagerTeam: [ "PUT /orgs/{org}/security-managers/teams/{team_slug}" ], assignTeamToOrgRole: [ "PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" ], assignUserToOrgRole: [ "PUT /orgs/{org}/organization-roles/users/{username}/{role_id}" ], blockUser: ["PUT /orgs/{org}/blocks/{username}"], cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], convertMemberToOutsideCollaborator: [ "PUT /orgs/{org}/outside_collaborators/{username}" ], createCustomOrganizationRole: ["POST /orgs/{org}/organization-roles"], createInvitation: ["POST /orgs/{org}/invitations"], createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"], createOrUpdateCustomPropertiesValuesForRepos: [ "PATCH /orgs/{org}/properties/values" ], createOrUpdateCustomProperty: [ "PUT /orgs/{org}/properties/schema/{custom_property_name}" ], createWebhook: ["POST /orgs/{org}/hooks"], delete: ["DELETE /orgs/{org}"], deleteCustomOrganizationRole: [ "DELETE /orgs/{org}/organization-roles/{role_id}" ], deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], enableOrDisableSecurityProductOnAllOrgRepos: [ "POST /orgs/{org}/{security_product}/{enablement}" ], get: ["GET /orgs/{org}"], getAllCustomProperties: ["GET /orgs/{org}/properties/schema"], getCustomProperty: [ "GET /orgs/{org}/properties/schema/{custom_property_name}" ], getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], getOrgRole: ["GET /orgs/{org}/organization-roles/{role_id}"], getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], getWebhookDelivery: [ "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" ], list: ["GET /organizations"], listAppInstallations: ["GET /orgs/{org}/installations"], listBlockedUsers: ["GET /orgs/{org}/blocks"], listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"], listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], listForAuthenticatedUser: ["GET /user/orgs"], listForUser: ["GET /users/{username}/orgs"], listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], listMembers: ["GET /orgs/{org}/members"], listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], listOrgRoleTeams: ["GET /orgs/{org}/organization-roles/{role_id}/teams"], listOrgRoleUsers: ["GET /orgs/{org}/organization-roles/{role_id}/users"], listOrgRoles: ["GET /orgs/{org}/organization-roles"], listOrganizationFineGrainedPermissions: [ "GET /orgs/{org}/organization-fine-grained-permissions" ], listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], listPatGrantRepositories: [ "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" ], listPatGrantRequestRepositories: [ "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" ], listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], listPendingInvitations: ["GET /orgs/{org}/invitations"], listPublicMembers: ["GET /orgs/{org}/public_members"], listSecurityManagerTeams: ["GET /orgs/{org}/security-managers"], listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], listWebhooks: ["GET /orgs/{org}/hooks"], patchCustomOrganizationRole: [ "PATCH /orgs/{org}/organization-roles/{role_id}" ], pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], redeliverWebhookDelivery: [ "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" ], removeCustomProperty: [ "DELETE /orgs/{org}/properties/schema/{custom_property_name}" ], removeMember: ["DELETE /orgs/{org}/members/{username}"], removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], removeOutsideCollaborator: [ "DELETE /orgs/{org}/outside_collaborators/{username}" ], removePublicMembershipForAuthenticatedUser: [ "DELETE /orgs/{org}/public_members/{username}" ], removeSecurityManagerTeam: [ "DELETE /orgs/{org}/security-managers/teams/{team_slug}" ], reviewPatGrantRequest: [ "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" ], reviewPatGrantRequestsInBulk: [ "POST /orgs/{org}/personal-access-token-requests" ], revokeAllOrgRolesTeam: [ "DELETE /orgs/{org}/organization-roles/teams/{team_slug}" ], revokeAllOrgRolesUser: [ "DELETE /orgs/{org}/organization-roles/users/{username}" ], revokeOrgRoleTeam: [ "DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" ], revokeOrgRoleUser: [ "DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}" ], setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], setPublicMembershipForAuthenticatedUser: [ "PUT /orgs/{org}/public_members/{username}" ], unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], update: ["PATCH /orgs/{org}"], updateMembershipForAuthenticatedUser: [ "PATCH /user/memberships/orgs/{org}" ], updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] }, packages: { deletePackageForAuthenticatedUser: [ "DELETE /user/packages/{package_type}/{package_name}" ], deletePackageForOrg: [ "DELETE /orgs/{org}/packages/{package_type}/{package_name}" ], deletePackageForUser: [ "DELETE /users/{username}/packages/{package_type}/{package_name}" ], deletePackageVersionForAuthenticatedUser: [ "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" ], deletePackageVersionForOrg: [ "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" ], deletePackageVersionForUser: [ "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" ], getAllPackageVersionsForAPackageOwnedByAnOrg: [ "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", {}, { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } ], getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ "GET /user/packages/{package_type}/{package_name}/versions", {}, { renamed: [ "packages", "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" ] } ], getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ "GET /user/packages/{package_type}/{package_name}/versions" ], getAllPackageVersionsForPackageOwnedByOrg: [ "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" ], getAllPackageVersionsForPackageOwnedByUser: [ "GET /users/{username}/packages/{package_type}/{package_name}/versions" ], getPackageForAuthenticatedUser: [ "GET /user/packages/{package_type}/{package_name}" ], getPackageForOrganization: [ "GET /orgs/{org}/packages/{package_type}/{package_name}" ], getPackageForUser: [ "GET /users/{username}/packages/{package_type}/{package_name}" ], getPackageVersionForAuthenticatedUser: [ "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" ], getPackageVersionForOrganization: [ "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" ], getPackageVersionForUser: [ "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" ], listDockerMigrationConflictingPackagesForAuthenticatedUser: [ "GET /user/docker/conflicts" ], listDockerMigrationConflictingPackagesForOrganization: [ "GET /orgs/{org}/docker/conflicts" ], listDockerMigrationConflictingPackagesForUser: [ "GET /users/{username}/docker/conflicts" ], listPackagesForAuthenticatedUser: ["GET /user/packages"], listPackagesForOrganization: ["GET /orgs/{org}/packages"], listPackagesForUser: ["GET /users/{username}/packages"], restorePackageForAuthenticatedUser: [ "POST /user/packages/{package_type}/{package_name}/restore{?token}" ], restorePackageForOrg: [ "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" ], restorePackageForUser: [ "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" ], restorePackageVersionForAuthenticatedUser: [ "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" ], restorePackageVersionForOrg: [ "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" ], restorePackageVersionForUser: [ "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" ] }, projects: { addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"], createCard: ["POST /projects/columns/{column_id}/cards"], createColumn: ["POST /projects/{project_id}/columns"], createForAuthenticatedUser: ["POST /user/projects"], createForOrg: ["POST /orgs/{org}/projects"], createForRepo: ["POST /repos/{owner}/{repo}/projects"], delete: ["DELETE /projects/{project_id}"], deleteCard: ["DELETE /projects/columns/cards/{card_id}"], deleteColumn: ["DELETE /projects/columns/{column_id}"], get: ["GET /projects/{project_id}"], getCard: ["GET /projects/columns/cards/{card_id}"], getColumn: ["GET /projects/columns/{column_id}"], getPermissionForUser: [ "GET /projects/{project_id}/collaborators/{username}/permission" ], listCards: ["GET /projects/columns/{column_id}/cards"], listCollaborators: ["GET /projects/{project_id}/collaborators"], listColumns: ["GET /projects/{project_id}/columns"], listForOrg: ["GET /orgs/{org}/projects"], listForRepo: ["GET /repos/{owner}/{repo}/projects"], listForUser: ["GET /users/{username}/projects"], moveCard: ["POST /projects/columns/cards/{card_id}/moves"], moveColumn: ["POST /projects/columns/{column_id}/moves"], removeCollaborator: [ "DELETE /projects/{project_id}/collaborators/{username}" ], update: ["PATCH /projects/{project_id}"], updateCard: ["PATCH /projects/columns/cards/{card_id}"], updateColumn: ["PATCH /projects/columns/{column_id}"] }, pulls: { checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], create: ["POST /repos/{owner}/{repo}/pulls"], createReplyForReviewComment: [ "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" ], createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], createReviewComment: [ "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" ], deletePendingReview: [ "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" ], deleteReviewComment: [ "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" ], dismissReview: [ "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" ], get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], getReview: [ "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" ], getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], list: ["GET /repos/{owner}/{repo}/pulls"], listCommentsForReview: [ "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" ], listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], listRequestedReviewers: [ "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" ], listReviewComments: [ "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" ], listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], removeRequestedReviewers: [ "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" ], requestReviewers: [ "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" ], submitReview: [ "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" ], update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], updateBranch: [ "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" ], updateReview: [ "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" ], updateReviewComment: [ "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" ] }, rateLimit: { get: ["GET /rate_limit"] }, reactions: { createForCommitComment: [ "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" ], createForIssue: [ "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" ], createForIssueComment: [ "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" ], createForPullRequestReviewComment: [ "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" ], createForRelease: [ "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" ], createForTeamDiscussionCommentInOrg: [ "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" ], createForTeamDiscussionInOrg: [ "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" ], deleteForCommitComment: [ "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" ], deleteForIssue: [ "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" ], deleteForIssueComment: [ "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" ], deleteForPullRequestComment: [ "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" ], deleteForRelease: [ "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" ], deleteForTeamDiscussion: [ "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" ], deleteForTeamDiscussionComment: [ "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" ], listForCommitComment: [ "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" ], listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], listForIssueComment: [ "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" ], listForPullRequestReviewComment: [ "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" ], listForRelease: [ "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" ], listForTeamDiscussionCommentInOrg: [ "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" ], listForTeamDiscussionInOrg: [ "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" ] }, repos: { acceptInvitation: [ "PATCH /user/repository_invitations/{invitation_id}", {}, { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } ], acceptInvitationForAuthenticatedUser: [ "PATCH /user/repository_invitations/{invitation_id}" ], addAppAccessRestrictions: [ "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { mapToData: "apps" } ], addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], addStatusCheckContexts: [ "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { mapToData: "contexts" } ], addTeamAccessRestrictions: [ "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { mapToData: "teams" } ], addUserAccessRestrictions: [ "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { mapToData: "users" } ], cancelPagesDeployment: [ "POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel" ], checkAutomatedSecurityFixes: [ "GET /repos/{owner}/{repo}/automated-security-fixes" ], checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], checkVulnerabilityAlerts: [ "GET /repos/{owner}/{repo}/vulnerability-alerts" ], codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], compareCommitsWithBasehead: [ "GET /repos/{owner}/{repo}/compare/{basehead}" ], createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], createCommitComment: [ "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" ], createCommitSignatureProtection: [ "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" ], createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], createDeployKey: ["POST /repos/{owner}/{repo}/keys"], createDeployment: ["POST /repos/{owner}/{repo}/deployments"], createDeploymentBranchPolicy: [ "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" ], createDeploymentProtectionRule: [ "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" ], createDeploymentStatus: [ "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" ], createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], createForAuthenticatedUser: ["POST /user/repos"], createFork: ["POST /repos/{owner}/{repo}/forks"], createInOrg: ["POST /orgs/{org}/repos"], createOrUpdateCustomPropertiesValues: [ "PATCH /repos/{owner}/{repo}/properties/values" ], createOrUpdateEnvironment: [ "PUT /repos/{owner}/{repo}/environments/{environment_name}" ], createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], createOrgRuleset: ["POST /orgs/{org}/rulesets"], createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployments"], createPagesSite: ["POST /repos/{owner}/{repo}/pages"], createRelease: ["POST /repos/{owner}/{repo}/releases"], createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], createTagProtection: ["POST /repos/{owner}/{repo}/tags/protection"], createUsingTemplate: [ "POST /repos/{template_owner}/{template_repo}/generate" ], createWebhook: ["POST /repos/{owner}/{repo}/hooks"], declineInvitation: [ "DELETE /user/repository_invitations/{invitation_id}", {}, { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } ], declineInvitationForAuthenticatedUser: [ "DELETE /user/repository_invitations/{invitation_id}" ], delete: ["DELETE /repos/{owner}/{repo}"], deleteAccessRestrictions: [ "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" ], deleteAdminBranchProtection: [ "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" ], deleteAnEnvironment: [ "DELETE /repos/{owner}/{repo}/environments/{environment_name}" ], deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], deleteBranchProtection: [ "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" ], deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], deleteCommitSignatureProtection: [ "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" ], deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], deleteDeployment: [ "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" ], deleteDeploymentBranchPolicy: [ "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" ], deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], deleteInvitation: [ "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" ], deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], deletePullRequestReviewProtection: [ "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" ], deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], deleteReleaseAsset: [ "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" ], deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], deleteTagProtection: [ "DELETE /repos/{owner}/{repo}/tags/protection/{tag_protection_id}" ], deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], disableAutomatedSecurityFixes: [ "DELETE /repos/{owner}/{repo}/automated-security-fixes" ], disableDeploymentProtectionRule: [ "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" ], disablePrivateVulnerabilityReporting: [ "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" ], disableVulnerabilityAlerts: [ "DELETE /repos/{owner}/{repo}/vulnerability-alerts" ], downloadArchive: [ "GET /repos/{owner}/{repo}/zipball/{ref}", {}, { renamed: ["repos", "downloadZipballArchive"] } ], downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], enableAutomatedSecurityFixes: [ "PUT /repos/{owner}/{repo}/automated-security-fixes" ], enablePrivateVulnerabilityReporting: [ "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" ], enableVulnerabilityAlerts: [ "PUT /repos/{owner}/{repo}/vulnerability-alerts" ], generateReleaseNotes: [ "POST /repos/{owner}/{repo}/releases/generate-notes" ], get: ["GET /repos/{owner}/{repo}"], getAccessRestrictions: [ "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" ], getAdminBranchProtection: [ "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" ], getAllDeploymentProtectionRules: [ "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" ], getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], getAllStatusCheckContexts: [ "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" ], getAllTopics: ["GET /repos/{owner}/{repo}/topics"], getAppsWithAccessToProtectedBranch: [ "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" ], getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], getBranchProtection: [ "GET /repos/{owner}/{repo}/branches/{branch}/protection" ], getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], getCollaboratorPermissionLevel: [ "GET /repos/{owner}/{repo}/collaborators/{username}/permission" ], getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], getCommitSignatureProtection: [ "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" ], getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], getCustomDeploymentProtectionRule: [ "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" ], getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"], getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], getDeploymentBranchPolicy: [ "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" ], getDeploymentStatus: [ "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" ], getEnvironment: [ "GET /repos/{owner}/{repo}/environments/{environment_name}" ], getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], getOrgRulesets: ["GET /orgs/{org}/rulesets"], getPages: ["GET /repos/{owner}/{repo}/pages"], getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], getPagesDeployment: [ "GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}" ], getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], getPullRequestReviewProtection: [ "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" ], getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], getReadme: ["GET /repos/{owner}/{repo}/readme"], getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], getRepoRuleSuite: [ "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" ], getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], getStatusChecksProtection: [ "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" ], getTeamsWithAccessToProtectedBranch: [ "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" ], getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], getUsersWithAccessToProtectedBranch: [ "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" ], getViews: ["GET /repos/{owner}/{repo}/traffic/views"], getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], getWebhookConfigForRepo: [ "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" ], getWebhookDelivery: [ "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" ], listActivities: ["GET /repos/{owner}/{repo}/activity"], listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], listBranches: ["GET /repos/{owner}/{repo}/branches"], listBranchesForHeadCommit: [ "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" ], listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], listCommentsForCommit: [ "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" ], listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], listCommitStatusesForRef: [ "GET /repos/{owner}/{repo}/commits/{ref}/statuses" ], listCommits: ["GET /repos/{owner}/{repo}/commits"], listContributors: ["GET /repos/{owner}/{repo}/contributors"], listCustomDeploymentRuleIntegrations: [ "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" ], listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], listDeploymentBranchPolicies: [ "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" ], listDeploymentStatuses: [ "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" ], listDeployments: ["GET /repos/{owner}/{repo}/deployments"], listForAuthenticatedUser: ["GET /user/repos"], listForOrg: ["GET /orgs/{org}/repos"], listForUser: ["GET /users/{username}/repos"], listForks: ["GET /repos/{owner}/{repo}/forks"], listInvitations: ["GET /repos/{owner}/{repo}/invitations"], listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], listLanguages: ["GET /repos/{owner}/{repo}/languages"], listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], listPublic: ["GET /repositories"], listPullRequestsAssociatedWithCommit: [ "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" ], listReleaseAssets: [ "GET /repos/{owner}/{repo}/releases/{release_id}/assets" ], listReleases: ["GET /repos/{owner}/{repo}/releases"], listTagProtection: ["GET /repos/{owner}/{repo}/tags/protection"], listTags: ["GET /repos/{owner}/{repo}/tags"], listTeams: ["GET /repos/{owner}/{repo}/teams"], listWebhookDeliveries: [ "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" ], listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], merge: ["POST /repos/{owner}/{repo}/merges"], mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], redeliverWebhookDelivery: [ "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" ], removeAppAccessRestrictions: [ "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { mapToData: "apps" } ], removeCollaborator: [ "DELETE /repos/{owner}/{repo}/collaborators/{username}" ], removeStatusCheckContexts: [ "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { mapToData: "contexts" } ], removeStatusCheckProtection: [ "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" ], removeTeamAccessRestrictions: [ "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { mapToData: "teams" } ], removeUserAccessRestrictions: [ "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { mapToData: "users" } ], renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], setAdminBranchProtection: [ "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" ], setAppAccessRestrictions: [ "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { mapToData: "apps" } ], setStatusCheckContexts: [ "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { mapToData: "contexts" } ], setTeamAccessRestrictions: [ "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { mapToData: "teams" } ], setUserAccessRestrictions: [ "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { mapToData: "users" } ], testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], transfer: ["POST /repos/{owner}/{repo}/transfer"], update: ["PATCH /repos/{owner}/{repo}"], updateBranchProtection: [ "PUT /repos/{owner}/{repo}/branches/{branch}/protection" ], updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], updateDeploymentBranchPolicy: [ "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" ], updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], updateInvitation: [ "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" ], updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], updatePullRequestReviewProtection: [ "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" ], updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], updateReleaseAsset: [ "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" ], updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], updateStatusCheckPotection: [ "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, { renamed: ["repos", "updateStatusCheckProtection"] } ], updateStatusCheckProtection: [ "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" ], updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], updateWebhookConfigForRepo: [ "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" ], uploadReleaseAsset: [ "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", { baseUrl: "https://uploads.github.com" } ] }, search: { code: ["GET /search/code"], commits: ["GET /search/commits"], issuesAndPullRequests: ["GET /search/issues"], labels: ["GET /search/labels"], repos: ["GET /search/repositories"], topics: ["GET /search/topics"], users: ["GET /search/users"] }, secretScanning: { getAlert: [ "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" ], listAlertsForEnterprise: [ "GET /enterprises/{enterprise}/secret-scanning/alerts" ], listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], listLocationsForAlert: [ "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" ], updateAlert: [ "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" ] }, securityAdvisories: { createFork: [ "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks" ], createPrivateVulnerabilityReport: [ "POST /repos/{owner}/{repo}/security-advisories/reports" ], createRepositoryAdvisory: [ "POST /repos/{owner}/{repo}/security-advisories" ], createRepositoryAdvisoryCveRequest: [ "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" ], getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], getRepositoryAdvisory: [ "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" ], listGlobalAdvisories: ["GET /advisories"], listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], updateRepositoryAdvisory: [ "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" ] }, teams: { addOrUpdateMembershipForUserInOrg: [ "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" ], addOrUpdateProjectPermissionsInOrg: [ "PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}" ], addOrUpdateRepoPermissionsInOrg: [ "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" ], checkPermissionsForProjectInOrg: [ "GET /orgs/{org}/teams/{team_slug}/projects/{project_id}" ], checkPermissionsForRepoInOrg: [ "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" ], create: ["POST /orgs/{org}/teams"], createDiscussionCommentInOrg: [ "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" ], createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], deleteDiscussionCommentInOrg: [ "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" ], deleteDiscussionInOrg: [ "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" ], deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], getByName: ["GET /orgs/{org}/teams/{team_slug}"], getDiscussionCommentInOrg: [ "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" ], getDiscussionInOrg: [ "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" ], getMembershipForUserInOrg: [ "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" ], list: ["GET /orgs/{org}/teams"], listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], listDiscussionCommentsInOrg: [ "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" ], listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], listForAuthenticatedUser: ["GET /user/teams"], listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], listPendingInvitationsInOrg: [ "GET /orgs/{org}/teams/{team_slug}/invitations" ], listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"], listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], removeMembershipForUserInOrg: [ "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" ], removeProjectInOrg: [ "DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}" ], removeRepoInOrg: [ "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" ], updateDiscussionCommentInOrg: [ "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" ], updateDiscussionInOrg: [ "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" ], updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] }, users: { addEmailForAuthenticated: [ "POST /user/emails", {}, { renamed: ["users", "addEmailForAuthenticatedUser"] } ], addEmailForAuthenticatedUser: ["POST /user/emails"], addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], block: ["PUT /user/blocks/{username}"], checkBlocked: ["GET /user/blocks/{username}"], checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], createGpgKeyForAuthenticated: [ "POST /user/gpg_keys", {}, { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } ], createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], createPublicSshKeyForAuthenticated: [ "POST /user/keys", {}, { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } ], createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], deleteEmailForAuthenticated: [ "DELETE /user/emails", {}, { renamed: ["users", "deleteEmailForAuthenticatedUser"] } ], deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], deleteGpgKeyForAuthenticated: [ "DELETE /user/gpg_keys/{gpg_key_id}", {}, { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } ], deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], deletePublicSshKeyForAuthenticated: [ "DELETE /user/keys/{key_id}", {}, { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } ], deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], deleteSshSigningKeyForAuthenticatedUser: [ "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" ], follow: ["PUT /user/following/{username}"], getAuthenticated: ["GET /user"], getByUsername: ["GET /users/{username}"], getContextForUser: ["GET /users/{username}/hovercard"], getGpgKeyForAuthenticated: [ "GET /user/gpg_keys/{gpg_key_id}", {}, { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } ], getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], getPublicSshKeyForAuthenticated: [ "GET /user/keys/{key_id}", {}, { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } ], getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], getSshSigningKeyForAuthenticatedUser: [ "GET /user/ssh_signing_keys/{ssh_signing_key_id}" ], list: ["GET /users"], listBlockedByAuthenticated: [ "GET /user/blocks", {}, { renamed: ["users", "listBlockedByAuthenticatedUser"] } ], listBlockedByAuthenticatedUser: ["GET /user/blocks"], listEmailsForAuthenticated: [ "GET /user/emails", {}, { renamed: ["users", "listEmailsForAuthenticatedUser"] } ], listEmailsForAuthenticatedUser: ["GET /user/emails"], listFollowedByAuthenticated: [ "GET /user/following", {}, { renamed: ["users", "listFollowedByAuthenticatedUser"] } ], listFollowedByAuthenticatedUser: ["GET /user/following"], listFollowersForAuthenticatedUser: ["GET /user/followers"], listFollowersForUser: ["GET /users/{username}/followers"], listFollowingForUser: ["GET /users/{username}/following"], listGpgKeysForAuthenticated: [ "GET /user/gpg_keys", {}, { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } ], listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], listPublicEmailsForAuthenticated: [ "GET /user/public_emails", {}, { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } ], listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], listPublicKeysForUser: ["GET /users/{username}/keys"], listPublicSshKeysForAuthenticated: [ "GET /user/keys", {}, { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } ], listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], setPrimaryEmailVisibilityForAuthenticated: [ "PATCH /user/email/visibility", {}, { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } ], setPrimaryEmailVisibilityForAuthenticatedUser: [ "PATCH /user/email/visibility" ], unblock: ["DELETE /user/blocks/{username}"], unfollow: ["DELETE /user/following/{username}"], updateAuthenticated: ["PATCH /user"] } }; var endpoints_default = Endpoints; // pkg/dist-src/endpoints-to-methods.js var endpointMethodsMap = /* @__PURE__ */ new Map(); for (const [scope, endpoints] of Object.entries(endpoints_default)) { for (const [methodName, endpoint] of Object.entries(endpoints)) { const [route, defaults, decorations] = endpoint; const [method, url] = route.split(/ /); const endpointDefaults = Object.assign( { method, url }, defaults ); if (!endpointMethodsMap.has(scope)) { endpointMethodsMap.set(scope, /* @__PURE__ */ new Map()); } endpointMethodsMap.get(scope).set(methodName, { scope, methodName, endpointDefaults, decorations }); } } var handler = { has({ scope }, methodName) { return endpointMethodsMap.get(scope).has(methodName); }, getOwnPropertyDescriptor(target, methodName) { return { value: this.get(target, methodName), // ensures method is in the cache configurable: true, writable: true, enumerable: true }; }, defineProperty(target, methodName, descriptor) { Object.defineProperty(target.cache, methodName, descriptor); return true; }, deleteProperty(target, methodName) { delete target.cache[methodName]; return true; }, ownKeys({ scope }) { return [...endpointMethodsMap.get(scope).keys()]; }, set(target, methodName, value) { return target.cache[methodName] = value; }, get({ octokit, scope, cache }, methodName) { if (cache[methodName]) { return cache[methodName]; } const method = endpointMethodsMap.get(scope).get(methodName); if (!method) { return void 0; } const { endpointDefaults, decorations } = method; if (decorations) { cache[methodName] = decorate( octokit, scope, methodName, endpointDefaults, decorations ); } else { cache[methodName] = octokit.request.defaults(endpointDefaults); } return cache[methodName]; } }; function endpointsToMethods(octokit) { const newMethods = {}; for (const scope of endpointMethodsMap.keys()) { newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler); } return newMethods; } function decorate(octokit, scope, methodName, defaults, decorations) { const requestWithDefaults = octokit.request.defaults(defaults); function withDecorations(...args) { let options = requestWithDefaults.endpoint.merge(...args); if (decorations.mapToData) { options = Object.assign({}, options, { data: options[decorations.mapToData], [decorations.mapToData]: void 0 }); return requestWithDefaults(options); } if (decorations.renamed) { const [newScope, newMethodName] = decorations.renamed; octokit.log.warn( `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` ); } if (decorations.deprecated) { octokit.log.warn(decorations.deprecated); } if (decorations.renamedParameters) { const options2 = requestWithDefaults.endpoint.merge(...args); for (const [name, alias] of Object.entries( decorations.renamedParameters )) { if (name in options2) { octokit.log.warn( `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead` ); if (!(alias in options2)) { options2[alias] = options2[name]; } delete options2[name]; } } return requestWithDefaults(options2); } return requestWithDefaults(...args); } return Object.assign(withDecorations, requestWithDefaults); } // pkg/dist-src/index.js function restEndpointMethods(octokit) { const api = endpointsToMethods(octokit); return { rest: api }; } restEndpointMethods.VERSION = VERSION; function legacyRestEndpointMethods(octokit) { const api = endpointsToMethods(octokit); return { ...api, rest: api }; } legacyRestEndpointMethods.VERSION = VERSION; // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 44552: /***/ (function(__unused_webpack_module, exports) { "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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; class BasicCredentialHandler { constructor(username, password) { this.username = username; this.password = password; } prepareRequest(options) { if (!options.headers) { throw Error('The request has no headers'); } options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; } // This handler cannot handle 401 canHandleAuthentication() { return false; } handleAuthentication() { return __awaiter(this, void 0, void 0, function* () { throw new Error('not implemented'); }); } } exports.BasicCredentialHandler = BasicCredentialHandler; class BearerCredentialHandler { constructor(token) { this.token = token; } // currently implements pre-authorization // TODO: support preAuth = false where it hooks on 401 prepareRequest(options) { if (!options.headers) { throw Error('The request has no headers'); } options.headers['Authorization'] = `Bearer ${this.token}`; } // This handler cannot handle 401 canHandleAuthentication() { return false; } handleAuthentication() { return __awaiter(this, void 0, void 0, function* () { throw new Error('not implemented'); }); } } exports.BearerCredentialHandler = BearerCredentialHandler; class PersonalAccessTokenCredentialHandler { constructor(token) { this.token = token; } // currently implements pre-authorization // TODO: support preAuth = false where it hooks on 401 prepareRequest(options) { if (!options.headers) { throw Error('The request has no headers'); } options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; } // This handler cannot handle 401 canHandleAuthentication() { return false; } handleAuthentication() { return __awaiter(this, void 0, void 0, function* () { throw new Error('not implemented'); }); } } exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; //# sourceMappingURL=auth.js.map /***/ }), /***/ 54844: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; /* eslint-disable @typescript-eslint/no-explicit-any */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; 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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; const http = __importStar(__nccwpck_require__(58611)); const https = __importStar(__nccwpck_require__(65692)); const pm = __importStar(__nccwpck_require__(54988)); const tunnel = __importStar(__nccwpck_require__(20770)); const undici_1 = __nccwpck_require__(46752); var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; })(HttpCodes || (exports.HttpCodes = HttpCodes = {})); var Headers; (function (Headers) { Headers["Accept"] = "accept"; Headers["ContentType"] = "content-type"; })(Headers || (exports.Headers = Headers = {})); var MediaTypes; (function (MediaTypes) { MediaTypes["ApplicationJson"] = "application/json"; })(MediaTypes || (exports.MediaTypes = MediaTypes = {})); /** * Returns the proxy URL, depending upon the supplied url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ function getProxyUrl(serverUrl) { const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); return proxyUrl ? proxyUrl.href : ''; } exports.getProxyUrl = getProxyUrl; const HttpRedirectCodes = [ HttpCodes.MovedPermanently, HttpCodes.ResourceMoved, HttpCodes.SeeOther, HttpCodes.TemporaryRedirect, HttpCodes.PermanentRedirect ]; const HttpResponseRetryCodes = [ HttpCodes.BadGateway, HttpCodes.ServiceUnavailable, HttpCodes.GatewayTimeout ]; const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; const ExponentialBackoffCeiling = 10; const ExponentialBackoffTimeSlice = 5; class HttpClientError extends Error { constructor(message, statusCode) { super(message); this.name = 'HttpClientError'; this.statusCode = statusCode; Object.setPrototypeOf(this, HttpClientError.prototype); } } exports.HttpClientError = HttpClientError; class HttpClientResponse { constructor(message) { this.message = message; } readBody() { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { let output = Buffer.alloc(0); this.message.on('data', (chunk) => { output = Buffer.concat([output, chunk]); }); this.message.on('end', () => { resolve(output.toString()); }); })); }); } readBodyBuffer() { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { const chunks = []; this.message.on('data', (chunk) => { chunks.push(chunk); }); this.message.on('end', () => { resolve(Buffer.concat(chunks)); }); })); }); } } exports.HttpClientResponse = HttpClientResponse; function isHttps(requestUrl) { const parsedUrl = new URL(requestUrl); return parsedUrl.protocol === 'https:'; } exports.isHttps = isHttps; class HttpClient { constructor(userAgent, handlers, requestOptions) { this._ignoreSslError = false; this._allowRedirects = true; this._allowRedirectDowngrade = false; this._maxRedirects = 50; this._allowRetries = false; this._maxRetries = 1; this._keepAlive = false; this._disposed = false; this.userAgent = userAgent; this.handlers = handlers || []; this.requestOptions = requestOptions; if (requestOptions) { if (requestOptions.ignoreSslError != null) { this._ignoreSslError = requestOptions.ignoreSslError; } this._socketTimeout = requestOptions.socketTimeout; if (requestOptions.allowRedirects != null) { this._allowRedirects = requestOptions.allowRedirects; } if (requestOptions.allowRedirectDowngrade != null) { this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } if (requestOptions.maxRedirects != null) { this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); } if (requestOptions.keepAlive != null) { this._keepAlive = requestOptions.keepAlive; } if (requestOptions.allowRetries != null) { this._allowRetries = requestOptions.allowRetries; } if (requestOptions.maxRetries != null) { this._maxRetries = requestOptions.maxRetries; } } } options(requestUrl, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); }); } get(requestUrl, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('GET', requestUrl, null, additionalHeaders || {}); }); } del(requestUrl, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('DELETE', requestUrl, null, additionalHeaders || {}); }); } post(requestUrl, data, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('POST', requestUrl, data, additionalHeaders || {}); }); } patch(requestUrl, data, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('PATCH', requestUrl, data, additionalHeaders || {}); }); } put(requestUrl, data, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('PUT', requestUrl, data, additionalHeaders || {}); }); } head(requestUrl, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('HEAD', requestUrl, null, additionalHeaders || {}); }); } sendStream(verb, requestUrl, stream, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request(verb, requestUrl, stream, additionalHeaders); }); } /** * Gets a typed object from an endpoint * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise */ getJson(requestUrl, additionalHeaders = {}) { return __awaiter(this, void 0, void 0, function* () { additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); const res = yield this.get(requestUrl, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } postJson(requestUrl, obj, additionalHeaders = {}) { return __awaiter(this, void 0, void 0, function* () { const data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); const res = yield this.post(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } putJson(requestUrl, obj, additionalHeaders = {}) { return __awaiter(this, void 0, void 0, function* () { const data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); const res = yield this.put(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } patchJson(requestUrl, obj, additionalHeaders = {}) { return __awaiter(this, void 0, void 0, function* () { const data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); const res = yield this.patch(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } /** * Makes a raw http request. * All other methods such as get, post, patch, and request ultimately call this. * Prefer get, del, post and patch */ request(verb, requestUrl, data, headers) { return __awaiter(this, void 0, void 0, function* () { if (this._disposed) { throw new Error('Client has already been disposed.'); } const parsedUrl = new URL(requestUrl); let info = this._prepareRequest(verb, parsedUrl, headers); // Only perform retries on reads since writes may not be idempotent. const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; let numTries = 0; let response; do { response = yield this.requestRaw(info, data); // Check if it's an authentication challenge if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { let authenticationHandler; for (const handler of this.handlers) { if (handler.canHandleAuthentication(response)) { authenticationHandler = handler; break; } } if (authenticationHandler) { return authenticationHandler.handleAuthentication(this, info, data); } else { // We have received an unauthorized response but have no handlers to handle it. // Let the response return to the caller. return response; } } let redirectsRemaining = this._maxRedirects; while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { const redirectUrl = response.message.headers['location']; if (!redirectUrl) { // if there's no location to redirect to, we won't break; } const parsedRedirectUrl = new URL(redirectUrl); if (parsedUrl.protocol === 'https:' && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); } // we need to finish reading the response before reassigning response // which will leak the open socket. yield response.readBody(); // strip authorization header if redirected to a different hostname if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { for (const header in headers) { // header names are case insensitive if (header.toLowerCase() === 'authorization') { delete headers[header]; } } } // let's make the request with the new redirectUrl info = this._prepareRequest(verb, parsedRedirectUrl, headers); response = yield this.requestRaw(info, data); redirectsRemaining--; } if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { // If not a retry code, return immediately instead of retrying return response; } numTries += 1; if (numTries < maxTries) { yield response.readBody(); yield this._performExponentialBackoff(numTries); } } while (numTries < maxTries); return response; }); } /** * Needs to be called if keepAlive is set to true in request options. */ dispose() { if (this._agent) { this._agent.destroy(); } this._disposed = true; } /** * Raw request. * @param info * @param data */ requestRaw(info, data) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { function callbackForResult(err, res) { if (err) { reject(err); } else if (!res) { // If `err` is not passed, then `res` must be passed. reject(new Error('Unknown error')); } else { resolve(res); } } this.requestRawWithCallback(info, data, callbackForResult); }); }); } /** * Raw request with callback. * @param info * @param data * @param onResult */ requestRawWithCallback(info, data, onResult) { if (typeof data === 'string') { if (!info.options.headers) { info.options.headers = {}; } info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); } let callbackCalled = false; function handleResult(err, res) { if (!callbackCalled) { callbackCalled = true; onResult(err, res); } } const req = info.httpModule.request(info.options, (msg) => { const res = new HttpClientResponse(msg); handleResult(undefined, res); }); let socket; req.on('socket', sock => { socket = sock; }); // If we ever get disconnected, we want the socket to timeout eventually req.setTimeout(this._socketTimeout || 3 * 60000, () => { if (socket) { socket.end(); } handleResult(new Error(`Request timeout: ${info.options.path}`)); }); req.on('error', function (err) { // err has statusCode property // res should have headers handleResult(err); }); if (data && typeof data === 'string') { req.write(data, 'utf8'); } if (data && typeof data !== 'string') { data.on('close', function () { req.end(); }); data.pipe(req); } else { req.end(); } } /** * Gets an http agent. This function is useful when you need an http agent that handles * routing through a proxy server - depending upon the url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ getAgent(serverUrl) { const parsedUrl = new URL(serverUrl); return this._getAgent(parsedUrl); } getAgentDispatcher(serverUrl) { const parsedUrl = new URL(serverUrl); const proxyUrl = pm.getProxyUrl(parsedUrl); const useProxy = proxyUrl && proxyUrl.hostname; if (!useProxy) { return; } return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } _prepareRequest(method, requestUrl, headers) { const info = {}; info.parsedUrl = requestUrl; const usingSsl = info.parsedUrl.protocol === 'https:'; info.httpModule = usingSsl ? https : http; const defaultPort = usingSsl ? 443 : 80; info.options = {}; info.options.host = info.parsedUrl.hostname; info.options.port = info.parsedUrl.port ? parseInt(info.parsedUrl.port) : defaultPort; info.options.path = (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); info.options.method = method; info.options.headers = this._mergeHeaders(headers); if (this.userAgent != null) { info.options.headers['user-agent'] = this.userAgent; } info.options.agent = this._getAgent(info.parsedUrl); // gives handlers an opportunity to participate if (this.handlers) { for (const handler of this.handlers) { handler.prepareRequest(info.options); } } return info; } _mergeHeaders(headers) { if (this.requestOptions && this.requestOptions.headers) { return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } return lowercaseKeys(headers || {}); } _getExistingOrDefaultHeader(additionalHeaders, header, _default) { let clientHeader; if (this.requestOptions && this.requestOptions.headers) { clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } return additionalHeaders[header] || clientHeader || _default; } _getAgent(parsedUrl) { let agent; const proxyUrl = pm.getProxyUrl(parsedUrl); const useProxy = proxyUrl && proxyUrl.hostname; if (this._keepAlive && useProxy) { agent = this._proxyAgent; } if (!useProxy) { agent = this._agent; } // if agent is already assigned use that agent. if (agent) { return agent; } const usingSsl = parsedUrl.protocol === 'https:'; let maxSockets = 100; if (this.requestOptions) { maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; } // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. if (proxyUrl && proxyUrl.hostname) { const agentOptions = { maxSockets, keepAlive: this._keepAlive, proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` })), { host: proxyUrl.hostname, port: proxyUrl.port }) }; let tunnelAgent; const overHttps = proxyUrl.protocol === 'https:'; if (usingSsl) { tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } agent = tunnelAgent(agentOptions); this._proxyAgent = agent; } // if tunneling agent isn't assigned create a new agent if (!agent) { const options = { keepAlive: this._keepAlive, maxSockets }; agent = usingSsl ? new https.Agent(options) : new http.Agent(options); this._agent = agent; } if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options // we have to cast it to any and change it directly agent.options = Object.assign(agent.options || {}, { rejectUnauthorized: false }); } return agent; } _getProxyAgentDispatcher(parsedUrl, proxyUrl) { let proxyAgent; if (this._keepAlive) { proxyAgent = this._proxyAgentDispatcher; } // if agent is already assigned use that agent. if (proxyAgent) { return proxyAgent; } const usingSsl = parsedUrl.protocol === 'https:'; proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && { token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString('base64')}` }))); this._proxyAgentDispatcher = proxyAgent; if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options // we have to cast it to any and change it directly proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { rejectUnauthorized: false }); } return proxyAgent; } _performExponentialBackoff(retryNumber) { return __awaiter(this, void 0, void 0, function* () { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); return new Promise(resolve => setTimeout(() => resolve(), ms)); }); } _processResponse(res, options) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { const statusCode = res.message.statusCode || 0; const response = { statusCode, result: null, headers: {} }; // not found leads to null obj returned if (statusCode === HttpCodes.NotFound) { resolve(response); } // get the result from the body function dateTimeDeserializer(key, value) { if (typeof value === 'string') { const a = new Date(value); if (!isNaN(a.valueOf())) { return a; } } return value; } let obj; let contents; try { contents = yield res.readBody(); if (contents && contents.length > 0) { if (options && options.deserializeDates) { obj = JSON.parse(contents, dateTimeDeserializer); } else { obj = JSON.parse(contents); } response.result = obj; } response.headers = res.message.headers; } catch (err) { // Invalid resource (contents not json); leaving result obj null } // note that 3xx redirects are handled by the http layer. if (statusCode > 299) { let msg; // if exception/error in body, attempt to get better error if (obj && obj.message) { msg = obj.message; } else if (contents && contents.length > 0) { // it may be the case that the exception is in the body message as string msg = contents; } else { msg = `Failed request: (${statusCode})`; } const err = new HttpClientError(msg, statusCode); err.result = response.result; reject(err); } else { resolve(response); } })); }); } } exports.HttpClient = HttpClient; const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); //# sourceMappingURL=index.js.map /***/ }), /***/ 54988: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.checkBypass = exports.getProxyUrl = void 0; function getProxyUrl(reqUrl) { const usingSsl = reqUrl.protocol === 'https:'; if (checkBypass(reqUrl)) { return undefined; } const proxyVar = (() => { if (usingSsl) { return process.env['https_proxy'] || process.env['HTTPS_PROXY']; } else { return process.env['http_proxy'] || process.env['HTTP_PROXY']; } })(); if (proxyVar) { try { return new DecodedURL(proxyVar); } catch (_a) { if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) return new DecodedURL(`http://${proxyVar}`); } } else { return undefined; } } exports.getProxyUrl = getProxyUrl; function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; } const reqHost = reqUrl.hostname; if (isLoopbackAddress(reqHost)) { return true; } const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; if (!noProxy) { return false; } // Determine the request port let reqPort; if (reqUrl.port) { reqPort = Number(reqUrl.port); } else if (reqUrl.protocol === 'http:') { reqPort = 80; } else if (reqUrl.protocol === 'https:') { reqPort = 443; } // Format the request hostname and hostname with port const upperReqHosts = [reqUrl.hostname.toUpperCase()]; if (typeof reqPort === 'number') { upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } // Compare request host against noproxy for (const upperNoProxyItem of noProxy .split(',') .map(x => x.trim().toUpperCase()) .filter(x => x)) { if (upperNoProxyItem === '*' || upperReqHosts.some(x => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || (upperNoProxyItem.startsWith('.') && x.endsWith(`${upperNoProxyItem}`)))) { return true; } } return false; } exports.checkBypass = checkBypass; function isLoopbackAddress(host) { const hostLower = host.toLowerCase(); return (hostLower === 'localhost' || hostLower.startsWith('127.') || hostLower.startsWith('[::1]') || hostLower.startsWith('[0:0:0:0:0:0:0:1]')); } class DecodedURL extends URL { constructor(url, base) { super(url, base); this._decodedUsername = decodeURIComponent(super.username); this._decodedPassword = decodeURIComponent(super.password); } get username() { return this._decodedUsername; } get password() { return this._decodedPassword; } } //# sourceMappingURL=proxy.js.map /***/ }), /***/ 75207: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; 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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; 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 _a; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.READONLY = exports.UV_FS_O_EXLOCK = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.readlink = exports.readdir = exports.open = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; const fs = __importStar(__nccwpck_require__(79896)); const path = __importStar(__nccwpck_require__(16928)); _a = fs.promises // export const {open} = 'fs' , exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.open = _a.open, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rm = _a.rm, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; // export const {open} = 'fs' exports.IS_WINDOWS = process.platform === 'win32'; // See https://github.com/nodejs/node/blob/d0153aee367422d0858105abec186da4dff0a0c5/deps/uv/include/uv/win.h#L691 exports.UV_FS_O_EXLOCK = 0x10000000; exports.READONLY = fs.constants.O_RDONLY; function exists(fsPath) { return __awaiter(this, void 0, void 0, function* () { try { yield exports.stat(fsPath); } catch (err) { if (err.code === 'ENOENT') { return false; } throw err; } return true; }); } exports.exists = exists; function isDirectory(fsPath, useStat = false) { return __awaiter(this, void 0, void 0, function* () { const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath); return stats.isDirectory(); }); } exports.isDirectory = isDirectory; /** * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). */ function isRooted(p) { p = normalizeSeparators(p); if (!p) { throw new Error('isRooted() parameter "p" cannot be empty'); } if (exports.IS_WINDOWS) { return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello ); // e.g. C: or C:\hello } return p.startsWith('/'); } exports.isRooted = isRooted; /** * Best effort attempt to determine whether a file exists and is executable. * @param filePath file path to check * @param extensions additional file extensions to try * @return if file exists and is executable, returns the file path. otherwise empty string. */ function tryGetExecutablePath(filePath, extensions) { return __awaiter(this, void 0, void 0, function* () { let stats = undefined; try { // test file exists stats = yield exports.stat(filePath); } catch (err) { if (err.code !== 'ENOENT') { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); } } if (stats && stats.isFile()) { if (exports.IS_WINDOWS) { // on Windows, test for valid extension const upperExt = path.extname(filePath).toUpperCase(); if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { return filePath; } } else { if (isUnixExecutable(stats)) { return filePath; } } } // try each extension const originalFilePath = filePath; for (const extension of extensions) { filePath = originalFilePath + extension; stats = undefined; try { stats = yield exports.stat(filePath); } catch (err) { if (err.code !== 'ENOENT') { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); } } if (stats && stats.isFile()) { if (exports.IS_WINDOWS) { // preserve the case of the actual file (since an extension was appended) try { const directory = path.dirname(filePath); const upperName = path.basename(filePath).toUpperCase(); for (const actualName of yield exports.readdir(directory)) { if (upperName === actualName.toUpperCase()) { filePath = path.join(directory, actualName); break; } } } catch (err) { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); } return filePath; } else { if (isUnixExecutable(stats)) { return filePath; } } } } return ''; }); } exports.tryGetExecutablePath = tryGetExecutablePath; function normalizeSeparators(p) { p = p || ''; if (exports.IS_WINDOWS) { // convert slashes on Windows p = p.replace(/\//g, '\\'); // remove redundant slashes return p.replace(/\\\\+/g, '\\'); } // remove redundant slashes return p.replace(/\/\/+/g, '/'); } // on Mac/Linux, test the execute bit // R W X R W X R W X // 256 128 64 32 16 8 4 2 1 function isUnixExecutable(stats) { return ((stats.mode & 1) > 0 || ((stats.mode & 8) > 0 && stats.gid === process.getgid()) || ((stats.mode & 64) > 0 && stats.uid === process.getuid())); } // Get the path of cmd.exe in windows function getCmdPath() { var _a; return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`; } exports.getCmdPath = getCmdPath; //# sourceMappingURL=io-util.js.map /***/ }), /***/ 94994: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; 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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; 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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0; const assert_1 = __nccwpck_require__(42613); const path = __importStar(__nccwpck_require__(16928)); const ioUtil = __importStar(__nccwpck_require__(75207)); /** * Copies a file or folder. * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js * * @param source source path * @param dest destination path * @param options optional. See CopyOptions. */ function cp(source, dest, options = {}) { return __awaiter(this, void 0, void 0, function* () { const { force, recursive, copySourceDirectory } = readCopyOptions(options); const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; // Dest is an existing file, but not forcing if (destStat && destStat.isFile() && !force) { return; } // If dest is an existing directory, should copy inside. const newDest = destStat && destStat.isDirectory() && copySourceDirectory ? path.join(dest, path.basename(source)) : dest; if (!(yield ioUtil.exists(source))) { throw new Error(`no such file or directory: ${source}`); } const sourceStat = yield ioUtil.stat(source); if (sourceStat.isDirectory()) { if (!recursive) { throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); } else { yield cpDirRecursive(source, newDest, 0, force); } } else { if (path.relative(source, newDest) === '') { // a file cannot be copied to itself throw new Error(`'${newDest}' and '${source}' are the same file`); } yield copyFile(source, newDest, force); } }); } exports.cp = cp; /** * Moves a path. * * @param source source path * @param dest destination path * @param options optional. See MoveOptions. */ function mv(source, dest, options = {}) { return __awaiter(this, void 0, void 0, function* () { if (yield ioUtil.exists(dest)) { let destExists = true; if (yield ioUtil.isDirectory(dest)) { // If dest is directory copy src into dest dest = path.join(dest, path.basename(source)); destExists = yield ioUtil.exists(dest); } if (destExists) { if (options.force == null || options.force) { yield rmRF(dest); } else { throw new Error('Destination already exists'); } } } yield mkdirP(path.dirname(dest)); yield ioUtil.rename(source, dest); }); } exports.mv = mv; /** * Remove a path recursively with force * * @param inputPath path to remove */ function rmRF(inputPath) { return __awaiter(this, void 0, void 0, function* () { if (ioUtil.IS_WINDOWS) { // Check for invalid characters // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file if (/[*"<>|]/.test(inputPath)) { throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows'); } } try { // note if path does not exist, error is silent yield ioUtil.rm(inputPath, { force: true, maxRetries: 3, recursive: true, retryDelay: 300 }); } catch (err) { throw new Error(`File was unable to be removed ${err}`); } }); } exports.rmRF = rmRF; /** * Make a directory. Creates the full path with folders in between * Will throw if it fails * * @param fsPath path to create * @returns Promise */ function mkdirP(fsPath) { return __awaiter(this, void 0, void 0, function* () { assert_1.ok(fsPath, 'a path argument must be provided'); yield ioUtil.mkdir(fsPath, { recursive: true }); }); } exports.mkdirP = mkdirP; /** * Returns path of a tool had the tool actually been invoked. Resolves via paths. * If you check and the tool does not exist, it will throw. * * @param tool name of the tool * @param check whether to check if tool exists * @returns Promise path to tool */ function which(tool, check) { return __awaiter(this, void 0, void 0, function* () { if (!tool) { throw new Error("parameter 'tool' is required"); } // recursive when check=true if (check) { const result = yield which(tool, false); if (!result) { if (ioUtil.IS_WINDOWS) { throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); } else { throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); } } return result; } const matches = yield findInPath(tool); if (matches && matches.length > 0) { return matches[0]; } return ''; }); } exports.which = which; /** * Returns a list of all occurrences of the given tool on the system path. * * @returns Promise the paths of the tool */ function findInPath(tool) { return __awaiter(this, void 0, void 0, function* () { if (!tool) { throw new Error("parameter 'tool' is required"); } // build the list of extensions to try const extensions = []; if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) { for (const extension of process.env['PATHEXT'].split(path.delimiter)) { if (extension) { extensions.push(extension); } } } // if it's rooted, return it if exists. otherwise return empty. if (ioUtil.isRooted(tool)) { const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); if (filePath) { return [filePath]; } return []; } // if any path separators, return empty if (tool.includes(path.sep)) { return []; } // build the list of directories // // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, // it feels like we should not do this. Checking the current directory seems like more of a use // case of a shell, and the which() function exposed by the toolkit should strive for consistency // across platforms. const directories = []; if (process.env.PATH) { for (const p of process.env.PATH.split(path.delimiter)) { if (p) { directories.push(p); } } } // find all matches const matches = []; for (const directory of directories) { const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions); if (filePath) { matches.push(filePath); } } return matches; }); } exports.findInPath = findInPath; function readCopyOptions(options) { const force = options.force == null ? true : options.force; const recursive = Boolean(options.recursive); const copySourceDirectory = options.copySourceDirectory == null ? true : Boolean(options.copySourceDirectory); return { force, recursive, copySourceDirectory }; } function cpDirRecursive(sourceDir, destDir, currentDepth, force) { return __awaiter(this, void 0, void 0, function* () { // Ensure there is not a run away recursive copy if (currentDepth >= 255) return; currentDepth++; yield mkdirP(destDir); const files = yield ioUtil.readdir(sourceDir); for (const fileName of files) { const srcFile = `${sourceDir}/${fileName}`; const destFile = `${destDir}/${fileName}`; const srcFileStat = yield ioUtil.lstat(srcFile); if (srcFileStat.isDirectory()) { // Recurse yield cpDirRecursive(srcFile, destFile, currentDepth, force); } else { yield copyFile(srcFile, destFile, force); } } // Change the mode for the newly created directory yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); }); } // Buffered file copy function copyFile(srcFile, destFile, force) { return __awaiter(this, void 0, void 0, function* () { if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { // unlink/re-link it try { yield ioUtil.lstat(destFile); yield ioUtil.unlink(destFile); } catch (e) { // Try to override file permission if (e.code === 'EPERM') { yield ioUtil.chmod(destFile, '0666'); yield ioUtil.unlink(destFile); } // other errors = it doesn't exist, no work to do } // Copy over symlink const symlinkFull = yield ioUtil.readlink(srcFile); yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null); } else if (!(yield ioUtil.exists(destFile)) || force) { yield ioUtil.copyFile(srcFile, destFile); } }); } //# sourceMappingURL=io.js.map /***/ }), /***/ 68110: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /// const listenersMap = new WeakMap(); const abortedMap = new WeakMap(); /** * An aborter instance implements AbortSignal interface, can abort HTTP requests. * * - Call AbortSignal.none to create a new AbortSignal instance that cannot be cancelled. * Use `AbortSignal.none` when you are required to pass a cancellation token but the operation * cannot or will not ever be cancelled. * * @example * Abort without timeout * ```ts * await doAsyncWork(AbortSignal.none); * ``` */ class AbortSignal { constructor() { /** * onabort event listener. */ this.onabort = null; listenersMap.set(this, []); abortedMap.set(this, false); } /** * Status of whether aborted or not. * * @readonly */ get aborted() { if (!abortedMap.has(this)) { throw new TypeError("Expected `this` to be an instance of AbortSignal."); } return abortedMap.get(this); } /** * Creates a new AbortSignal instance that will never be aborted. * * @readonly */ static get none() { return new AbortSignal(); } /** * Added new "abort" event listener, only support "abort" event. * * @param _type - Only support "abort" event * @param listener - The listener to be added */ addEventListener( // tslint:disable-next-line:variable-name _type, listener) { if (!listenersMap.has(this)) { throw new TypeError("Expected `this` to be an instance of AbortSignal."); } const listeners = listenersMap.get(this); listeners.push(listener); } /** * Remove "abort" event listener, only support "abort" event. * * @param _type - Only support "abort" event * @param listener - The listener to be removed */ removeEventListener( // tslint:disable-next-line:variable-name _type, listener) { if (!listenersMap.has(this)) { throw new TypeError("Expected `this` to be an instance of AbortSignal."); } const listeners = listenersMap.get(this); const index = listeners.indexOf(listener); if (index > -1) { listeners.splice(index, 1); } } /** * Dispatches a synthetic event to the AbortSignal. */ dispatchEvent(_event) { throw new Error("This is a stub dispatchEvent implementation that should not be used. It only exists for type-checking purposes."); } } /** * Helper to trigger an abort event immediately, the onabort and all abort event listeners will be triggered. * Will try to trigger abort event for all linked AbortSignal nodes. * * - If there is a timeout, the timer will be cancelled. * - If aborted is true, nothing will happen. * * @internal */ // eslint-disable-next-line @azure/azure-sdk/ts-use-interface-parameters function abortSignal(signal) { if (signal.aborted) { return; } if (signal.onabort) { signal.onabort.call(signal); } const listeners = listenersMap.get(signal); if (listeners) { // Create a copy of listeners so mutations to the array // (e.g. via removeListener calls) don't affect the listeners // we invoke. listeners.slice().forEach((listener) => { listener.call(signal, { type: "abort" }); }); } abortedMap.set(signal, true); } // Copyright (c) Microsoft Corporation. /** * This error is thrown when an asynchronous operation has been aborted. * Check for this error by testing the `name` that the name property of the * error matches `"AbortError"`. * * @example * ```ts * const controller = new AbortController(); * controller.abort(); * try { * doAsyncWork(controller.signal) * } catch (e) { * if (e.name === 'AbortError') { * // handle abort error here. * } * } * ``` */ class AbortError extends Error { constructor(message) { super(message); this.name = "AbortError"; } } /** * An AbortController provides an AbortSignal and the associated controls to signal * that an asynchronous operation should be aborted. * * @example * Abort an operation when another event fires * ```ts * const controller = new AbortController(); * const signal = controller.signal; * doAsyncWork(signal); * button.addEventListener('click', () => controller.abort()); * ``` * * @example * Share aborter cross multiple operations in 30s * ```ts * // Upload the same data to 2 different data centers at the same time, * // abort another when any of them is finished * const controller = AbortController.withTimeout(30 * 1000); * doAsyncWork(controller.signal).then(controller.abort); * doAsyncWork(controller.signal).then(controller.abort); *``` * * @example * Cascaded aborting * ```ts * // All operations can't take more than 30 seconds * const aborter = Aborter.timeout(30 * 1000); * * // Following 2 operations can't take more than 25 seconds * await doAsyncWork(aborter.withTimeout(25 * 1000)); * await doAsyncWork(aborter.withTimeout(25 * 1000)); * ``` */ class AbortController { // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types constructor(parentSignals) { this._signal = new AbortSignal(); if (!parentSignals) { return; } // coerce parentSignals into an array if (!Array.isArray(parentSignals)) { // eslint-disable-next-line prefer-rest-params parentSignals = arguments; } for (const parentSignal of parentSignals) { // if the parent signal has already had abort() called, // then call abort on this signal as well. if (parentSignal.aborted) { this.abort(); } else { // when the parent signal aborts, this signal should as well. parentSignal.addEventListener("abort", () => { this.abort(); }); } } } /** * The AbortSignal associated with this controller that will signal aborted * when the abort method is called on this controller. * * @readonly */ get signal() { return this._signal; } /** * Signal that any operations passed this controller's associated abort signal * to cancel any remaining work and throw an `AbortError`. */ abort() { abortSignal(this._signal); } /** * Creates a new AbortSignal instance that will abort after the provided ms. * @param ms - Elapsed time in milliseconds to trigger an abort. */ static timeout(ms) { const signal = new AbortSignal(); const timer = setTimeout(abortSignal, ms, signal); // Prevent the active Timer from keeping the Node.js event loop active. if (typeof timer.unref === "function") { timer.unref(); } return signal; } } exports.AbortController = AbortController; exports.AbortError = AbortError; exports.AbortSignal = AbortSignal; //# sourceMappingURL=index.js.map /***/ }), /***/ 1012: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var coreRestPipeline = __nccwpck_require__(20778); var tslib = __nccwpck_require__(61860); var coreAuth = __nccwpck_require__(50417); var coreUtil = __nccwpck_require__(87779); var coreHttpCompat = __nccwpck_require__(61584); var coreClient = __nccwpck_require__(60160); var coreXml = __nccwpck_require__(78756); var logger$1 = __nccwpck_require__(26515); var abortController = __nccwpck_require__(24517); var crypto = __nccwpck_require__(76982); var coreTracing = __nccwpck_require__(20623); var stream = __nccwpck_require__(2203); var coreLro = __nccwpck_require__(91754); var events = __nccwpck_require__(24434); var fs = __nccwpck_require__(79896); var util = __nccwpck_require__(39023); var buffer = __nccwpck_require__(20181); function _interopNamespaceDefault(e) { var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n.default = e; return Object.freeze(n); } var coreHttpCompat__namespace = /*#__PURE__*/_interopNamespaceDefault(coreHttpCompat); var coreClient__namespace = /*#__PURE__*/_interopNamespaceDefault(coreClient); var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs); var util__namespace = /*#__PURE__*/_interopNamespaceDefault(util); // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * The `@azure/logger` configuration for this package. */ const logger = logger$1.createClientLogger("storage-blob"); // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * The base class from which all request policies derive. */ class BaseRequestPolicy { /** * The main method to implement that manipulates a request/response. */ constructor( /** * The next policy in the pipeline. Each policy is responsible for executing the next one if the request is to continue through the pipeline. */ _nextPolicy, /** * The options that can be passed to a given request policy. */ _options) { this._nextPolicy = _nextPolicy; this._options = _options; } /** * 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. * @returns Whether or not a log with the provided log level should be logged. */ shouldLog(logLevel) { return this._options.shouldLog(logLevel); } /** * 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. */ log(logLevel, message) { this._options.log(logLevel, message); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. const SDK_VERSION = "12.27.0"; const SERVICE_VERSION = "2025-05-05"; const BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES = 256 * 1024 * 1024; // 256MB const BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES = 4000 * 1024 * 1024; // 4000MB const BLOCK_BLOB_MAX_BLOCKS = 50000; const DEFAULT_BLOCK_BUFFER_SIZE_BYTES = 8 * 1024 * 1024; // 8MB const DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES = 4 * 1024 * 1024; // 4MB const DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS = 5; const REQUEST_TIMEOUT = 100 * 1000; // In ms /** * The OAuth scope to use with Azure Storage. */ const StorageOAuthScopes = "https://storage.azure.com/.default"; const URLConstants = { Parameters: { FORCE_BROWSER_NO_CACHE: "_", SNAPSHOT: "snapshot", VERSIONID: "versionid", TIMEOUT: "timeout", }, }; const HTTPURLConnection = { HTTP_ACCEPTED: 202}; const HeaderConstants = { AUTHORIZATION: "Authorization", CONTENT_ENCODING: "Content-Encoding", CONTENT_ID: "Content-ID", CONTENT_LANGUAGE: "Content-Language", CONTENT_LENGTH: "Content-Length", CONTENT_MD5: "Content-Md5", CONTENT_TRANSFER_ENCODING: "Content-Transfer-Encoding", CONTENT_TYPE: "Content-Type", COOKIE: "Cookie", DATE: "date", IF_MATCH: "if-match", IF_MODIFIED_SINCE: "if-modified-since", IF_NONE_MATCH: "if-none-match", IF_UNMODIFIED_SINCE: "if-unmodified-since", PREFIX_FOR_STORAGE: "x-ms-", RANGE: "Range", X_MS_DATE: "x-ms-date", X_MS_ERROR_CODE: "x-ms-error-code", X_MS_VERSION: "x-ms-version"}; const ETagNone = ""; const ETagAny = "*"; const SIZE_1_MB = 1 * 1024 * 1024; const BATCH_MAX_REQUEST = 256; const BATCH_MAX_PAYLOAD_IN_BYTES = 4 * SIZE_1_MB; const HTTP_LINE_ENDING = "\r\n"; const HTTP_VERSION_1_1 = "HTTP/1.1"; const EncryptionAlgorithmAES25 = "AES256"; const DevelopmentConnectionString = `DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;`; const StorageBlobLoggingAllowedHeaderNames = [ "Access-Control-Allow-Origin", "Cache-Control", "Content-Length", "Content-Type", "Date", "Request-Id", "traceparent", "Transfer-Encoding", "User-Agent", "x-ms-client-request-id", "x-ms-date", "x-ms-error-code", "x-ms-request-id", "x-ms-return-client-request-id", "x-ms-version", "Accept-Ranges", "Content-Disposition", "Content-Encoding", "Content-Language", "Content-MD5", "Content-Range", "ETag", "Last-Modified", "Server", "Vary", "x-ms-content-crc64", "x-ms-copy-action", "x-ms-copy-completion-time", "x-ms-copy-id", "x-ms-copy-progress", "x-ms-copy-status", "x-ms-has-immutability-policy", "x-ms-has-legal-hold", "x-ms-lease-state", "x-ms-lease-status", "x-ms-range", "x-ms-request-server-encrypted", "x-ms-server-encrypted", "x-ms-snapshot", "x-ms-source-range", "If-Match", "If-Modified-Since", "If-None-Match", "If-Unmodified-Since", "x-ms-access-tier", "x-ms-access-tier-change-time", "x-ms-access-tier-inferred", "x-ms-account-kind", "x-ms-archive-status", "x-ms-blob-append-offset", "x-ms-blob-cache-control", "x-ms-blob-committed-block-count", "x-ms-blob-condition-appendpos", "x-ms-blob-condition-maxsize", "x-ms-blob-content-disposition", "x-ms-blob-content-encoding", "x-ms-blob-content-language", "x-ms-blob-content-length", "x-ms-blob-content-md5", "x-ms-blob-content-type", "x-ms-blob-public-access", "x-ms-blob-sequence-number", "x-ms-blob-type", "x-ms-copy-destination-snapshot", "x-ms-creation-time", "x-ms-default-encryption-scope", "x-ms-delete-snapshots", "x-ms-delete-type-permanent", "x-ms-deny-encryption-scope-override", "x-ms-encryption-algorithm", "x-ms-if-sequence-number-eq", "x-ms-if-sequence-number-le", "x-ms-if-sequence-number-lt", "x-ms-incremental-copy", "x-ms-lease-action", "x-ms-lease-break-period", "x-ms-lease-duration", "x-ms-lease-id", "x-ms-lease-time", "x-ms-page-write", "x-ms-proposed-lease-id", "x-ms-range-get-content-md5", "x-ms-rehydrate-priority", "x-ms-sequence-number-action", "x-ms-sku-name", "x-ms-source-content-md5", "x-ms-source-if-match", "x-ms-source-if-modified-since", "x-ms-source-if-none-match", "x-ms-source-if-unmodified-since", "x-ms-tag-count", "x-ms-encryption-key-sha256", "x-ms-copy-source-error-code", "x-ms-copy-source-status-code", "x-ms-if-tags", "x-ms-source-if-tags", ]; const StorageBlobLoggingAllowedQueryParameters = [ "comp", "maxresults", "rscc", "rscd", "rsce", "rscl", "rsct", "se", "si", "sip", "sp", "spr", "sr", "srt", "ss", "st", "sv", "include", "marker", "prefix", "copyid", "restype", "blockid", "blocklisttype", "delimiter", "prevsnapshot", "ske", "skoid", "sks", "skt", "sktid", "skv", "snapshot", ]; const BlobUsesCustomerSpecifiedEncryptionMsg = "BlobUsesCustomerSpecifiedEncryption"; const BlobDoesNotUseCustomerSpecifiedEncryption = "BlobDoesNotUseCustomerSpecifiedEncryption"; /// List of ports used for path style addressing. /// Path style addressing means that storage account is put in URI's Path segment in instead of in host. const PathStylePorts = [ "10000", "10001", "10002", "10003", "10004", "10100", "10101", "10102", "10103", "10104", "11000", "11001", "11002", "11003", "11004", "11100", "11101", "11102", "11103", "11104", ]; // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * Reserved URL characters must be properly escaped for Storage services like Blob or File. * * ## URL encode and escape strategy for JS SDKs * * When customers pass a URL string into XxxClient classes constructor, the URL string may already be URL encoded or not. * But before sending to Azure Storage server, the URL must be encoded. However, it's hard for a SDK to guess whether the URL * string has been encoded or not. We have 2 potential strategies, and chose strategy two for the XxxClient constructors. * * ### Strategy One: Assume the customer URL string is not encoded, and always encode URL string in SDK. * * This is what legacy V2 SDK does, simple and works for most of the cases. * - When customer URL string is "http://account.blob.core.windows.net/con/b:", * SDK will encode it to "http://account.blob.core.windows.net/con/b%3A" and send to server. A blob named "b:" will be created. * - When customer URL string is "http://account.blob.core.windows.net/con/b%3A", * SDK will encode it to "http://account.blob.core.windows.net/con/b%253A" and send to server. A blob named "b%3A" will be created. * * But this strategy will make it not possible to create a blob with "?" in it's name. Because when customer URL string is * "http://account.blob.core.windows.net/con/blob?name", the "?name" will be treated as URL paramter instead of blob name. * If customer URL string is "http://account.blob.core.windows.net/con/blob%3Fname", a blob named "blob%3Fname" will be created. * V2 SDK doesn't have this issue because it doesn't allow customer pass in a full URL, it accepts a separate blob name and encodeURIComponent for it. * We cannot accept a SDK cannot create a blob name with "?". So we implement strategy two: * * ### Strategy Two: SDK doesn't assume the URL has been encoded or not. It will just escape the special characters. * * This is what V10 Blob Go SDK does. It accepts a URL type in Go, and call url.EscapedPath() to escape the special chars unescaped. * - When customer URL string is "http://account.blob.core.windows.net/con/b:", * SDK will escape ":" like "http://account.blob.core.windows.net/con/b%3A" and send to server. A blob named "b:" will be created. * - When customer URL string is "http://account.blob.core.windows.net/con/b%3A", * There is no special characters, so send "http://account.blob.core.windows.net/con/b%3A" to server. A blob named "b:" will be created. * - When customer URL string is "http://account.blob.core.windows.net/con/b%253A", * There is no special characters, so send "http://account.blob.core.windows.net/con/b%253A" to server. A blob named "b%3A" will be created. * * This strategy gives us flexibility to create with any special characters. But "%" will be treated as a special characters, if the URL string * is not encoded, there shouldn't a "%" in the URL string, otherwise the URL is not a valid URL. * If customer needs to create a blob with "%" in it's blob name, use "%25" instead of "%". Just like above 3rd sample. * And following URL strings are invalid: * - "http://account.blob.core.windows.net/con/b%" * - "http://account.blob.core.windows.net/con/b%2" * - "http://account.blob.core.windows.net/con/b%G" * * Another special character is "?", use "%2F" to represent a blob name with "?" in a URL string. * * ### Strategy for containerName, blobName or other specific XXXName parameters in methods such as `containerClient.getBlobClient(blobName)` * * We will apply strategy one, and call encodeURIComponent for these parameters like blobName. Because what customers passes in is a plain name instead of a URL. * * @see https://learn.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata * @see https://learn.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-shares--directories--files--and-metadata * * @param url - */ function escapeURLPath(url) { const urlParsed = new URL(url); let path = urlParsed.pathname; path = path || "/"; path = escape(path); urlParsed.pathname = path; return urlParsed.toString(); } function getProxyUriFromDevConnString(connectionString) { // Development Connection String // https://learn.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string#connect-to-the-emulator-account-using-the-well-known-account-name-and-key let proxyUri = ""; if (connectionString.search("DevelopmentStorageProxyUri=") !== -1) { // CONNECTION_STRING=UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://myProxyUri const matchCredentials = connectionString.split(";"); for (const element of matchCredentials) { if (element.trim().startsWith("DevelopmentStorageProxyUri=")) { proxyUri = element.trim().match("DevelopmentStorageProxyUri=(.*)")[1]; } } } return proxyUri; } function getValueInConnString(connectionString, argument) { const elements = connectionString.split(";"); for (const element of elements) { if (element.trim().startsWith(argument)) { return element.trim().match(argument + "=(.*)")[1]; } } return ""; } /** * Extracts the parts of an Azure Storage account connection string. * * @param connectionString - Connection string. * @returns String key value pairs of the storage account's url and credentials. */ function extractConnectionStringParts(connectionString) { let proxyUri = ""; if (connectionString.startsWith("UseDevelopmentStorage=true")) { // Development connection string proxyUri = getProxyUriFromDevConnString(connectionString); connectionString = DevelopmentConnectionString; } // Matching BlobEndpoint in the Account connection string let blobEndpoint = getValueInConnString(connectionString, "BlobEndpoint"); // Slicing off '/' at the end if exists // (The methods that use `extractConnectionStringParts` expect the url to not have `/` at the end) blobEndpoint = blobEndpoint.endsWith("/") ? blobEndpoint.slice(0, -1) : blobEndpoint; if (connectionString.search("DefaultEndpointsProtocol=") !== -1 && connectionString.search("AccountKey=") !== -1) { // Account connection string let defaultEndpointsProtocol = ""; let accountName = ""; let accountKey = Buffer.from("accountKey", "base64"); let endpointSuffix = ""; // Get account name and key accountName = getValueInConnString(connectionString, "AccountName"); accountKey = Buffer.from(getValueInConnString(connectionString, "AccountKey"), "base64"); if (!blobEndpoint) { // BlobEndpoint is not present in the Account connection string // Can be obtained from `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}` defaultEndpointsProtocol = getValueInConnString(connectionString, "DefaultEndpointsProtocol"); const protocol = defaultEndpointsProtocol.toLowerCase(); if (protocol !== "https" && protocol !== "http") { throw new Error("Invalid DefaultEndpointsProtocol in the provided Connection String. Expecting 'https' or 'http'"); } endpointSuffix = getValueInConnString(connectionString, "EndpointSuffix"); if (!endpointSuffix) { throw new Error("Invalid EndpointSuffix in the provided Connection String"); } blobEndpoint = `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; } if (!accountName) { throw new Error("Invalid AccountName in the provided Connection String"); } else if (accountKey.length === 0) { throw new Error("Invalid AccountKey in the provided Connection String"); } return { kind: "AccountConnString", url: blobEndpoint, accountName, accountKey, proxyUri, }; } else { // SAS connection string let accountSas = getValueInConnString(connectionString, "SharedAccessSignature"); let accountName = getValueInConnString(connectionString, "AccountName"); // if accountName is empty, try to read it from BlobEndpoint if (!accountName) { accountName = getAccountNameFromUrl(blobEndpoint); } if (!blobEndpoint) { throw new Error("Invalid BlobEndpoint in the provided SAS Connection String"); } else if (!accountSas) { throw new Error("Invalid SharedAccessSignature in the provided SAS Connection String"); } // client constructors assume accountSas does *not* start with ? if (accountSas.startsWith("?")) { accountSas = accountSas.substring(1); } return { kind: "SASConnString", url: blobEndpoint, accountName, accountSas }; } } /** * Internal escape method implemented Strategy Two mentioned in escapeURL() description. * * @param text - */ function escape(text) { return encodeURIComponent(text) .replace(/%2F/g, "/") // Don't escape for "/" .replace(/'/g, "%27") // Escape for "'" .replace(/\+/g, "%20") .replace(/%25/g, "%"); // Revert encoded "%" } /** * Append a string to URL path. Will remove duplicated "/" in front of the string * when URL path ends with a "/". * * @param url - Source URL string * @param name - String to be appended to URL * @returns An updated URL string */ function appendToURLPath(url, name) { const urlParsed = new URL(url); let path = urlParsed.pathname; path = path ? (path.endsWith("/") ? `${path}${name}` : `${path}/${name}`) : name; urlParsed.pathname = path; return urlParsed.toString(); } /** * Set URL parameter name and value. If name exists in URL parameters, old value * will be replaced by name key. If not provide value, the parameter will be deleted. * * @param url - Source URL string * @param name - Parameter name * @param value - Parameter value * @returns An updated URL string */ function setURLParameter(url, name, value) { const urlParsed = new URL(url); const encodedName = encodeURIComponent(name); const encodedValue = value ? encodeURIComponent(value) : undefined; // mutating searchParams will change the encoding, so we have to do this ourselves const searchString = urlParsed.search === "" ? "?" : urlParsed.search; const searchPieces = []; for (const pair of searchString.slice(1).split("&")) { if (pair) { const [key] = pair.split("=", 2); if (key !== encodedName) { searchPieces.push(pair); } } } if (encodedValue) { searchPieces.push(`${encodedName}=${encodedValue}`); } urlParsed.search = searchPieces.length ? `?${searchPieces.join("&")}` : ""; return urlParsed.toString(); } /** * Get URL parameter by name. * * @param url - * @param name - */ function getURLParameter(url, name) { var _a; const urlParsed = new URL(url); return (_a = urlParsed.searchParams.get(name)) !== null && _a !== void 0 ? _a : undefined; } /** * Set URL host. * * @param url - Source URL string * @param host - New host string * @returns An updated URL string */ function setURLHost(url, host) { const urlParsed = new URL(url); urlParsed.hostname = host; return urlParsed.toString(); } /** * Get URL path from an URL string. * * @param url - Source URL string */ function getURLPath(url) { try { const urlParsed = new URL(url); return urlParsed.pathname; } catch (e) { return undefined; } } /** * Get URL scheme from an URL string. * * @param url - Source URL string */ function getURLScheme(url) { try { const urlParsed = new URL(url); return urlParsed.protocol.endsWith(":") ? urlParsed.protocol.slice(0, -1) : urlParsed.protocol; } catch (e) { return undefined; } } /** * Get URL path and query from an URL string. * * @param url - Source URL string */ function getURLPathAndQuery(url) { const urlParsed = new URL(url); const pathString = urlParsed.pathname; if (!pathString) { throw new RangeError("Invalid url without valid path."); } let queryString = urlParsed.search || ""; queryString = queryString.trim(); if (queryString !== "") { queryString = queryString.startsWith("?") ? queryString : `?${queryString}`; // Ensure query string start with '?' } return `${pathString}${queryString}`; } /** * Get URL query key value pairs from an URL string. * * @param url - */ function getURLQueries(url) { let queryString = new URL(url).search; if (!queryString) { return {}; } queryString = queryString.trim(); queryString = queryString.startsWith("?") ? queryString.substring(1) : queryString; let querySubStrings = queryString.split("&"); querySubStrings = querySubStrings.filter((value) => { const indexOfEqual = value.indexOf("="); const lastIndexOfEqual = value.lastIndexOf("="); return (indexOfEqual > 0 && indexOfEqual === lastIndexOfEqual && lastIndexOfEqual < value.length - 1); }); const queries = {}; for (const querySubString of querySubStrings) { const splitResults = querySubString.split("="); const key = splitResults[0]; const value = splitResults[1]; queries[key] = value; } return queries; } /** * Append a string to URL query. * * @param url - Source URL string. * @param queryParts - String to be appended to the URL query. * @returns An updated URL string. */ function appendToURLQuery(url, queryParts) { const urlParsed = new URL(url); let query = urlParsed.search; if (query) { query += "&" + queryParts; } else { query = queryParts; } urlParsed.search = query; return urlParsed.toString(); } /** * Rounds a date off to seconds. * * @param date - * @param withMilliseconds - If true, YYYY-MM-DDThh:mm:ss.fffffffZ will be returned; * If false, YYYY-MM-DDThh:mm:ssZ will be returned. * @returns Date string in ISO8061 format, with or without 7 milliseconds component */ function truncatedISO8061Date(date, withMilliseconds = true) { // Date.toISOString() will return like "2018-10-29T06:34:36.139Z" const dateString = date.toISOString(); return withMilliseconds ? dateString.substring(0, dateString.length - 1) + "0000" + "Z" : dateString.substring(0, dateString.length - 5) + "Z"; } /** * Base64 encode. * * @param content - */ function base64encode(content) { return !coreUtil.isNode ? btoa(content) : Buffer.from(content).toString("base64"); } /** * Generate a 64 bytes base64 block ID string. * * @param blockIndex - */ function generateBlockID(blockIDPrefix, blockIndex) { // To generate a 64 bytes base64 string, source string should be 48 const maxSourceStringLength = 48; // A blob can have a maximum of 100,000 uncommitted blocks at any given time const maxBlockIndexLength = 6; const maxAllowedBlockIDPrefixLength = maxSourceStringLength - maxBlockIndexLength; if (blockIDPrefix.length > maxAllowedBlockIDPrefixLength) { blockIDPrefix = blockIDPrefix.slice(0, maxAllowedBlockIDPrefixLength); } const res = blockIDPrefix + padStart(blockIndex.toString(), maxSourceStringLength - blockIDPrefix.length, "0"); return base64encode(res); } /** * Delay specified time interval. * * @param timeInMs - * @param aborter - * @param abortError - */ async function delay(timeInMs, aborter, abortError) { return new Promise((resolve, reject) => { /* eslint-disable-next-line prefer-const */ let timeout; const abortHandler = () => { if (timeout !== undefined) { clearTimeout(timeout); } reject(abortError); }; const resolveHandler = () => { if (aborter !== undefined) { aborter.removeEventListener("abort", abortHandler); } resolve(); }; timeout = setTimeout(resolveHandler, timeInMs); if (aborter !== undefined) { aborter.addEventListener("abort", abortHandler); } }); } /** * String.prototype.padStart() * * @param currentString - * @param targetLength - * @param padString - */ function padStart(currentString, targetLength, padString = " ") { // @ts-expect-error: TS doesn't know this code needs to run downlevel sometimes if (String.prototype.padStart) { return currentString.padStart(targetLength, padString); } padString = padString || " "; if (currentString.length > targetLength) { return currentString; } else { targetLength = targetLength - currentString.length; if (targetLength > padString.length) { padString += padString.repeat(targetLength / padString.length); } return padString.slice(0, targetLength) + currentString; } } /** * If two strings are equal when compared case insensitive. * * @param str1 - * @param str2 - */ function iEqual(str1, str2) { return str1.toLocaleLowerCase() === str2.toLocaleLowerCase(); } /** * Extracts account name from the url * @param url - url to extract the account name from * @returns with the account name */ function getAccountNameFromUrl(url) { const parsedUrl = new URL(url); let accountName; try { if (parsedUrl.hostname.split(".")[1] === "blob") { // `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; accountName = parsedUrl.hostname.split(".")[0]; } else if (isIpEndpointStyle(parsedUrl)) { // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/ // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/ // .getPath() -> /devstoreaccount1/ accountName = parsedUrl.pathname.split("/")[1]; } else { // Custom domain case: "https://customdomain.com/containername/blob". accountName = ""; } return accountName; } catch (error) { throw new Error("Unable to extract accountName with provided information."); } } function isIpEndpointStyle(parsedUrl) { const host = parsedUrl.host; // Case 1: Ipv6, use a broad regex to find out candidates whose host contains two ':'. // Case 2: localhost(:port) or host.docker.internal, use broad regex to match port part. // Case 3: Ipv4, use broad regex which just check if host contains Ipv4. // For valid host please refer to https://man7.org/linux/man-pages/man7/hostname.7.html. return (/^.*:.*:.*$|^(localhost|host.docker.internal)(:[0-9]+)?$|^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])){3}(:[0-9]+)?$/.test(host) || (Boolean(parsedUrl.port) && PathStylePorts.includes(parsedUrl.port))); } /** * Convert Tags to encoded string. * * @param tags - */ function toBlobTagsString(tags) { if (tags === undefined) { return undefined; } const tagPairs = []; for (const key in tags) { if (Object.prototype.hasOwnProperty.call(tags, key)) { const value = tags[key]; tagPairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`); } } return tagPairs.join("&"); } /** * Convert Tags type to BlobTags. * * @param tags - */ function toBlobTags(tags) { if (tags === undefined) { return undefined; } const res = { blobTagSet: [], }; for (const key in tags) { if (Object.prototype.hasOwnProperty.call(tags, key)) { const value = tags[key]; res.blobTagSet.push({ key, value, }); } } return res; } /** * Covert BlobTags to Tags type. * * @param tags - */ function toTags(tags) { if (tags === undefined) { return undefined; } const res = {}; for (const blobTag of tags.blobTagSet) { res[blobTag.key] = blobTag.value; } return res; } /** * Convert BlobQueryTextConfiguration to QuerySerialization type. * * @param textConfiguration - */ function toQuerySerialization(textConfiguration) { if (textConfiguration === undefined) { return undefined; } switch (textConfiguration.kind) { case "csv": return { format: { type: "delimited", delimitedTextConfiguration: { columnSeparator: textConfiguration.columnSeparator || ",", fieldQuote: textConfiguration.fieldQuote || "", recordSeparator: textConfiguration.recordSeparator, escapeChar: textConfiguration.escapeCharacter || "", headersPresent: textConfiguration.hasHeaders || false, }, }, }; case "json": return { format: { type: "json", jsonTextConfiguration: { recordSeparator: textConfiguration.recordSeparator, }, }, }; case "arrow": return { format: { type: "arrow", arrowConfiguration: { schema: textConfiguration.schema, }, }, }; case "parquet": return { format: { type: "parquet", }, }; default: throw Error("Invalid BlobQueryTextConfiguration."); } } function parseObjectReplicationRecord(objectReplicationRecord) { if (!objectReplicationRecord) { return undefined; } if ("policy-id" in objectReplicationRecord) { // If the dictionary contains a key with policy id, we are not required to do any parsing since // the policy id should already be stored in the ObjectReplicationDestinationPolicyId. return undefined; } const orProperties = []; for (const key in objectReplicationRecord) { const ids = key.split("_"); const policyPrefix = "or-"; if (ids[0].startsWith(policyPrefix)) { ids[0] = ids[0].substring(policyPrefix.length); } const rule = { ruleId: ids[1], replicationStatus: objectReplicationRecord[key], }; const policyIndex = orProperties.findIndex((policy) => policy.policyId === ids[0]); if (policyIndex > -1) { orProperties[policyIndex].rules.push(rule); } else { orProperties.push({ policyId: ids[0], rules: [rule], }); } } return orProperties; } function httpAuthorizationToString(httpAuthorization) { return httpAuthorization ? httpAuthorization.scheme + " " + httpAuthorization.value : undefined; } function BlobNameToString(name) { if (name.encoded) { return decodeURIComponent(name.content); } else { return name.content; } } function ConvertInternalResponseOfListBlobFlat(internalResponse) { return Object.assign(Object.assign({}, internalResponse), { segment: { blobItems: internalResponse.segment.blobItems.map((blobItemInteral) => { const blobItem = Object.assign(Object.assign({}, blobItemInteral), { name: BlobNameToString(blobItemInteral.name) }); return blobItem; }), } }); } function ConvertInternalResponseOfListBlobHierarchy(internalResponse) { var _a; return Object.assign(Object.assign({}, internalResponse), { segment: { blobPrefixes: (_a = internalResponse.segment.blobPrefixes) === null || _a === void 0 ? void 0 : _a.map((blobPrefixInternal) => { const blobPrefix = Object.assign(Object.assign({}, blobPrefixInternal), { name: BlobNameToString(blobPrefixInternal.name) }); return blobPrefix; }), blobItems: internalResponse.segment.blobItems.map((blobItemInteral) => { const blobItem = Object.assign(Object.assign({}, blobItemInteral), { name: BlobNameToString(blobItemInteral.name) }); return blobItem; }), } }); } function* ExtractPageRangeInfoItems(getPageRangesSegment) { let pageRange = []; let clearRange = []; if (getPageRangesSegment.pageRange) pageRange = getPageRangesSegment.pageRange; if (getPageRangesSegment.clearRange) clearRange = getPageRangesSegment.clearRange; let pageRangeIndex = 0; let clearRangeIndex = 0; while (pageRangeIndex < pageRange.length && clearRangeIndex < clearRange.length) { if (pageRange[pageRangeIndex].start < clearRange[clearRangeIndex].start) { yield { start: pageRange[pageRangeIndex].start, end: pageRange[pageRangeIndex].end, isClear: false, }; ++pageRangeIndex; } else { yield { start: clearRange[clearRangeIndex].start, end: clearRange[clearRangeIndex].end, isClear: true, }; ++clearRangeIndex; } } for (; pageRangeIndex < pageRange.length; ++pageRangeIndex) { yield { start: pageRange[pageRangeIndex].start, end: pageRange[pageRangeIndex].end, isClear: false, }; } for (; clearRangeIndex < clearRange.length; ++clearRangeIndex) { yield { start: clearRange[clearRangeIndex].start, end: clearRange[clearRangeIndex].end, isClear: true, }; } } /** * Escape the blobName but keep path separator ('/'). */ function EscapePath(blobName) { const split = blobName.split("/"); for (let i = 0; i < split.length; i++) { split[i] = encodeURIComponent(split[i]); } return split.join("/"); } /** * A typesafe helper for ensuring that a given response object has * the original _response attached. * @param response - A response object from calling a client operation * @returns The same object, but with known _response property */ function assertResponse(response) { if (`_response` in response) { return response; } throw new TypeError(`Unexpected response object ${response}`); } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * RetryPolicy types. */ exports.StorageRetryPolicyType = void 0; (function (StorageRetryPolicyType) { /** * Exponential retry. Retry time delay grows exponentially. */ StorageRetryPolicyType[StorageRetryPolicyType["EXPONENTIAL"] = 0] = "EXPONENTIAL"; /** * Linear retry. Retry time delay grows linearly. */ StorageRetryPolicyType[StorageRetryPolicyType["FIXED"] = 1] = "FIXED"; })(exports.StorageRetryPolicyType || (exports.StorageRetryPolicyType = {})); // Default values of StorageRetryOptions const DEFAULT_RETRY_OPTIONS$1 = { maxRetryDelayInMs: 120 * 1000, maxTries: 4, retryDelayInMs: 4 * 1000, retryPolicyType: exports.StorageRetryPolicyType.EXPONENTIAL, secondaryHost: "", tryTimeoutInMs: undefined, // Use server side default timeout strategy }; const RETRY_ABORT_ERROR$1 = new abortController.AbortError("The operation was aborted."); /** * Retry policy with exponential retry and linear retry implemented. */ class StorageRetryPolicy extends BaseRequestPolicy { /** * Creates an instance of RetryPolicy. * * @param nextPolicy - * @param options - * @param retryOptions - */ constructor(nextPolicy, options, retryOptions = DEFAULT_RETRY_OPTIONS$1) { super(nextPolicy, options); // Initialize retry options this.retryOptions = { retryPolicyType: retryOptions.retryPolicyType ? retryOptions.retryPolicyType : DEFAULT_RETRY_OPTIONS$1.retryPolicyType, maxTries: retryOptions.maxTries && retryOptions.maxTries >= 1 ? Math.floor(retryOptions.maxTries) : DEFAULT_RETRY_OPTIONS$1.maxTries, tryTimeoutInMs: retryOptions.tryTimeoutInMs && retryOptions.tryTimeoutInMs >= 0 ? retryOptions.tryTimeoutInMs : DEFAULT_RETRY_OPTIONS$1.tryTimeoutInMs, retryDelayInMs: retryOptions.retryDelayInMs && retryOptions.retryDelayInMs >= 0 ? Math.min(retryOptions.retryDelayInMs, retryOptions.maxRetryDelayInMs ? retryOptions.maxRetryDelayInMs : DEFAULT_RETRY_OPTIONS$1.maxRetryDelayInMs) : DEFAULT_RETRY_OPTIONS$1.retryDelayInMs, maxRetryDelayInMs: retryOptions.maxRetryDelayInMs && retryOptions.maxRetryDelayInMs >= 0 ? retryOptions.maxRetryDelayInMs : DEFAULT_RETRY_OPTIONS$1.maxRetryDelayInMs, secondaryHost: retryOptions.secondaryHost ? retryOptions.secondaryHost : DEFAULT_RETRY_OPTIONS$1.secondaryHost, }; } /** * Sends request. * * @param request - */ async sendRequest(request) { return this.attemptSendRequest(request, false, 1); } /** * Decide and perform next retry. Won't mutate request parameter. * * @param request - * @param secondaryHas404 - If attempt was against the secondary & it returned a StatusNotFound (404), then * the resource was not found. This may be due to replication delay. So, in this * case, we'll never try the secondary again for this operation. * @param attempt - How many retries has been attempted to performed, starting from 1, which includes * the attempt will be performed by this method call. */ async attemptSendRequest(request, secondaryHas404, attempt) { const newRequest = request.clone(); const isPrimaryRetry = secondaryHas404 || !this.retryOptions.secondaryHost || !(request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") || attempt % 2 === 1; if (!isPrimaryRetry) { newRequest.url = setURLHost(newRequest.url, this.retryOptions.secondaryHost); } // Set the server-side timeout query parameter "timeout=[seconds]" if (this.retryOptions.tryTimeoutInMs) { newRequest.url = setURLParameter(newRequest.url, URLConstants.Parameters.TIMEOUT, Math.floor(this.retryOptions.tryTimeoutInMs / 1000).toString()); } let response; try { logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`); response = await this._nextPolicy.sendRequest(newRequest); if (!this.shouldRetry(isPrimaryRetry, attempt, response)) { return response; } secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404); } catch (err) { logger.error(`RetryPolicy: Caught error, message: ${err.message}, code: ${err.code}`); if (!this.shouldRetry(isPrimaryRetry, attempt, response, err)) { throw err; } } await this.delay(isPrimaryRetry, attempt, request.abortSignal); return this.attemptSendRequest(request, secondaryHas404, ++attempt); } /** * Decide whether to retry according to last HTTP response and retry counters. * * @param isPrimaryRetry - * @param attempt - * @param response - * @param err - */ shouldRetry(isPrimaryRetry, attempt, response, err) { if (attempt >= this.retryOptions.maxTries) { logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${this.retryOptions .maxTries}, no further try.`); return false; } // Handle network failures, you may need to customize the list when you implement // your own http client const retriableErrors = [ "ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNREFUSED", "ECONNRESET", "ENOENT", "ENOTFOUND", "TIMEOUT", "EPIPE", "REQUEST_SEND_ERROR", // For default xhr based http client provided in ms-rest-js ]; if (err) { for (const retriableError of retriableErrors) { if (err.name.toUpperCase().includes(retriableError) || err.message.toUpperCase().includes(retriableError) || (err.code && err.code.toString().toUpperCase() === retriableError)) { logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); return true; } } } // If attempt was against the secondary & it returned a StatusNotFound (404), then // the resource was not found. This may be due to replication delay. So, in this // case, we'll never try the secondary again for this operation. if (response || err) { const statusCode = response ? response.status : err ? err.statusCode : 0; if (!isPrimaryRetry && statusCode === 404) { logger.info(`RetryPolicy: Secondary access with 404, will retry.`); return true; } // Server internal error or server timeout if (statusCode === 503 || statusCode === 500) { logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); return true; } } // [Copy source error code] Feature is pending on service side, skip retry on copy source error for now. // if (response) { // // Retry select Copy Source Error Codes. // if (response?.status >= 400) { // const copySourceError = response.headers.get(HeaderConstants.X_MS_CopySourceErrorCode); // if (copySourceError !== undefined) { // switch (copySourceError) { // case "InternalError": // case "OperationTimedOut": // case "ServerBusy": // 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; } /** * Delay a calculated time between retries. * * @param isPrimaryRetry - * @param attempt - * @param abortSignal - */ async delay(isPrimaryRetry, attempt, abortSignal) { let delayTimeInMs = 0; if (isPrimaryRetry) { switch (this.retryOptions.retryPolicyType) { case exports.StorageRetryPolicyType.EXPONENTIAL: delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * this.retryOptions.retryDelayInMs, this.retryOptions.maxRetryDelayInMs); break; case exports.StorageRetryPolicyType.FIXED: delayTimeInMs = this.retryOptions.retryDelayInMs; break; } } else { delayTimeInMs = Math.random() * 1000; } logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); return delay(delayTimeInMs, abortSignal, RETRY_ABORT_ERROR$1); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * StorageRetryPolicyFactory is a factory class helping generating {@link StorageRetryPolicy} objects. */ class StorageRetryPolicyFactory { /** * Creates an instance of StorageRetryPolicyFactory. * @param retryOptions - */ constructor(retryOptions) { this.retryOptions = retryOptions; } /** * Creates a StorageRetryPolicy object. * * @param nextPolicy - * @param options - */ create(nextPolicy, options) { return new StorageRetryPolicy(nextPolicy, options, this.retryOptions); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * Credential policy used to sign HTTP(S) requests before sending. This is an * abstract class. */ class CredentialPolicy extends BaseRequestPolicy { /** * Sends out request. * * @param request - */ sendRequest(request) { return this._nextPolicy.sendRequest(this.signRequest(request)); } /** * Child classes must implement this method with request signing. This method * will be executed in {@link sendRequest}. * * @param request - */ signRequest(request) { // Child classes must override this method with request signing. This method // will be executed in sendRequest(). return request; } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /* * We need to imitate .Net culture-aware sorting, which is used in storage service. * Below tables contain sort-keys for en-US culture. */ const table_lv0 = new Uint32Array([ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x71c, 0x0, 0x71f, 0x721, 0x723, 0x725, 0x0, 0x0, 0x0, 0x72d, 0x803, 0x0, 0x0, 0x733, 0x0, 0xd03, 0xd1a, 0xd1c, 0xd1e, 0xd20, 0xd22, 0xd24, 0xd26, 0xd28, 0xd2a, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xe02, 0xe09, 0xe0a, 0xe1a, 0xe21, 0xe23, 0xe25, 0xe2c, 0xe32, 0xe35, 0xe36, 0xe48, 0xe51, 0xe70, 0xe7c, 0xe7e, 0xe89, 0xe8a, 0xe91, 0xe99, 0xe9f, 0xea2, 0xea4, 0xea6, 0xea7, 0xea9, 0x0, 0x0, 0x0, 0x743, 0x744, 0x748, 0xe02, 0xe09, 0xe0a, 0xe1a, 0xe21, 0xe23, 0xe25, 0xe2c, 0xe32, 0xe35, 0xe36, 0xe48, 0xe51, 0xe70, 0xe7c, 0xe7e, 0xe89, 0xe8a, 0xe91, 0xe99, 0xe9f, 0xea2, 0xea4, 0xea6, 0xea7, 0xea9, 0x0, 0x74c, 0x0, 0x750, 0x0, ]); const table_lv2 = new Uint32Array([ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, ]); const table_lv4 = new Uint32Array([ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8012, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8212, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, ]); function compareHeader(lhs, rhs) { if (isLessThan(lhs, rhs)) return -1; return 1; } function isLessThan(lhs, rhs) { const tables = [table_lv0, table_lv2, table_lv4]; let curr_level = 0; let i = 0; let j = 0; while (curr_level < tables.length) { if (curr_level === tables.length - 1 && i !== j) { return i > j; } const weight1 = i < lhs.length ? tables[curr_level][lhs[i].charCodeAt(0)] : 0x1; const weight2 = j < rhs.length ? tables[curr_level][rhs[j].charCodeAt(0)] : 0x1; if (weight1 === 0x1 && weight2 === 0x1) { i = 0; j = 0; ++curr_level; } else if (weight1 === weight2) { ++i; ++j; } else if (weight1 === 0) { ++i; } else if (weight2 === 0) { ++j; } else { return weight1 < weight2; } } return false; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * StorageSharedKeyCredentialPolicy is a policy used to sign HTTP request with a shared key. */ class StorageSharedKeyCredentialPolicy extends CredentialPolicy { /** * Creates an instance of StorageSharedKeyCredentialPolicy. * @param nextPolicy - * @param options - * @param factory - */ constructor(nextPolicy, options, factory) { super(nextPolicy, options); this.factory = factory; } /** * Signs request. * * @param request - */ signRequest(request) { request.headers.set(HeaderConstants.X_MS_DATE, new Date().toUTCString()); if (request.body && (typeof request.body === "string" || request.body !== undefined) && request.body.length > 0) { request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); } const stringToSign = [ request.method.toUpperCase(), this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LANGUAGE), this.getHeaderValueToSign(request, HeaderConstants.CONTENT_ENCODING), this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LENGTH), this.getHeaderValueToSign(request, HeaderConstants.CONTENT_MD5), this.getHeaderValueToSign(request, HeaderConstants.CONTENT_TYPE), this.getHeaderValueToSign(request, HeaderConstants.DATE), this.getHeaderValueToSign(request, HeaderConstants.IF_MODIFIED_SINCE), this.getHeaderValueToSign(request, HeaderConstants.IF_MATCH), this.getHeaderValueToSign(request, HeaderConstants.IF_NONE_MATCH), this.getHeaderValueToSign(request, HeaderConstants.IF_UNMODIFIED_SINCE), this.getHeaderValueToSign(request, HeaderConstants.RANGE), ].join("\n") + "\n" + this.getCanonicalizedHeadersString(request) + this.getCanonicalizedResourceString(request); const signature = this.factory.computeHMACSHA256(stringToSign); request.headers.set(HeaderConstants.AUTHORIZATION, `SharedKey ${this.factory.accountName}:${signature}`); // console.log(`[URL]:${request.url}`); // console.log(`[HEADERS]:${request.headers.toString()}`); // console.log(`[STRING TO SIGN]:${JSON.stringify(stringToSign)}`); // console.log(`[KEY]: ${request.headers.get(HeaderConstants.AUTHORIZATION)}`); return request; } /** * Retrieve header value according to shared key sign rules. * @see https://learn.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key * * @param request - * @param headerName - */ getHeaderValueToSign(request, headerName) { const value = request.headers.get(headerName); if (!value) { return ""; } // When using version 2015-02-21 or later, if Content-Length is zero, then // set the Content-Length part of the StringToSign to an empty string. // https://learn.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key if (headerName === HeaderConstants.CONTENT_LENGTH && value === "0") { return ""; } return value; } /** * To construct the CanonicalizedHeaders portion of the signature string, follow these steps: * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header. * 2. Convert each HTTP header name to lowercase. * 3. Sort the headers lexicographically by header name, in ascending order. * Each header may appear only once in the string. * 4. Replace any linear whitespace in the header value with a single space. * 5. Trim any whitespace around the colon in the header. * 6. Finally, append a new-line character to each canonicalized header in the resulting list. * Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string. * * @param request - */ getCanonicalizedHeadersString(request) { let headersArray = request.headers.headersArray().filter((value) => { return value.name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE); }); headersArray.sort((a, b) => { return compareHeader(a.name.toLowerCase(), b.name.toLowerCase()); }); // Remove duplicate headers headersArray = headersArray.filter((value, index, array) => { if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) { return false; } return true; }); let canonicalizedHeadersStringToSign = ""; headersArray.forEach((header) => { canonicalizedHeadersStringToSign += `${header.name .toLowerCase() .trimRight()}:${header.value.trimLeft()}\n`; }); return canonicalizedHeadersStringToSign; } /** * Retrieves the webResource canonicalized resource string. * * @param request - */ getCanonicalizedResourceString(request) { const path = getURLPath(request.url) || "/"; let canonicalizedResourceString = ""; canonicalizedResourceString += `/${this.factory.accountName}${path}`; const queries = getURLQueries(request.url); const lowercaseQueries = {}; if (queries) { const queryKeys = []; for (const key in queries) { if (Object.prototype.hasOwnProperty.call(queries, key)) { const lowercaseKey = key.toLowerCase(); lowercaseQueries[lowercaseKey] = queries[key]; queryKeys.push(lowercaseKey); } } queryKeys.sort(); for (const key of queryKeys) { canonicalizedResourceString += `\n${key}:${decodeURIComponent(lowercaseQueries[key])}`; } } return canonicalizedResourceString; } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * Credential is an abstract class for Azure Storage HTTP requests signing. This * class will host an credentialPolicyCreator factory which generates CredentialPolicy. */ class Credential { /** * Creates a RequestPolicy object. * * @param _nextPolicy - * @param _options - */ create(_nextPolicy, _options) { throw new Error("Method should be implemented in children classes."); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * StorageSharedKeyCredential for account key authorization of Azure Storage service. */ class StorageSharedKeyCredential extends Credential { /** * Creates an instance of StorageSharedKeyCredential. * @param accountName - * @param accountKey - */ constructor(accountName, accountKey) { super(); this.accountName = accountName; this.accountKey = Buffer.from(accountKey, "base64"); } /** * Creates a StorageSharedKeyCredentialPolicy object. * * @param nextPolicy - * @param options - */ create(nextPolicy, options) { return new StorageSharedKeyCredentialPolicy(nextPolicy, options, this); } /** * Generates a hash signature for an HTTP request or for a SAS. * * @param stringToSign - */ computeHMACSHA256(stringToSign) { return crypto.createHmac("sha256", this.accountKey).update(stringToSign, "utf8").digest("base64"); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * AnonymousCredentialPolicy is used with HTTP(S) requests that read public resources * or for use with Shared Access Signatures (SAS). */ class AnonymousCredentialPolicy extends CredentialPolicy { /** * Creates an instance of AnonymousCredentialPolicy. * @param nextPolicy - * @param options - */ // The base class has a protected constructor. Adding a public one to enable constructing of this class. /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ constructor(nextPolicy, options) { super(nextPolicy, options); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * AnonymousCredential provides a credentialPolicyCreator member used to create * AnonymousCredentialPolicy objects. AnonymousCredentialPolicy is used with * HTTP(S) requests that read public resources or for use with Shared Access * Signatures (SAS). */ class AnonymousCredential extends Credential { /** * Creates an {@link AnonymousCredentialPolicy} object. * * @param nextPolicy - * @param options - */ create(nextPolicy, options) { return new AnonymousCredentialPolicy(nextPolicy, options); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. let _defaultHttpClient; function getCachedDefaultHttpClient() { if (!_defaultHttpClient) { _defaultHttpClient = coreRestPipeline.createDefaultHttpClient(); } return _defaultHttpClient; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * The programmatic identifier of the StorageBrowserPolicy. */ const storageBrowserPolicyName = "storageBrowserPolicy"; /** * storageBrowserPolicy is a policy used to prevent browsers from caching requests * and to remove cookies and explicit content-length headers. */ function storageBrowserPolicy() { return { name: storageBrowserPolicyName, async sendRequest(request, next) { if (coreUtil.isNode) { return next(request); } if (request.method === "GET" || request.method === "HEAD") { request.url = setURLParameter(request.url, URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, new Date().getTime().toString()); } request.headers.delete(HeaderConstants.COOKIE); // According to XHR standards, content-length should be fully controlled by browsers request.headers.delete(HeaderConstants.CONTENT_LENGTH); return next(request); }, }; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * Name of the {@link storageRetryPolicy} */ const storageRetryPolicyName = "storageRetryPolicy"; /** * RetryPolicy types. */ var StorageRetryPolicyType; (function (StorageRetryPolicyType) { /** * Exponential retry. Retry time delay grows exponentially. */ StorageRetryPolicyType[StorageRetryPolicyType["EXPONENTIAL"] = 0] = "EXPONENTIAL"; /** * Linear retry. Retry time delay grows linearly. */ StorageRetryPolicyType[StorageRetryPolicyType["FIXED"] = 1] = "FIXED"; })(StorageRetryPolicyType || (StorageRetryPolicyType = {})); // Default values of StorageRetryOptions const DEFAULT_RETRY_OPTIONS = { maxRetryDelayInMs: 120 * 1000, maxTries: 4, retryDelayInMs: 4 * 1000, retryPolicyType: StorageRetryPolicyType.EXPONENTIAL, secondaryHost: "", tryTimeoutInMs: undefined, // Use server side default timeout strategy }; const retriableErrors = [ "ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNREFUSED", "ECONNRESET", "ENOENT", "ENOTFOUND", "TIMEOUT", "EPIPE", "REQUEST_SEND_ERROR", ]; const RETRY_ABORT_ERROR = new abortController.AbortError("The operation was aborted."); /** * Retry policy with exponential retry and linear retry implemented. */ function storageRetryPolicy(options = {}) { var _a, _b, _c, _d, _e, _f; const retryPolicyType = (_a = options.retryPolicyType) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_OPTIONS.retryPolicyType; const maxTries = (_b = options.maxTries) !== null && _b !== void 0 ? _b : DEFAULT_RETRY_OPTIONS.maxTries; const retryDelayInMs = (_c = options.retryDelayInMs) !== null && _c !== void 0 ? _c : DEFAULT_RETRY_OPTIONS.retryDelayInMs; const maxRetryDelayInMs = (_d = options.maxRetryDelayInMs) !== null && _d !== void 0 ? _d : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs; const secondaryHost = (_e = options.secondaryHost) !== null && _e !== void 0 ? _e : DEFAULT_RETRY_OPTIONS.secondaryHost; const tryTimeoutInMs = (_f = options.tryTimeoutInMs) !== null && _f !== void 0 ? _f : DEFAULT_RETRY_OPTIONS.tryTimeoutInMs; function shouldRetry({ isPrimaryRetry, attempt, response, error, }) { var _a, _b; if (attempt >= maxTries) { logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${maxTries}, no further try.`); return false; } if (error) { for (const retriableError of retriableErrors) { if (error.name.toUpperCase().includes(retriableError) || error.message.toUpperCase().includes(retriableError) || (error.code && error.code.toString().toUpperCase() === retriableError)) { logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); return true; } } if ((error === null || error === void 0 ? void 0 : error.code) === "PARSE_ERROR" && (error === null || error === void 0 ? void 0 : error.message.startsWith(`Error "Error: Unclosed root tag`))) { logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry."); return true; } } // If attempt was against the secondary & it returned a StatusNotFound (404), then // the resource was not found. This may be due to replication delay. So, in this // case, we'll never try the secondary again for this operation. if (response || error) { const statusCode = (_b = (_a = response === null || response === void 0 ? void 0 : response.status) !== null && _a !== void 0 ? _a : error === null || error === void 0 ? void 0 : error.statusCode) !== null && _b !== void 0 ? _b : 0; if (!isPrimaryRetry && statusCode === 404) { logger.info(`RetryPolicy: Secondary access with 404, will retry.`); return true; } // Server internal error or server timeout if (statusCode === 503 || statusCode === 500) { logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); return true; } } // [Copy source error code] Feature is pending on service side, skip retry on copy source error for now. // if (response) { // // Retry select Copy Source Error Codes. // if (response?.status >= 400) { // const copySourceError = response.headers.get(HeaderConstants.X_MS_CopySourceErrorCode); // if (copySourceError !== undefined) { // switch (copySourceError) { // case "InternalError": // case "OperationTimedOut": // case "ServerBusy": // return true; // } // } // } // } return false; } function calculateDelay(isPrimaryRetry, attempt) { let delayTimeInMs = 0; if (isPrimaryRetry) { switch (retryPolicyType) { case StorageRetryPolicyType.EXPONENTIAL: delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * retryDelayInMs, maxRetryDelayInMs); break; case StorageRetryPolicyType.FIXED: delayTimeInMs = retryDelayInMs; break; } } else { delayTimeInMs = Math.random() * 1000; } logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); return delayTimeInMs; } return { name: storageRetryPolicyName, async sendRequest(request, next) { // Set the server-side timeout query parameter "timeout=[seconds]" if (tryTimeoutInMs) { request.url = setURLParameter(request.url, URLConstants.Parameters.TIMEOUT, String(Math.floor(tryTimeoutInMs / 1000))); } const primaryUrl = request.url; const secondaryUrl = secondaryHost ? setURLHost(request.url, secondaryHost) : undefined; let secondaryHas404 = false; let attempt = 1; let retryAgain = true; let response; let error; while (retryAgain) { const isPrimaryRetry = secondaryHas404 || !secondaryUrl || !["GET", "HEAD", "OPTIONS"].includes(request.method) || attempt % 2 === 1; request.url = isPrimaryRetry ? primaryUrl : secondaryUrl; response = undefined; error = undefined; try { logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`); response = await next(request); secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404); } catch (e) { if (coreRestPipeline.isRestError(e)) { logger.error(`RetryPolicy: Caught error, message: ${e.message}, code: ${e.code}`); error = e; } else { logger.error(`RetryPolicy: Caught error, message: ${coreUtil.getErrorMessage(e)}`); throw e; } } retryAgain = shouldRetry({ isPrimaryRetry, attempt, response, error }); if (retryAgain) { await delay(calculateDelay(isPrimaryRetry, attempt), request.abortSignal, RETRY_ABORT_ERROR); } attempt++; } if (response) { return response; } throw error !== null && error !== void 0 ? error : new coreRestPipeline.RestError("RetryPolicy failed without known error."); }, }; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * The programmatic identifier of the storageSharedKeyCredentialPolicy. */ const storageSharedKeyCredentialPolicyName = "storageSharedKeyCredentialPolicy"; /** * storageSharedKeyCredentialPolicy handles signing requests using storage account keys. */ function storageSharedKeyCredentialPolicy(options) { function signRequest(request) { request.headers.set(HeaderConstants.X_MS_DATE, new Date().toUTCString()); if (request.body && (typeof request.body === "string" || Buffer.isBuffer(request.body)) && request.body.length > 0) { request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); } const stringToSign = [ request.method.toUpperCase(), getHeaderValueToSign(request, HeaderConstants.CONTENT_LANGUAGE), getHeaderValueToSign(request, HeaderConstants.CONTENT_ENCODING), getHeaderValueToSign(request, HeaderConstants.CONTENT_LENGTH), getHeaderValueToSign(request, HeaderConstants.CONTENT_MD5), getHeaderValueToSign(request, HeaderConstants.CONTENT_TYPE), getHeaderValueToSign(request, HeaderConstants.DATE), getHeaderValueToSign(request, HeaderConstants.IF_MODIFIED_SINCE), getHeaderValueToSign(request, HeaderConstants.IF_MATCH), getHeaderValueToSign(request, HeaderConstants.IF_NONE_MATCH), getHeaderValueToSign(request, HeaderConstants.IF_UNMODIFIED_SINCE), getHeaderValueToSign(request, HeaderConstants.RANGE), ].join("\n") + "\n" + getCanonicalizedHeadersString(request) + getCanonicalizedResourceString(request); const signature = crypto.createHmac("sha256", options.accountKey) .update(stringToSign, "utf8") .digest("base64"); request.headers.set(HeaderConstants.AUTHORIZATION, `SharedKey ${options.accountName}:${signature}`); // console.log(`[URL]:${request.url}`); // console.log(`[HEADERS]:${request.headers.toString()}`); // console.log(`[STRING TO SIGN]:${JSON.stringify(stringToSign)}`); // console.log(`[KEY]: ${request.headers.get(HeaderConstants.AUTHORIZATION)}`); } /** * Retrieve header value according to shared key sign rules. * @see https://learn.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key */ function getHeaderValueToSign(request, headerName) { const value = request.headers.get(headerName); if (!value) { return ""; } // When using version 2015-02-21 or later, if Content-Length is zero, then // set the Content-Length part of the StringToSign to an empty string. // https://learn.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key if (headerName === HeaderConstants.CONTENT_LENGTH && value === "0") { return ""; } return value; } /** * To construct the CanonicalizedHeaders portion of the signature string, follow these steps: * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header. * 2. Convert each HTTP header name to lowercase. * 3. Sort the headers lexicographically by header name, in ascending order. * Each header may appear only once in the string. * 4. Replace any linear whitespace in the header value with a single space. * 5. Trim any whitespace around the colon in the header. * 6. Finally, append a new-line character to each canonicalized header in the resulting list. * Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string. * */ function getCanonicalizedHeadersString(request) { let headersArray = []; for (const [name, value] of request.headers) { if (name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE)) { headersArray.push({ name, value }); } } headersArray.sort((a, b) => { return compareHeader(a.name.toLowerCase(), b.name.toLowerCase()); }); // Remove duplicate headers headersArray = headersArray.filter((value, index, array) => { if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) { return false; } return true; }); let canonicalizedHeadersStringToSign = ""; headersArray.forEach((header) => { canonicalizedHeadersStringToSign += `${header.name .toLowerCase() .trimRight()}:${header.value.trimLeft()}\n`; }); return canonicalizedHeadersStringToSign; } function getCanonicalizedResourceString(request) { const path = getURLPath(request.url) || "/"; let canonicalizedResourceString = ""; canonicalizedResourceString += `/${options.accountName}${path}`; const queries = getURLQueries(request.url); const lowercaseQueries = {}; if (queries) { const queryKeys = []; for (const key in queries) { if (Object.prototype.hasOwnProperty.call(queries, key)) { const lowercaseKey = key.toLowerCase(); lowercaseQueries[lowercaseKey] = queries[key]; queryKeys.push(lowercaseKey); } } queryKeys.sort(); for (const key of queryKeys) { canonicalizedResourceString += `\n${key}:${decodeURIComponent(lowercaseQueries[key])}`; } } return canonicalizedResourceString; } return { name: storageSharedKeyCredentialPolicyName, async sendRequest(request, next) { signRequest(request); return next(request); }, }; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * StorageBrowserPolicy will handle differences between Node.js and browser runtime, including: * * 1. Browsers cache GET/HEAD requests by adding conditional headers such as 'IF_MODIFIED_SINCE'. * StorageBrowserPolicy is a policy used to add a timestamp query to GET/HEAD request URL * thus avoid the browser cache. * * 2. Remove cookie header for security * * 3. Remove content-length header to avoid browsers warning */ class StorageBrowserPolicy extends BaseRequestPolicy { /** * Creates an instance of StorageBrowserPolicy. * @param nextPolicy - * @param options - */ // The base class has a protected constructor. Adding a public one to enable constructing of this class. /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ constructor(nextPolicy, options) { super(nextPolicy, options); } /** * Sends out request. * * @param request - */ async sendRequest(request) { if (coreUtil.isNode) { return this._nextPolicy.sendRequest(request); } if (request.method.toUpperCase() === "GET" || request.method.toUpperCase() === "HEAD") { request.url = setURLParameter(request.url, URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, new Date().getTime().toString()); } request.headers.remove(HeaderConstants.COOKIE); // According to XHR standards, content-length should be fully controlled by browsers request.headers.remove(HeaderConstants.CONTENT_LENGTH); return this._nextPolicy.sendRequest(request); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * StorageBrowserPolicyFactory is a factory class helping generating StorageBrowserPolicy objects. */ class StorageBrowserPolicyFactory { /** * Creates a StorageBrowserPolicyFactory object. * * @param nextPolicy - * @param options - */ create(nextPolicy, options) { return new StorageBrowserPolicy(nextPolicy, options); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * The programmatic identifier of the storageCorrectContentLengthPolicy. */ const storageCorrectContentLengthPolicyName = "StorageCorrectContentLengthPolicy"; /** * storageCorrectContentLengthPolicy to correctly set Content-Length header with request body length. */ function storageCorrectContentLengthPolicy() { function correctContentLength(request) { if (request.body && (typeof request.body === "string" || Buffer.isBuffer(request.body)) && request.body.length > 0) { request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); } } return { name: storageCorrectContentLengthPolicyName, async sendRequest(request, next) { correctContentLength(request); return next(request); }, }; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * A helper to decide if a given argument satisfies the Pipeline contract * @param pipeline - An argument that may be a Pipeline * @returns true when the argument satisfies the Pipeline contract */ function isPipelineLike(pipeline) { if (!pipeline || typeof pipeline !== "object") { return false; } const castPipeline = pipeline; return (Array.isArray(castPipeline.factories) && typeof castPipeline.options === "object" && typeof castPipeline.toServiceClientOptions === "function"); } /** * A Pipeline class containing HTTP request policies. * You can create a default Pipeline by calling {@link newPipeline}. * Or you can create a Pipeline with your own policies by the constructor of Pipeline. * * Refer to {@link newPipeline} and provided policies before implementing your * customized Pipeline. */ class Pipeline { /** * Creates an instance of Pipeline. Customize HTTPClient by implementing IHttpClient interface. * * @param factories - * @param options - */ constructor(factories, options = {}) { this.factories = factories; this.options = options; } /** * Transfer Pipeline object to ServiceClientOptions object which is required by * ServiceClient constructor. * * @returns The ServiceClientOptions object from this Pipeline. */ toServiceClientOptions() { return { httpClient: this.options.httpClient, requestPolicyFactories: this.factories, }; } } /** * Creates a new Pipeline object with Credential provided. * * @param 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. * @param pipelineOptions - Optional. Options. * @returns A new Pipeline object. */ function newPipeline(credential, pipelineOptions = {}) { if (!credential) { credential = new AnonymousCredential(); } const pipeline = new Pipeline([], pipelineOptions); pipeline._credential = credential; return pipeline; } function processDownlevelPipeline(pipeline) { const knownFactoryFunctions = [ isAnonymousCredential, isStorageSharedKeyCredential, isCoreHttpBearerTokenFactory, isStorageBrowserPolicyFactory, isStorageRetryPolicyFactory, isStorageTelemetryPolicyFactory, isCoreHttpPolicyFactory, ]; if (pipeline.factories.length) { const novelFactories = pipeline.factories.filter((factory) => { return !knownFactoryFunctions.some((knownFactory) => knownFactory(factory)); }); if (novelFactories.length) { const hasInjector = novelFactories.some((factory) => isInjectorPolicyFactory(factory)); // if there are any left over, wrap in a requestPolicyFactoryPolicy return { wrappedPolicies: coreHttpCompat.createRequestPolicyFactoryPolicy(novelFactories), afterRetry: hasInjector, }; } } return undefined; } function getCoreClientOptions(pipeline) { var _a; const _b = pipeline.options, { httpClient: v1Client } = _b, restOptions = tslib.__rest(_b, ["httpClient"]); let httpClient = pipeline._coreHttpClient; if (!httpClient) { httpClient = v1Client ? coreHttpCompat.convertHttpClient(v1Client) : getCachedDefaultHttpClient(); pipeline._coreHttpClient = httpClient; } let corePipeline = pipeline._corePipeline; if (!corePipeline) { const packageDetails = `azsdk-js-azure-storage-blob/${SDK_VERSION}`; const userAgentPrefix = restOptions.userAgentOptions && restOptions.userAgentOptions.userAgentPrefix ? `${restOptions.userAgentOptions.userAgentPrefix} ${packageDetails}` : `${packageDetails}`; corePipeline = coreClient.createClientPipeline(Object.assign(Object.assign({}, restOptions), { loggingOptions: { additionalAllowedHeaderNames: StorageBlobLoggingAllowedHeaderNames, additionalAllowedQueryParameters: StorageBlobLoggingAllowedQueryParameters, logger: logger.info, }, userAgentOptions: { userAgentPrefix, }, serializationOptions: { stringifyXML: coreXml.stringifyXML, serializerOptions: { xml: { // Use customized XML char key of "#" so we can deserialize metadata // with "_" key xmlCharKey: "#", }, }, }, deserializationOptions: { parseXML: coreXml.parseXML, serializerOptions: { xml: { // Use customized XML char key of "#" so we can deserialize metadata // with "_" key xmlCharKey: "#", }, }, } })); corePipeline.removePolicy({ phase: "Retry" }); corePipeline.removePolicy({ name: coreRestPipeline.decompressResponsePolicyName }); corePipeline.addPolicy(storageCorrectContentLengthPolicy()); corePipeline.addPolicy(storageRetryPolicy(restOptions.retryOptions), { phase: "Retry" }); corePipeline.addPolicy(storageBrowserPolicy()); const downlevelResults = processDownlevelPipeline(pipeline); if (downlevelResults) { corePipeline.addPolicy(downlevelResults.wrappedPolicies, downlevelResults.afterRetry ? { afterPhase: "Retry" } : undefined); } const credential = getCredentialFromPipeline(pipeline); if (coreAuth.isTokenCredential(credential)) { corePipeline.addPolicy(coreRestPipeline.bearerTokenAuthenticationPolicy({ credential, scopes: (_a = restOptions.audience) !== null && _a !== void 0 ? _a : StorageOAuthScopes, challengeCallbacks: { authorizeRequestOnChallenge: coreClient.authorizeRequestOnTenantChallenge }, }), { phase: "Sign" }); } else if (credential instanceof StorageSharedKeyCredential) { corePipeline.addPolicy(storageSharedKeyCredentialPolicy({ accountName: credential.accountName, accountKey: credential.accountKey, }), { phase: "Sign" }); } pipeline._corePipeline = corePipeline; } return Object.assign(Object.assign({}, restOptions), { allowInsecureConnection: true, httpClient, pipeline: corePipeline }); } function getCredentialFromPipeline(pipeline) { // see if we squirreled one away on the type itself if (pipeline._credential) { return pipeline._credential; } // if it came from another package, loop over the factories and look for one like before let credential = new AnonymousCredential(); for (const factory of pipeline.factories) { if (coreAuth.isTokenCredential(factory.credential)) { // Only works if the factory has been attached a "credential" property. // We do that in newPipeline() when using TokenCredential. credential = factory.credential; } else if (isStorageSharedKeyCredential(factory)) { return factory; } } return credential; } function isStorageSharedKeyCredential(factory) { if (factory instanceof StorageSharedKeyCredential) { return true; } return factory.constructor.name === "StorageSharedKeyCredential"; } function isAnonymousCredential(factory) { if (factory instanceof AnonymousCredential) { return true; } return factory.constructor.name === "AnonymousCredential"; } function isCoreHttpBearerTokenFactory(factory) { return coreAuth.isTokenCredential(factory.credential); } function isStorageBrowserPolicyFactory(factory) { if (factory instanceof StorageBrowserPolicyFactory) { return true; } return factory.constructor.name === "StorageBrowserPolicyFactory"; } function isStorageRetryPolicyFactory(factory) { if (factory instanceof StorageRetryPolicyFactory) { return true; } return factory.constructor.name === "StorageRetryPolicyFactory"; } function isStorageTelemetryPolicyFactory(factory) { return factory.constructor.name === "TelemetryPolicyFactory"; } function isInjectorPolicyFactory(factory) { return factory.constructor.name === "InjectorPolicyFactory"; } function isCoreHttpPolicyFactory(factory) { const knownPolicies = [ "GenerateClientRequestIdPolicy", "TracingPolicy", "LogPolicy", "ProxyPolicy", "DisableResponseDecompressionPolicy", "KeepAlivePolicy", "DeserializationPolicy", ]; const mockHttpClient = { sendRequest: async (request) => { return { request, headers: request.headers.clone(), status: 500, }; }, }; const mockRequestPolicyOptions = { log(_logLevel, _message) { /* do nothing */ }, shouldLog(_logLevel) { return false; }, }; const policyInstance = factory.create(mockHttpClient, mockRequestPolicyOptions); const policyName = policyInstance.constructor.name; // bundlers sometimes add a custom suffix to the class name to make it unique return knownPolicies.some((knownPolicyName) => { return policyName.startsWith(knownPolicyName); }); } /* * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ const BlobServiceProperties = { serializedName: "BlobServiceProperties", xmlName: "StorageServiceProperties", type: { name: "Composite", className: "BlobServiceProperties", modelProperties: { blobAnalyticsLogging: { serializedName: "Logging", xmlName: "Logging", type: { name: "Composite", className: "Logging", }, }, hourMetrics: { serializedName: "HourMetrics", xmlName: "HourMetrics", type: { name: "Composite", className: "Metrics", }, }, minuteMetrics: { serializedName: "MinuteMetrics", xmlName: "MinuteMetrics", type: { name: "Composite", className: "Metrics", }, }, cors: { serializedName: "Cors", xmlName: "Cors", xmlIsWrapped: true, xmlElementName: "CorsRule", type: { name: "Sequence", element: { type: { name: "Composite", className: "CorsRule", }, }, }, }, defaultServiceVersion: { serializedName: "DefaultServiceVersion", xmlName: "DefaultServiceVersion", type: { name: "String", }, }, deleteRetentionPolicy: { serializedName: "DeleteRetentionPolicy", xmlName: "DeleteRetentionPolicy", type: { name: "Composite", className: "RetentionPolicy", }, }, staticWebsite: { serializedName: "StaticWebsite", xmlName: "StaticWebsite", type: { name: "Composite", className: "StaticWebsite", }, }, }, }, }; const Logging = { serializedName: "Logging", type: { name: "Composite", className: "Logging", modelProperties: { version: { serializedName: "Version", required: true, xmlName: "Version", type: { name: "String", }, }, deleteProperty: { serializedName: "Delete", required: true, xmlName: "Delete", type: { name: "Boolean", }, }, read: { serializedName: "Read", required: true, xmlName: "Read", type: { name: "Boolean", }, }, write: { serializedName: "Write", required: true, xmlName: "Write", type: { name: "Boolean", }, }, retentionPolicy: { serializedName: "RetentionPolicy", xmlName: "RetentionPolicy", type: { name: "Composite", className: "RetentionPolicy", }, }, }, }, }; const RetentionPolicy = { serializedName: "RetentionPolicy", type: { name: "Composite", className: "RetentionPolicy", modelProperties: { enabled: { serializedName: "Enabled", required: true, xmlName: "Enabled", type: { name: "Boolean", }, }, days: { constraints: { InclusiveMinimum: 1, }, serializedName: "Days", xmlName: "Days", type: { name: "Number", }, }, }, }, }; const Metrics = { serializedName: "Metrics", type: { name: "Composite", className: "Metrics", modelProperties: { version: { serializedName: "Version", xmlName: "Version", type: { name: "String", }, }, enabled: { serializedName: "Enabled", required: true, xmlName: "Enabled", type: { name: "Boolean", }, }, includeAPIs: { serializedName: "IncludeAPIs", xmlName: "IncludeAPIs", type: { name: "Boolean", }, }, retentionPolicy: { serializedName: "RetentionPolicy", xmlName: "RetentionPolicy", type: { name: "Composite", className: "RetentionPolicy", }, }, }, }, }; const CorsRule = { serializedName: "CorsRule", type: { name: "Composite", className: "CorsRule", modelProperties: { allowedOrigins: { serializedName: "AllowedOrigins", required: true, xmlName: "AllowedOrigins", type: { name: "String", }, }, allowedMethods: { serializedName: "AllowedMethods", required: true, xmlName: "AllowedMethods", type: { name: "String", }, }, allowedHeaders: { serializedName: "AllowedHeaders", required: true, xmlName: "AllowedHeaders", type: { name: "String", }, }, exposedHeaders: { serializedName: "ExposedHeaders", required: true, xmlName: "ExposedHeaders", type: { name: "String", }, }, maxAgeInSeconds: { constraints: { InclusiveMinimum: 0, }, serializedName: "MaxAgeInSeconds", required: true, xmlName: "MaxAgeInSeconds", type: { name: "Number", }, }, }, }, }; const StaticWebsite = { serializedName: "StaticWebsite", type: { name: "Composite", className: "StaticWebsite", modelProperties: { enabled: { serializedName: "Enabled", required: true, xmlName: "Enabled", type: { name: "Boolean", }, }, indexDocument: { serializedName: "IndexDocument", xmlName: "IndexDocument", type: { name: "String", }, }, errorDocument404Path: { serializedName: "ErrorDocument404Path", xmlName: "ErrorDocument404Path", type: { name: "String", }, }, defaultIndexDocumentPath: { serializedName: "DefaultIndexDocumentPath", xmlName: "DefaultIndexDocumentPath", type: { name: "String", }, }, }, }, }; const StorageError = { serializedName: "StorageError", type: { name: "Composite", className: "StorageError", modelProperties: { message: { serializedName: "Message", xmlName: "Message", type: { name: "String", }, }, code: { serializedName: "Code", xmlName: "Code", type: { name: "String", }, }, authenticationErrorDetail: { serializedName: "AuthenticationErrorDetail", xmlName: "AuthenticationErrorDetail", type: { name: "String", }, }, }, }, }; const BlobServiceStatistics = { serializedName: "BlobServiceStatistics", xmlName: "StorageServiceStats", type: { name: "Composite", className: "BlobServiceStatistics", modelProperties: { geoReplication: { serializedName: "GeoReplication", xmlName: "GeoReplication", type: { name: "Composite", className: "GeoReplication", }, }, }, }, }; const GeoReplication = { serializedName: "GeoReplication", type: { name: "Composite", className: "GeoReplication", modelProperties: { status: { serializedName: "Status", required: true, xmlName: "Status", type: { name: "Enum", allowedValues: ["live", "bootstrap", "unavailable"], }, }, lastSyncOn: { serializedName: "LastSyncTime", required: true, xmlName: "LastSyncTime", type: { name: "DateTimeRfc1123", }, }, }, }, }; const ListContainersSegmentResponse = { serializedName: "ListContainersSegmentResponse", xmlName: "EnumerationResults", type: { name: "Composite", className: "ListContainersSegmentResponse", modelProperties: { serviceEndpoint: { serializedName: "ServiceEndpoint", required: true, xmlName: "ServiceEndpoint", xmlIsAttribute: true, type: { name: "String", }, }, prefix: { serializedName: "Prefix", xmlName: "Prefix", type: { name: "String", }, }, marker: { serializedName: "Marker", xmlName: "Marker", type: { name: "String", }, }, maxPageSize: { serializedName: "MaxResults", xmlName: "MaxResults", type: { name: "Number", }, }, containerItems: { serializedName: "ContainerItems", required: true, xmlName: "Containers", xmlIsWrapped: true, xmlElementName: "Container", type: { name: "Sequence", element: { type: { name: "Composite", className: "ContainerItem", }, }, }, }, continuationToken: { serializedName: "NextMarker", xmlName: "NextMarker", type: { name: "String", }, }, }, }, }; const ContainerItem = { serializedName: "ContainerItem", xmlName: "Container", type: { name: "Composite", className: "ContainerItem", modelProperties: { name: { serializedName: "Name", required: true, xmlName: "Name", type: { name: "String", }, }, deleted: { serializedName: "Deleted", xmlName: "Deleted", type: { name: "Boolean", }, }, version: { serializedName: "Version", xmlName: "Version", type: { name: "String", }, }, properties: { serializedName: "Properties", xmlName: "Properties", type: { name: "Composite", className: "ContainerProperties", }, }, metadata: { serializedName: "Metadata", xmlName: "Metadata", type: { name: "Dictionary", value: { type: { name: "String" } }, }, }, }, }, }; const ContainerProperties = { serializedName: "ContainerProperties", type: { name: "Composite", className: "ContainerProperties", modelProperties: { lastModified: { serializedName: "Last-Modified", required: true, xmlName: "Last-Modified", type: { name: "DateTimeRfc1123", }, }, etag: { serializedName: "Etag", required: true, xmlName: "Etag", type: { name: "String", }, }, leaseStatus: { serializedName: "LeaseStatus", xmlName: "LeaseStatus", type: { name: "Enum", allowedValues: ["locked", "unlocked"], }, }, leaseState: { serializedName: "LeaseState", xmlName: "LeaseState", type: { name: "Enum", allowedValues: [ "available", "leased", "expired", "breaking", "broken", ], }, }, leaseDuration: { serializedName: "LeaseDuration", xmlName: "LeaseDuration", type: { name: "Enum", allowedValues: ["infinite", "fixed"], }, }, publicAccess: { serializedName: "PublicAccess", xmlName: "PublicAccess", type: { name: "Enum", allowedValues: ["container", "blob"], }, }, hasImmutabilityPolicy: { serializedName: "HasImmutabilityPolicy", xmlName: "HasImmutabilityPolicy", type: { name: "Boolean", }, }, hasLegalHold: { serializedName: "HasLegalHold", xmlName: "HasLegalHold", type: { name: "Boolean", }, }, defaultEncryptionScope: { serializedName: "DefaultEncryptionScope", xmlName: "DefaultEncryptionScope", type: { name: "String", }, }, preventEncryptionScopeOverride: { serializedName: "DenyEncryptionScopeOverride", xmlName: "DenyEncryptionScopeOverride", type: { name: "Boolean", }, }, deletedOn: { serializedName: "DeletedTime", xmlName: "DeletedTime", type: { name: "DateTimeRfc1123", }, }, remainingRetentionDays: { serializedName: "RemainingRetentionDays", xmlName: "RemainingRetentionDays", type: { name: "Number", }, }, isImmutableStorageWithVersioningEnabled: { serializedName: "ImmutableStorageWithVersioningEnabled", xmlName: "ImmutableStorageWithVersioningEnabled", type: { name: "Boolean", }, }, }, }, }; const KeyInfo = { serializedName: "KeyInfo", type: { name: "Composite", className: "KeyInfo", modelProperties: { startsOn: { serializedName: "Start", required: true, xmlName: "Start", type: { name: "String", }, }, expiresOn: { serializedName: "Expiry", required: true, xmlName: "Expiry", type: { name: "String", }, }, }, }, }; const UserDelegationKey = { serializedName: "UserDelegationKey", type: { name: "Composite", className: "UserDelegationKey", modelProperties: { signedObjectId: { serializedName: "SignedOid", required: true, xmlName: "SignedOid", type: { name: "String", }, }, signedTenantId: { serializedName: "SignedTid", required: true, xmlName: "SignedTid", type: { name: "String", }, }, signedStartsOn: { serializedName: "SignedStart", required: true, xmlName: "SignedStart", type: { name: "String", }, }, signedExpiresOn: { serializedName: "SignedExpiry", required: true, xmlName: "SignedExpiry", type: { name: "String", }, }, signedService: { serializedName: "SignedService", required: true, xmlName: "SignedService", type: { name: "String", }, }, signedVersion: { serializedName: "SignedVersion", required: true, xmlName: "SignedVersion", type: { name: "String", }, }, value: { serializedName: "Value", required: true, xmlName: "Value", type: { name: "String", }, }, }, }, }; const FilterBlobSegment = { serializedName: "FilterBlobSegment", xmlName: "EnumerationResults", type: { name: "Composite", className: "FilterBlobSegment", modelProperties: { serviceEndpoint: { serializedName: "ServiceEndpoint", required: true, xmlName: "ServiceEndpoint", xmlIsAttribute: true, type: { name: "String", }, }, where: { serializedName: "Where", required: true, xmlName: "Where", type: { name: "String", }, }, blobs: { serializedName: "Blobs", required: true, xmlName: "Blobs", xmlIsWrapped: true, xmlElementName: "Blob", type: { name: "Sequence", element: { type: { name: "Composite", className: "FilterBlobItem", }, }, }, }, continuationToken: { serializedName: "NextMarker", xmlName: "NextMarker", type: { name: "String", }, }, }, }, }; const FilterBlobItem = { serializedName: "FilterBlobItem", xmlName: "Blob", type: { name: "Composite", className: "FilterBlobItem", modelProperties: { name: { serializedName: "Name", required: true, xmlName: "Name", type: { name: "String", }, }, containerName: { serializedName: "ContainerName", required: true, xmlName: "ContainerName", type: { name: "String", }, }, tags: { serializedName: "Tags", xmlName: "Tags", type: { name: "Composite", className: "BlobTags", }, }, }, }, }; const BlobTags = { serializedName: "BlobTags", xmlName: "Tags", type: { name: "Composite", className: "BlobTags", modelProperties: { blobTagSet: { serializedName: "BlobTagSet", required: true, xmlName: "TagSet", xmlIsWrapped: true, xmlElementName: "Tag", type: { name: "Sequence", element: { type: { name: "Composite", className: "BlobTag", }, }, }, }, }, }, }; const BlobTag = { serializedName: "BlobTag", xmlName: "Tag", type: { name: "Composite", className: "BlobTag", modelProperties: { key: { serializedName: "Key", required: true, xmlName: "Key", type: { name: "String", }, }, value: { serializedName: "Value", required: true, xmlName: "Value", type: { name: "String", }, }, }, }, }; const SignedIdentifier = { serializedName: "SignedIdentifier", xmlName: "SignedIdentifier", type: { name: "Composite", className: "SignedIdentifier", modelProperties: { id: { serializedName: "Id", required: true, xmlName: "Id", type: { name: "String", }, }, accessPolicy: { serializedName: "AccessPolicy", xmlName: "AccessPolicy", type: { name: "Composite", className: "AccessPolicy", }, }, }, }, }; const AccessPolicy = { serializedName: "AccessPolicy", type: { name: "Composite", className: "AccessPolicy", modelProperties: { startsOn: { serializedName: "Start", xmlName: "Start", type: { name: "String", }, }, expiresOn: { serializedName: "Expiry", xmlName: "Expiry", type: { name: "String", }, }, permissions: { serializedName: "Permission", xmlName: "Permission", type: { name: "String", }, }, }, }, }; const ListBlobsFlatSegmentResponse = { serializedName: "ListBlobsFlatSegmentResponse", xmlName: "EnumerationResults", type: { name: "Composite", className: "ListBlobsFlatSegmentResponse", modelProperties: { serviceEndpoint: { serializedName: "ServiceEndpoint", required: true, xmlName: "ServiceEndpoint", xmlIsAttribute: true, type: { name: "String", }, }, containerName: { serializedName: "ContainerName", required: true, xmlName: "ContainerName", xmlIsAttribute: true, type: { name: "String", }, }, prefix: { serializedName: "Prefix", xmlName: "Prefix", type: { name: "String", }, }, marker: { serializedName: "Marker", xmlName: "Marker", type: { name: "String", }, }, maxPageSize: { serializedName: "MaxResults", xmlName: "MaxResults", type: { name: "Number", }, }, segment: { serializedName: "Segment", xmlName: "Blobs", type: { name: "Composite", className: "BlobFlatListSegment", }, }, continuationToken: { serializedName: "NextMarker", xmlName: "NextMarker", type: { name: "String", }, }, }, }, }; const BlobFlatListSegment = { serializedName: "BlobFlatListSegment", xmlName: "Blobs", type: { name: "Composite", className: "BlobFlatListSegment", modelProperties: { blobItems: { serializedName: "BlobItems", required: true, xmlName: "BlobItems", xmlElementName: "Blob", type: { name: "Sequence", element: { type: { name: "Composite", className: "BlobItemInternal", }, }, }, }, }, }, }; const BlobItemInternal = { serializedName: "BlobItemInternal", xmlName: "Blob", type: { name: "Composite", className: "BlobItemInternal", modelProperties: { name: { serializedName: "Name", xmlName: "Name", type: { name: "Composite", className: "BlobName", }, }, deleted: { serializedName: "Deleted", required: true, xmlName: "Deleted", type: { name: "Boolean", }, }, snapshot: { serializedName: "Snapshot", required: true, xmlName: "Snapshot", type: { name: "String", }, }, versionId: { serializedName: "VersionId", xmlName: "VersionId", type: { name: "String", }, }, isCurrentVersion: { serializedName: "IsCurrentVersion", xmlName: "IsCurrentVersion", type: { name: "Boolean", }, }, properties: { serializedName: "Properties", xmlName: "Properties", type: { name: "Composite", className: "BlobPropertiesInternal", }, }, metadata: { serializedName: "Metadata", xmlName: "Metadata", type: { name: "Dictionary", value: { type: { name: "String" } }, }, }, blobTags: { serializedName: "BlobTags", xmlName: "Tags", type: { name: "Composite", className: "BlobTags", }, }, objectReplicationMetadata: { serializedName: "ObjectReplicationMetadata", xmlName: "OrMetadata", type: { name: "Dictionary", value: { type: { name: "String" } }, }, }, hasVersionsOnly: { serializedName: "HasVersionsOnly", xmlName: "HasVersionsOnly", type: { name: "Boolean", }, }, }, }, }; const BlobName = { serializedName: "BlobName", type: { name: "Composite", className: "BlobName", modelProperties: { encoded: { serializedName: "Encoded", xmlName: "Encoded", xmlIsAttribute: true, type: { name: "Boolean", }, }, content: { serializedName: "content", xmlName: "content", xmlIsMsText: true, type: { name: "String", }, }, }, }, }; const BlobPropertiesInternal = { serializedName: "BlobPropertiesInternal", xmlName: "Properties", type: { name: "Composite", className: "BlobPropertiesInternal", modelProperties: { createdOn: { serializedName: "Creation-Time", xmlName: "Creation-Time", type: { name: "DateTimeRfc1123", }, }, lastModified: { serializedName: "Last-Modified", required: true, xmlName: "Last-Modified", type: { name: "DateTimeRfc1123", }, }, etag: { serializedName: "Etag", required: true, xmlName: "Etag", type: { name: "String", }, }, contentLength: { serializedName: "Content-Length", xmlName: "Content-Length", type: { name: "Number", }, }, contentType: { serializedName: "Content-Type", xmlName: "Content-Type", type: { name: "String", }, }, contentEncoding: { serializedName: "Content-Encoding", xmlName: "Content-Encoding", type: { name: "String", }, }, contentLanguage: { serializedName: "Content-Language", xmlName: "Content-Language", type: { name: "String", }, }, contentMD5: { serializedName: "Content-MD5", xmlName: "Content-MD5", type: { name: "ByteArray", }, }, contentDisposition: { serializedName: "Content-Disposition", xmlName: "Content-Disposition", type: { name: "String", }, }, cacheControl: { serializedName: "Cache-Control", xmlName: "Cache-Control", type: { name: "String", }, }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number", }, }, blobType: { serializedName: "BlobType", xmlName: "BlobType", type: { name: "Enum", allowedValues: ["BlockBlob", "PageBlob", "AppendBlob"], }, }, leaseStatus: { serializedName: "LeaseStatus", xmlName: "LeaseStatus", type: { name: "Enum", allowedValues: ["locked", "unlocked"], }, }, leaseState: { serializedName: "LeaseState", xmlName: "LeaseState", type: { name: "Enum", allowedValues: [ "available", "leased", "expired", "breaking", "broken", ], }, }, leaseDuration: { serializedName: "LeaseDuration", xmlName: "LeaseDuration", type: { name: "Enum", allowedValues: ["infinite", "fixed"], }, }, copyId: { serializedName: "CopyId", xmlName: "CopyId", type: { name: "String", }, }, copyStatus: { serializedName: "CopyStatus", xmlName: "CopyStatus", type: { name: "Enum", allowedValues: ["pending", "success", "aborted", "failed"], }, }, copySource: { serializedName: "CopySource", xmlName: "CopySource", type: { name: "String", }, }, copyProgress: { serializedName: "CopyProgress", xmlName: "CopyProgress", type: { name: "String", }, }, copyCompletedOn: { serializedName: "CopyCompletionTime", xmlName: "CopyCompletionTime", type: { name: "DateTimeRfc1123", }, }, copyStatusDescription: { serializedName: "CopyStatusDescription", xmlName: "CopyStatusDescription", type: { name: "String", }, }, serverEncrypted: { serializedName: "ServerEncrypted", xmlName: "ServerEncrypted", type: { name: "Boolean", }, }, incrementalCopy: { serializedName: "IncrementalCopy", xmlName: "IncrementalCopy", type: { name: "Boolean", }, }, destinationSnapshot: { serializedName: "DestinationSnapshot", xmlName: "DestinationSnapshot", type: { name: "String", }, }, deletedOn: { serializedName: "DeletedTime", xmlName: "DeletedTime", type: { name: "DateTimeRfc1123", }, }, remainingRetentionDays: { serializedName: "RemainingRetentionDays", xmlName: "RemainingRetentionDays", type: { name: "Number", }, }, accessTier: { serializedName: "AccessTier", xmlName: "AccessTier", type: { name: "Enum", allowedValues: [ "P4", "P6", "P10", "P15", "P20", "P30", "P40", "P50", "P60", "P70", "P80", "Hot", "Cool", "Archive", "Cold", ], }, }, accessTierInferred: { serializedName: "AccessTierInferred", xmlName: "AccessTierInferred", type: { name: "Boolean", }, }, archiveStatus: { serializedName: "ArchiveStatus", xmlName: "ArchiveStatus", type: { name: "Enum", allowedValues: [ "rehydrate-pending-to-hot", "rehydrate-pending-to-cool", "rehydrate-pending-to-cold", ], }, }, customerProvidedKeySha256: { serializedName: "CustomerProvidedKeySha256", xmlName: "CustomerProvidedKeySha256", type: { name: "String", }, }, encryptionScope: { serializedName: "EncryptionScope", xmlName: "EncryptionScope", type: { name: "String", }, }, accessTierChangedOn: { serializedName: "AccessTierChangeTime", xmlName: "AccessTierChangeTime", type: { name: "DateTimeRfc1123", }, }, tagCount: { serializedName: "TagCount", xmlName: "TagCount", type: { name: "Number", }, }, expiresOn: { serializedName: "Expiry-Time", xmlName: "Expiry-Time", type: { name: "DateTimeRfc1123", }, }, isSealed: { serializedName: "Sealed", xmlName: "Sealed", type: { name: "Boolean", }, }, rehydratePriority: { serializedName: "RehydratePriority", xmlName: "RehydratePriority", type: { name: "Enum", allowedValues: ["High", "Standard"], }, }, lastAccessedOn: { serializedName: "LastAccessTime", xmlName: "LastAccessTime", type: { name: "DateTimeRfc1123", }, }, immutabilityPolicyExpiresOn: { serializedName: "ImmutabilityPolicyUntilDate", xmlName: "ImmutabilityPolicyUntilDate", type: { name: "DateTimeRfc1123", }, }, immutabilityPolicyMode: { serializedName: "ImmutabilityPolicyMode", xmlName: "ImmutabilityPolicyMode", type: { name: "Enum", allowedValues: ["Mutable", "Unlocked", "Locked"], }, }, legalHold: { serializedName: "LegalHold", xmlName: "LegalHold", type: { name: "Boolean", }, }, }, }, }; const ListBlobsHierarchySegmentResponse = { serializedName: "ListBlobsHierarchySegmentResponse", xmlName: "EnumerationResults", type: { name: "Composite", className: "ListBlobsHierarchySegmentResponse", modelProperties: { serviceEndpoint: { serializedName: "ServiceEndpoint", required: true, xmlName: "ServiceEndpoint", xmlIsAttribute: true, type: { name: "String", }, }, containerName: { serializedName: "ContainerName", required: true, xmlName: "ContainerName", xmlIsAttribute: true, type: { name: "String", }, }, prefix: { serializedName: "Prefix", xmlName: "Prefix", type: { name: "String", }, }, marker: { serializedName: "Marker", xmlName: "Marker", type: { name: "String", }, }, maxPageSize: { serializedName: "MaxResults", xmlName: "MaxResults", type: { name: "Number", }, }, delimiter: { serializedName: "Delimiter", xmlName: "Delimiter", type: { name: "String", }, }, segment: { serializedName: "Segment", xmlName: "Blobs", type: { name: "Composite", className: "BlobHierarchyListSegment", }, }, continuationToken: { serializedName: "NextMarker", xmlName: "NextMarker", type: { name: "String", }, }, }, }, }; const BlobHierarchyListSegment = { serializedName: "BlobHierarchyListSegment", xmlName: "Blobs", type: { name: "Composite", className: "BlobHierarchyListSegment", modelProperties: { blobPrefixes: { serializedName: "BlobPrefixes", xmlName: "BlobPrefixes", xmlElementName: "BlobPrefix", type: { name: "Sequence", element: { type: { name: "Composite", className: "BlobPrefix", }, }, }, }, blobItems: { serializedName: "BlobItems", required: true, xmlName: "BlobItems", xmlElementName: "Blob", type: { name: "Sequence", element: { type: { name: "Composite", className: "BlobItemInternal", }, }, }, }, }, }, }; const BlobPrefix = { serializedName: "BlobPrefix", type: { name: "Composite", className: "BlobPrefix", modelProperties: { name: { serializedName: "Name", xmlName: "Name", type: { name: "Composite", className: "BlobName", }, }, }, }, }; const BlockLookupList = { serializedName: "BlockLookupList", xmlName: "BlockList", type: { name: "Composite", className: "BlockLookupList", modelProperties: { committed: { serializedName: "Committed", xmlName: "Committed", xmlElementName: "Committed", type: { name: "Sequence", element: { type: { name: "String", }, }, }, }, uncommitted: { serializedName: "Uncommitted", xmlName: "Uncommitted", xmlElementName: "Uncommitted", type: { name: "Sequence", element: { type: { name: "String", }, }, }, }, latest: { serializedName: "Latest", xmlName: "Latest", xmlElementName: "Latest", type: { name: "Sequence", element: { type: { name: "String", }, }, }, }, }, }, }; const BlockList = { serializedName: "BlockList", type: { name: "Composite", className: "BlockList", modelProperties: { committedBlocks: { serializedName: "CommittedBlocks", xmlName: "CommittedBlocks", xmlIsWrapped: true, xmlElementName: "Block", type: { name: "Sequence", element: { type: { name: "Composite", className: "Block", }, }, }, }, uncommittedBlocks: { serializedName: "UncommittedBlocks", xmlName: "UncommittedBlocks", xmlIsWrapped: true, xmlElementName: "Block", type: { name: "Sequence", element: { type: { name: "Composite", className: "Block", }, }, }, }, }, }, }; const Block = { serializedName: "Block", type: { name: "Composite", className: "Block", modelProperties: { name: { serializedName: "Name", required: true, xmlName: "Name", type: { name: "String", }, }, size: { serializedName: "Size", required: true, xmlName: "Size", type: { name: "Number", }, }, }, }, }; const PageList = { serializedName: "PageList", type: { name: "Composite", className: "PageList", modelProperties: { pageRange: { serializedName: "PageRange", xmlName: "PageRange", xmlElementName: "PageRange", type: { name: "Sequence", element: { type: { name: "Composite", className: "PageRange", }, }, }, }, clearRange: { serializedName: "ClearRange", xmlName: "ClearRange", xmlElementName: "ClearRange", type: { name: "Sequence", element: { type: { name: "Composite", className: "ClearRange", }, }, }, }, continuationToken: { serializedName: "NextMarker", xmlName: "NextMarker", type: { name: "String", }, }, }, }, }; const PageRange = { serializedName: "PageRange", xmlName: "PageRange", type: { name: "Composite", className: "PageRange", modelProperties: { start: { serializedName: "Start", required: true, xmlName: "Start", type: { name: "Number", }, }, end: { serializedName: "End", required: true, xmlName: "End", type: { name: "Number", }, }, }, }, }; const ClearRange = { serializedName: "ClearRange", xmlName: "ClearRange", type: { name: "Composite", className: "ClearRange", modelProperties: { start: { serializedName: "Start", required: true, xmlName: "Start", type: { name: "Number", }, }, end: { serializedName: "End", required: true, xmlName: "End", type: { name: "Number", }, }, }, }, }; const QueryRequest = { serializedName: "QueryRequest", xmlName: "QueryRequest", type: { name: "Composite", className: "QueryRequest", modelProperties: { queryType: { serializedName: "QueryType", required: true, xmlName: "QueryType", type: { name: "String", }, }, expression: { serializedName: "Expression", required: true, xmlName: "Expression", type: { name: "String", }, }, inputSerialization: { serializedName: "InputSerialization", xmlName: "InputSerialization", type: { name: "Composite", className: "QuerySerialization", }, }, outputSerialization: { serializedName: "OutputSerialization", xmlName: "OutputSerialization", type: { name: "Composite", className: "QuerySerialization", }, }, }, }, }; const QuerySerialization = { serializedName: "QuerySerialization", type: { name: "Composite", className: "QuerySerialization", modelProperties: { format: { serializedName: "Format", xmlName: "Format", type: { name: "Composite", className: "QueryFormat", }, }, }, }, }; const QueryFormat = { serializedName: "QueryFormat", type: { name: "Composite", className: "QueryFormat", modelProperties: { type: { serializedName: "Type", required: true, xmlName: "Type", type: { name: "Enum", allowedValues: ["delimited", "json", "arrow", "parquet"], }, }, delimitedTextConfiguration: { serializedName: "DelimitedTextConfiguration", xmlName: "DelimitedTextConfiguration", type: { name: "Composite", className: "DelimitedTextConfiguration", }, }, jsonTextConfiguration: { serializedName: "JsonTextConfiguration", xmlName: "JsonTextConfiguration", type: { name: "Composite", className: "JsonTextConfiguration", }, }, arrowConfiguration: { serializedName: "ArrowConfiguration", xmlName: "ArrowConfiguration", type: { name: "Composite", className: "ArrowConfiguration", }, }, parquetTextConfiguration: { serializedName: "ParquetTextConfiguration", xmlName: "ParquetTextConfiguration", type: { name: "Dictionary", value: { type: { name: "any" } }, }, }, }, }, }; const DelimitedTextConfiguration = { serializedName: "DelimitedTextConfiguration", xmlName: "DelimitedTextConfiguration", type: { name: "Composite", className: "DelimitedTextConfiguration", modelProperties: { columnSeparator: { serializedName: "ColumnSeparator", xmlName: "ColumnSeparator", type: { name: "String", }, }, fieldQuote: { serializedName: "FieldQuote", xmlName: "FieldQuote", type: { name: "String", }, }, recordSeparator: { serializedName: "RecordSeparator", xmlName: "RecordSeparator", type: { name: "String", }, }, escapeChar: { serializedName: "EscapeChar", xmlName: "EscapeChar", type: { name: "String", }, }, headersPresent: { serializedName: "HeadersPresent", xmlName: "HasHeaders", type: { name: "Boolean", }, }, }, }, }; const JsonTextConfiguration = { serializedName: "JsonTextConfiguration", xmlName: "JsonTextConfiguration", type: { name: "Composite", className: "JsonTextConfiguration", modelProperties: { recordSeparator: { serializedName: "RecordSeparator", xmlName: "RecordSeparator", type: { name: "String", }, }, }, }, }; const ArrowConfiguration = { serializedName: "ArrowConfiguration", xmlName: "ArrowConfiguration", type: { name: "Composite", className: "ArrowConfiguration", modelProperties: { schema: { serializedName: "Schema", required: true, xmlName: "Schema", xmlIsWrapped: true, xmlElementName: "Field", type: { name: "Sequence", element: { type: { name: "Composite", className: "ArrowField", }, }, }, }, }, }, }; const ArrowField = { serializedName: "ArrowField", xmlName: "Field", type: { name: "Composite", className: "ArrowField", modelProperties: { type: { serializedName: "Type", required: true, xmlName: "Type", type: { name: "String", }, }, name: { serializedName: "Name", xmlName: "Name", type: { name: "String", }, }, precision: { serializedName: "Precision", xmlName: "Precision", type: { name: "Number", }, }, scale: { serializedName: "Scale", xmlName: "Scale", type: { name: "Number", }, }, }, }, }; const ServiceSetPropertiesHeaders = { serializedName: "Service_setPropertiesHeaders", type: { name: "Composite", className: "ServiceSetPropertiesHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ServiceSetPropertiesExceptionHeaders = { serializedName: "Service_setPropertiesExceptionHeaders", type: { name: "Composite", className: "ServiceSetPropertiesExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ServiceGetPropertiesHeaders = { serializedName: "Service_getPropertiesHeaders", type: { name: "Composite", className: "ServiceGetPropertiesHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ServiceGetPropertiesExceptionHeaders = { serializedName: "Service_getPropertiesExceptionHeaders", type: { name: "Composite", className: "ServiceGetPropertiesExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ServiceGetStatisticsHeaders = { serializedName: "Service_getStatisticsHeaders", type: { name: "Composite", className: "ServiceGetStatisticsHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ServiceGetStatisticsExceptionHeaders = { serializedName: "Service_getStatisticsExceptionHeaders", type: { name: "Composite", className: "ServiceGetStatisticsExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ServiceListContainersSegmentHeaders = { serializedName: "Service_listContainersSegmentHeaders", type: { name: "Composite", className: "ServiceListContainersSegmentHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ServiceListContainersSegmentExceptionHeaders = { serializedName: "Service_listContainersSegmentExceptionHeaders", type: { name: "Composite", className: "ServiceListContainersSegmentExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ServiceGetUserDelegationKeyHeaders = { serializedName: "Service_getUserDelegationKeyHeaders", type: { name: "Composite", className: "ServiceGetUserDelegationKeyHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ServiceGetUserDelegationKeyExceptionHeaders = { serializedName: "Service_getUserDelegationKeyExceptionHeaders", type: { name: "Composite", className: "ServiceGetUserDelegationKeyExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ServiceGetAccountInfoHeaders = { serializedName: "Service_getAccountInfoHeaders", type: { name: "Composite", className: "ServiceGetAccountInfoHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, skuName: { serializedName: "x-ms-sku-name", xmlName: "x-ms-sku-name", type: { name: "Enum", allowedValues: [ "Standard_LRS", "Standard_GRS", "Standard_RAGRS", "Standard_ZRS", "Premium_LRS", ], }, }, accountKind: { serializedName: "x-ms-account-kind", xmlName: "x-ms-account-kind", type: { name: "Enum", allowedValues: [ "Storage", "BlobStorage", "StorageV2", "FileStorage", "BlockBlobStorage", ], }, }, isHierarchicalNamespaceEnabled: { serializedName: "x-ms-is-hns-enabled", xmlName: "x-ms-is-hns-enabled", type: { name: "Boolean", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ServiceGetAccountInfoExceptionHeaders = { serializedName: "Service_getAccountInfoExceptionHeaders", type: { name: "Composite", className: "ServiceGetAccountInfoExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ServiceSubmitBatchHeaders = { serializedName: "Service_submitBatchHeaders", type: { name: "Composite", className: "ServiceSubmitBatchHeaders", modelProperties: { contentType: { serializedName: "content-type", xmlName: "content-type", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ServiceSubmitBatchExceptionHeaders = { serializedName: "Service_submitBatchExceptionHeaders", type: { name: "Composite", className: "ServiceSubmitBatchExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ServiceFilterBlobsHeaders = { serializedName: "Service_filterBlobsHeaders", type: { name: "Composite", className: "ServiceFilterBlobsHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ServiceFilterBlobsExceptionHeaders = { serializedName: "Service_filterBlobsExceptionHeaders", type: { name: "Composite", className: "ServiceFilterBlobsExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerCreateHeaders = { serializedName: "Container_createHeaders", type: { name: "Composite", className: "ContainerCreateHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerCreateExceptionHeaders = { serializedName: "Container_createExceptionHeaders", type: { name: "Composite", className: "ContainerCreateExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerGetPropertiesHeaders = { serializedName: "Container_getPropertiesHeaders", type: { name: "Composite", className: "ContainerGetPropertiesHeaders", modelProperties: { metadata: { serializedName: "x-ms-meta", headerCollectionPrefix: "x-ms-meta-", xmlName: "x-ms-meta", type: { name: "Dictionary", value: { type: { name: "String" } }, }, }, etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, leaseDuration: { serializedName: "x-ms-lease-duration", xmlName: "x-ms-lease-duration", type: { name: "Enum", allowedValues: ["infinite", "fixed"], }, }, leaseState: { serializedName: "x-ms-lease-state", xmlName: "x-ms-lease-state", type: { name: "Enum", allowedValues: [ "available", "leased", "expired", "breaking", "broken", ], }, }, leaseStatus: { serializedName: "x-ms-lease-status", xmlName: "x-ms-lease-status", type: { name: "Enum", allowedValues: ["locked", "unlocked"], }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, blobPublicAccess: { serializedName: "x-ms-blob-public-access", xmlName: "x-ms-blob-public-access", type: { name: "Enum", allowedValues: ["container", "blob"], }, }, hasImmutabilityPolicy: { serializedName: "x-ms-has-immutability-policy", xmlName: "x-ms-has-immutability-policy", type: { name: "Boolean", }, }, hasLegalHold: { serializedName: "x-ms-has-legal-hold", xmlName: "x-ms-has-legal-hold", type: { name: "Boolean", }, }, defaultEncryptionScope: { serializedName: "x-ms-default-encryption-scope", xmlName: "x-ms-default-encryption-scope", type: { name: "String", }, }, denyEncryptionScopeOverride: { serializedName: "x-ms-deny-encryption-scope-override", xmlName: "x-ms-deny-encryption-scope-override", type: { name: "Boolean", }, }, isImmutableStorageWithVersioningEnabled: { serializedName: "x-ms-immutable-storage-with-versioning-enabled", xmlName: "x-ms-immutable-storage-with-versioning-enabled", type: { name: "Boolean", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerGetPropertiesExceptionHeaders = { serializedName: "Container_getPropertiesExceptionHeaders", type: { name: "Composite", className: "ContainerGetPropertiesExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerDeleteHeaders = { serializedName: "Container_deleteHeaders", type: { name: "Composite", className: "ContainerDeleteHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerDeleteExceptionHeaders = { serializedName: "Container_deleteExceptionHeaders", type: { name: "Composite", className: "ContainerDeleteExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerSetMetadataHeaders = { serializedName: "Container_setMetadataHeaders", type: { name: "Composite", className: "ContainerSetMetadataHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerSetMetadataExceptionHeaders = { serializedName: "Container_setMetadataExceptionHeaders", type: { name: "Composite", className: "ContainerSetMetadataExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerGetAccessPolicyHeaders = { serializedName: "Container_getAccessPolicyHeaders", type: { name: "Composite", className: "ContainerGetAccessPolicyHeaders", modelProperties: { blobPublicAccess: { serializedName: "x-ms-blob-public-access", xmlName: "x-ms-blob-public-access", type: { name: "Enum", allowedValues: ["container", "blob"], }, }, etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerGetAccessPolicyExceptionHeaders = { serializedName: "Container_getAccessPolicyExceptionHeaders", type: { name: "Composite", className: "ContainerGetAccessPolicyExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerSetAccessPolicyHeaders = { serializedName: "Container_setAccessPolicyHeaders", type: { name: "Composite", className: "ContainerSetAccessPolicyHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerSetAccessPolicyExceptionHeaders = { serializedName: "Container_setAccessPolicyExceptionHeaders", type: { name: "Composite", className: "ContainerSetAccessPolicyExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerRestoreHeaders = { serializedName: "Container_restoreHeaders", type: { name: "Composite", className: "ContainerRestoreHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerRestoreExceptionHeaders = { serializedName: "Container_restoreExceptionHeaders", type: { name: "Composite", className: "ContainerRestoreExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerRenameHeaders = { serializedName: "Container_renameHeaders", type: { name: "Composite", className: "ContainerRenameHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerRenameExceptionHeaders = { serializedName: "Container_renameExceptionHeaders", type: { name: "Composite", className: "ContainerRenameExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerSubmitBatchHeaders = { serializedName: "Container_submitBatchHeaders", type: { name: "Composite", className: "ContainerSubmitBatchHeaders", modelProperties: { contentType: { serializedName: "content-type", xmlName: "content-type", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, }, }, }; const ContainerSubmitBatchExceptionHeaders = { serializedName: "Container_submitBatchExceptionHeaders", type: { name: "Composite", className: "ContainerSubmitBatchExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerFilterBlobsHeaders = { serializedName: "Container_filterBlobsHeaders", type: { name: "Composite", className: "ContainerFilterBlobsHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, }, }, }; const ContainerFilterBlobsExceptionHeaders = { serializedName: "Container_filterBlobsExceptionHeaders", type: { name: "Composite", className: "ContainerFilterBlobsExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerAcquireLeaseHeaders = { serializedName: "Container_acquireLeaseHeaders", type: { name: "Composite", className: "ContainerAcquireLeaseHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, leaseId: { serializedName: "x-ms-lease-id", xmlName: "x-ms-lease-id", type: { name: "String", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, }, }, }; const ContainerAcquireLeaseExceptionHeaders = { serializedName: "Container_acquireLeaseExceptionHeaders", type: { name: "Composite", className: "ContainerAcquireLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerReleaseLeaseHeaders = { serializedName: "Container_releaseLeaseHeaders", type: { name: "Composite", className: "ContainerReleaseLeaseHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, }, }, }; const ContainerReleaseLeaseExceptionHeaders = { serializedName: "Container_releaseLeaseExceptionHeaders", type: { name: "Composite", className: "ContainerReleaseLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerRenewLeaseHeaders = { serializedName: "Container_renewLeaseHeaders", type: { name: "Composite", className: "ContainerRenewLeaseHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, leaseId: { serializedName: "x-ms-lease-id", xmlName: "x-ms-lease-id", type: { name: "String", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, }, }, }; const ContainerRenewLeaseExceptionHeaders = { serializedName: "Container_renewLeaseExceptionHeaders", type: { name: "Composite", className: "ContainerRenewLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerBreakLeaseHeaders = { serializedName: "Container_breakLeaseHeaders", type: { name: "Composite", className: "ContainerBreakLeaseHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, leaseTime: { serializedName: "x-ms-lease-time", xmlName: "x-ms-lease-time", type: { name: "Number", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, }, }, }; const ContainerBreakLeaseExceptionHeaders = { serializedName: "Container_breakLeaseExceptionHeaders", type: { name: "Composite", className: "ContainerBreakLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerChangeLeaseHeaders = { serializedName: "Container_changeLeaseHeaders", type: { name: "Composite", className: "ContainerChangeLeaseHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, leaseId: { serializedName: "x-ms-lease-id", xmlName: "x-ms-lease-id", type: { name: "String", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, }, }, }; const ContainerChangeLeaseExceptionHeaders = { serializedName: "Container_changeLeaseExceptionHeaders", type: { name: "Composite", className: "ContainerChangeLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerListBlobFlatSegmentHeaders = { serializedName: "Container_listBlobFlatSegmentHeaders", type: { name: "Composite", className: "ContainerListBlobFlatSegmentHeaders", modelProperties: { contentType: { serializedName: "content-type", xmlName: "content-type", type: { name: "String", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerListBlobFlatSegmentExceptionHeaders = { serializedName: "Container_listBlobFlatSegmentExceptionHeaders", type: { name: "Composite", className: "ContainerListBlobFlatSegmentExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerListBlobHierarchySegmentHeaders = { serializedName: "Container_listBlobHierarchySegmentHeaders", type: { name: "Composite", className: "ContainerListBlobHierarchySegmentHeaders", modelProperties: { contentType: { serializedName: "content-type", xmlName: "content-type", type: { name: "String", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerListBlobHierarchySegmentExceptionHeaders = { serializedName: "Container_listBlobHierarchySegmentExceptionHeaders", type: { name: "Composite", className: "ContainerListBlobHierarchySegmentExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const ContainerGetAccountInfoHeaders = { serializedName: "Container_getAccountInfoHeaders", type: { name: "Composite", className: "ContainerGetAccountInfoHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, skuName: { serializedName: "x-ms-sku-name", xmlName: "x-ms-sku-name", type: { name: "Enum", allowedValues: [ "Standard_LRS", "Standard_GRS", "Standard_RAGRS", "Standard_ZRS", "Premium_LRS", ], }, }, accountKind: { serializedName: "x-ms-account-kind", xmlName: "x-ms-account-kind", type: { name: "Enum", allowedValues: [ "Storage", "BlobStorage", "StorageV2", "FileStorage", "BlockBlobStorage", ], }, }, isHierarchicalNamespaceEnabled: { serializedName: "x-ms-is-hns-enabled", xmlName: "x-ms-is-hns-enabled", type: { name: "Boolean", }, }, }, }, }; const ContainerGetAccountInfoExceptionHeaders = { serializedName: "Container_getAccountInfoExceptionHeaders", type: { name: "Composite", className: "ContainerGetAccountInfoExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobDownloadHeaders = { serializedName: "Blob_downloadHeaders", type: { name: "Composite", className: "BlobDownloadHeaders", modelProperties: { lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, createdOn: { serializedName: "x-ms-creation-time", xmlName: "x-ms-creation-time", type: { name: "DateTimeRfc1123", }, }, metadata: { serializedName: "x-ms-meta", headerCollectionPrefix: "x-ms-meta-", xmlName: "x-ms-meta", type: { name: "Dictionary", value: { type: { name: "String" } }, }, }, objectReplicationPolicyId: { serializedName: "x-ms-or-policy-id", xmlName: "x-ms-or-policy-id", type: { name: "String", }, }, objectReplicationRules: { serializedName: "x-ms-or", headerCollectionPrefix: "x-ms-or-", xmlName: "x-ms-or", type: { name: "Dictionary", value: { type: { name: "String" } }, }, }, contentLength: { serializedName: "content-length", xmlName: "content-length", type: { name: "Number", }, }, contentType: { serializedName: "content-type", xmlName: "content-type", type: { name: "String", }, }, contentRange: { serializedName: "content-range", xmlName: "content-range", type: { name: "String", }, }, etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray", }, }, contentEncoding: { serializedName: "content-encoding", xmlName: "content-encoding", type: { name: "String", }, }, cacheControl: { serializedName: "cache-control", xmlName: "cache-control", type: { name: "String", }, }, contentDisposition: { serializedName: "content-disposition", xmlName: "content-disposition", type: { name: "String", }, }, contentLanguage: { serializedName: "content-language", xmlName: "content-language", type: { name: "String", }, }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number", }, }, blobType: { serializedName: "x-ms-blob-type", xmlName: "x-ms-blob-type", type: { name: "Enum", allowedValues: ["BlockBlob", "PageBlob", "AppendBlob"], }, }, copyCompletedOn: { serializedName: "x-ms-copy-completion-time", xmlName: "x-ms-copy-completion-time", type: { name: "DateTimeRfc1123", }, }, copyStatusDescription: { serializedName: "x-ms-copy-status-description", xmlName: "x-ms-copy-status-description", type: { name: "String", }, }, copyId: { serializedName: "x-ms-copy-id", xmlName: "x-ms-copy-id", type: { name: "String", }, }, copyProgress: { serializedName: "x-ms-copy-progress", xmlName: "x-ms-copy-progress", type: { name: "String", }, }, copySource: { serializedName: "x-ms-copy-source", xmlName: "x-ms-copy-source", type: { name: "String", }, }, copyStatus: { serializedName: "x-ms-copy-status", xmlName: "x-ms-copy-status", type: { name: "Enum", allowedValues: ["pending", "success", "aborted", "failed"], }, }, leaseDuration: { serializedName: "x-ms-lease-duration", xmlName: "x-ms-lease-duration", type: { name: "Enum", allowedValues: ["infinite", "fixed"], }, }, leaseState: { serializedName: "x-ms-lease-state", xmlName: "x-ms-lease-state", type: { name: "Enum", allowedValues: [ "available", "leased", "expired", "breaking", "broken", ], }, }, leaseStatus: { serializedName: "x-ms-lease-status", xmlName: "x-ms-lease-status", type: { name: "Enum", allowedValues: ["locked", "unlocked"], }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String", }, }, isCurrentVersion: { serializedName: "x-ms-is-current-version", xmlName: "x-ms-is-current-version", type: { name: "Boolean", }, }, acceptRanges: { serializedName: "accept-ranges", xmlName: "accept-ranges", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, blobCommittedBlockCount: { serializedName: "x-ms-blob-committed-block-count", xmlName: "x-ms-blob-committed-block-count", type: { name: "Number", }, }, isServerEncrypted: { serializedName: "x-ms-server-encrypted", xmlName: "x-ms-server-encrypted", type: { name: "Boolean", }, }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String", }, }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String", }, }, blobContentMD5: { serializedName: "x-ms-blob-content-md5", xmlName: "x-ms-blob-content-md5", type: { name: "ByteArray", }, }, tagCount: { serializedName: "x-ms-tag-count", xmlName: "x-ms-tag-count", type: { name: "Number", }, }, isSealed: { serializedName: "x-ms-blob-sealed", xmlName: "x-ms-blob-sealed", type: { name: "Boolean", }, }, lastAccessed: { serializedName: "x-ms-last-access-time", xmlName: "x-ms-last-access-time", type: { name: "DateTimeRfc1123", }, }, immutabilityPolicyExpiresOn: { serializedName: "x-ms-immutability-policy-until-date", xmlName: "x-ms-immutability-policy-until-date", type: { name: "DateTimeRfc1123", }, }, immutabilityPolicyMode: { serializedName: "x-ms-immutability-policy-mode", xmlName: "x-ms-immutability-policy-mode", type: { name: "Enum", allowedValues: ["Mutable", "Unlocked", "Locked"], }, }, legalHold: { serializedName: "x-ms-legal-hold", xmlName: "x-ms-legal-hold", type: { name: "Boolean", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, contentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray", }, }, }, }, }; const BlobDownloadExceptionHeaders = { serializedName: "Blob_downloadExceptionHeaders", type: { name: "Composite", className: "BlobDownloadExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobGetPropertiesHeaders = { serializedName: "Blob_getPropertiesHeaders", type: { name: "Composite", className: "BlobGetPropertiesHeaders", modelProperties: { lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, createdOn: { serializedName: "x-ms-creation-time", xmlName: "x-ms-creation-time", type: { name: "DateTimeRfc1123", }, }, metadata: { serializedName: "x-ms-meta", headerCollectionPrefix: "x-ms-meta-", xmlName: "x-ms-meta", type: { name: "Dictionary", value: { type: { name: "String" } }, }, }, objectReplicationPolicyId: { serializedName: "x-ms-or-policy-id", xmlName: "x-ms-or-policy-id", type: { name: "String", }, }, objectReplicationRules: { serializedName: "x-ms-or", headerCollectionPrefix: "x-ms-or-", xmlName: "x-ms-or", type: { name: "Dictionary", value: { type: { name: "String" } }, }, }, blobType: { serializedName: "x-ms-blob-type", xmlName: "x-ms-blob-type", type: { name: "Enum", allowedValues: ["BlockBlob", "PageBlob", "AppendBlob"], }, }, copyCompletedOn: { serializedName: "x-ms-copy-completion-time", xmlName: "x-ms-copy-completion-time", type: { name: "DateTimeRfc1123", }, }, copyStatusDescription: { serializedName: "x-ms-copy-status-description", xmlName: "x-ms-copy-status-description", type: { name: "String", }, }, copyId: { serializedName: "x-ms-copy-id", xmlName: "x-ms-copy-id", type: { name: "String", }, }, copyProgress: { serializedName: "x-ms-copy-progress", xmlName: "x-ms-copy-progress", type: { name: "String", }, }, copySource: { serializedName: "x-ms-copy-source", xmlName: "x-ms-copy-source", type: { name: "String", }, }, copyStatus: { serializedName: "x-ms-copy-status", xmlName: "x-ms-copy-status", type: { name: "Enum", allowedValues: ["pending", "success", "aborted", "failed"], }, }, isIncrementalCopy: { serializedName: "x-ms-incremental-copy", xmlName: "x-ms-incremental-copy", type: { name: "Boolean", }, }, destinationSnapshot: { serializedName: "x-ms-copy-destination-snapshot", xmlName: "x-ms-copy-destination-snapshot", type: { name: "String", }, }, leaseDuration: { serializedName: "x-ms-lease-duration", xmlName: "x-ms-lease-duration", type: { name: "Enum", allowedValues: ["infinite", "fixed"], }, }, leaseState: { serializedName: "x-ms-lease-state", xmlName: "x-ms-lease-state", type: { name: "Enum", allowedValues: [ "available", "leased", "expired", "breaking", "broken", ], }, }, leaseStatus: { serializedName: "x-ms-lease-status", xmlName: "x-ms-lease-status", type: { name: "Enum", allowedValues: ["locked", "unlocked"], }, }, contentLength: { serializedName: "content-length", xmlName: "content-length", type: { name: "Number", }, }, contentType: { serializedName: "content-type", xmlName: "content-type", type: { name: "String", }, }, etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray", }, }, contentEncoding: { serializedName: "content-encoding", xmlName: "content-encoding", type: { name: "String", }, }, contentDisposition: { serializedName: "content-disposition", xmlName: "content-disposition", type: { name: "String", }, }, contentLanguage: { serializedName: "content-language", xmlName: "content-language", type: { name: "String", }, }, cacheControl: { serializedName: "cache-control", xmlName: "cache-control", type: { name: "String", }, }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, acceptRanges: { serializedName: "accept-ranges", xmlName: "accept-ranges", type: { name: "String", }, }, blobCommittedBlockCount: { serializedName: "x-ms-blob-committed-block-count", xmlName: "x-ms-blob-committed-block-count", type: { name: "Number", }, }, isServerEncrypted: { serializedName: "x-ms-server-encrypted", xmlName: "x-ms-server-encrypted", type: { name: "Boolean", }, }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String", }, }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String", }, }, accessTier: { serializedName: "x-ms-access-tier", xmlName: "x-ms-access-tier", type: { name: "String", }, }, accessTierInferred: { serializedName: "x-ms-access-tier-inferred", xmlName: "x-ms-access-tier-inferred", type: { name: "Boolean", }, }, archiveStatus: { serializedName: "x-ms-archive-status", xmlName: "x-ms-archive-status", type: { name: "String", }, }, accessTierChangedOn: { serializedName: "x-ms-access-tier-change-time", xmlName: "x-ms-access-tier-change-time", type: { name: "DateTimeRfc1123", }, }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String", }, }, isCurrentVersion: { serializedName: "x-ms-is-current-version", xmlName: "x-ms-is-current-version", type: { name: "Boolean", }, }, tagCount: { serializedName: "x-ms-tag-count", xmlName: "x-ms-tag-count", type: { name: "Number", }, }, expiresOn: { serializedName: "x-ms-expiry-time", xmlName: "x-ms-expiry-time", type: { name: "DateTimeRfc1123", }, }, isSealed: { serializedName: "x-ms-blob-sealed", xmlName: "x-ms-blob-sealed", type: { name: "Boolean", }, }, rehydratePriority: { serializedName: "x-ms-rehydrate-priority", xmlName: "x-ms-rehydrate-priority", type: { name: "Enum", allowedValues: ["High", "Standard"], }, }, lastAccessed: { serializedName: "x-ms-last-access-time", xmlName: "x-ms-last-access-time", type: { name: "DateTimeRfc1123", }, }, immutabilityPolicyExpiresOn: { serializedName: "x-ms-immutability-policy-until-date", xmlName: "x-ms-immutability-policy-until-date", type: { name: "DateTimeRfc1123", }, }, immutabilityPolicyMode: { serializedName: "x-ms-immutability-policy-mode", xmlName: "x-ms-immutability-policy-mode", type: { name: "Enum", allowedValues: ["Mutable", "Unlocked", "Locked"], }, }, legalHold: { serializedName: "x-ms-legal-hold", xmlName: "x-ms-legal-hold", type: { name: "Boolean", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobGetPropertiesExceptionHeaders = { serializedName: "Blob_getPropertiesExceptionHeaders", type: { name: "Composite", className: "BlobGetPropertiesExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobDeleteHeaders = { serializedName: "Blob_deleteHeaders", type: { name: "Composite", className: "BlobDeleteHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobDeleteExceptionHeaders = { serializedName: "Blob_deleteExceptionHeaders", type: { name: "Composite", className: "BlobDeleteExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobUndeleteHeaders = { serializedName: "Blob_undeleteHeaders", type: { name: "Composite", className: "BlobUndeleteHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobUndeleteExceptionHeaders = { serializedName: "Blob_undeleteExceptionHeaders", type: { name: "Composite", className: "BlobUndeleteExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobSetExpiryHeaders = { serializedName: "Blob_setExpiryHeaders", type: { name: "Composite", className: "BlobSetExpiryHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, }, }, }; const BlobSetExpiryExceptionHeaders = { serializedName: "Blob_setExpiryExceptionHeaders", type: { name: "Composite", className: "BlobSetExpiryExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobSetHttpHeadersHeaders = { serializedName: "Blob_setHttpHeadersHeaders", type: { name: "Composite", className: "BlobSetHttpHeadersHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobSetHttpHeadersExceptionHeaders = { serializedName: "Blob_setHttpHeadersExceptionHeaders", type: { name: "Composite", className: "BlobSetHttpHeadersExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobSetImmutabilityPolicyHeaders = { serializedName: "Blob_setImmutabilityPolicyHeaders", type: { name: "Composite", className: "BlobSetImmutabilityPolicyHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, immutabilityPolicyExpiry: { serializedName: "x-ms-immutability-policy-until-date", xmlName: "x-ms-immutability-policy-until-date", type: { name: "DateTimeRfc1123", }, }, immutabilityPolicyMode: { serializedName: "x-ms-immutability-policy-mode", xmlName: "x-ms-immutability-policy-mode", type: { name: "Enum", allowedValues: ["Mutable", "Unlocked", "Locked"], }, }, }, }, }; const BlobSetImmutabilityPolicyExceptionHeaders = { serializedName: "Blob_setImmutabilityPolicyExceptionHeaders", type: { name: "Composite", className: "BlobSetImmutabilityPolicyExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobDeleteImmutabilityPolicyHeaders = { serializedName: "Blob_deleteImmutabilityPolicyHeaders", type: { name: "Composite", className: "BlobDeleteImmutabilityPolicyHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, }, }, }; const BlobDeleteImmutabilityPolicyExceptionHeaders = { serializedName: "Blob_deleteImmutabilityPolicyExceptionHeaders", type: { name: "Composite", className: "BlobDeleteImmutabilityPolicyExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobSetLegalHoldHeaders = { serializedName: "Blob_setLegalHoldHeaders", type: { name: "Composite", className: "BlobSetLegalHoldHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, legalHold: { serializedName: "x-ms-legal-hold", xmlName: "x-ms-legal-hold", type: { name: "Boolean", }, }, }, }, }; const BlobSetLegalHoldExceptionHeaders = { serializedName: "Blob_setLegalHoldExceptionHeaders", type: { name: "Composite", className: "BlobSetLegalHoldExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobSetMetadataHeaders = { serializedName: "Blob_setMetadataHeaders", type: { name: "Composite", className: "BlobSetMetadataHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean", }, }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String", }, }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobSetMetadataExceptionHeaders = { serializedName: "Blob_setMetadataExceptionHeaders", type: { name: "Composite", className: "BlobSetMetadataExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobAcquireLeaseHeaders = { serializedName: "Blob_acquireLeaseHeaders", type: { name: "Composite", className: "BlobAcquireLeaseHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, leaseId: { serializedName: "x-ms-lease-id", xmlName: "x-ms-lease-id", type: { name: "String", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, }, }, }; const BlobAcquireLeaseExceptionHeaders = { serializedName: "Blob_acquireLeaseExceptionHeaders", type: { name: "Composite", className: "BlobAcquireLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobReleaseLeaseHeaders = { serializedName: "Blob_releaseLeaseHeaders", type: { name: "Composite", className: "BlobReleaseLeaseHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, }, }, }; const BlobReleaseLeaseExceptionHeaders = { serializedName: "Blob_releaseLeaseExceptionHeaders", type: { name: "Composite", className: "BlobReleaseLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobRenewLeaseHeaders = { serializedName: "Blob_renewLeaseHeaders", type: { name: "Composite", className: "BlobRenewLeaseHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, leaseId: { serializedName: "x-ms-lease-id", xmlName: "x-ms-lease-id", type: { name: "String", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, }, }, }; const BlobRenewLeaseExceptionHeaders = { serializedName: "Blob_renewLeaseExceptionHeaders", type: { name: "Composite", className: "BlobRenewLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobChangeLeaseHeaders = { serializedName: "Blob_changeLeaseHeaders", type: { name: "Composite", className: "BlobChangeLeaseHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, leaseId: { serializedName: "x-ms-lease-id", xmlName: "x-ms-lease-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, }, }, }; const BlobChangeLeaseExceptionHeaders = { serializedName: "Blob_changeLeaseExceptionHeaders", type: { name: "Composite", className: "BlobChangeLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobBreakLeaseHeaders = { serializedName: "Blob_breakLeaseHeaders", type: { name: "Composite", className: "BlobBreakLeaseHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, leaseTime: { serializedName: "x-ms-lease-time", xmlName: "x-ms-lease-time", type: { name: "Number", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, }, }, }; const BlobBreakLeaseExceptionHeaders = { serializedName: "Blob_breakLeaseExceptionHeaders", type: { name: "Composite", className: "BlobBreakLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobCreateSnapshotHeaders = { serializedName: "Blob_createSnapshotHeaders", type: { name: "Composite", className: "BlobCreateSnapshotHeaders", modelProperties: { snapshot: { serializedName: "x-ms-snapshot", xmlName: "x-ms-snapshot", type: { name: "String", }, }, etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobCreateSnapshotExceptionHeaders = { serializedName: "Blob_createSnapshotExceptionHeaders", type: { name: "Composite", className: "BlobCreateSnapshotExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobStartCopyFromURLHeaders = { serializedName: "Blob_startCopyFromURLHeaders", type: { name: "Composite", className: "BlobStartCopyFromURLHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, copyId: { serializedName: "x-ms-copy-id", xmlName: "x-ms-copy-id", type: { name: "String", }, }, copyStatus: { serializedName: "x-ms-copy-status", xmlName: "x-ms-copy-status", type: { name: "Enum", allowedValues: ["pending", "success", "aborted", "failed"], }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobStartCopyFromURLExceptionHeaders = { serializedName: "Blob_startCopyFromURLExceptionHeaders", type: { name: "Composite", className: "BlobStartCopyFromURLExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobCopyFromURLHeaders = { serializedName: "Blob_copyFromURLHeaders", type: { name: "Composite", className: "BlobCopyFromURLHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, copyId: { serializedName: "x-ms-copy-id", xmlName: "x-ms-copy-id", type: { name: "String", }, }, copyStatus: { defaultValue: "success", isConstant: true, serializedName: "x-ms-copy-status", type: { name: "String", }, }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray", }, }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray", }, }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobCopyFromURLExceptionHeaders = { serializedName: "Blob_copyFromURLExceptionHeaders", type: { name: "Composite", className: "BlobCopyFromURLExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobAbortCopyFromURLHeaders = { serializedName: "Blob_abortCopyFromURLHeaders", type: { name: "Composite", className: "BlobAbortCopyFromURLHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobAbortCopyFromURLExceptionHeaders = { serializedName: "Blob_abortCopyFromURLExceptionHeaders", type: { name: "Composite", className: "BlobAbortCopyFromURLExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobSetTierHeaders = { serializedName: "Blob_setTierHeaders", type: { name: "Composite", className: "BlobSetTierHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobSetTierExceptionHeaders = { serializedName: "Blob_setTierExceptionHeaders", type: { name: "Composite", className: "BlobSetTierExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobGetAccountInfoHeaders = { serializedName: "Blob_getAccountInfoHeaders", type: { name: "Composite", className: "BlobGetAccountInfoHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, skuName: { serializedName: "x-ms-sku-name", xmlName: "x-ms-sku-name", type: { name: "Enum", allowedValues: [ "Standard_LRS", "Standard_GRS", "Standard_RAGRS", "Standard_ZRS", "Premium_LRS", ], }, }, accountKind: { serializedName: "x-ms-account-kind", xmlName: "x-ms-account-kind", type: { name: "Enum", allowedValues: [ "Storage", "BlobStorage", "StorageV2", "FileStorage", "BlockBlobStorage", ], }, }, isHierarchicalNamespaceEnabled: { serializedName: "x-ms-is-hns-enabled", xmlName: "x-ms-is-hns-enabled", type: { name: "Boolean", }, }, }, }, }; const BlobGetAccountInfoExceptionHeaders = { serializedName: "Blob_getAccountInfoExceptionHeaders", type: { name: "Composite", className: "BlobGetAccountInfoExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobQueryHeaders = { serializedName: "Blob_queryHeaders", type: { name: "Composite", className: "BlobQueryHeaders", modelProperties: { lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, metadata: { serializedName: "x-ms-meta", headerCollectionPrefix: "x-ms-meta-", xmlName: "x-ms-meta", type: { name: "Dictionary", value: { type: { name: "String" } }, }, }, contentLength: { serializedName: "content-length", xmlName: "content-length", type: { name: "Number", }, }, contentType: { serializedName: "content-type", xmlName: "content-type", type: { name: "String", }, }, contentRange: { serializedName: "content-range", xmlName: "content-range", type: { name: "String", }, }, etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray", }, }, contentEncoding: { serializedName: "content-encoding", xmlName: "content-encoding", type: { name: "String", }, }, cacheControl: { serializedName: "cache-control", xmlName: "cache-control", type: { name: "String", }, }, contentDisposition: { serializedName: "content-disposition", xmlName: "content-disposition", type: { name: "String", }, }, contentLanguage: { serializedName: "content-language", xmlName: "content-language", type: { name: "String", }, }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number", }, }, blobType: { serializedName: "x-ms-blob-type", xmlName: "x-ms-blob-type", type: { name: "Enum", allowedValues: ["BlockBlob", "PageBlob", "AppendBlob"], }, }, copyCompletionTime: { serializedName: "x-ms-copy-completion-time", xmlName: "x-ms-copy-completion-time", type: { name: "DateTimeRfc1123", }, }, copyStatusDescription: { serializedName: "x-ms-copy-status-description", xmlName: "x-ms-copy-status-description", type: { name: "String", }, }, copyId: { serializedName: "x-ms-copy-id", xmlName: "x-ms-copy-id", type: { name: "String", }, }, copyProgress: { serializedName: "x-ms-copy-progress", xmlName: "x-ms-copy-progress", type: { name: "String", }, }, copySource: { serializedName: "x-ms-copy-source", xmlName: "x-ms-copy-source", type: { name: "String", }, }, copyStatus: { serializedName: "x-ms-copy-status", xmlName: "x-ms-copy-status", type: { name: "Enum", allowedValues: ["pending", "success", "aborted", "failed"], }, }, leaseDuration: { serializedName: "x-ms-lease-duration", xmlName: "x-ms-lease-duration", type: { name: "Enum", allowedValues: ["infinite", "fixed"], }, }, leaseState: { serializedName: "x-ms-lease-state", xmlName: "x-ms-lease-state", type: { name: "Enum", allowedValues: [ "available", "leased", "expired", "breaking", "broken", ], }, }, leaseStatus: { serializedName: "x-ms-lease-status", xmlName: "x-ms-lease-status", type: { name: "Enum", allowedValues: ["locked", "unlocked"], }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, acceptRanges: { serializedName: "accept-ranges", xmlName: "accept-ranges", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, blobCommittedBlockCount: { serializedName: "x-ms-blob-committed-block-count", xmlName: "x-ms-blob-committed-block-count", type: { name: "Number", }, }, isServerEncrypted: { serializedName: "x-ms-server-encrypted", xmlName: "x-ms-server-encrypted", type: { name: "Boolean", }, }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String", }, }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String", }, }, blobContentMD5: { serializedName: "x-ms-blob-content-md5", xmlName: "x-ms-blob-content-md5", type: { name: "ByteArray", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, contentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray", }, }, }, }, }; const BlobQueryExceptionHeaders = { serializedName: "Blob_queryExceptionHeaders", type: { name: "Composite", className: "BlobQueryExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobGetTagsHeaders = { serializedName: "Blob_getTagsHeaders", type: { name: "Composite", className: "BlobGetTagsHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobGetTagsExceptionHeaders = { serializedName: "Blob_getTagsExceptionHeaders", type: { name: "Composite", className: "BlobGetTagsExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobSetTagsHeaders = { serializedName: "Blob_setTagsHeaders", type: { name: "Composite", className: "BlobSetTagsHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlobSetTagsExceptionHeaders = { serializedName: "Blob_setTagsExceptionHeaders", type: { name: "Composite", className: "BlobSetTagsExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const PageBlobCreateHeaders = { serializedName: "PageBlob_createHeaders", type: { name: "Composite", className: "PageBlobCreateHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean", }, }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String", }, }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const PageBlobCreateExceptionHeaders = { serializedName: "PageBlob_createExceptionHeaders", type: { name: "Composite", className: "PageBlobCreateExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const PageBlobUploadPagesHeaders = { serializedName: "PageBlob_uploadPagesHeaders", type: { name: "Composite", className: "PageBlobUploadPagesHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray", }, }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray", }, }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean", }, }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String", }, }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const PageBlobUploadPagesExceptionHeaders = { serializedName: "PageBlob_uploadPagesExceptionHeaders", type: { name: "Composite", className: "PageBlobUploadPagesExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const PageBlobClearPagesHeaders = { serializedName: "PageBlob_clearPagesHeaders", type: { name: "Composite", className: "PageBlobClearPagesHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray", }, }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray", }, }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const PageBlobClearPagesExceptionHeaders = { serializedName: "PageBlob_clearPagesExceptionHeaders", type: { name: "Composite", className: "PageBlobClearPagesExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const PageBlobUploadPagesFromURLHeaders = { serializedName: "PageBlob_uploadPagesFromURLHeaders", type: { name: "Composite", className: "PageBlobUploadPagesFromURLHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray", }, }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray", }, }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean", }, }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String", }, }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const PageBlobUploadPagesFromURLExceptionHeaders = { serializedName: "PageBlob_uploadPagesFromURLExceptionHeaders", type: { name: "Composite", className: "PageBlobUploadPagesFromURLExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const PageBlobGetPageRangesHeaders = { serializedName: "PageBlob_getPageRangesHeaders", type: { name: "Composite", className: "PageBlobGetPageRangesHeaders", modelProperties: { lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, blobContentLength: { serializedName: "x-ms-blob-content-length", xmlName: "x-ms-blob-content-length", type: { name: "Number", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const PageBlobGetPageRangesExceptionHeaders = { serializedName: "PageBlob_getPageRangesExceptionHeaders", type: { name: "Composite", className: "PageBlobGetPageRangesExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const PageBlobGetPageRangesDiffHeaders = { serializedName: "PageBlob_getPageRangesDiffHeaders", type: { name: "Composite", className: "PageBlobGetPageRangesDiffHeaders", modelProperties: { lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, blobContentLength: { serializedName: "x-ms-blob-content-length", xmlName: "x-ms-blob-content-length", type: { name: "Number", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const PageBlobGetPageRangesDiffExceptionHeaders = { serializedName: "PageBlob_getPageRangesDiffExceptionHeaders", type: { name: "Composite", className: "PageBlobGetPageRangesDiffExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const PageBlobResizeHeaders = { serializedName: "PageBlob_resizeHeaders", type: { name: "Composite", className: "PageBlobResizeHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const PageBlobResizeExceptionHeaders = { serializedName: "PageBlob_resizeExceptionHeaders", type: { name: "Composite", className: "PageBlobResizeExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const PageBlobUpdateSequenceNumberHeaders = { serializedName: "PageBlob_updateSequenceNumberHeaders", type: { name: "Composite", className: "PageBlobUpdateSequenceNumberHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const PageBlobUpdateSequenceNumberExceptionHeaders = { serializedName: "PageBlob_updateSequenceNumberExceptionHeaders", type: { name: "Composite", className: "PageBlobUpdateSequenceNumberExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const PageBlobCopyIncrementalHeaders = { serializedName: "PageBlob_copyIncrementalHeaders", type: { name: "Composite", className: "PageBlobCopyIncrementalHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, copyId: { serializedName: "x-ms-copy-id", xmlName: "x-ms-copy-id", type: { name: "String", }, }, copyStatus: { serializedName: "x-ms-copy-status", xmlName: "x-ms-copy-status", type: { name: "Enum", allowedValues: ["pending", "success", "aborted", "failed"], }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const PageBlobCopyIncrementalExceptionHeaders = { serializedName: "PageBlob_copyIncrementalExceptionHeaders", type: { name: "Composite", className: "PageBlobCopyIncrementalExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const AppendBlobCreateHeaders = { serializedName: "AppendBlob_createHeaders", type: { name: "Composite", className: "AppendBlobCreateHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean", }, }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String", }, }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const AppendBlobCreateExceptionHeaders = { serializedName: "AppendBlob_createExceptionHeaders", type: { name: "Composite", className: "AppendBlobCreateExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const AppendBlobAppendBlockHeaders = { serializedName: "AppendBlob_appendBlockHeaders", type: { name: "Composite", className: "AppendBlobAppendBlockHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray", }, }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, blobAppendOffset: { serializedName: "x-ms-blob-append-offset", xmlName: "x-ms-blob-append-offset", type: { name: "String", }, }, blobCommittedBlockCount: { serializedName: "x-ms-blob-committed-block-count", xmlName: "x-ms-blob-committed-block-count", type: { name: "Number", }, }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean", }, }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String", }, }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const AppendBlobAppendBlockExceptionHeaders = { serializedName: "AppendBlob_appendBlockExceptionHeaders", type: { name: "Composite", className: "AppendBlobAppendBlockExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const AppendBlobAppendBlockFromUrlHeaders = { serializedName: "AppendBlob_appendBlockFromUrlHeaders", type: { name: "Composite", className: "AppendBlobAppendBlockFromUrlHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray", }, }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, blobAppendOffset: { serializedName: "x-ms-blob-append-offset", xmlName: "x-ms-blob-append-offset", type: { name: "String", }, }, blobCommittedBlockCount: { serializedName: "x-ms-blob-committed-block-count", xmlName: "x-ms-blob-committed-block-count", type: { name: "Number", }, }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String", }, }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String", }, }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const AppendBlobAppendBlockFromUrlExceptionHeaders = { serializedName: "AppendBlob_appendBlockFromUrlExceptionHeaders", type: { name: "Composite", className: "AppendBlobAppendBlockFromUrlExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const AppendBlobSealHeaders = { serializedName: "AppendBlob_sealHeaders", type: { name: "Composite", className: "AppendBlobSealHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, isSealed: { serializedName: "x-ms-blob-sealed", xmlName: "x-ms-blob-sealed", type: { name: "Boolean", }, }, }, }, }; const AppendBlobSealExceptionHeaders = { serializedName: "AppendBlob_sealExceptionHeaders", type: { name: "Composite", className: "AppendBlobSealExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlockBlobUploadHeaders = { serializedName: "BlockBlob_uploadHeaders", type: { name: "Composite", className: "BlockBlobUploadHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean", }, }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String", }, }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlockBlobUploadExceptionHeaders = { serializedName: "BlockBlob_uploadExceptionHeaders", type: { name: "Composite", className: "BlockBlobUploadExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlockBlobPutBlobFromUrlHeaders = { serializedName: "BlockBlob_putBlobFromUrlHeaders", type: { name: "Composite", className: "BlockBlobPutBlobFromUrlHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean", }, }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String", }, }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlockBlobPutBlobFromUrlExceptionHeaders = { serializedName: "BlockBlob_putBlobFromUrlExceptionHeaders", type: { name: "Composite", className: "BlockBlobPutBlobFromUrlExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlockBlobStageBlockHeaders = { serializedName: "BlockBlob_stageBlockHeaders", type: { name: "Composite", className: "BlockBlobStageBlockHeaders", modelProperties: { contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray", }, }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean", }, }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String", }, }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlockBlobStageBlockExceptionHeaders = { serializedName: "BlockBlob_stageBlockExceptionHeaders", type: { name: "Composite", className: "BlockBlobStageBlockExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlockBlobStageBlockFromURLHeaders = { serializedName: "BlockBlob_stageBlockFromURLHeaders", type: { name: "Composite", className: "BlockBlobStageBlockFromURLHeaders", modelProperties: { contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray", }, }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean", }, }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String", }, }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlockBlobStageBlockFromURLExceptionHeaders = { serializedName: "BlockBlob_stageBlockFromURLExceptionHeaders", type: { name: "Composite", className: "BlockBlobStageBlockFromURLExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlockBlobCommitBlockListHeaders = { serializedName: "BlockBlob_commitBlockListHeaders", type: { name: "Composite", className: "BlockBlobCommitBlockListHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray", }, }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean", }, }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String", }, }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlockBlobCommitBlockListExceptionHeaders = { serializedName: "BlockBlob_commitBlockListExceptionHeaders", type: { name: "Composite", className: "BlockBlobCommitBlockListExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlockBlobGetBlockListHeaders = { serializedName: "BlockBlob_getBlockListHeaders", type: { name: "Composite", className: "BlockBlobGetBlockListHeaders", modelProperties: { lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123", }, }, etag: { serializedName: "etag", xmlName: "etag", type: { name: "String", }, }, contentType: { serializedName: "content-type", xmlName: "content-type", type: { name: "String", }, }, blobContentLength: { serializedName: "x-ms-blob-content-length", xmlName: "x-ms-blob-content-length", type: { name: "Number", }, }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String", }, }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String", }, }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123", }, }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; const BlockBlobGetBlockListExceptionHeaders = { serializedName: "BlockBlob_getBlockListExceptionHeaders", type: { name: "Composite", className: "BlockBlobGetBlockListExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String", }, }, }, }, }; var Mappers = /*#__PURE__*/Object.freeze({ __proto__: null, AccessPolicy: AccessPolicy, AppendBlobAppendBlockExceptionHeaders: AppendBlobAppendBlockExceptionHeaders, AppendBlobAppendBlockFromUrlExceptionHeaders: AppendBlobAppendBlockFromUrlExceptionHeaders, AppendBlobAppendBlockFromUrlHeaders: AppendBlobAppendBlockFromUrlHeaders, AppendBlobAppendBlockHeaders: AppendBlobAppendBlockHeaders, AppendBlobCreateExceptionHeaders: AppendBlobCreateExceptionHeaders, AppendBlobCreateHeaders: AppendBlobCreateHeaders, AppendBlobSealExceptionHeaders: AppendBlobSealExceptionHeaders, AppendBlobSealHeaders: AppendBlobSealHeaders, ArrowConfiguration: ArrowConfiguration, ArrowField: ArrowField, BlobAbortCopyFromURLExceptionHeaders: BlobAbortCopyFromURLExceptionHeaders, BlobAbortCopyFromURLHeaders: BlobAbortCopyFromURLHeaders, BlobAcquireLeaseExceptionHeaders: BlobAcquireLeaseExceptionHeaders, BlobAcquireLeaseHeaders: BlobAcquireLeaseHeaders, BlobBreakLeaseExceptionHeaders: BlobBreakLeaseExceptionHeaders, BlobBreakLeaseHeaders: BlobBreakLeaseHeaders, BlobChangeLeaseExceptionHeaders: BlobChangeLeaseExceptionHeaders, BlobChangeLeaseHeaders: BlobChangeLeaseHeaders, BlobCopyFromURLExceptionHeaders: BlobCopyFromURLExceptionHeaders, BlobCopyFromURLHeaders: BlobCopyFromURLHeaders, BlobCreateSnapshotExceptionHeaders: BlobCreateSnapshotExceptionHeaders, BlobCreateSnapshotHeaders: BlobCreateSnapshotHeaders, BlobDeleteExceptionHeaders: BlobDeleteExceptionHeaders, BlobDeleteHeaders: BlobDeleteHeaders, BlobDeleteImmutabilityPolicyExceptionHeaders: BlobDeleteImmutabilityPolicyExceptionHeaders, BlobDeleteImmutabilityPolicyHeaders: BlobDeleteImmutabilityPolicyHeaders, BlobDownloadExceptionHeaders: BlobDownloadExceptionHeaders, BlobDownloadHeaders: BlobDownloadHeaders, BlobFlatListSegment: BlobFlatListSegment, BlobGetAccountInfoExceptionHeaders: BlobGetAccountInfoExceptionHeaders, BlobGetAccountInfoHeaders: BlobGetAccountInfoHeaders, BlobGetPropertiesExceptionHeaders: BlobGetPropertiesExceptionHeaders, BlobGetPropertiesHeaders: BlobGetPropertiesHeaders, BlobGetTagsExceptionHeaders: BlobGetTagsExceptionHeaders, BlobGetTagsHeaders: BlobGetTagsHeaders, BlobHierarchyListSegment: BlobHierarchyListSegment, BlobItemInternal: BlobItemInternal, BlobName: BlobName, BlobPrefix: BlobPrefix, BlobPropertiesInternal: BlobPropertiesInternal, BlobQueryExceptionHeaders: BlobQueryExceptionHeaders, BlobQueryHeaders: BlobQueryHeaders, BlobReleaseLeaseExceptionHeaders: BlobReleaseLeaseExceptionHeaders, BlobReleaseLeaseHeaders: BlobReleaseLeaseHeaders, BlobRenewLeaseExceptionHeaders: BlobRenewLeaseExceptionHeaders, BlobRenewLeaseHeaders: BlobRenewLeaseHeaders, BlobServiceProperties: BlobServiceProperties, BlobServiceStatistics: BlobServiceStatistics, BlobSetExpiryExceptionHeaders: BlobSetExpiryExceptionHeaders, BlobSetExpiryHeaders: BlobSetExpiryHeaders, BlobSetHttpHeadersExceptionHeaders: BlobSetHttpHeadersExceptionHeaders, BlobSetHttpHeadersHeaders: BlobSetHttpHeadersHeaders, BlobSetImmutabilityPolicyExceptionHeaders: BlobSetImmutabilityPolicyExceptionHeaders, BlobSetImmutabilityPolicyHeaders: BlobSetImmutabilityPolicyHeaders, BlobSetLegalHoldExceptionHeaders: BlobSetLegalHoldExceptionHeaders, BlobSetLegalHoldHeaders: BlobSetLegalHoldHeaders, BlobSetMetadataExceptionHeaders: BlobSetMetadataExceptionHeaders, BlobSetMetadataHeaders: BlobSetMetadataHeaders, BlobSetTagsExceptionHeaders: BlobSetTagsExceptionHeaders, BlobSetTagsHeaders: BlobSetTagsHeaders, BlobSetTierExceptionHeaders: BlobSetTierExceptionHeaders, BlobSetTierHeaders: BlobSetTierHeaders, BlobStartCopyFromURLExceptionHeaders: BlobStartCopyFromURLExceptionHeaders, BlobStartCopyFromURLHeaders: BlobStartCopyFromURLHeaders, BlobTag: BlobTag, BlobTags: BlobTags, BlobUndeleteExceptionHeaders: BlobUndeleteExceptionHeaders, BlobUndeleteHeaders: BlobUndeleteHeaders, Block: Block, BlockBlobCommitBlockListExceptionHeaders: BlockBlobCommitBlockListExceptionHeaders, BlockBlobCommitBlockListHeaders: BlockBlobCommitBlockListHeaders, BlockBlobGetBlockListExceptionHeaders: BlockBlobGetBlockListExceptionHeaders, BlockBlobGetBlockListHeaders: BlockBlobGetBlockListHeaders, BlockBlobPutBlobFromUrlExceptionHeaders: BlockBlobPutBlobFromUrlExceptionHeaders, BlockBlobPutBlobFromUrlHeaders: BlockBlobPutBlobFromUrlHeaders, BlockBlobStageBlockExceptionHeaders: BlockBlobStageBlockExceptionHeaders, BlockBlobStageBlockFromURLExceptionHeaders: BlockBlobStageBlockFromURLExceptionHeaders, BlockBlobStageBlockFromURLHeaders: BlockBlobStageBlockFromURLHeaders, BlockBlobStageBlockHeaders: BlockBlobStageBlockHeaders, BlockBlobUploadExceptionHeaders: BlockBlobUploadExceptionHeaders, BlockBlobUploadHeaders: BlockBlobUploadHeaders, BlockList: BlockList, BlockLookupList: BlockLookupList, ClearRange: ClearRange, ContainerAcquireLeaseExceptionHeaders: ContainerAcquireLeaseExceptionHeaders, ContainerAcquireLeaseHeaders: ContainerAcquireLeaseHeaders, ContainerBreakLeaseExceptionHeaders: ContainerBreakLeaseExceptionHeaders, ContainerBreakLeaseHeaders: ContainerBreakLeaseHeaders, ContainerChangeLeaseExceptionHeaders: ContainerChangeLeaseExceptionHeaders, ContainerChangeLeaseHeaders: ContainerChangeLeaseHeaders, ContainerCreateExceptionHeaders: ContainerCreateExceptionHeaders, ContainerCreateHeaders: ContainerCreateHeaders, ContainerDeleteExceptionHeaders: ContainerDeleteExceptionHeaders, ContainerDeleteHeaders: ContainerDeleteHeaders, ContainerFilterBlobsExceptionHeaders: ContainerFilterBlobsExceptionHeaders, ContainerFilterBlobsHeaders: ContainerFilterBlobsHeaders, ContainerGetAccessPolicyExceptionHeaders: ContainerGetAccessPolicyExceptionHeaders, ContainerGetAccessPolicyHeaders: ContainerGetAccessPolicyHeaders, ContainerGetAccountInfoExceptionHeaders: ContainerGetAccountInfoExceptionHeaders, ContainerGetAccountInfoHeaders: ContainerGetAccountInfoHeaders, ContainerGetPropertiesExceptionHeaders: ContainerGetPropertiesExceptionHeaders, ContainerGetPropertiesHeaders: ContainerGetPropertiesHeaders, ContainerItem: ContainerItem, ContainerListBlobFlatSegmentExceptionHeaders: ContainerListBlobFlatSegmentExceptionHeaders, ContainerListBlobFlatSegmentHeaders: ContainerListBlobFlatSegmentHeaders, ContainerListBlobHierarchySegmentExceptionHeaders: ContainerListBlobHierarchySegmentExceptionHeaders, ContainerListBlobHierarchySegmentHeaders: ContainerListBlobHierarchySegmentHeaders, ContainerProperties: ContainerProperties, ContainerReleaseLeaseExceptionHeaders: ContainerReleaseLeaseExceptionHeaders, ContainerReleaseLeaseHeaders: ContainerReleaseLeaseHeaders, ContainerRenameExceptionHeaders: ContainerRenameExceptionHeaders, ContainerRenameHeaders: ContainerRenameHeaders, ContainerRenewLeaseExceptionHeaders: ContainerRenewLeaseExceptionHeaders, ContainerRenewLeaseHeaders: ContainerRenewLeaseHeaders, ContainerRestoreExceptionHeaders: ContainerRestoreExceptionHeaders, ContainerRestoreHeaders: ContainerRestoreHeaders, ContainerSetAccessPolicyExceptionHeaders: ContainerSetAccessPolicyExceptionHeaders, ContainerSetAccessPolicyHeaders: ContainerSetAccessPolicyHeaders, ContainerSetMetadataExceptionHeaders: ContainerSetMetadataExceptionHeaders, ContainerSetMetadataHeaders: ContainerSetMetadataHeaders, ContainerSubmitBatchExceptionHeaders: ContainerSubmitBatchExceptionHeaders, ContainerSubmitBatchHeaders: ContainerSubmitBatchHeaders, CorsRule: CorsRule, DelimitedTextConfiguration: DelimitedTextConfiguration, FilterBlobItem: FilterBlobItem, FilterBlobSegment: FilterBlobSegment, GeoReplication: GeoReplication, JsonTextConfiguration: JsonTextConfiguration, KeyInfo: KeyInfo, ListBlobsFlatSegmentResponse: ListBlobsFlatSegmentResponse, ListBlobsHierarchySegmentResponse: ListBlobsHierarchySegmentResponse, ListContainersSegmentResponse: ListContainersSegmentResponse, Logging: Logging, Metrics: Metrics, PageBlobClearPagesExceptionHeaders: PageBlobClearPagesExceptionHeaders, PageBlobClearPagesHeaders: PageBlobClearPagesHeaders, PageBlobCopyIncrementalExceptionHeaders: PageBlobCopyIncrementalExceptionHeaders, PageBlobCopyIncrementalHeaders: PageBlobCopyIncrementalHeaders, PageBlobCreateExceptionHeaders: PageBlobCreateExceptionHeaders, PageBlobCreateHeaders: PageBlobCreateHeaders, PageBlobGetPageRangesDiffExceptionHeaders: PageBlobGetPageRangesDiffExceptionHeaders, PageBlobGetPageRangesDiffHeaders: PageBlobGetPageRangesDiffHeaders, PageBlobGetPageRangesExceptionHeaders: PageBlobGetPageRangesExceptionHeaders, PageBlobGetPageRangesHeaders: PageBlobGetPageRangesHeaders, PageBlobResizeExceptionHeaders: PageBlobResizeExceptionHeaders, PageBlobResizeHeaders: PageBlobResizeHeaders, PageBlobUpdateSequenceNumberExceptionHeaders: PageBlobUpdateSequenceNumberExceptionHeaders, PageBlobUpdateSequenceNumberHeaders: PageBlobUpdateSequenceNumberHeaders, PageBlobUploadPagesExceptionHeaders: PageBlobUploadPagesExceptionHeaders, PageBlobUploadPagesFromURLExceptionHeaders: PageBlobUploadPagesFromURLExceptionHeaders, PageBlobUploadPagesFromURLHeaders: PageBlobUploadPagesFromURLHeaders, PageBlobUploadPagesHeaders: PageBlobUploadPagesHeaders, PageList: PageList, PageRange: PageRange, QueryFormat: QueryFormat, QueryRequest: QueryRequest, QuerySerialization: QuerySerialization, RetentionPolicy: RetentionPolicy, ServiceFilterBlobsExceptionHeaders: ServiceFilterBlobsExceptionHeaders, ServiceFilterBlobsHeaders: ServiceFilterBlobsHeaders, ServiceGetAccountInfoExceptionHeaders: ServiceGetAccountInfoExceptionHeaders, ServiceGetAccountInfoHeaders: ServiceGetAccountInfoHeaders, ServiceGetPropertiesExceptionHeaders: ServiceGetPropertiesExceptionHeaders, ServiceGetPropertiesHeaders: ServiceGetPropertiesHeaders, ServiceGetStatisticsExceptionHeaders: ServiceGetStatisticsExceptionHeaders, ServiceGetStatisticsHeaders: ServiceGetStatisticsHeaders, ServiceGetUserDelegationKeyExceptionHeaders: ServiceGetUserDelegationKeyExceptionHeaders, ServiceGetUserDelegationKeyHeaders: ServiceGetUserDelegationKeyHeaders, ServiceListContainersSegmentExceptionHeaders: ServiceListContainersSegmentExceptionHeaders, ServiceListContainersSegmentHeaders: ServiceListContainersSegmentHeaders, ServiceSetPropertiesExceptionHeaders: ServiceSetPropertiesExceptionHeaders, ServiceSetPropertiesHeaders: ServiceSetPropertiesHeaders, ServiceSubmitBatchExceptionHeaders: ServiceSubmitBatchExceptionHeaders, ServiceSubmitBatchHeaders: ServiceSubmitBatchHeaders, SignedIdentifier: SignedIdentifier, StaticWebsite: StaticWebsite, StorageError: StorageError, UserDelegationKey: UserDelegationKey }); /* * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ const contentType = { parameterPath: ["options", "contentType"], mapper: { defaultValue: "application/xml", isConstant: true, serializedName: "Content-Type", type: { name: "String", }, }, }; const blobServiceProperties = { parameterPath: "blobServiceProperties", mapper: BlobServiceProperties, }; const accept = { parameterPath: "accept", mapper: { defaultValue: "application/xml", isConstant: true, serializedName: "Accept", type: { name: "String", }, }, }; const url = { parameterPath: "url", mapper: { serializedName: "url", required: true, xmlName: "url", type: { name: "String", }, }, skipEncoding: true, }; const restype = { parameterPath: "restype", mapper: { defaultValue: "service", isConstant: true, serializedName: "restype", type: { name: "String", }, }, }; const comp = { parameterPath: "comp", mapper: { defaultValue: "properties", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const timeoutInSeconds = { parameterPath: ["options", "timeoutInSeconds"], mapper: { constraints: { InclusiveMinimum: 0, }, serializedName: "timeout", xmlName: "timeout", type: { name: "Number", }, }, }; const version = { parameterPath: "version", mapper: { defaultValue: "2025-05-05", isConstant: true, serializedName: "x-ms-version", type: { name: "String", }, }, }; const requestId = { parameterPath: ["options", "requestId"], mapper: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String", }, }, }; const accept1 = { parameterPath: "accept", mapper: { defaultValue: "application/xml", isConstant: true, serializedName: "Accept", type: { name: "String", }, }, }; const comp1 = { parameterPath: "comp", mapper: { defaultValue: "stats", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const comp2 = { parameterPath: "comp", mapper: { defaultValue: "list", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const prefix = { parameterPath: ["options", "prefix"], mapper: { serializedName: "prefix", xmlName: "prefix", type: { name: "String", }, }, }; const marker = { parameterPath: ["options", "marker"], mapper: { serializedName: "marker", xmlName: "marker", type: { name: "String", }, }, }; const maxPageSize = { parameterPath: ["options", "maxPageSize"], mapper: { constraints: { InclusiveMinimum: 1, }, serializedName: "maxresults", xmlName: "maxresults", type: { name: "Number", }, }, }; const include = { parameterPath: ["options", "include"], mapper: { serializedName: "include", xmlName: "include", xmlElementName: "ListContainersIncludeType", type: { name: "Sequence", element: { type: { name: "Enum", allowedValues: ["metadata", "deleted", "system"], }, }, }, }, collectionFormat: "CSV", }; const keyInfo = { parameterPath: "keyInfo", mapper: KeyInfo, }; const comp3 = { parameterPath: "comp", mapper: { defaultValue: "userdelegationkey", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const restype1 = { parameterPath: "restype", mapper: { defaultValue: "account", isConstant: true, serializedName: "restype", type: { name: "String", }, }, }; const body = { parameterPath: "body", mapper: { serializedName: "body", required: true, xmlName: "body", type: { name: "Stream", }, }, }; const comp4 = { parameterPath: "comp", mapper: { defaultValue: "batch", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const contentLength = { parameterPath: "contentLength", mapper: { serializedName: "Content-Length", required: true, xmlName: "Content-Length", type: { name: "Number", }, }, }; const multipartContentType = { parameterPath: "multipartContentType", mapper: { serializedName: "Content-Type", required: true, xmlName: "Content-Type", type: { name: "String", }, }, }; const comp5 = { parameterPath: "comp", mapper: { defaultValue: "blobs", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const where = { parameterPath: ["options", "where"], mapper: { serializedName: "where", xmlName: "where", type: { name: "String", }, }, }; const restype2 = { parameterPath: "restype", mapper: { defaultValue: "container", isConstant: true, serializedName: "restype", type: { name: "String", }, }, }; const metadata = { parameterPath: ["options", "metadata"], mapper: { serializedName: "x-ms-meta", xmlName: "x-ms-meta", headerCollectionPrefix: "x-ms-meta-", type: { name: "Dictionary", value: { type: { name: "String" } }, }, }, }; const access = { parameterPath: ["options", "access"], mapper: { serializedName: "x-ms-blob-public-access", xmlName: "x-ms-blob-public-access", type: { name: "Enum", allowedValues: ["container", "blob"], }, }, }; const defaultEncryptionScope = { parameterPath: [ "options", "containerEncryptionScope", "defaultEncryptionScope", ], mapper: { serializedName: "x-ms-default-encryption-scope", xmlName: "x-ms-default-encryption-scope", type: { name: "String", }, }, }; const preventEncryptionScopeOverride = { parameterPath: [ "options", "containerEncryptionScope", "preventEncryptionScopeOverride", ], mapper: { serializedName: "x-ms-deny-encryption-scope-override", xmlName: "x-ms-deny-encryption-scope-override", type: { name: "Boolean", }, }, }; const leaseId = { parameterPath: ["options", "leaseAccessConditions", "leaseId"], mapper: { serializedName: "x-ms-lease-id", xmlName: "x-ms-lease-id", type: { name: "String", }, }, }; const ifModifiedSince = { parameterPath: ["options", "modifiedAccessConditions", "ifModifiedSince"], mapper: { serializedName: "If-Modified-Since", xmlName: "If-Modified-Since", type: { name: "DateTimeRfc1123", }, }, }; const ifUnmodifiedSince = { parameterPath: ["options", "modifiedAccessConditions", "ifUnmodifiedSince"], mapper: { serializedName: "If-Unmodified-Since", xmlName: "If-Unmodified-Since", type: { name: "DateTimeRfc1123", }, }, }; const comp6 = { parameterPath: "comp", mapper: { defaultValue: "metadata", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const comp7 = { parameterPath: "comp", mapper: { defaultValue: "acl", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const containerAcl = { parameterPath: ["options", "containerAcl"], mapper: { serializedName: "containerAcl", xmlName: "SignedIdentifiers", xmlIsWrapped: true, xmlElementName: "SignedIdentifier", type: { name: "Sequence", element: { type: { name: "Composite", className: "SignedIdentifier", }, }, }, }, }; const comp8 = { parameterPath: "comp", mapper: { defaultValue: "undelete", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const deletedContainerName = { parameterPath: ["options", "deletedContainerName"], mapper: { serializedName: "x-ms-deleted-container-name", xmlName: "x-ms-deleted-container-name", type: { name: "String", }, }, }; const deletedContainerVersion = { parameterPath: ["options", "deletedContainerVersion"], mapper: { serializedName: "x-ms-deleted-container-version", xmlName: "x-ms-deleted-container-version", type: { name: "String", }, }, }; const comp9 = { parameterPath: "comp", mapper: { defaultValue: "rename", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const sourceContainerName = { parameterPath: "sourceContainerName", mapper: { serializedName: "x-ms-source-container-name", required: true, xmlName: "x-ms-source-container-name", type: { name: "String", }, }, }; const sourceLeaseId = { parameterPath: ["options", "sourceLeaseId"], mapper: { serializedName: "x-ms-source-lease-id", xmlName: "x-ms-source-lease-id", type: { name: "String", }, }, }; const comp10 = { parameterPath: "comp", mapper: { defaultValue: "lease", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const action = { parameterPath: "action", mapper: { defaultValue: "acquire", isConstant: true, serializedName: "x-ms-lease-action", type: { name: "String", }, }, }; const duration = { parameterPath: ["options", "duration"], mapper: { serializedName: "x-ms-lease-duration", xmlName: "x-ms-lease-duration", type: { name: "Number", }, }, }; const proposedLeaseId = { parameterPath: ["options", "proposedLeaseId"], mapper: { serializedName: "x-ms-proposed-lease-id", xmlName: "x-ms-proposed-lease-id", type: { name: "String", }, }, }; const action1 = { parameterPath: "action", mapper: { defaultValue: "release", isConstant: true, serializedName: "x-ms-lease-action", type: { name: "String", }, }, }; const leaseId1 = { parameterPath: "leaseId", mapper: { serializedName: "x-ms-lease-id", required: true, xmlName: "x-ms-lease-id", type: { name: "String", }, }, }; const action2 = { parameterPath: "action", mapper: { defaultValue: "renew", isConstant: true, serializedName: "x-ms-lease-action", type: { name: "String", }, }, }; const action3 = { parameterPath: "action", mapper: { defaultValue: "break", isConstant: true, serializedName: "x-ms-lease-action", type: { name: "String", }, }, }; const breakPeriod = { parameterPath: ["options", "breakPeriod"], mapper: { serializedName: "x-ms-lease-break-period", xmlName: "x-ms-lease-break-period", type: { name: "Number", }, }, }; const action4 = { parameterPath: "action", mapper: { defaultValue: "change", isConstant: true, serializedName: "x-ms-lease-action", type: { name: "String", }, }, }; const proposedLeaseId1 = { parameterPath: "proposedLeaseId", mapper: { serializedName: "x-ms-proposed-lease-id", required: true, xmlName: "x-ms-proposed-lease-id", type: { name: "String", }, }, }; const include1 = { parameterPath: ["options", "include"], mapper: { serializedName: "include", xmlName: "include", xmlElementName: "ListBlobsIncludeItem", type: { name: "Sequence", element: { type: { name: "Enum", allowedValues: [ "copy", "deleted", "metadata", "snapshots", "uncommittedblobs", "versions", "tags", "immutabilitypolicy", "legalhold", "deletedwithversions", ], }, }, }, }, collectionFormat: "CSV", }; const delimiter = { parameterPath: "delimiter", mapper: { serializedName: "delimiter", required: true, xmlName: "delimiter", type: { name: "String", }, }, }; const snapshot = { parameterPath: ["options", "snapshot"], mapper: { serializedName: "snapshot", xmlName: "snapshot", type: { name: "String", }, }, }; const versionId = { parameterPath: ["options", "versionId"], mapper: { serializedName: "versionid", xmlName: "versionid", type: { name: "String", }, }, }; const range = { parameterPath: ["options", "range"], mapper: { serializedName: "x-ms-range", xmlName: "x-ms-range", type: { name: "String", }, }, }; const rangeGetContentMD5 = { parameterPath: ["options", "rangeGetContentMD5"], mapper: { serializedName: "x-ms-range-get-content-md5", xmlName: "x-ms-range-get-content-md5", type: { name: "Boolean", }, }, }; const rangeGetContentCRC64 = { parameterPath: ["options", "rangeGetContentCRC64"], mapper: { serializedName: "x-ms-range-get-content-crc64", xmlName: "x-ms-range-get-content-crc64", type: { name: "Boolean", }, }, }; const encryptionKey = { parameterPath: ["options", "cpkInfo", "encryptionKey"], mapper: { serializedName: "x-ms-encryption-key", xmlName: "x-ms-encryption-key", type: { name: "String", }, }, }; const encryptionKeySha256 = { parameterPath: ["options", "cpkInfo", "encryptionKeySha256"], mapper: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String", }, }, }; const encryptionAlgorithm = { parameterPath: ["options", "cpkInfo", "encryptionAlgorithm"], mapper: { serializedName: "x-ms-encryption-algorithm", xmlName: "x-ms-encryption-algorithm", type: { name: "String", }, }, }; const ifMatch = { parameterPath: ["options", "modifiedAccessConditions", "ifMatch"], mapper: { serializedName: "If-Match", xmlName: "If-Match", type: { name: "String", }, }, }; const ifNoneMatch = { parameterPath: ["options", "modifiedAccessConditions", "ifNoneMatch"], mapper: { serializedName: "If-None-Match", xmlName: "If-None-Match", type: { name: "String", }, }, }; const ifTags = { parameterPath: ["options", "modifiedAccessConditions", "ifTags"], mapper: { serializedName: "x-ms-if-tags", xmlName: "x-ms-if-tags", type: { name: "String", }, }, }; const deleteSnapshots = { parameterPath: ["options", "deleteSnapshots"], mapper: { serializedName: "x-ms-delete-snapshots", xmlName: "x-ms-delete-snapshots", type: { name: "Enum", allowedValues: ["include", "only"], }, }, }; const blobDeleteType = { parameterPath: ["options", "blobDeleteType"], mapper: { serializedName: "deletetype", xmlName: "deletetype", type: { name: "String", }, }, }; const comp11 = { parameterPath: "comp", mapper: { defaultValue: "expiry", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const expiryOptions = { parameterPath: "expiryOptions", mapper: { serializedName: "x-ms-expiry-option", required: true, xmlName: "x-ms-expiry-option", type: { name: "String", }, }, }; const expiresOn = { parameterPath: ["options", "expiresOn"], mapper: { serializedName: "x-ms-expiry-time", xmlName: "x-ms-expiry-time", type: { name: "String", }, }, }; const blobCacheControl = { parameterPath: ["options", "blobHttpHeaders", "blobCacheControl"], mapper: { serializedName: "x-ms-blob-cache-control", xmlName: "x-ms-blob-cache-control", type: { name: "String", }, }, }; const blobContentType = { parameterPath: ["options", "blobHttpHeaders", "blobContentType"], mapper: { serializedName: "x-ms-blob-content-type", xmlName: "x-ms-blob-content-type", type: { name: "String", }, }, }; const blobContentMD5 = { parameterPath: ["options", "blobHttpHeaders", "blobContentMD5"], mapper: { serializedName: "x-ms-blob-content-md5", xmlName: "x-ms-blob-content-md5", type: { name: "ByteArray", }, }, }; const blobContentEncoding = { parameterPath: ["options", "blobHttpHeaders", "blobContentEncoding"], mapper: { serializedName: "x-ms-blob-content-encoding", xmlName: "x-ms-blob-content-encoding", type: { name: "String", }, }, }; const blobContentLanguage = { parameterPath: ["options", "blobHttpHeaders", "blobContentLanguage"], mapper: { serializedName: "x-ms-blob-content-language", xmlName: "x-ms-blob-content-language", type: { name: "String", }, }, }; const blobContentDisposition = { parameterPath: ["options", "blobHttpHeaders", "blobContentDisposition"], mapper: { serializedName: "x-ms-blob-content-disposition", xmlName: "x-ms-blob-content-disposition", type: { name: "String", }, }, }; const comp12 = { parameterPath: "comp", mapper: { defaultValue: "immutabilityPolicies", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const immutabilityPolicyExpiry = { parameterPath: ["options", "immutabilityPolicyExpiry"], mapper: { serializedName: "x-ms-immutability-policy-until-date", xmlName: "x-ms-immutability-policy-until-date", type: { name: "DateTimeRfc1123", }, }, }; const immutabilityPolicyMode = { parameterPath: ["options", "immutabilityPolicyMode"], mapper: { serializedName: "x-ms-immutability-policy-mode", xmlName: "x-ms-immutability-policy-mode", type: { name: "Enum", allowedValues: ["Mutable", "Unlocked", "Locked"], }, }, }; const comp13 = { parameterPath: "comp", mapper: { defaultValue: "legalhold", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const legalHold = { parameterPath: "legalHold", mapper: { serializedName: "x-ms-legal-hold", required: true, xmlName: "x-ms-legal-hold", type: { name: "Boolean", }, }, }; const encryptionScope = { parameterPath: ["options", "encryptionScope"], mapper: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String", }, }, }; const comp14 = { parameterPath: "comp", mapper: { defaultValue: "snapshot", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const tier = { parameterPath: ["options", "tier"], mapper: { serializedName: "x-ms-access-tier", xmlName: "x-ms-access-tier", type: { name: "Enum", allowedValues: [ "P4", "P6", "P10", "P15", "P20", "P30", "P40", "P50", "P60", "P70", "P80", "Hot", "Cool", "Archive", "Cold", ], }, }, }; const rehydratePriority = { parameterPath: ["options", "rehydratePriority"], mapper: { serializedName: "x-ms-rehydrate-priority", xmlName: "x-ms-rehydrate-priority", type: { name: "Enum", allowedValues: ["High", "Standard"], }, }, }; const sourceIfModifiedSince = { parameterPath: [ "options", "sourceModifiedAccessConditions", "sourceIfModifiedSince", ], mapper: { serializedName: "x-ms-source-if-modified-since", xmlName: "x-ms-source-if-modified-since", type: { name: "DateTimeRfc1123", }, }, }; const sourceIfUnmodifiedSince = { parameterPath: [ "options", "sourceModifiedAccessConditions", "sourceIfUnmodifiedSince", ], mapper: { serializedName: "x-ms-source-if-unmodified-since", xmlName: "x-ms-source-if-unmodified-since", type: { name: "DateTimeRfc1123", }, }, }; const sourceIfMatch = { parameterPath: ["options", "sourceModifiedAccessConditions", "sourceIfMatch"], mapper: { serializedName: "x-ms-source-if-match", xmlName: "x-ms-source-if-match", type: { name: "String", }, }, }; const sourceIfNoneMatch = { parameterPath: [ "options", "sourceModifiedAccessConditions", "sourceIfNoneMatch", ], mapper: { serializedName: "x-ms-source-if-none-match", xmlName: "x-ms-source-if-none-match", type: { name: "String", }, }, }; const sourceIfTags = { parameterPath: ["options", "sourceModifiedAccessConditions", "sourceIfTags"], mapper: { serializedName: "x-ms-source-if-tags", xmlName: "x-ms-source-if-tags", type: { name: "String", }, }, }; const copySource = { parameterPath: "copySource", mapper: { serializedName: "x-ms-copy-source", required: true, xmlName: "x-ms-copy-source", type: { name: "String", }, }, }; const blobTagsString = { parameterPath: ["options", "blobTagsString"], mapper: { serializedName: "x-ms-tags", xmlName: "x-ms-tags", type: { name: "String", }, }, }; const sealBlob = { parameterPath: ["options", "sealBlob"], mapper: { serializedName: "x-ms-seal-blob", xmlName: "x-ms-seal-blob", type: { name: "Boolean", }, }, }; const legalHold1 = { parameterPath: ["options", "legalHold"], mapper: { serializedName: "x-ms-legal-hold", xmlName: "x-ms-legal-hold", type: { name: "Boolean", }, }, }; const xMsRequiresSync = { parameterPath: "xMsRequiresSync", mapper: { defaultValue: "true", isConstant: true, serializedName: "x-ms-requires-sync", type: { name: "String", }, }, }; const sourceContentMD5 = { parameterPath: ["options", "sourceContentMD5"], mapper: { serializedName: "x-ms-source-content-md5", xmlName: "x-ms-source-content-md5", type: { name: "ByteArray", }, }, }; const copySourceAuthorization = { parameterPath: ["options", "copySourceAuthorization"], mapper: { serializedName: "x-ms-copy-source-authorization", xmlName: "x-ms-copy-source-authorization", type: { name: "String", }, }, }; const copySourceTags = { parameterPath: ["options", "copySourceTags"], mapper: { serializedName: "x-ms-copy-source-tag-option", xmlName: "x-ms-copy-source-tag-option", type: { name: "Enum", allowedValues: ["REPLACE", "COPY"], }, }, }; const comp15 = { parameterPath: "comp", mapper: { defaultValue: "copy", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const copyActionAbortConstant = { parameterPath: "copyActionAbortConstant", mapper: { defaultValue: "abort", isConstant: true, serializedName: "x-ms-copy-action", type: { name: "String", }, }, }; const copyId = { parameterPath: "copyId", mapper: { serializedName: "copyid", required: true, xmlName: "copyid", type: { name: "String", }, }, }; const comp16 = { parameterPath: "comp", mapper: { defaultValue: "tier", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const tier1 = { parameterPath: "tier", mapper: { serializedName: "x-ms-access-tier", required: true, xmlName: "x-ms-access-tier", type: { name: "Enum", allowedValues: [ "P4", "P6", "P10", "P15", "P20", "P30", "P40", "P50", "P60", "P70", "P80", "Hot", "Cool", "Archive", "Cold", ], }, }, }; const queryRequest = { parameterPath: ["options", "queryRequest"], mapper: QueryRequest, }; const comp17 = { parameterPath: "comp", mapper: { defaultValue: "query", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const comp18 = { parameterPath: "comp", mapper: { defaultValue: "tags", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const tags = { parameterPath: ["options", "tags"], mapper: BlobTags, }; const transactionalContentMD5 = { parameterPath: ["options", "transactionalContentMD5"], mapper: { serializedName: "Content-MD5", xmlName: "Content-MD5", type: { name: "ByteArray", }, }, }; const transactionalContentCrc64 = { parameterPath: ["options", "transactionalContentCrc64"], mapper: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray", }, }, }; const blobType = { parameterPath: "blobType", mapper: { defaultValue: "PageBlob", isConstant: true, serializedName: "x-ms-blob-type", type: { name: "String", }, }, }; const blobContentLength = { parameterPath: "blobContentLength", mapper: { serializedName: "x-ms-blob-content-length", required: true, xmlName: "x-ms-blob-content-length", type: { name: "Number", }, }, }; const blobSequenceNumber = { parameterPath: ["options", "blobSequenceNumber"], mapper: { defaultValue: 0, serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number", }, }, }; const contentType1 = { parameterPath: ["options", "contentType"], mapper: { defaultValue: "application/octet-stream", isConstant: true, serializedName: "Content-Type", type: { name: "String", }, }, }; const body1 = { parameterPath: "body", mapper: { serializedName: "body", required: true, xmlName: "body", type: { name: "Stream", }, }, }; const accept2 = { parameterPath: "accept", mapper: { defaultValue: "application/xml", isConstant: true, serializedName: "Accept", type: { name: "String", }, }, }; const comp19 = { parameterPath: "comp", mapper: { defaultValue: "page", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const pageWrite = { parameterPath: "pageWrite", mapper: { defaultValue: "update", isConstant: true, serializedName: "x-ms-page-write", type: { name: "String", }, }, }; const ifSequenceNumberLessThanOrEqualTo = { parameterPath: [ "options", "sequenceNumberAccessConditions", "ifSequenceNumberLessThanOrEqualTo", ], mapper: { serializedName: "x-ms-if-sequence-number-le", xmlName: "x-ms-if-sequence-number-le", type: { name: "Number", }, }, }; const ifSequenceNumberLessThan = { parameterPath: [ "options", "sequenceNumberAccessConditions", "ifSequenceNumberLessThan", ], mapper: { serializedName: "x-ms-if-sequence-number-lt", xmlName: "x-ms-if-sequence-number-lt", type: { name: "Number", }, }, }; const ifSequenceNumberEqualTo = { parameterPath: [ "options", "sequenceNumberAccessConditions", "ifSequenceNumberEqualTo", ], mapper: { serializedName: "x-ms-if-sequence-number-eq", xmlName: "x-ms-if-sequence-number-eq", type: { name: "Number", }, }, }; const pageWrite1 = { parameterPath: "pageWrite", mapper: { defaultValue: "clear", isConstant: true, serializedName: "x-ms-page-write", type: { name: "String", }, }, }; const sourceUrl = { parameterPath: "sourceUrl", mapper: { serializedName: "x-ms-copy-source", required: true, xmlName: "x-ms-copy-source", type: { name: "String", }, }, }; const sourceRange = { parameterPath: "sourceRange", mapper: { serializedName: "x-ms-source-range", required: true, xmlName: "x-ms-source-range", type: { name: "String", }, }, }; const sourceContentCrc64 = { parameterPath: ["options", "sourceContentCrc64"], mapper: { serializedName: "x-ms-source-content-crc64", xmlName: "x-ms-source-content-crc64", type: { name: "ByteArray", }, }, }; const range1 = { parameterPath: "range", mapper: { serializedName: "x-ms-range", required: true, xmlName: "x-ms-range", type: { name: "String", }, }, }; const comp20 = { parameterPath: "comp", mapper: { defaultValue: "pagelist", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const prevsnapshot = { parameterPath: ["options", "prevsnapshot"], mapper: { serializedName: "prevsnapshot", xmlName: "prevsnapshot", type: { name: "String", }, }, }; const prevSnapshotUrl = { parameterPath: ["options", "prevSnapshotUrl"], mapper: { serializedName: "x-ms-previous-snapshot-url", xmlName: "x-ms-previous-snapshot-url", type: { name: "String", }, }, }; const sequenceNumberAction = { parameterPath: "sequenceNumberAction", mapper: { serializedName: "x-ms-sequence-number-action", required: true, xmlName: "x-ms-sequence-number-action", type: { name: "Enum", allowedValues: ["max", "update", "increment"], }, }, }; const comp21 = { parameterPath: "comp", mapper: { defaultValue: "incrementalcopy", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const blobType1 = { parameterPath: "blobType", mapper: { defaultValue: "AppendBlob", isConstant: true, serializedName: "x-ms-blob-type", type: { name: "String", }, }, }; const comp22 = { parameterPath: "comp", mapper: { defaultValue: "appendblock", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const maxSize = { parameterPath: ["options", "appendPositionAccessConditions", "maxSize"], mapper: { serializedName: "x-ms-blob-condition-maxsize", xmlName: "x-ms-blob-condition-maxsize", type: { name: "Number", }, }, }; const appendPosition = { parameterPath: [ "options", "appendPositionAccessConditions", "appendPosition", ], mapper: { serializedName: "x-ms-blob-condition-appendpos", xmlName: "x-ms-blob-condition-appendpos", type: { name: "Number", }, }, }; const sourceRange1 = { parameterPath: ["options", "sourceRange"], mapper: { serializedName: "x-ms-source-range", xmlName: "x-ms-source-range", type: { name: "String", }, }, }; const comp23 = { parameterPath: "comp", mapper: { defaultValue: "seal", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const blobType2 = { parameterPath: "blobType", mapper: { defaultValue: "BlockBlob", isConstant: true, serializedName: "x-ms-blob-type", type: { name: "String", }, }, }; const copySourceBlobProperties = { parameterPath: ["options", "copySourceBlobProperties"], mapper: { serializedName: "x-ms-copy-source-blob-properties", xmlName: "x-ms-copy-source-blob-properties", type: { name: "Boolean", }, }, }; const comp24 = { parameterPath: "comp", mapper: { defaultValue: "block", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const blockId = { parameterPath: "blockId", mapper: { serializedName: "blockid", required: true, xmlName: "blockid", type: { name: "String", }, }, }; const blocks = { parameterPath: "blocks", mapper: BlockLookupList, }; const comp25 = { parameterPath: "comp", mapper: { defaultValue: "blocklist", isConstant: true, serializedName: "comp", type: { name: "String", }, }, }; const listType = { parameterPath: "listType", mapper: { defaultValue: "committed", serializedName: "blocklisttype", required: true, xmlName: "blocklisttype", type: { name: "Enum", allowedValues: ["committed", "uncommitted", "all"], }, }, }; /* * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ /** Class containing Service operations. */ class ServiceImpl { /** * Initialize a new instance of the class Service class. * @param client Reference to the service client */ constructor(client) { this.client = client; } /** * Sets properties for a storage account's Blob service endpoint, including properties for Storage * Analytics and CORS (Cross-Origin Resource Sharing) rules * @param blobServiceProperties The StorageService properties. * @param options The options parameters. */ setProperties(blobServiceProperties, options) { return this.client.sendOperationRequest({ blobServiceProperties, options }, setPropertiesOperationSpec); } /** * gets the properties of a storage account's Blob service, including properties for Storage Analytics * and CORS (Cross-Origin Resource Sharing) rules. * @param options The options parameters. */ getProperties(options) { return this.client.sendOperationRequest({ options }, getPropertiesOperationSpec$2); } /** * 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. * @param options The options parameters. */ getStatistics(options) { return this.client.sendOperationRequest({ options }, getStatisticsOperationSpec); } /** * The List Containers Segment operation returns a list of the containers under the specified account * @param options The options parameters. */ listContainersSegment(options) { return this.client.sendOperationRequest({ options }, listContainersSegmentOperationSpec); } /** * Retrieves a user delegation key for the Blob service. This is only a valid operation when using * bearer token authentication. * @param keyInfo Key information * @param options The options parameters. */ getUserDelegationKey(keyInfo, options) { return this.client.sendOperationRequest({ keyInfo, options }, getUserDelegationKeyOperationSpec); } /** * Returns the sku name and account kind * @param options The options parameters. */ getAccountInfo(options) { return this.client.sendOperationRequest({ options }, getAccountInfoOperationSpec$2); } /** * The Batch operation allows multiple API calls to be embedded into a single HTTP request. * @param contentLength The length of the request. * @param multipartContentType Required. The value of this header must be multipart/mixed with a batch * boundary. Example header value: multipart/mixed; boundary=batch_ * @param body Initial data * @param options The options parameters. */ submitBatch(contentLength, multipartContentType, body, options) { return this.client.sendOperationRequest({ contentLength, multipartContentType, body, options }, submitBatchOperationSpec$1); } /** * 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. * @param options The options parameters. */ filterBlobs(options) { return this.client.sendOperationRequest({ options }, filterBlobsOperationSpec$1); } } // Operation Specifications const xmlSerializer$5 = coreClient__namespace.createSerializer(Mappers, /* isXml */ true); const setPropertiesOperationSpec = { path: "/", httpMethod: "PUT", responses: { 202: { headersMapper: ServiceSetPropertiesHeaders, }, default: { bodyMapper: StorageError, headersMapper: ServiceSetPropertiesExceptionHeaders, }, }, requestBody: blobServiceProperties, queryParameters: [ restype, comp, timeoutInSeconds, ], urlParameters: [url], headerParameters: [ contentType, accept, version, requestId, ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "xml", serializer: xmlSerializer$5, }; const getPropertiesOperationSpec$2 = { path: "/", httpMethod: "GET", responses: { 200: { bodyMapper: BlobServiceProperties, headersMapper: ServiceGetPropertiesHeaders, }, default: { bodyMapper: StorageError, headersMapper: ServiceGetPropertiesExceptionHeaders, }, }, queryParameters: [ restype, comp, timeoutInSeconds, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ], isXML: true, serializer: xmlSerializer$5, }; const getStatisticsOperationSpec = { path: "/", httpMethod: "GET", responses: { 200: { bodyMapper: BlobServiceStatistics, headersMapper: ServiceGetStatisticsHeaders, }, default: { bodyMapper: StorageError, headersMapper: ServiceGetStatisticsExceptionHeaders, }, }, queryParameters: [ restype, timeoutInSeconds, comp1, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ], isXML: true, serializer: xmlSerializer$5, }; const listContainersSegmentOperationSpec = { path: "/", httpMethod: "GET", responses: { 200: { bodyMapper: ListContainersSegmentResponse, headersMapper: ServiceListContainersSegmentHeaders, }, default: { bodyMapper: StorageError, headersMapper: ServiceListContainersSegmentExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, comp2, prefix, marker, maxPageSize, include, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ], isXML: true, serializer: xmlSerializer$5, }; const getUserDelegationKeyOperationSpec = { path: "/", httpMethod: "POST", responses: { 200: { bodyMapper: UserDelegationKey, headersMapper: ServiceGetUserDelegationKeyHeaders, }, default: { bodyMapper: StorageError, headersMapper: ServiceGetUserDelegationKeyExceptionHeaders, }, }, requestBody: keyInfo, queryParameters: [ restype, timeoutInSeconds, comp3, ], urlParameters: [url], headerParameters: [ contentType, accept, version, requestId, ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "xml", serializer: xmlSerializer$5, }; const getAccountInfoOperationSpec$2 = { path: "/", httpMethod: "GET", responses: { 200: { headersMapper: ServiceGetAccountInfoHeaders, }, default: { bodyMapper: StorageError, headersMapper: ServiceGetAccountInfoExceptionHeaders, }, }, queryParameters: [ comp, timeoutInSeconds, restype1, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ], isXML: true, serializer: xmlSerializer$5, }; const submitBatchOperationSpec$1 = { path: "/", httpMethod: "POST", responses: { 202: { bodyMapper: { type: { name: "Stream" }, serializedName: "parsedResponse", }, headersMapper: ServiceSubmitBatchHeaders, }, default: { bodyMapper: StorageError, headersMapper: ServiceSubmitBatchExceptionHeaders, }, }, requestBody: body, queryParameters: [timeoutInSeconds, comp4], urlParameters: [url], headerParameters: [ accept, version, requestId, contentLength, multipartContentType, ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "xml", serializer: xmlSerializer$5, }; const filterBlobsOperationSpec$1 = { path: "/", httpMethod: "GET", responses: { 200: { bodyMapper: FilterBlobSegment, headersMapper: ServiceFilterBlobsHeaders, }, default: { bodyMapper: StorageError, headersMapper: ServiceFilterBlobsExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, marker, maxPageSize, comp5, where, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ], isXML: true, serializer: xmlSerializer$5, }; /* * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ /** Class containing Container operations. */ class ContainerImpl { /** * Initialize a new instance of the class Container class. * @param client Reference to the service client */ constructor(client) { this.client = client; } /** * creates a new container under the specified account. If the container with the same name already * exists, the operation fails * @param options The options parameters. */ create(options) { return this.client.sendOperationRequest({ options }, createOperationSpec$2); } /** * returns all user-defined metadata and system properties for the specified container. The data * returned does not include the container's list of blobs * @param options The options parameters. */ getProperties(options) { return this.client.sendOperationRequest({ options }, getPropertiesOperationSpec$1); } /** * operation marks the specified container for deletion. The container and any blobs contained within * it are later deleted during garbage collection * @param options The options parameters. */ delete(options) { return this.client.sendOperationRequest({ options }, deleteOperationSpec$1); } /** * operation sets one or more user-defined name-value pairs for the specified container. * @param options The options parameters. */ setMetadata(options) { return this.client.sendOperationRequest({ options }, setMetadataOperationSpec$1); } /** * gets the permissions for the specified container. The permissions indicate whether container data * may be accessed publicly. * @param options The options parameters. */ getAccessPolicy(options) { return this.client.sendOperationRequest({ options }, getAccessPolicyOperationSpec); } /** * sets the permissions for the specified container. The permissions indicate whether blobs in a * container may be accessed publicly. * @param options The options parameters. */ setAccessPolicy(options) { return this.client.sendOperationRequest({ options }, setAccessPolicyOperationSpec); } /** * Restores a previously-deleted container. * @param options The options parameters. */ restore(options) { return this.client.sendOperationRequest({ options }, restoreOperationSpec); } /** * Renames an existing container. * @param sourceContainerName Required. Specifies the name of the container to rename. * @param options The options parameters. */ rename(sourceContainerName, options) { return this.client.sendOperationRequest({ sourceContainerName, options }, renameOperationSpec); } /** * The Batch operation allows multiple API calls to be embedded into a single HTTP request. * @param contentLength The length of the request. * @param multipartContentType Required. The value of this header must be multipart/mixed with a batch * boundary. Example header value: multipart/mixed; boundary=batch_ * @param body Initial data * @param options The options parameters. */ submitBatch(contentLength, multipartContentType, body, options) { return this.client.sendOperationRequest({ contentLength, multipartContentType, body, options }, submitBatchOperationSpec); } /** * The Filter Blobs operation enables callers to list blobs in a container whose tags match a given * search expression. Filter blobs searches within the given container. * @param options The options parameters. */ filterBlobs(options) { return this.client.sendOperationRequest({ options }, filterBlobsOperationSpec); } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param options The options parameters. */ acquireLease(options) { return this.client.sendOperationRequest({ options }, acquireLeaseOperationSpec$1); } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ releaseLease(leaseId, options) { return this.client.sendOperationRequest({ leaseId, options }, releaseLeaseOperationSpec$1); } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ renewLease(leaseId, options) { return this.client.sendOperationRequest({ leaseId, options }, renewLeaseOperationSpec$1); } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param options The options parameters. */ breakLease(options) { return this.client.sendOperationRequest({ options }, breakLeaseOperationSpec$1); } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param leaseId Specifies the current lease ID on the resource. * @param proposedLeaseId Proposed lease ID, in a GUID string format. The Blob service returns 400 * (Invalid request) if the proposed lease ID is not in the correct format. See Guid Constructor * (String) for a list of valid GUID string formats. * @param options The options parameters. */ changeLease(leaseId, proposedLeaseId, options) { return this.client.sendOperationRequest({ leaseId, proposedLeaseId, options }, changeLeaseOperationSpec$1); } /** * [Update] The List Blobs operation returns a list of the blobs under the specified container * @param options The options parameters. */ listBlobFlatSegment(options) { return this.client.sendOperationRequest({ options }, listBlobFlatSegmentOperationSpec); } /** * [Update] The List Blobs operation returns a list of the blobs under the specified container * @param delimiter When the request includes this parameter, the operation returns a BlobPrefix * element in the response body that acts as a placeholder for all blobs whose names begin with the * same substring up to the appearance of the delimiter character. The delimiter may be a single * character or a string. * @param options The options parameters. */ listBlobHierarchySegment(delimiter, options) { return this.client.sendOperationRequest({ delimiter, options }, listBlobHierarchySegmentOperationSpec); } /** * Returns the sku name and account kind * @param options The options parameters. */ getAccountInfo(options) { return this.client.sendOperationRequest({ options }, getAccountInfoOperationSpec$1); } } // Operation Specifications const xmlSerializer$4 = coreClient__namespace.createSerializer(Mappers, /* isXml */ true); const createOperationSpec$2 = { path: "/{containerName}", httpMethod: "PUT", responses: { 201: { headersMapper: ContainerCreateHeaders, }, default: { bodyMapper: StorageError, headersMapper: ContainerCreateExceptionHeaders, }, }, queryParameters: [timeoutInSeconds, restype2], urlParameters: [url], headerParameters: [ version, requestId, accept1, metadata, access, defaultEncryptionScope, preventEncryptionScopeOverride, ], isXML: true, serializer: xmlSerializer$4, }; const getPropertiesOperationSpec$1 = { path: "/{containerName}", httpMethod: "GET", responses: { 200: { headersMapper: ContainerGetPropertiesHeaders, }, default: { bodyMapper: StorageError, headersMapper: ContainerGetPropertiesExceptionHeaders, }, }, queryParameters: [timeoutInSeconds, restype2], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ], isXML: true, serializer: xmlSerializer$4, }; const deleteOperationSpec$1 = { path: "/{containerName}", httpMethod: "DELETE", responses: { 202: { headersMapper: ContainerDeleteHeaders, }, default: { bodyMapper: StorageError, headersMapper: ContainerDeleteExceptionHeaders, }, }, queryParameters: [timeoutInSeconds, restype2], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifModifiedSince, ifUnmodifiedSince, ], isXML: true, serializer: xmlSerializer$4, }; const setMetadataOperationSpec$1 = { path: "/{containerName}", httpMethod: "PUT", responses: { 200: { headersMapper: ContainerSetMetadataHeaders, }, default: { bodyMapper: StorageError, headersMapper: ContainerSetMetadataExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, restype2, comp6, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, metadata, leaseId, ifModifiedSince, ], isXML: true, serializer: xmlSerializer$4, }; const getAccessPolicyOperationSpec = { path: "/{containerName}", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Composite", className: "SignedIdentifier" }, }, }, serializedName: "SignedIdentifiers", xmlName: "SignedIdentifiers", xmlIsWrapped: true, xmlElementName: "SignedIdentifier", }, headersMapper: ContainerGetAccessPolicyHeaders, }, default: { bodyMapper: StorageError, headersMapper: ContainerGetAccessPolicyExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, restype2, comp7, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ], isXML: true, serializer: xmlSerializer$4, }; const setAccessPolicyOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { 200: { headersMapper: ContainerSetAccessPolicyHeaders, }, default: { bodyMapper: StorageError, headersMapper: ContainerSetAccessPolicyExceptionHeaders, }, }, requestBody: containerAcl, queryParameters: [ timeoutInSeconds, restype2, comp7, ], urlParameters: [url], headerParameters: [ contentType, accept, version, requestId, access, leaseId, ifModifiedSince, ifUnmodifiedSince, ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "xml", serializer: xmlSerializer$4, }; const restoreOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { 201: { headersMapper: ContainerRestoreHeaders, }, default: { bodyMapper: StorageError, headersMapper: ContainerRestoreExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, restype2, comp8, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, deletedContainerName, deletedContainerVersion, ], isXML: true, serializer: xmlSerializer$4, }; const renameOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { 200: { headersMapper: ContainerRenameHeaders, }, default: { bodyMapper: StorageError, headersMapper: ContainerRenameExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, restype2, comp9, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, sourceContainerName, sourceLeaseId, ], isXML: true, serializer: xmlSerializer$4, }; const submitBatchOperationSpec = { path: "/{containerName}", httpMethod: "POST", responses: { 202: { bodyMapper: { type: { name: "Stream" }, serializedName: "parsedResponse", }, headersMapper: ContainerSubmitBatchHeaders, }, default: { bodyMapper: StorageError, headersMapper: ContainerSubmitBatchExceptionHeaders, }, }, requestBody: body, queryParameters: [ timeoutInSeconds, comp4, restype2, ], urlParameters: [url], headerParameters: [ accept, version, requestId, contentLength, multipartContentType, ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "xml", serializer: xmlSerializer$4, }; const filterBlobsOperationSpec = { path: "/{containerName}", httpMethod: "GET", responses: { 200: { bodyMapper: FilterBlobSegment, headersMapper: ContainerFilterBlobsHeaders, }, default: { bodyMapper: StorageError, headersMapper: ContainerFilterBlobsExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, marker, maxPageSize, comp5, where, restype2, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ], isXML: true, serializer: xmlSerializer$4, }; const acquireLeaseOperationSpec$1 = { path: "/{containerName}", httpMethod: "PUT", responses: { 201: { headersMapper: ContainerAcquireLeaseHeaders, }, default: { bodyMapper: StorageError, headersMapper: ContainerAcquireLeaseExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, restype2, comp10, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, action, duration, proposedLeaseId, ], isXML: true, serializer: xmlSerializer$4, }; const releaseLeaseOperationSpec$1 = { path: "/{containerName}", httpMethod: "PUT", responses: { 200: { headersMapper: ContainerReleaseLeaseHeaders, }, default: { bodyMapper: StorageError, headersMapper: ContainerReleaseLeaseExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, restype2, comp10, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, action1, leaseId1, ], isXML: true, serializer: xmlSerializer$4, }; const renewLeaseOperationSpec$1 = { path: "/{containerName}", httpMethod: "PUT", responses: { 200: { headersMapper: ContainerRenewLeaseHeaders, }, default: { bodyMapper: StorageError, headersMapper: ContainerRenewLeaseExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, restype2, comp10, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, leaseId1, action2, ], isXML: true, serializer: xmlSerializer$4, }; const breakLeaseOperationSpec$1 = { path: "/{containerName}", httpMethod: "PUT", responses: { 202: { headersMapper: ContainerBreakLeaseHeaders, }, default: { bodyMapper: StorageError, headersMapper: ContainerBreakLeaseExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, restype2, comp10, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, action3, breakPeriod, ], isXML: true, serializer: xmlSerializer$4, }; const changeLeaseOperationSpec$1 = { path: "/{containerName}", httpMethod: "PUT", responses: { 200: { headersMapper: ContainerChangeLeaseHeaders, }, default: { bodyMapper: StorageError, headersMapper: ContainerChangeLeaseExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, restype2, comp10, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, leaseId1, action4, proposedLeaseId1, ], isXML: true, serializer: xmlSerializer$4, }; const listBlobFlatSegmentOperationSpec = { path: "/{containerName}", httpMethod: "GET", responses: { 200: { bodyMapper: ListBlobsFlatSegmentResponse, headersMapper: ContainerListBlobFlatSegmentHeaders, }, default: { bodyMapper: StorageError, headersMapper: ContainerListBlobFlatSegmentExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, comp2, prefix, marker, maxPageSize, restype2, include1, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ], isXML: true, serializer: xmlSerializer$4, }; const listBlobHierarchySegmentOperationSpec = { path: "/{containerName}", httpMethod: "GET", responses: { 200: { bodyMapper: ListBlobsHierarchySegmentResponse, headersMapper: ContainerListBlobHierarchySegmentHeaders, }, default: { bodyMapper: StorageError, headersMapper: ContainerListBlobHierarchySegmentExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, comp2, prefix, marker, maxPageSize, restype2, include1, delimiter, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ], isXML: true, serializer: xmlSerializer$4, }; const getAccountInfoOperationSpec$1 = { path: "/{containerName}", httpMethod: "GET", responses: { 200: { headersMapper: ContainerGetAccountInfoHeaders, }, default: { bodyMapper: StorageError, headersMapper: ContainerGetAccountInfoExceptionHeaders, }, }, queryParameters: [ comp, timeoutInSeconds, restype1, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ], isXML: true, serializer: xmlSerializer$4, }; /* * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ /** Class containing Blob operations. */ class BlobImpl { /** * Initialize a new instance of the class Blob class. * @param client Reference to the service client */ constructor(client) { this.client = client; } /** * The Download operation reads or downloads a blob from the system, including its metadata and * properties. You can also call Download to read a snapshot. * @param options The options parameters. */ download(options) { return this.client.sendOperationRequest({ options }, downloadOperationSpec); } /** * The Get Properties operation returns all user-defined metadata, standard HTTP properties, and system * properties for the blob. It does not return the content of the blob. * @param options The options parameters. */ getProperties(options) { return this.client.sendOperationRequest({ options }, getPropertiesOperationSpec); } /** * If the storage account's soft delete feature is disabled then, when a blob is deleted, it is * permanently removed from the storage account. If the storage account's soft delete feature is * enabled, then, when a blob is deleted, it is marked for deletion and becomes inaccessible * immediately. However, the blob service retains the blob or snapshot for the number of days specified * by the DeleteRetentionPolicy section of [Storage service properties] * (Set-Blob-Service-Properties.md). After the specified number of days has passed, the blob's data is * permanently removed from the storage account. Note that you continue to be charged for the * soft-deleted blob's storage until it is permanently removed. Use the List Blobs API and specify the * "include=deleted" query parameter to discover which blobs and snapshots have been soft deleted. You * can then use the Undelete Blob API to restore a soft-deleted blob. All other operations on a * soft-deleted blob or snapshot causes the service to return an HTTP status code of 404 * (ResourceNotFound). * @param options The options parameters. */ delete(options) { return this.client.sendOperationRequest({ options }, deleteOperationSpec); } /** * Undelete a blob that was previously soft deleted * @param options The options parameters. */ undelete(options) { return this.client.sendOperationRequest({ options }, undeleteOperationSpec); } /** * Sets the time a blob will expire and be deleted. * @param expiryOptions Required. Indicates mode of the expiry time * @param options The options parameters. */ setExpiry(expiryOptions, options) { return this.client.sendOperationRequest({ expiryOptions, options }, setExpiryOperationSpec); } /** * The Set HTTP Headers operation sets system properties on the blob * @param options The options parameters. */ setHttpHeaders(options) { return this.client.sendOperationRequest({ options }, setHttpHeadersOperationSpec); } /** * The Set Immutability Policy operation sets the immutability policy on the blob * @param options The options parameters. */ setImmutabilityPolicy(options) { return this.client.sendOperationRequest({ options }, setImmutabilityPolicyOperationSpec); } /** * The Delete Immutability Policy operation deletes the immutability policy on the blob * @param options The options parameters. */ deleteImmutabilityPolicy(options) { return this.client.sendOperationRequest({ options }, deleteImmutabilityPolicyOperationSpec); } /** * The Set Legal Hold operation sets a legal hold on the blob. * @param legalHold Specified if a legal hold should be set on the blob. * @param options The options parameters. */ setLegalHold(legalHold, options) { return this.client.sendOperationRequest({ legalHold, options }, setLegalHoldOperationSpec); } /** * The Set Blob Metadata operation sets user-defined metadata for the specified blob as one or more * name-value pairs * @param options The options parameters. */ setMetadata(options) { return this.client.sendOperationRequest({ options }, setMetadataOperationSpec); } /** * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete * operations * @param options The options parameters. */ acquireLease(options) { return this.client.sendOperationRequest({ options }, acquireLeaseOperationSpec); } /** * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete * operations * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ releaseLease(leaseId, options) { return this.client.sendOperationRequest({ leaseId, options }, releaseLeaseOperationSpec); } /** * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete * operations * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ renewLease(leaseId, options) { return this.client.sendOperationRequest({ leaseId, options }, renewLeaseOperationSpec); } /** * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete * operations * @param leaseId Specifies the current lease ID on the resource. * @param proposedLeaseId Proposed lease ID, in a GUID string format. The Blob service returns 400 * (Invalid request) if the proposed lease ID is not in the correct format. See Guid Constructor * (String) for a list of valid GUID string formats. * @param options The options parameters. */ changeLease(leaseId, proposedLeaseId, options) { return this.client.sendOperationRequest({ leaseId, proposedLeaseId, options }, changeLeaseOperationSpec); } /** * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete * operations * @param options The options parameters. */ breakLease(options) { return this.client.sendOperationRequest({ options }, breakLeaseOperationSpec); } /** * The Create Snapshot operation creates a read-only snapshot of a blob * @param options The options parameters. */ createSnapshot(options) { return this.client.sendOperationRequest({ options }, createSnapshotOperationSpec); } /** * The Start Copy From URL operation copies a blob or an internet resource to a new blob. * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to * 2 KB in length that specifies a page blob snapshot. 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. * @param options The options parameters. */ startCopyFromURL(copySource, options) { return this.client.sendOperationRequest({ copySource, options }, startCopyFromURLOperationSpec); } /** * The 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. * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to * 2 KB in length that specifies a page blob snapshot. 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. * @param options The options parameters. */ copyFromURL(copySource, options) { return this.client.sendOperationRequest({ copySource, options }, copyFromURLOperationSpec); } /** * The Abort Copy From URL operation aborts a pending Copy From URL operation, and leaves a destination * blob with zero length and full metadata. * @param copyId The copy identifier provided in the x-ms-copy-id header of the original Copy Blob * operation. * @param options The options parameters. */ abortCopyFromURL(copyId, options) { return this.client.sendOperationRequest({ copyId, options }, abortCopyFromURLOperationSpec); } /** * The Set Tier operation 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. * @param tier Indicates the tier to be set on the blob. * @param options The options parameters. */ setTier(tier, options) { return this.client.sendOperationRequest({ tier, options }, setTierOperationSpec); } /** * Returns the sku name and account kind * @param options The options parameters. */ getAccountInfo(options) { return this.client.sendOperationRequest({ options }, getAccountInfoOperationSpec); } /** * The Query operation enables users to select/project on blob data by providing simple query * expressions. * @param options The options parameters. */ query(options) { return this.client.sendOperationRequest({ options }, queryOperationSpec); } /** * The Get Tags operation enables users to get the tags associated with a blob. * @param options The options parameters. */ getTags(options) { return this.client.sendOperationRequest({ options }, getTagsOperationSpec); } /** * The Set Tags operation enables users to set tags on a blob. * @param options The options parameters. */ setTags(options) { return this.client.sendOperationRequest({ options }, setTagsOperationSpec); } } // Operation Specifications const xmlSerializer$3 = coreClient__namespace.createSerializer(Mappers, /* isXml */ true); const downloadOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Stream" }, serializedName: "parsedResponse", }, headersMapper: BlobDownloadHeaders, }, 206: { bodyMapper: { type: { name: "Stream" }, serializedName: "parsedResponse", }, headersMapper: BlobDownloadHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobDownloadExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, snapshot, versionId, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifModifiedSince, ifUnmodifiedSince, range, rangeGetContentMD5, rangeGetContentCRC64, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, ], isXML: true, serializer: xmlSerializer$3, }; const getPropertiesOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "HEAD", responses: { 200: { headersMapper: BlobGetPropertiesHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobGetPropertiesExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, snapshot, versionId, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, ], isXML: true, serializer: xmlSerializer$3, }; const deleteOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "DELETE", responses: { 202: { headersMapper: BlobDeleteHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobDeleteExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, snapshot, versionId, blobDeleteType, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags, deleteSnapshots, ], isXML: true, serializer: xmlSerializer$3, }; const undeleteOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: BlobUndeleteHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobUndeleteExceptionHeaders, }, }, queryParameters: [timeoutInSeconds, comp8], urlParameters: [url], headerParameters: [ version, requestId, accept1, ], isXML: true, serializer: xmlSerializer$3, }; const setExpiryOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: BlobSetExpiryHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobSetExpiryExceptionHeaders, }, }, queryParameters: [timeoutInSeconds, comp11], urlParameters: [url], headerParameters: [ version, requestId, accept1, expiryOptions, expiresOn, ], isXML: true, serializer: xmlSerializer$3, }; const setHttpHeadersOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: BlobSetHttpHeadersHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobSetHttpHeadersExceptionHeaders, }, }, queryParameters: [comp, timeoutInSeconds], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags, blobCacheControl, blobContentType, blobContentMD5, blobContentEncoding, blobContentLanguage, blobContentDisposition, ], isXML: true, serializer: xmlSerializer$3, }; const setImmutabilityPolicyOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: BlobSetImmutabilityPolicyHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobSetImmutabilityPolicyExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, snapshot, versionId, comp12, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifUnmodifiedSince, immutabilityPolicyExpiry, immutabilityPolicyMode, ], isXML: true, serializer: xmlSerializer$3, }; const deleteImmutabilityPolicyOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "DELETE", responses: { 200: { headersMapper: BlobDeleteImmutabilityPolicyHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobDeleteImmutabilityPolicyExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, snapshot, versionId, comp12, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ], isXML: true, serializer: xmlSerializer$3, }; const setLegalHoldOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: BlobSetLegalHoldHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobSetLegalHoldExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, snapshot, versionId, comp13, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, legalHold, ], isXML: true, serializer: xmlSerializer$3, }; const setMetadataOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: BlobSetMetadataHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobSetMetadataExceptionHeaders, }, }, queryParameters: [timeoutInSeconds, comp6], urlParameters: [url], headerParameters: [ version, requestId, accept1, metadata, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, encryptionScope, ], isXML: true, serializer: xmlSerializer$3, }; const acquireLeaseOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: BlobAcquireLeaseHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobAcquireLeaseExceptionHeaders, }, }, queryParameters: [timeoutInSeconds, comp10], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, action, duration, proposedLeaseId, ifMatch, ifNoneMatch, ifTags, ], isXML: true, serializer: xmlSerializer$3, }; const releaseLeaseOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: BlobReleaseLeaseHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobReleaseLeaseExceptionHeaders, }, }, queryParameters: [timeoutInSeconds, comp10], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, action1, leaseId1, ifMatch, ifNoneMatch, ifTags, ], isXML: true, serializer: xmlSerializer$3, }; const renewLeaseOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: BlobRenewLeaseHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobRenewLeaseExceptionHeaders, }, }, queryParameters: [timeoutInSeconds, comp10], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, leaseId1, action2, ifMatch, ifNoneMatch, ifTags, ], isXML: true, serializer: xmlSerializer$3, }; const changeLeaseOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: BlobChangeLeaseHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobChangeLeaseExceptionHeaders, }, }, queryParameters: [timeoutInSeconds, comp10], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, leaseId1, action4, proposedLeaseId1, ifMatch, ifNoneMatch, ifTags, ], isXML: true, serializer: xmlSerializer$3, }; const breakLeaseOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 202: { headersMapper: BlobBreakLeaseHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobBreakLeaseExceptionHeaders, }, }, queryParameters: [timeoutInSeconds, comp10], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, action3, breakPeriod, ifMatch, ifNoneMatch, ifTags, ], isXML: true, serializer: xmlSerializer$3, }; const createSnapshotOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: BlobCreateSnapshotHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobCreateSnapshotExceptionHeaders, }, }, queryParameters: [timeoutInSeconds, comp14], urlParameters: [url], headerParameters: [ version, requestId, accept1, metadata, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, encryptionScope, ], isXML: true, serializer: xmlSerializer$3, }; const startCopyFromURLOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 202: { headersMapper: BlobStartCopyFromURLHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobStartCopyFromURLExceptionHeaders, }, }, queryParameters: [timeoutInSeconds], urlParameters: [url], headerParameters: [ version, requestId, accept1, metadata, leaseId, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags, immutabilityPolicyExpiry, immutabilityPolicyMode, tier, rehydratePriority, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, sourceIfTags, copySource, blobTagsString, sealBlob, legalHold1, ], isXML: true, serializer: xmlSerializer$3, }; const copyFromURLOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 202: { headersMapper: BlobCopyFromURLHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobCopyFromURLExceptionHeaders, }, }, queryParameters: [timeoutInSeconds], urlParameters: [url], headerParameters: [ version, requestId, accept1, metadata, leaseId, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags, immutabilityPolicyExpiry, immutabilityPolicyMode, encryptionScope, tier, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, copySource, blobTagsString, legalHold1, xMsRequiresSync, sourceContentMD5, copySourceAuthorization, copySourceTags, ], isXML: true, serializer: xmlSerializer$3, }; const abortCopyFromURLOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 204: { headersMapper: BlobAbortCopyFromURLHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobAbortCopyFromURLExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, comp15, copyId, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, copyActionAbortConstant, ], isXML: true, serializer: xmlSerializer$3, }; const setTierOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: BlobSetTierHeaders, }, 202: { headersMapper: BlobSetTierHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobSetTierExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, snapshot, versionId, comp16, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifTags, rehydratePriority, tier1, ], isXML: true, serializer: xmlSerializer$3, }; const getAccountInfoOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { 200: { headersMapper: BlobGetAccountInfoHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobGetAccountInfoExceptionHeaders, }, }, queryParameters: [ comp, timeoutInSeconds, restype1, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ], isXML: true, serializer: xmlSerializer$3, }; const queryOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "POST", responses: { 200: { bodyMapper: { type: { name: "Stream" }, serializedName: "parsedResponse", }, headersMapper: BlobQueryHeaders, }, 206: { bodyMapper: { type: { name: "Stream" }, serializedName: "parsedResponse", }, headersMapper: BlobQueryHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobQueryExceptionHeaders, }, }, requestBody: queryRequest, queryParameters: [ timeoutInSeconds, snapshot, comp17, ], urlParameters: [url], headerParameters: [ contentType, accept, version, requestId, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "xml", serializer: xmlSerializer$3, }; const getTagsOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { 200: { bodyMapper: BlobTags, headersMapper: BlobGetTagsHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobGetTagsExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, snapshot, versionId, comp18, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifTags, ], isXML: true, serializer: xmlSerializer$3, }; const setTagsOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 204: { headersMapper: BlobSetTagsHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlobSetTagsExceptionHeaders, }, }, requestBody: tags, queryParameters: [ timeoutInSeconds, versionId, comp18, ], urlParameters: [url], headerParameters: [ contentType, accept, version, requestId, leaseId, ifTags, transactionalContentMD5, transactionalContentCrc64, ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "xml", serializer: xmlSerializer$3, }; /* * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ /** Class containing PageBlob operations. */ class PageBlobImpl { /** * Initialize a new instance of the class PageBlob class. * @param client Reference to the service client */ constructor(client) { this.client = client; } /** * The Create operation creates a new page blob. * @param contentLength The length of the request. * @param blobContentLength This header specifies the maximum size for the page blob, up to 1 TB. The * page blob size must be aligned to a 512-byte boundary. * @param options The options parameters. */ create(contentLength, blobContentLength, options) { return this.client.sendOperationRequest({ contentLength, blobContentLength, options }, createOperationSpec$1); } /** * The Upload Pages operation writes a range of pages to a page blob * @param contentLength The length of the request. * @param body Initial data * @param options The options parameters. */ uploadPages(contentLength, body, options) { return this.client.sendOperationRequest({ contentLength, body, options }, uploadPagesOperationSpec); } /** * The Clear Pages operation clears a set of pages from a page blob * @param contentLength The length of the request. * @param options The options parameters. */ clearPages(contentLength, options) { return this.client.sendOperationRequest({ contentLength, options }, clearPagesOperationSpec); } /** * The Upload Pages operation writes a range of pages to a page blob where the contents are read from a * URL * @param sourceUrl Specify a URL to the copy source. * @param sourceRange Bytes of source data in the specified range. The length of this range should * match the ContentLength header and x-ms-range/Range destination range header. * @param contentLength The length of the request. * @param range The range of bytes to which the source range would be written. The range should be 512 * aligned and range-end is required. * @param options The options parameters. */ uploadPagesFromURL(sourceUrl, sourceRange, contentLength, range, options) { return this.client.sendOperationRequest({ sourceUrl, sourceRange, contentLength, range, options }, uploadPagesFromURLOperationSpec); } /** * The Get Page Ranges operation returns the list of valid page ranges for a page blob or snapshot of a * page blob * @param options The options parameters. */ getPageRanges(options) { return this.client.sendOperationRequest({ options }, getPageRangesOperationSpec); } /** * The Get Page Ranges Diff operation returns the list of valid page ranges for a page blob that were * changed between target blob and previous snapshot. * @param options The options parameters. */ getPageRangesDiff(options) { return this.client.sendOperationRequest({ options }, getPageRangesDiffOperationSpec); } /** * Resize the Blob * @param blobContentLength This header specifies the maximum size for the page blob, up to 1 TB. The * page blob size must be aligned to a 512-byte boundary. * @param options The options parameters. */ resize(blobContentLength, options) { return this.client.sendOperationRequest({ blobContentLength, options }, resizeOperationSpec); } /** * Update the sequence number of the blob * @param sequenceNumberAction Required if the x-ms-blob-sequence-number header is set for the request. * This property applies to page blobs only. This property indicates how the service should modify the * blob's sequence number * @param options The options parameters. */ updateSequenceNumber(sequenceNumberAction, options) { return this.client.sendOperationRequest({ sequenceNumberAction, options }, updateSequenceNumberOperationSpec); } /** * The Copy Incremental operation copies a snapshot of the source page blob to a destination 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. This API is supported since REST version * 2016-05-31. * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to * 2 KB in length that specifies a page blob snapshot. 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. * @param options The options parameters. */ copyIncremental(copySource, options) { return this.client.sendOperationRequest({ copySource, options }, copyIncrementalOperationSpec); } } // Operation Specifications const xmlSerializer$2 = coreClient__namespace.createSerializer(Mappers, /* isXml */ true); const createOperationSpec$1 = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: PageBlobCreateHeaders, }, default: { bodyMapper: StorageError, headersMapper: PageBlobCreateExceptionHeaders, }, }, queryParameters: [timeoutInSeconds], urlParameters: [url], headerParameters: [ version, requestId, accept1, contentLength, metadata, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, blobCacheControl, blobContentType, blobContentMD5, blobContentEncoding, blobContentLanguage, blobContentDisposition, immutabilityPolicyExpiry, immutabilityPolicyMode, encryptionScope, tier, blobTagsString, legalHold1, blobType, blobContentLength, blobSequenceNumber, ], isXML: true, serializer: xmlSerializer$2, }; const uploadPagesOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: PageBlobUploadPagesHeaders, }, default: { bodyMapper: StorageError, headersMapper: PageBlobUploadPagesExceptionHeaders, }, }, requestBody: body1, queryParameters: [timeoutInSeconds, comp19], urlParameters: [url], headerParameters: [ version, requestId, contentLength, leaseId, ifModifiedSince, ifUnmodifiedSince, range, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, encryptionScope, transactionalContentMD5, transactionalContentCrc64, contentType1, accept2, pageWrite, ifSequenceNumberLessThanOrEqualTo, ifSequenceNumberLessThan, ifSequenceNumberEqualTo, ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "binary", serializer: xmlSerializer$2, }; const clearPagesOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: PageBlobClearPagesHeaders, }, default: { bodyMapper: StorageError, headersMapper: PageBlobClearPagesExceptionHeaders, }, }, queryParameters: [timeoutInSeconds, comp19], urlParameters: [url], headerParameters: [ version, requestId, accept1, contentLength, leaseId, ifModifiedSince, ifUnmodifiedSince, range, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, encryptionScope, ifSequenceNumberLessThanOrEqualTo, ifSequenceNumberLessThan, ifSequenceNumberEqualTo, pageWrite1, ], isXML: true, serializer: xmlSerializer$2, }; const uploadPagesFromURLOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: PageBlobUploadPagesFromURLHeaders, }, default: { bodyMapper: StorageError, headersMapper: PageBlobUploadPagesFromURLExceptionHeaders, }, }, queryParameters: [timeoutInSeconds, comp19], urlParameters: [url], headerParameters: [ version, requestId, accept1, contentLength, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, encryptionScope, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, sourceContentMD5, copySourceAuthorization, pageWrite, ifSequenceNumberLessThanOrEqualTo, ifSequenceNumberLessThan, ifSequenceNumberEqualTo, sourceUrl, sourceRange, sourceContentCrc64, range1, ], isXML: true, serializer: xmlSerializer$2, }; const getPageRangesOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { 200: { bodyMapper: PageList, headersMapper: PageBlobGetPageRangesHeaders, }, default: { bodyMapper: StorageError, headersMapper: PageBlobGetPageRangesExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, marker, maxPageSize, snapshot, comp20, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifModifiedSince, ifUnmodifiedSince, range, ifMatch, ifNoneMatch, ifTags, ], isXML: true, serializer: xmlSerializer$2, }; const getPageRangesDiffOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { 200: { bodyMapper: PageList, headersMapper: PageBlobGetPageRangesDiffHeaders, }, default: { bodyMapper: StorageError, headersMapper: PageBlobGetPageRangesDiffExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, marker, maxPageSize, snapshot, comp20, prevsnapshot, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifModifiedSince, ifUnmodifiedSince, range, ifMatch, ifNoneMatch, ifTags, prevSnapshotUrl, ], isXML: true, serializer: xmlSerializer$2, }; const resizeOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: PageBlobResizeHeaders, }, default: { bodyMapper: StorageError, headersMapper: PageBlobResizeExceptionHeaders, }, }, queryParameters: [comp, timeoutInSeconds], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, encryptionScope, blobContentLength, ], isXML: true, serializer: xmlSerializer$2, }; const updateSequenceNumberOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: PageBlobUpdateSequenceNumberHeaders, }, default: { bodyMapper: StorageError, headersMapper: PageBlobUpdateSequenceNumberExceptionHeaders, }, }, queryParameters: [comp, timeoutInSeconds], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags, blobSequenceNumber, sequenceNumberAction, ], isXML: true, serializer: xmlSerializer$2, }; const copyIncrementalOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 202: { headersMapper: PageBlobCopyIncrementalHeaders, }, default: { bodyMapper: StorageError, headersMapper: PageBlobCopyIncrementalExceptionHeaders, }, }, queryParameters: [timeoutInSeconds, comp21], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags, copySource, ], isXML: true, serializer: xmlSerializer$2, }; /* * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ /** Class containing AppendBlob operations. */ class AppendBlobImpl { /** * Initialize a new instance of the class AppendBlob class. * @param client Reference to the service client */ constructor(client) { this.client = client; } /** * The Create Append Blob operation creates a new append blob. * @param contentLength The length of the request. * @param options The options parameters. */ create(contentLength, options) { return this.client.sendOperationRequest({ contentLength, options }, createOperationSpec); } /** * The Append Block operation commits a new block of data to the end of an existing append blob. The * Append Block operation is permitted only if the blob was created with x-ms-blob-type set to * AppendBlob. Append Block is supported only on version 2015-02-21 version or later. * @param contentLength The length of the request. * @param body Initial data * @param options The options parameters. */ appendBlock(contentLength, body, options) { return this.client.sendOperationRequest({ contentLength, body, options }, appendBlockOperationSpec); } /** * 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. The Append Block operation is permitted only if the blob * was created with x-ms-blob-type set to AppendBlob. Append Block is supported only on version * 2015-02-21 version or later. * @param sourceUrl Specify a URL to the copy source. * @param contentLength The length of the request. * @param options The options parameters. */ appendBlockFromUrl(sourceUrl, contentLength, options) { return this.client.sendOperationRequest({ sourceUrl, contentLength, options }, appendBlockFromUrlOperationSpec); } /** * The Seal operation seals the Append Blob to make it read-only. Seal is supported only on version * 2019-12-12 version or later. * @param options The options parameters. */ seal(options) { return this.client.sendOperationRequest({ options }, sealOperationSpec); } } // Operation Specifications const xmlSerializer$1 = coreClient__namespace.createSerializer(Mappers, /* isXml */ true); const createOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: AppendBlobCreateHeaders, }, default: { bodyMapper: StorageError, headersMapper: AppendBlobCreateExceptionHeaders, }, }, queryParameters: [timeoutInSeconds], urlParameters: [url], headerParameters: [ version, requestId, accept1, contentLength, metadata, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, blobCacheControl, blobContentType, blobContentMD5, blobContentEncoding, blobContentLanguage, blobContentDisposition, immutabilityPolicyExpiry, immutabilityPolicyMode, encryptionScope, blobTagsString, legalHold1, blobType1, ], isXML: true, serializer: xmlSerializer$1, }; const appendBlockOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: AppendBlobAppendBlockHeaders, }, default: { bodyMapper: StorageError, headersMapper: AppendBlobAppendBlockExceptionHeaders, }, }, requestBody: body1, queryParameters: [timeoutInSeconds, comp22], urlParameters: [url], headerParameters: [ version, requestId, contentLength, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, encryptionScope, transactionalContentMD5, transactionalContentCrc64, contentType1, accept2, maxSize, appendPosition, ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "binary", serializer: xmlSerializer$1, }; const appendBlockFromUrlOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: AppendBlobAppendBlockFromUrlHeaders, }, default: { bodyMapper: StorageError, headersMapper: AppendBlobAppendBlockFromUrlExceptionHeaders, }, }, queryParameters: [timeoutInSeconds, comp22], urlParameters: [url], headerParameters: [ version, requestId, accept1, contentLength, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, encryptionScope, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, sourceContentMD5, copySourceAuthorization, transactionalContentMD5, sourceUrl, sourceContentCrc64, maxSize, appendPosition, sourceRange1, ], isXML: true, serializer: xmlSerializer$1, }; const sealOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: AppendBlobSealHeaders, }, default: { bodyMapper: StorageError, headersMapper: AppendBlobSealExceptionHeaders, }, }, queryParameters: [timeoutInSeconds, comp23], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, appendPosition, ], isXML: true, serializer: xmlSerializer$1, }; /* * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ /** Class containing BlockBlob operations. */ class BlockBlobImpl { /** * Initialize a new instance of the class BlockBlob class. * @param client Reference to the service client */ constructor(client) { this.client = client; } /** * The Upload Block Blob operation 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 with Put * Blob; the content of the existing blob is overwritten with the content of the new blob. To perform a * partial update of the content of a block blob, use the Put Block List operation. * @param contentLength The length of the request. * @param body Initial data * @param options The options parameters. */ upload(contentLength, body, options) { return this.client.sendOperationRequest({ contentLength, body, options }, uploadOperationSpec); } /** * The Put Blob from URL operation 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 the Put Block from URL API in conjunction with Put Block List. * @param contentLength The length of the request. * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to * 2 KB in length that specifies a page blob snapshot. 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. * @param options The options parameters. */ putBlobFromUrl(contentLength, copySource, options) { return this.client.sendOperationRequest({ contentLength, copySource, options }, putBlobFromUrlOperationSpec); } /** * The Stage Block operation creates a new block to be committed as part of a blob * @param blockId A valid Base64 string value that identifies the block. Prior to encoding, the string * must be less than or equal to 64 bytes in size. For a given blob, the length of the value specified * for the blockid parameter must be the same size for each block. * @param contentLength The length of the request. * @param body Initial data * @param options The options parameters. */ stageBlock(blockId, contentLength, body, options) { return this.client.sendOperationRequest({ blockId, contentLength, body, options }, stageBlockOperationSpec); } /** * The Stage Block operation creates a new block to be committed as part of a blob where the contents * are read from a URL. * @param blockId A valid Base64 string value that identifies the block. Prior to encoding, the string * must be less than or equal to 64 bytes in size. For a given blob, the length of the value specified * for the blockid parameter must be the same size for each block. * @param contentLength The length of the request. * @param sourceUrl Specify a URL to the copy source. * @param options The options parameters. */ stageBlockFromURL(blockId, contentLength, sourceUrl, options) { return this.client.sendOperationRequest({ blockId, contentLength, sourceUrl, options }, stageBlockFromURLOperationSpec); } /** * The Commit Block List operation 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 Put Block operation. You can call Put Block List to update a blob by uploading * only those blocks that have changed, then committing the new and existing blocks together. You can * do this by specifying whether to commit a block from the committed block list or from the * uncommitted block list, or to commit the most recently uploaded version of the block, whichever list * it may belong to. * @param blocks Blob Blocks. * @param options The options parameters. */ commitBlockList(blocks, options) { return this.client.sendOperationRequest({ blocks, options }, commitBlockListOperationSpec); } /** * The Get Block List operation retrieves the list of blocks that have been uploaded as part of a block * blob * @param listType Specifies whether to return the list of committed blocks, the list of uncommitted * blocks, or both lists together. * @param options The options parameters. */ getBlockList(listType, options) { return this.client.sendOperationRequest({ listType, options }, getBlockListOperationSpec); } } // Operation Specifications const xmlSerializer = coreClient__namespace.createSerializer(Mappers, /* isXml */ true); const uploadOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: BlockBlobUploadHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlockBlobUploadExceptionHeaders, }, }, requestBody: body1, queryParameters: [timeoutInSeconds], urlParameters: [url], headerParameters: [ version, requestId, contentLength, metadata, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, blobCacheControl, blobContentType, blobContentMD5, blobContentEncoding, blobContentLanguage, blobContentDisposition, immutabilityPolicyExpiry, immutabilityPolicyMode, encryptionScope, tier, blobTagsString, legalHold1, transactionalContentMD5, transactionalContentCrc64, contentType1, accept2, blobType2, ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "binary", serializer: xmlSerializer, }; const putBlobFromUrlOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: BlockBlobPutBlobFromUrlHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlockBlobPutBlobFromUrlExceptionHeaders, }, }, queryParameters: [timeoutInSeconds], urlParameters: [url], headerParameters: [ version, requestId, accept1, contentLength, metadata, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, blobCacheControl, blobContentType, blobContentMD5, blobContentEncoding, blobContentLanguage, blobContentDisposition, encryptionScope, tier, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, sourceIfTags, copySource, blobTagsString, sourceContentMD5, copySourceAuthorization, copySourceTags, transactionalContentMD5, blobType2, copySourceBlobProperties, ], isXML: true, serializer: xmlSerializer, }; const stageBlockOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: BlockBlobStageBlockHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlockBlobStageBlockExceptionHeaders, }, }, requestBody: body1, queryParameters: [ timeoutInSeconds, comp24, blockId, ], urlParameters: [url], headerParameters: [ version, requestId, contentLength, leaseId, encryptionKey, encryptionKeySha256, encryptionAlgorithm, encryptionScope, transactionalContentMD5, transactionalContentCrc64, contentType1, accept2, ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "binary", serializer: xmlSerializer, }; const stageBlockFromURLOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: BlockBlobStageBlockFromURLHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlockBlobStageBlockFromURLExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, comp24, blockId, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, contentLength, leaseId, encryptionKey, encryptionKeySha256, encryptionAlgorithm, encryptionScope, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, sourceContentMD5, copySourceAuthorization, sourceUrl, sourceContentCrc64, sourceRange1, ], isXML: true, serializer: xmlSerializer, }; const commitBlockListOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: BlockBlobCommitBlockListHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlockBlobCommitBlockListExceptionHeaders, }, }, requestBody: blocks, queryParameters: [timeoutInSeconds, comp25], urlParameters: [url], headerParameters: [ contentType, accept, version, requestId, metadata, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, blobCacheControl, blobContentType, blobContentMD5, blobContentEncoding, blobContentLanguage, blobContentDisposition, immutabilityPolicyExpiry, immutabilityPolicyMode, encryptionScope, tier, blobTagsString, legalHold1, transactionalContentMD5, transactionalContentCrc64, ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "xml", serializer: xmlSerializer, }; const getBlockListOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { 200: { bodyMapper: BlockList, headersMapper: BlockBlobGetBlockListHeaders, }, default: { bodyMapper: StorageError, headersMapper: BlockBlobGetBlockListExceptionHeaders, }, }, queryParameters: [ timeoutInSeconds, snapshot, comp25, listType, ], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifTags, ], isXML: true, serializer: xmlSerializer, }; /* * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ let StorageClient$1 = class StorageClient extends coreHttpCompat__namespace.ExtendedServiceClient { /** * Initializes a new instance of the StorageClient class. * @param url The URL of the service account, container, or blob that is the target of the desired * operation. * @param options The parameter options */ constructor(url, options) { var _a, _b; if (url === undefined) { throw new Error("'url' cannot be null"); } // Initializing default values for options if (!options) { options = {}; } const defaults = { requestContentType: "application/json; charset=utf-8", }; const packageDetails = `azsdk-js-azure-storage-blob/12.27.0`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` : `${packageDetails}`; const optionsWithDefaults = Object.assign(Object.assign(Object.assign({}, defaults), options), { userAgentOptions: { userAgentPrefix, }, endpoint: (_b = (_a = options.endpoint) !== null && _a !== void 0 ? _a : options.baseUri) !== null && _b !== void 0 ? _b : "{url}" }); super(optionsWithDefaults); // Parameter assignments this.url = url; // Assigning values to Constant parameters this.version = options.version || "2025-05-05"; this.service = new ServiceImpl(this); this.container = new ContainerImpl(this); this.blob = new BlobImpl(this); this.pageBlob = new PageBlobImpl(this); this.appendBlob = new AppendBlobImpl(this); this.blockBlob = new BlockBlobImpl(this); } }; // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * @internal */ class StorageContextClient extends StorageClient$1 { async sendOperationRequest(operationArguments, operationSpec) { const operationSpecToSend = Object.assign({}, operationSpec); if (operationSpecToSend.path === "/{containerName}" || operationSpecToSend.path === "/{containerName}/{blob}") { operationSpecToSend.path = ""; } return super.sendOperationRequest(operationArguments, operationSpecToSend); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * A StorageClient represents a based URL class for {@link BlobServiceClient}, {@link ContainerClient} * and etc. */ class StorageClient { /** * Creates an instance of StorageClient. * @param url - url to resource * @param pipeline - request policy pipeline. */ constructor(url, pipeline) { // URL should be encoded and only once, protocol layer shouldn't encode URL again this.url = escapeURLPath(url); this.accountName = getAccountNameFromUrl(url); this.pipeline = pipeline; this.storageClientContext = new StorageContextClient(this.url, getCoreClientOptions(pipeline)); this.isHttps = iEqual(getURLScheme(this.url) || "", "https"); this.credential = getCredentialFromPipeline(pipeline); // Override protocol layer's default content-type const storageClientContext = this.storageClientContext; storageClientContext.requestContentType = undefined; } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * Creates a span using the global tracer. * @internal */ const tracingClient = coreTracing.createTracingClient({ packageName: "@azure/storage-blob", packageVersion: SDK_VERSION, namespace: "Microsoft.Storage", }); // Copyright (c) Microsoft Corporation. // 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. */ class BlobSASPermissions { constructor() { /** * Specifies Read access granted. */ this.read = false; /** * Specifies Add access granted. */ this.add = false; /** * Specifies Create access granted. */ this.create = false; /** * Specifies Write access granted. */ this.write = false; /** * Specifies Delete access granted. */ this.delete = false; /** * Specifies Delete version access granted. */ this.deleteVersion = false; /** * Specfies Tag access granted. */ this.tag = false; /** * Specifies Move access granted. */ this.move = false; /** * Specifies Execute access granted. */ this.execute = false; /** * Specifies SetImmutabilityPolicy access granted. */ this.setImmutabilityPolicy = false; /** * Specifies that Permanent Delete is permitted. */ this.permanentDelete = 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. * * @param permissions - */ static parse(permissions) { const blobSASPermissions = new BlobSASPermissions(); for (const char of permissions) { 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; case "i": blobSASPermissions.setImmutabilityPolicy = true; break; case "y": blobSASPermissions.permanentDelete = true; break; default: throw new RangeError(`Invalid permission: ${char}`); } } return blobSASPermissions; } /** * Creates a {@link BlobSASPermissions} from a raw object which contains same keys as it * and boolean values for them. * * @param permissionLike - */ static from(permissionLike) { const 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; } if (permissionLike.setImmutabilityPolicy) { blobSASPermissions.setImmutabilityPolicy = true; } if (permissionLike.permanentDelete) { blobSASPermissions.permanentDelete = true; } return blobSASPermissions; } /** * Converts the given permissions to a string. Using this method will guarantee the permissions are in an * order accepted by the service. * * @returns A string which represents the BlobSASPermissions */ toString() { const 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"); } if (this.setImmutabilityPolicy) { permissions.push("i"); } if (this.permanentDelete) { permissions.push("y"); } return permissions.join(""); } } // Copyright (c) Microsoft Corporation. // 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. */ class ContainerSASPermissions { constructor() { /** * Specifies Read access granted. */ this.read = false; /** * Specifies Add access granted. */ this.add = false; /** * Specifies Create access granted. */ this.create = false; /** * Specifies Write access granted. */ this.write = false; /** * Specifies Delete access granted. */ this.delete = false; /** * Specifies Delete version access granted. */ this.deleteVersion = false; /** * Specifies List access granted. */ this.list = false; /** * Specfies Tag access granted. */ this.tag = false; /** * Specifies Move access granted. */ this.move = false; /** * Specifies Execute access granted. */ this.execute = false; /** * Specifies SetImmutabilityPolicy access granted. */ this.setImmutabilityPolicy = false; /** * Specifies that Permanent Delete is permitted. */ this.permanentDelete = false; /** * Specifies that Filter Blobs by Tags is permitted. */ this.filterByTags = 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. * * @param permissions - */ static parse(permissions) { const containerSASPermissions = new ContainerSASPermissions(); for (const char of permissions) { 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; case "i": containerSASPermissions.setImmutabilityPolicy = true; break; case "y": containerSASPermissions.permanentDelete = true; break; case "f": containerSASPermissions.filterByTags = true; break; default: throw new RangeError(`Invalid permission ${char}`); } } return containerSASPermissions; } /** * Creates a {@link ContainerSASPermissions} from a raw object which contains same keys as it * and boolean values for them. * * @param permissionLike - */ static from(permissionLike) { const 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; } if (permissionLike.setImmutabilityPolicy) { containerSASPermissions.setImmutabilityPolicy = true; } if (permissionLike.permanentDelete) { containerSASPermissions.permanentDelete = true; } if (permissionLike.filterByTags) { containerSASPermissions.filterByTags = true; } return containerSASPermissions; } /** * Converts the given permissions to a string. Using this method will guarantee the permissions are in an * order accepted by the service. * * The order of the characters should be as specified here to ensure correctness. * @see https://learn.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * */ toString() { const 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"); } if (this.setImmutabilityPolicy) { permissions.push("i"); } if (this.permanentDelete) { permissions.push("y"); } if (this.filterByTags) { permissions.push("f"); } return permissions.join(""); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * UserDelegationKeyCredential is only used for generation of user delegation SAS. * @see https://learn.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas */ class UserDelegationKeyCredential { /** * Creates an instance of UserDelegationKeyCredential. * @param accountName - * @param userDelegationKey - */ constructor(accountName, userDelegationKey) { this.accountName = accountName; this.userDelegationKey = userDelegationKey; this.key = Buffer.from(userDelegationKey.value, "base64"); } /** * Generates a hash signature for an HTTP request or for a SAS. * * @param stringToSign - */ computeHMACSHA256(stringToSign) { // console.log(`stringToSign: ${JSON.stringify(stringToSign)}`); return crypto.createHmac("sha256", this.key).update(stringToSign, "utf8").digest("base64"); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * Generate SasIPRange format string. For example: * * "8.8.8.8" or "1.1.1.1-255.255.255.255" * * @param ipRange - */ function ipRangeToString(ipRange) { return ipRange.end ? `${ipRange.start}-${ipRange.end}` : ipRange.start; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * Protocols for generated SAS. */ exports.SASProtocol = void 0; (function (SASProtocol) { /** * Protocol that allows HTTPS only */ SASProtocol["Https"] = "https"; /** * Protocol that allows both HTTPS and HTTP */ 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 {@link 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. */ class SASQueryParameters { /** * Optional. IP range allowed for this SAS. * * @readonly */ get ipRange() { if (this.ipRangeInner) { return { end: this.ipRangeInner.end, start: this.ipRangeInner.start, }; } return undefined; } constructor(version, signature, permissionsOrOptions, services, resourceTypes, protocol, startsOn, expiresOn, ipRange, identifier, resource, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType, userDelegationKey, preauthorizedAgentObjectId, correlationId, encryptionScope) { 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.encryptionScope = permissionsOrOptions.encryptionScope; 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.encryptionScope = encryptionScope; 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; } } } /** * Encodes all SAS query parameters into a string that can be appended to a URL. * */ toString() { const params = [ "sv", "ss", "srt", "spr", "st", "se", "sip", "si", "ses", "skoid", // Signed object ID "sktid", // Signed tenant ID "skt", // Signed key start time "ske", // Signed key expiry time "sks", // Signed key service "skv", // Signed key version "sr", "sp", "sig", "rscc", "rscd", "rsce", "rscl", "rsct", "saoid", "scid", ]; const queries = []; for (const param of params) { 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 "ses": this.tryAppendQueryParameter(queries, param, this.encryptionScope); 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("&"); } /** * A private helper method used to filter and append query key/value pairs into an array. * * @param queries - * @param key - * @param value - */ tryAppendQueryParameter(queries, key, value) { if (!value) { return; } key = encodeURIComponent(key); value = encodeURIComponent(value); if (key.length > 0 && value.length > 0) { queries.push(`${key}=${value}`); } } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. function generateBlobSASQueryParameters(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { return generateBlobSASQueryParametersInternal(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName).sasQueryParameters; } function generateBlobSASQueryParametersInternal(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { const version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; const sharedKeyCredential = sharedKeyCredentialOrUserDelegationKey instanceof StorageSharedKeyCredential ? sharedKeyCredentialOrUserDelegationKey : undefined; let userDelegationKeyCredential; if (sharedKeyCredential === undefined && accountName !== undefined) { userDelegationKeyCredential = new UserDelegationKeyCredential(accountName, sharedKeyCredentialOrUserDelegationKey); } if (sharedKeyCredential === undefined && userDelegationKeyCredential === undefined) { throw TypeError("Invalid sharedKeyCredential, userDelegationKey or accountName."); } // Version 2020-12-06 adds support for encryptionscope in SAS. if (version >= "2020-12-06") { if (sharedKeyCredential !== undefined) { return generateBlobSASQueryParameters20201206(blobSASSignatureValues, sharedKeyCredential); } else { return generateBlobSASQueryParametersUDK20201206(blobSASSignatureValues, userDelegationKeyCredential); } } // 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://learn.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 - * @param sharedKeyCredential - */ 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."); } let resource = "c"; if (blobSASSignatureValues.blobName) { resource = "b"; } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. let 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. const 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"); const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); return { sasQueryParameters: 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), stringToSign: stringToSign, }; } /** * 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 - * @param sharedKeyCredential - */ 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."); } let resource = "c"; let 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. let 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. const 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"); const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); return { sasQueryParameters: 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), stringToSign: stringToSign, }; } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * IMPLEMENTATION FOR API VERSION FROM 2020-12-06. * * 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 - * @param sharedKeyCredential - */ function generateBlobSASQueryParameters20201206(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."); } let resource = "c"; let 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. let 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. const 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.encryptionScope, blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "", ].join("\n"); const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); return { sasQueryParameters: 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, undefined, undefined, undefined, blobSASSignatureValues.encryptionScope), stringToSign: stringToSign, }; } /** * 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 - * @param userDelegationKeyCredential - */ 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."); } let resource = "c"; let 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. let 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. const 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"); const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); return { sasQueryParameters: 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), stringToSign: stringToSign, }; } /** * 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 - * @param userDelegationKeyCredential - */ 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."); } let resource = "c"; let 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. let 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. const 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, // agentObjectId 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"); const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); return { sasQueryParameters: 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), stringToSign: stringToSign, }; } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * IMPLEMENTATION FOR API VERSION FROM 2020-12-06. * * 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 - * @param userDelegationKeyCredential - */ function generateBlobSASQueryParametersUDK20201206(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."); } let resource = "c"; let 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. let 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. const 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, // agentObjectId blobSASSignatureValues.correlationId, blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", blobSASSignatureValues.version, resource, timestamp, blobSASSignatureValues.encryptionScope, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, ].join("\n"); const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); return { sasQueryParameters: 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, blobSASSignatureValues.encryptionScope), stringToSign: stringToSign, }; } function getCanonicalName(accountName, containerName, blobName) { // Container: "/blob/account/containerName" // Blob: "/blob/account/containerName/blobName" const elements = [`/blob/${accountName}/${containerName}`]; if (blobName) { elements.push(`/${blobName}`); } return elements.join(""); } function SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues) { const 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.setImmutabilityPolicy && version < "2020-08-04") { throw RangeError("'version' must be >= '2020-08-04' when provided 'i' permission."); } 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.permanentDelete && version < "2019-10-10") { throw RangeError("'version' must be >= '2019-10-10' when providing 'y' 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 < "2021-04-10" && blobSASSignatureValues.permissions && blobSASSignatureValues.permissions.filterByTags) { throw RangeError("'version' must be >= '2021-04-10' when providing the 'f' permission."); } if (version < "2020-02-10" && (blobSASSignatureValues.preauthorizedAgentObjectId || blobSASSignatureValues.correlationId)) { throw RangeError("'version' must be >= '2020-02-10' when providing 'preauthorizedAgentObjectId' or 'correlationId'."); } if (blobSASSignatureValues.encryptionScope && version < "2020-12-06") { throw RangeError("'version' must be >= '2020-12-06' when provided 'encryptionScope' in SAS."); } blobSASSignatureValues.version = version; return blobSASSignatureValues; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * A client that manages leases for a {@link ContainerClient} or a {@link BlobClient}. */ class BlobLeaseClient { /** * Gets the lease Id. * * @readonly */ get leaseId() { return this._leaseId; } /** * Gets the url. * * @readonly */ get url() { return this._url; } /** * Creates an instance of BlobLeaseClient. * @param client - The client to make the lease operation requests. * @param leaseId - Initial proposed lease id. */ constructor(client, leaseId) { const clientContext = client.storageClientContext; this._url = client.url; if (client.name === undefined) { this._isContainer = true; this._containerOrBlobOperation = clientContext.container; } else { this._isContainer = false; this._containerOrBlobOperation = clientContext.blob; } if (!leaseId) { leaseId = coreUtil.randomUUID(); } this._leaseId = leaseId; } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/lease-container * and * @see https://learn.microsoft.com/en-us/rest/api/storageservices/lease-blob * * @param duration - Must be between 15 to 60 seconds, or infinite (-1) * @param options - option to configure lease management operations. * @returns Response data for acquire lease operation. */ async acquireLease(duration, options = {}) { var _a, _b, _c, _d, _e; 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 tracingClient.withSpan("BlobLeaseClient-acquireLease", options, async (updatedOptions) => { var _a; return assertResponse(await this._containerOrBlobOperation.acquireLease({ abortSignal: options.abortSignal, duration, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), proposedLeaseId: this._leaseId, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * To change the ID of the lease. * @see https://learn.microsoft.com/en-us/rest/api/storageservices/lease-container * and * @see https://learn.microsoft.com/en-us/rest/api/storageservices/lease-blob * * @param proposedLeaseId - the proposed new lease Id. * @param options - option to configure lease management operations. * @returns Response data for change lease operation. */ async changeLease(proposedLeaseId, options = {}) { var _a, _b, _c, _d, _e; 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 tracingClient.withSpan("BlobLeaseClient-changeLease", options, async (updatedOptions) => { var _a; const response = assertResponse(await this._containerOrBlobOperation.changeLease(this._leaseId, proposedLeaseId, { abortSignal: options.abortSignal, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), tracingOptions: updatedOptions.tracingOptions, })); this._leaseId = proposedLeaseId; return response; }); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/lease-container * and * @see https://learn.microsoft.com/en-us/rest/api/storageservices/lease-blob * * @param options - option to configure lease management operations. * @returns Response data for release lease operation. */ async releaseLease(options = {}) { var _a, _b, _c, _d, _e; 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 tracingClient.withSpan("BlobLeaseClient-releaseLease", options, async (updatedOptions) => { var _a; return assertResponse(await this._containerOrBlobOperation.releaseLease(this._leaseId, { abortSignal: options.abortSignal, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), tracingOptions: updatedOptions.tracingOptions, })); }); } /** * To renew the lease. * @see https://learn.microsoft.com/en-us/rest/api/storageservices/lease-container * and * @see https://learn.microsoft.com/en-us/rest/api/storageservices/lease-blob * * @param options - Optional option to configure lease management operations. * @returns Response data for renew lease operation. */ async renewLease(options = {}) { var _a, _b, _c, _d, _e; 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 tracingClient.withSpan("BlobLeaseClient-renewLease", options, async (updatedOptions) => { var _a; return this._containerOrBlobOperation.renewLease(this._leaseId, { abortSignal: options.abortSignal, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), tracingOptions: updatedOptions.tracingOptions, }); }); } /** * To end the lease but ensure that another client cannot acquire a new lease * until the current lease period has expired. * @see https://learn.microsoft.com/en-us/rest/api/storageservices/lease-container * and * @see https://learn.microsoft.com/en-us/rest/api/storageservices/lease-blob * * @param breakPeriod - Break period * @param options - Optional options to configure lease management operations. * @returns Response data for break lease operation. */ async breakLease(breakPeriod, options = {}) { var _a, _b, _c, _d, _e; 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 tracingClient.withSpan("BlobLeaseClient-breakLease", options, async (updatedOptions) => { var _a; const operationOptions = { abortSignal: options.abortSignal, breakPeriod, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), tracingOptions: updatedOptions.tracingOptions, }; return assertResponse(await this._containerOrBlobOperation.breakLease(operationOptions)); }); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * A Node.js ReadableStream will internally retry when internal ReadableStream unexpected ends. */ class RetriableReadableStream extends stream.Readable { /** * Creates an instance of RetriableReadableStream. * * @param source - The current ReadableStream returned from getter * @param getter - A method calling downloading request returning * a new ReadableStream from specified offset * @param offset - Offset position in original data source to read * @param count - How much data in original data source to read * @param options - */ constructor(source, getter, offset, count, options = {}) { super({ highWaterMark: options.highWaterMark }); this.retries = 0; this.sourceDataHandler = (data) => { if (this.options.doInjectErrorOnce) { this.options.doInjectErrorOnce = undefined; this.source.pause(); this.sourceErrorOrEndHandler(); this.source.destroy(); return; } // console.log( // `Offset: ${this.offset}, Received ${data.length} from internal stream` // ); this.offset += data.length; if (this.onProgress) { this.onProgress({ loadedBytes: this.offset - this.start }); } if (!this.push(data)) { this.source.pause(); } }; this.sourceAbortedHandler = () => { const abortError = new abortController.AbortError("The operation was aborted."); this.destroy(abortError); }; this.sourceErrorOrEndHandler = (err) => { if (err && err.name === "AbortError") { this.destroy(err); return; } // console.log( // `Source stream emits end or error, offset: ${ // this.offset // }, dest end : ${this.end}` // ); this.removeSourceEventHandlers(); if (this.offset - 1 === this.end) { this.push(null); } else if (this.offset <= this.end) { // console.log( // `retries: ${this.retries}, max retries: ${this.maxRetries}` // ); if (this.retries < this.maxRetryRequests) { this.retries += 1; this.getter(this.offset) .then((newSource) => { this.source = newSource; this.setSourceEventHandlers(); return; }) .catch((error) => { this.destroy(error); }); } else { this.destroy(new Error(`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.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(); } _read() { this.source.resume(); } setSourceEventHandlers() { this.source.on("data", this.sourceDataHandler); this.source.on("end", this.sourceErrorOrEndHandler); this.source.on("error", this.sourceErrorOrEndHandler); // needed for Node14 this.source.on("aborted", this.sourceAbortedHandler); } removeSourceEventHandlers() { this.source.removeListener("data", this.sourceDataHandler); this.source.removeListener("end", this.sourceErrorOrEndHandler); this.source.removeListener("error", this.sourceErrorOrEndHandler); this.source.removeListener("aborted", this.sourceAbortedHandler); } _destroy(error, callback) { // remove listener from source and release source this.removeSourceEventHandlers(); this.source.destroy(); callback(error === null ? undefined : error); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * BlobDownloadResponse implements BlobDownloadResponseParsed interface, and in Node.js runtime it will * automatically retry when internal read stream unexpected ends. (This kind of unexpected ends cannot * trigger retries defined in pipeline retry policy.) * * The {@link readableStreamBody} stream will retry underlayer, you can just use it as a normal Node.js * Readable stream. */ class BlobDownloadResponse { /** * Indicates that the service supports * requests for partial file content. * * @readonly */ get acceptRanges() { return this.originalResponse.acceptRanges; } /** * Returns if it was previously specified * for the file. * * @readonly */ get cacheControl() { return this.originalResponse.cacheControl; } /** * Returns the value that was specified * for the 'x-ms-content-disposition' header and specifies how to process the * response. * * @readonly */ get contentDisposition() { return this.originalResponse.contentDisposition; } /** * Returns the value that was specified * for the Content-Encoding request header. * * @readonly */ get contentEncoding() { return this.originalResponse.contentEncoding; } /** * Returns the value that was specified * for the Content-Language request header. * * @readonly */ get contentLanguage() { return this.originalResponse.contentLanguage; } /** * The current sequence number for a * page blob. This header is not returned for block blobs or append blobs. * * @readonly */ get blobSequenceNumber() { return this.originalResponse.blobSequenceNumber; } /** * The blob's type. Possible values include: * 'BlockBlob', 'PageBlob', 'AppendBlob'. * * @readonly */ get blobType() { return this.originalResponse.blobType; } /** * The number of bytes present in the * response body. * * @readonly */ get contentLength() { return this.originalResponse.contentLength; } /** * If the file has an MD5 hash and the * request is to read the full file, this response header is returned so that * the client can check for message content integrity. If the request is to * read a specified range and the 'x-ms-range-get-content-md5' is set to * true, then the request returns an MD5 hash for the range, as long as the * range size is less than or equal to 4 MB. If neither of these sets of * conditions is true, then no value is returned for the 'Content-MD5' * header. * * @readonly */ get contentMD5() { return this.originalResponse.contentMD5; } /** * Indicates the range of bytes returned if * the client requested a subset of the file by setting the Range request * header. * * @readonly */ get contentRange() { return this.originalResponse.contentRange; } /** * The content type specified for the file. * The default content type is 'application/octet-stream' * * @readonly */ get contentType() { return this.originalResponse.contentType; } /** * Conclusion time of the last attempted * Copy File operation where this file was the destination file. This value * can specify the time of a completed, aborted, or failed copy attempt. * * @readonly */ get copyCompletedOn() { return this.originalResponse.copyCompletedOn; } /** * String identifier for the last attempted Copy * File operation where this file was the destination file. * * @readonly */ get copyId() { return this.originalResponse.copyId; } /** * Contains the number of bytes copied and * the total bytes in the source in the last attempted Copy File operation * where this file was the destination file. Can show between 0 and * Content-Length bytes copied. * * @readonly */ get copyProgress() { return this.originalResponse.copyProgress; } /** * URL up to 2KB in length that specifies the * source file used in the last attempted Copy File operation where this file * was the destination file. * * @readonly */ get copySource() { return this.originalResponse.copySource; } /** * State of the copy operation * identified by 'x-ms-copy-id'. Possible values include: 'pending', * 'success', 'aborted', 'failed' * * @readonly */ get copyStatus() { return this.originalResponse.copyStatus; } /** * Only appears when * x-ms-copy-status is failed or pending. Describes cause of fatal or * non-fatal copy operation failure. * * @readonly */ get copyStatusDescription() { return this.originalResponse.copyStatusDescription; } /** * When a blob is leased, * specifies whether the lease is of infinite or fixed duration. Possible * values include: 'infinite', 'fixed'. * * @readonly */ get leaseDuration() { return this.originalResponse.leaseDuration; } /** * Lease state of the blob. Possible * values include: 'available', 'leased', 'expired', 'breaking', 'broken'. * * @readonly */ get leaseState() { return this.originalResponse.leaseState; } /** * The current lease status of the * blob. Possible values include: 'locked', 'unlocked'. * * @readonly */ get leaseStatus() { return this.originalResponse.leaseStatus; } /** * A UTC date/time value generated by the service that * indicates the time at which the response was initiated. * * @readonly */ get date() { return this.originalResponse.date; } /** * The number of committed blocks * present in the blob. This header is returned only for append blobs. * * @readonly */ get blobCommittedBlockCount() { return this.originalResponse.blobCommittedBlockCount; } /** * The ETag contains a value that you can use to * perform operations conditionally, in quotes. * * @readonly */ get etag() { return this.originalResponse.etag; } /** * The number of tags associated with the blob * * @readonly */ get tagCount() { return this.originalResponse.tagCount; } /** * The error code. * * @readonly */ get errorCode() { return this.originalResponse.errorCode; } /** * The value of this header is set to * true if the file data and application metadata are completely encrypted * using the specified algorithm. Otherwise, the value is set to false (when * the file is unencrypted, or if only parts of the file/application metadata * are encrypted). * * @readonly */ get isServerEncrypted() { return this.originalResponse.isServerEncrypted; } /** * If the blob has a MD5 hash, and if * request contains range header (Range or x-ms-range), this response header * is returned with the value of the whole blob's MD5 value. This value may * or may not be equal to the value returned in Content-MD5 header, with the * latter calculated from the requested range. * * @readonly */ get blobContentMD5() { return this.originalResponse.blobContentMD5; } /** * Returns the date and time the file was last * modified. Any operation that modifies the file or its properties updates * the last modified time. * * @readonly */ get lastModified() { return this.originalResponse.lastModified; } /** * Returns the UTC date and time generated by the service that indicates the time at which the blob was * last read or written to. * * @readonly */ get lastAccessed() { return this.originalResponse.lastAccessed; } /** * Returns the date and time the blob was created. * * @readonly */ get createdOn() { return this.originalResponse.createdOn; } /** * A name-value pair * to associate with a file storage object. * * @readonly */ get metadata() { return this.originalResponse.metadata; } /** * This header uniquely identifies the request * that was made and can be used for troubleshooting the request. * * @readonly */ get requestId() { return this.originalResponse.requestId; } /** * If a client request id header is sent in the request, this header will be present in the * response with the same value. * * @readonly */ get clientRequestId() { return this.originalResponse.clientRequestId; } /** * Indicates the version of the Blob service used * to execute the request. * * @readonly */ get version() { return this.originalResponse.version; } /** * Indicates the versionId of the downloaded blob version. * * @readonly */ get versionId() { return this.originalResponse.versionId; } /** * Indicates whether version of this blob is a current version. * * @readonly */ get isCurrentVersion() { return this.originalResponse.isCurrentVersion; } /** * The SHA-256 hash of the encryption key used to encrypt the blob. This value is only returned * when the blob was encrypted with a customer-provided key. * * @readonly */ get encryptionKeySha256() { return this.originalResponse.encryptionKeySha256; } /** * If the request is to read a specified range and the x-ms-range-get-content-crc64 is set to * true, then the request returns a crc64 for the range, as long as the range size is less than * or equal to 4 MB. If both x-ms-range-get-content-crc64 & x-ms-range-get-content-md5 is * specified in the same request, it will fail with 400(Bad Request) */ get contentCrc64() { return this.originalResponse.contentCrc64; } /** * Object Replication Policy Id of the destination blob. * * @readonly */ get objectReplicationDestinationPolicyId() { return this.originalResponse.objectReplicationDestinationPolicyId; } /** * Parsed Object Replication Policy Id, Rule Id(s) and status of the source blob. * * @readonly */ get objectReplicationSourceProperties() { return this.originalResponse.objectReplicationSourceProperties; } /** * If this blob has been sealed. * * @readonly */ get isSealed() { return this.originalResponse.isSealed; } /** * UTC date/time value generated by the service that indicates the time at which the blob immutability policy will expire. * * @readonly */ get immutabilityPolicyExpiresOn() { return this.originalResponse.immutabilityPolicyExpiresOn; } /** * Indicates immutability policy mode. * * @readonly */ get immutabilityPolicyMode() { return this.originalResponse.immutabilityPolicyMode; } /** * Indicates if a legal hold is present on the blob. * * @readonly */ get legalHold() { return this.originalResponse.legalHold; } /** * The response body as a browser Blob. * Always undefined in node.js. * * @readonly */ get contentAsBlob() { return this.originalResponse.blobBody; } /** * The response body as a node.js Readable stream. * Always undefined in the browser. * * It will automatically retry when internal read stream unexpected ends. * * @readonly */ get readableStreamBody() { return coreUtil.isNode ? this.blobDownloadStream : undefined; } /** * The HTTP response. */ get _response() { return this.originalResponse._response; } /** * Creates an instance of BlobDownloadResponse. * * @param originalResponse - * @param getter - * @param offset - * @param count - * @param options - */ constructor(originalResponse, getter, offset, count, options = {}) { this.originalResponse = originalResponse; this.blobDownloadStream = new RetriableReadableStream(this.originalResponse.readableStreamBody, getter, offset, count, options); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. const AVRO_SYNC_MARKER_SIZE = 16; const AVRO_INIT_BYTES = new Uint8Array([79, 98, 106, 1]); const AVRO_CODEC_KEY = "avro.codec"; const AVRO_SCHEMA_KEY = "avro.schema"; // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. class AvroParser { /** * Reads a fixed number of bytes from the stream. * * @param stream - * @param length - * @param options - */ static async readFixedBytes(stream, length, options = {}) { const bytes = await stream.read(length, { abortSignal: options.abortSignal }); if (bytes.length !== length) { throw new Error("Hit stream end."); } return bytes; } /** * Reads a single byte from the stream. * * @param stream - * @param options - */ static async readByte(stream, options = {}) { const buf = await AvroParser.readFixedBytes(stream, 1, options); return buf[0]; } // int and long are stored in variable-length zig-zag coding. // variable-length: https://lucene.apache.org/core/3_5_0/fileformats.html#VInt // zig-zag: https://developers.google.com/protocol-buffers/docs/encoding?csw=1#types static async readZigZagLong(stream, options = {}) { let zigZagEncoded = 0; let significanceInBit = 0; let byte, haveMoreByte, significanceInFloat; do { byte = await AvroParser.readByte(stream, options); haveMoreByte = byte & 0x80; zigZagEncoded |= (byte & 0x7f) << significanceInBit; significanceInBit += 7; } while (haveMoreByte && significanceInBit < 28); // bitwise operation only works for 32-bit integers if (haveMoreByte) { // Switch to float arithmetic // eslint-disable-next-line no-self-assign zigZagEncoded = zigZagEncoded; significanceInFloat = 268435456; // 2 ** 28. do { byte = await AvroParser.readByte(stream, options); zigZagEncoded += (byte & 0x7f) * significanceInFloat; significanceInFloat *= 128; // 2 ** 7 } while (byte & 0x80); const res = (zigZagEncoded % 2 ? -(zigZagEncoded + 1) : zigZagEncoded) / 2; if (res < Number.MIN_SAFE_INTEGER || res > Number.MAX_SAFE_INTEGER) { throw new Error("Integer overflow."); } return res; } return (zigZagEncoded >> 1) ^ -(zigZagEncoded & 1); } static async readLong(stream, options = {}) { return AvroParser.readZigZagLong(stream, options); } static async readInt(stream, options = {}) { return AvroParser.readZigZagLong(stream, options); } static async readNull() { return null; } static async readBoolean(stream, options = {}) { const b = await AvroParser.readByte(stream, options); if (b === 1) { return true; } else if (b === 0) { return false; } else { throw new Error("Byte was not a boolean."); } } static async readFloat(stream, options = {}) { const u8arr = await AvroParser.readFixedBytes(stream, 4, options); const view = new DataView(u8arr.buffer, u8arr.byteOffset, u8arr.byteLength); return view.getFloat32(0, true); // littleEndian = true } static async readDouble(stream, options = {}) { const u8arr = await AvroParser.readFixedBytes(stream, 8, options); const view = new DataView(u8arr.buffer, u8arr.byteOffset, u8arr.byteLength); return view.getFloat64(0, true); // littleEndian = true } static async readBytes(stream, options = {}) { const size = await AvroParser.readLong(stream, options); if (size < 0) { throw new Error("Bytes size was negative."); } return stream.read(size, { abortSignal: options.abortSignal }); } static async readString(stream, options = {}) { const u8arr = await AvroParser.readBytes(stream, options); const utf8decoder = new TextDecoder(); return utf8decoder.decode(u8arr); } static async readMapPair(stream, readItemMethod, options = {}) { const key = await AvroParser.readString(stream, options); // FUTURE: this won't work with readFixed (currently not supported) which needs a length as the parameter. const value = await readItemMethod(stream, options); return { key, value }; } static async readMap(stream, readItemMethod, options = {}) { const readPairMethod = (s, opts = {}) => { return AvroParser.readMapPair(s, readItemMethod, opts); }; const pairs = await AvroParser.readArray(stream, readPairMethod, options); const dict = {}; for (const pair of pairs) { dict[pair.key] = pair.value; } return dict; } static async readArray(stream, readItemMethod, options = {}) { const items = []; for (let count = await AvroParser.readLong(stream, options); count !== 0; count = await AvroParser.readLong(stream, options)) { if (count < 0) { // Ignore block sizes await AvroParser.readLong(stream, options); count = -count; } while (count--) { const item = await readItemMethod(stream, options); items.push(item); } } return items; } } var AvroComplex; (function (AvroComplex) { AvroComplex["RECORD"] = "record"; AvroComplex["ENUM"] = "enum"; AvroComplex["ARRAY"] = "array"; AvroComplex["MAP"] = "map"; AvroComplex["UNION"] = "union"; AvroComplex["FIXED"] = "fixed"; })(AvroComplex || (AvroComplex = {})); var AvroPrimitive; (function (AvroPrimitive) { AvroPrimitive["NULL"] = "null"; AvroPrimitive["BOOLEAN"] = "boolean"; AvroPrimitive["INT"] = "int"; AvroPrimitive["LONG"] = "long"; AvroPrimitive["FLOAT"] = "float"; AvroPrimitive["DOUBLE"] = "double"; AvroPrimitive["BYTES"] = "bytes"; AvroPrimitive["STRING"] = "string"; })(AvroPrimitive || (AvroPrimitive = {})); class AvroType { /** * Determines the AvroType from the Avro Schema. */ // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types static fromSchema(schema) { if (typeof schema === "string") { return AvroType.fromStringSchema(schema); } else if (Array.isArray(schema)) { return AvroType.fromArraySchema(schema); } else { return AvroType.fromObjectSchema(schema); } } static fromStringSchema(schema) { switch (schema) { case AvroPrimitive.NULL: case AvroPrimitive.BOOLEAN: case AvroPrimitive.INT: case AvroPrimitive.LONG: case AvroPrimitive.FLOAT: case AvroPrimitive.DOUBLE: case AvroPrimitive.BYTES: case AvroPrimitive.STRING: return new AvroPrimitiveType(schema); default: throw new Error(`Unexpected Avro type ${schema}`); } } static fromArraySchema(schema) { return new AvroUnionType(schema.map(AvroType.fromSchema)); } static fromObjectSchema(schema) { const type = schema.type; // Primitives can be defined as strings or objects try { return AvroType.fromStringSchema(type); } catch (_a) { // no-op } switch (type) { case AvroComplex.RECORD: if (schema.aliases) { throw new Error(`aliases currently is not supported, schema: ${schema}`); } if (!schema.name) { throw new Error(`Required attribute 'name' doesn't exist on schema: ${schema}`); } // eslint-disable-next-line no-case-declarations const fields = {}; if (!schema.fields) { throw new Error(`Required attribute 'fields' doesn't exist on schema: ${schema}`); } for (const field of schema.fields) { fields[field.name] = AvroType.fromSchema(field.type); } return new AvroRecordType(fields, schema.name); case AvroComplex.ENUM: if (schema.aliases) { throw new Error(`aliases currently is not supported, schema: ${schema}`); } if (!schema.symbols) { throw new Error(`Required attribute 'symbols' doesn't exist on schema: ${schema}`); } return new AvroEnumType(schema.symbols); case AvroComplex.MAP: if (!schema.values) { throw new Error(`Required attribute 'values' doesn't exist on schema: ${schema}`); } return new AvroMapType(AvroType.fromSchema(schema.values)); case AvroComplex.ARRAY: // Unused today case AvroComplex.FIXED: // Unused today default: throw new Error(`Unexpected Avro type ${type} in ${schema}`); } } } class AvroPrimitiveType extends AvroType { constructor(primitive) { super(); this._primitive = primitive; } // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types read(stream, options = {}) { switch (this._primitive) { case AvroPrimitive.NULL: return AvroParser.readNull(); case AvroPrimitive.BOOLEAN: return AvroParser.readBoolean(stream, options); case AvroPrimitive.INT: return AvroParser.readInt(stream, options); case AvroPrimitive.LONG: return AvroParser.readLong(stream, options); case AvroPrimitive.FLOAT: return AvroParser.readFloat(stream, options); case AvroPrimitive.DOUBLE: return AvroParser.readDouble(stream, options); case AvroPrimitive.BYTES: return AvroParser.readBytes(stream, options); case AvroPrimitive.STRING: return AvroParser.readString(stream, options); default: throw new Error("Unknown Avro Primitive"); } } } class AvroEnumType extends AvroType { constructor(symbols) { super(); this._symbols = symbols; } // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types async read(stream, options = {}) { const value = await AvroParser.readInt(stream, options); return this._symbols[value]; } } class AvroUnionType extends AvroType { constructor(types) { super(); this._types = types; } async read(stream, options = {}) { const typeIndex = await AvroParser.readInt(stream, options); return this._types[typeIndex].read(stream, options); } } class AvroMapType extends AvroType { constructor(itemType) { super(); this._itemType = itemType; } // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types read(stream, options = {}) { const readItemMethod = (s, opts) => { return this._itemType.read(s, opts); }; return AvroParser.readMap(stream, readItemMethod, options); } } class AvroRecordType extends AvroType { constructor(fields, name) { super(); this._fields = fields; this._name = name; } // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types async read(stream, options = {}) { // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types const record = {}; record["$schema"] = this._name; for (const key in this._fields) { if (Object.prototype.hasOwnProperty.call(this._fields, key)) { record[key] = await this._fields[key].read(stream, options); } } return record; } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. function arraysEqual(a, b) { if (a === b) return true; if (a == null || b == null) return false; if (a.length !== b.length) return false; for (let i = 0; i < a.length; ++i) { if (a[i] !== b[i]) return false; } return true; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. class AvroReader { get blockOffset() { return this._blockOffset; } get objectIndex() { return this._objectIndex; } constructor(dataStream, headerStream, currentBlockOffset, indexWithinCurrentBlock) { this._dataStream = dataStream; this._headerStream = headerStream || dataStream; this._initialized = false; this._blockOffset = currentBlockOffset || 0; this._objectIndex = indexWithinCurrentBlock || 0; this._initialBlockOffset = currentBlockOffset || 0; } async initialize(options = {}) { const header = await AvroParser.readFixedBytes(this._headerStream, AVRO_INIT_BYTES.length, { abortSignal: options.abortSignal, }); if (!arraysEqual(header, AVRO_INIT_BYTES)) { throw new Error("Stream is not an Avro file."); } // File metadata is written as if defined by the following map schema: // { "type": "map", "values": "bytes"} this._metadata = await AvroParser.readMap(this._headerStream, AvroParser.readString, { abortSignal: options.abortSignal, }); // Validate codec const codec = this._metadata[AVRO_CODEC_KEY]; if (!(codec === undefined || codec === null || codec === "null")) { throw new Error("Codecs are not supported"); } // The 16-byte, randomly-generated sync marker for this file. this._syncMarker = await AvroParser.readFixedBytes(this._headerStream, AVRO_SYNC_MARKER_SIZE, { abortSignal: options.abortSignal, }); // Parse the schema const schema = JSON.parse(this._metadata[AVRO_SCHEMA_KEY]); this._itemType = AvroType.fromSchema(schema); if (this._blockOffset === 0) { this._blockOffset = this._initialBlockOffset + this._dataStream.position; } this._itemsRemainingInBlock = await AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal, }); // skip block length await AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal }); this._initialized = true; if (this._objectIndex && this._objectIndex > 0) { for (let i = 0; i < this._objectIndex; i++) { await this._itemType.read(this._dataStream, { abortSignal: options.abortSignal }); this._itemsRemainingInBlock--; } } } hasNext() { return !this._initialized || this._itemsRemainingInBlock > 0; } parseObjects() { return tslib.__asyncGenerator(this, arguments, function* parseObjects_1(options = {}) { if (!this._initialized) { yield tslib.__await(this.initialize(options)); } while (this.hasNext()) { const result = yield tslib.__await(this._itemType.read(this._dataStream, { abortSignal: options.abortSignal, })); this._itemsRemainingInBlock--; this._objectIndex++; if (this._itemsRemainingInBlock === 0) { const marker = yield tslib.__await(AvroParser.readFixedBytes(this._dataStream, AVRO_SYNC_MARKER_SIZE, { abortSignal: options.abortSignal, })); this._blockOffset = this._initialBlockOffset + this._dataStream.position; this._objectIndex = 0; if (!arraysEqual(this._syncMarker, marker)) { throw new Error("Stream is not a valid Avro file."); } try { this._itemsRemainingInBlock = yield tslib.__await(AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal, })); } catch (_a) { // We hit the end of the stream. this._itemsRemainingInBlock = 0; } if (this._itemsRemainingInBlock > 0) { // Ignore block size yield tslib.__await(AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal })); } } yield yield tslib.__await(result); } }); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. class AvroReadable { } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. const ABORT_ERROR = new abortController.AbortError("Reading from the avro stream was aborted."); class AvroReadableFromStream extends AvroReadable { toUint8Array(data) { if (typeof data === "string") { return Buffer.from(data); } return data; } constructor(readable) { super(); this._readable = readable; this._position = 0; } get position() { return this._position; } async read(size, options = {}) { var _a; if ((_a = options.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { throw ABORT_ERROR; } if (size < 0) { throw new Error(`size parameter should be positive: ${size}`); } if (size === 0) { return new Uint8Array(); } if (!this._readable.readable) { throw new Error("Stream no longer readable."); } // See if there is already enough data. const chunk = this._readable.read(size); if (chunk) { this._position += chunk.length; // chunk.length maybe less than desired size if the stream ends. return this.toUint8Array(chunk); } else { // register callback to wait for enough data to read return new Promise((resolve, reject) => { /* eslint-disable @typescript-eslint/no-use-before-define */ const cleanUp = () => { this._readable.removeListener("readable", readableCallback); this._readable.removeListener("error", rejectCallback); this._readable.removeListener("end", rejectCallback); this._readable.removeListener("close", rejectCallback); if (options.abortSignal) { options.abortSignal.removeEventListener("abort", abortHandler); } }; const readableCallback = () => { const callbackChunk = this._readable.read(size); if (callbackChunk) { this._position += callbackChunk.length; cleanUp(); // callbackChunk.length maybe less than desired size if the stream ends. resolve(this.toUint8Array(callbackChunk)); } }; const rejectCallback = () => { cleanUp(); reject(); }; const abortHandler = () => { cleanUp(); reject(ABORT_ERROR); }; this._readable.on("readable", readableCallback); this._readable.once("error", rejectCallback); this._readable.once("end", rejectCallback); this._readable.once("close", rejectCallback); if (options.abortSignal) { options.abortSignal.addEventListener("abort", abortHandler); } /* eslint-enable @typescript-eslint/no-use-before-define */ }); } } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * A Node.js BlobQuickQueryStream will internally parse avro data stream for blob query. */ class BlobQuickQueryStream extends stream.Readable { /** * Creates an instance of BlobQuickQueryStream. * * @param source - The current ReadableStream returned from getter * @param options - */ constructor(source, options = {}) { super(); this.avroPaused = true; this.source = source; this.onProgress = options.onProgress; this.onError = options.onError; this.avroReader = new AvroReader(new AvroReadableFromStream(this.source)); this.avroIter = this.avroReader.parseObjects({ abortSignal: options.abortSignal }); } _read() { if (this.avroPaused) { this.readInternal().catch((err) => { this.emit("error", err); }); } } async readInternal() { this.avroPaused = false; let avroNext; do { avroNext = await this.avroIter.next(); if (avroNext.done) { break; } const obj = avroNext.value; const schema = obj.$schema; if (typeof schema !== "string") { throw Error("Missing schema in avro record."); } switch (schema) { case "com.microsoft.azure.storage.queryBlobContents.resultData": { const data = obj.data; if (data instanceof Uint8Array === false) { throw Error("Invalid data in avro result record."); } if (!this.push(Buffer.from(data))) { this.avroPaused = true; } } break; case "com.microsoft.azure.storage.queryBlobContents.progress": { const bytesScanned = obj.bytesScanned; if (typeof bytesScanned !== "number") { throw Error("Invalid bytesScanned in avro progress record."); } if (this.onProgress) { this.onProgress({ loadedBytes: bytesScanned }); } } break; case "com.microsoft.azure.storage.queryBlobContents.end": if (this.onProgress) { const totalBytes = obj.totalBytes; if (typeof totalBytes !== "number") { throw Error("Invalid totalBytes in avro end record."); } this.onProgress({ loadedBytes: totalBytes }); } this.push(null); break; case "com.microsoft.azure.storage.queryBlobContents.error": if (this.onError) { const fatal = obj.fatal; if (typeof fatal !== "boolean") { throw Error("Invalid fatal in avro error record."); } const name = obj.name; if (typeof name !== "string") { throw Error("Invalid name in avro error record."); } const description = obj.description; if (typeof description !== "string") { throw Error("Invalid description in avro error record."); } const position = obj.position; if (typeof position !== "number") { throw Error("Invalid position in avro error record."); } this.onError({ position, name, isFatal: fatal, description, }); } break; default: throw Error(`Unknown schema ${schema} in avro progress record.`); } } while (!avroNext.done && !this.avroPaused); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * BlobQueryResponse implements BlobDownloadResponseModel interface, and in Node.js runtime it will * parse avor data returned by blob query. */ class BlobQueryResponse { /** * Indicates that the service supports * requests for partial file content. * * @readonly */ get acceptRanges() { return this.originalResponse.acceptRanges; } /** * Returns if it was previously specified * for the file. * * @readonly */ get cacheControl() { return this.originalResponse.cacheControl; } /** * Returns the value that was specified * for the 'x-ms-content-disposition' header and specifies how to process the * response. * * @readonly */ get contentDisposition() { return this.originalResponse.contentDisposition; } /** * Returns the value that was specified * for the Content-Encoding request header. * * @readonly */ get contentEncoding() { return this.originalResponse.contentEncoding; } /** * Returns the value that was specified * for the Content-Language request header. * * @readonly */ get contentLanguage() { return this.originalResponse.contentLanguage; } /** * The current sequence number for a * page blob. This header is not returned for block blobs or append blobs. * * @readonly */ get blobSequenceNumber() { return this.originalResponse.blobSequenceNumber; } /** * The blob's type. Possible values include: * 'BlockBlob', 'PageBlob', 'AppendBlob'. * * @readonly */ get blobType() { return this.originalResponse.blobType; } /** * The number of bytes present in the * response body. * * @readonly */ get contentLength() { return this.originalResponse.contentLength; } /** * If the file has an MD5 hash and the * request is to read the full file, this response header is returned so that * the client can check for message content integrity. If the request is to * read a specified range and the 'x-ms-range-get-content-md5' is set to * true, then the request returns an MD5 hash for the range, as long as the * range size is less than or equal to 4 MB. If neither of these sets of * conditions is true, then no value is returned for the 'Content-MD5' * header. * * @readonly */ get contentMD5() { return this.originalResponse.contentMD5; } /** * Indicates the range of bytes returned if * the client requested a subset of the file by setting the Range request * header. * * @readonly */ get contentRange() { return this.originalResponse.contentRange; } /** * The content type specified for the file. * The default content type is 'application/octet-stream' * * @readonly */ get contentType() { return this.originalResponse.contentType; } /** * Conclusion time of the last attempted * Copy File operation where this file was the destination file. This value * can specify the time of a completed, aborted, or failed copy attempt. * * @readonly */ get copyCompletedOn() { return undefined; } /** * String identifier for the last attempted Copy * File operation where this file was the destination file. * * @readonly */ get copyId() { return this.originalResponse.copyId; } /** * Contains the number of bytes copied and * the total bytes in the source in the last attempted Copy File operation * where this file was the destination file. Can show between 0 and * Content-Length bytes copied. * * @readonly */ get copyProgress() { return this.originalResponse.copyProgress; } /** * URL up to 2KB in length that specifies the * source file used in the last attempted Copy File operation where this file * was the destination file. * * @readonly */ get copySource() { return this.originalResponse.copySource; } /** * State of the copy operation * identified by 'x-ms-copy-id'. Possible values include: 'pending', * 'success', 'aborted', 'failed' * * @readonly */ get copyStatus() { return this.originalResponse.copyStatus; } /** * Only appears when * x-ms-copy-status is failed or pending. Describes cause of fatal or * non-fatal copy operation failure. * * @readonly */ get copyStatusDescription() { return this.originalResponse.copyStatusDescription; } /** * When a blob is leased, * specifies whether the lease is of infinite or fixed duration. Possible * values include: 'infinite', 'fixed'. * * @readonly */ get leaseDuration() { return this.originalResponse.leaseDuration; } /** * Lease state of the blob. Possible * values include: 'available', 'leased', 'expired', 'breaking', 'broken'. * * @readonly */ get leaseState() { return this.originalResponse.leaseState; } /** * The current lease status of the * blob. Possible values include: 'locked', 'unlocked'. * * @readonly */ get leaseStatus() { return this.originalResponse.leaseStatus; } /** * A UTC date/time value generated by the service that * indicates the time at which the response was initiated. * * @readonly */ get date() { return this.originalResponse.date; } /** * The number of committed blocks * present in the blob. This header is returned only for append blobs. * * @readonly */ get blobCommittedBlockCount() { return this.originalResponse.blobCommittedBlockCount; } /** * The ETag contains a value that you can use to * perform operations conditionally, in quotes. * * @readonly */ get etag() { return this.originalResponse.etag; } /** * The error code. * * @readonly */ get errorCode() { return this.originalResponse.errorCode; } /** * The value of this header is set to * true if the file data and application metadata are completely encrypted * using the specified algorithm. Otherwise, the value is set to false (when * the file is unencrypted, or if only parts of the file/application metadata * are encrypted). * * @readonly */ get isServerEncrypted() { return this.originalResponse.isServerEncrypted; } /** * If the blob has a MD5 hash, and if * request contains range header (Range or x-ms-range), this response header * is returned with the value of the whole blob's MD5 value. This value may * or may not be equal to the value returned in Content-MD5 header, with the * latter calculated from the requested range. * * @readonly */ get blobContentMD5() { return this.originalResponse.blobContentMD5; } /** * Returns the date and time the file was last * modified. Any operation that modifies the file or its properties updates * the last modified time. * * @readonly */ get lastModified() { return this.originalResponse.lastModified; } /** * A name-value pair * to associate with a file storage object. * * @readonly */ get metadata() { return this.originalResponse.metadata; } /** * This header uniquely identifies the request * that was made and can be used for troubleshooting the request. * * @readonly */ get requestId() { return this.originalResponse.requestId; } /** * If a client request id header is sent in the request, this header will be present in the * response with the same value. * * @readonly */ get clientRequestId() { return this.originalResponse.clientRequestId; } /** * Indicates the version of the File service used * to execute the request. * * @readonly */ get version() { return this.originalResponse.version; } /** * The SHA-256 hash of the encryption key used to encrypt the blob. This value is only returned * when the blob was encrypted with a customer-provided key. * * @readonly */ get encryptionKeySha256() { return this.originalResponse.encryptionKeySha256; } /** * If the request is to read a specified range and the x-ms-range-get-content-crc64 is set to * true, then the request returns a crc64 for the range, as long as the range size is less than * or equal to 4 MB. If both x-ms-range-get-content-crc64 & x-ms-range-get-content-md5 is * specified in the same request, it will fail with 400(Bad Request) */ get contentCrc64() { return this.originalResponse.contentCrc64; } /** * The response body as a browser Blob. * Always undefined in node.js. * * @readonly */ get blobBody() { return undefined; } /** * The response body as a node.js Readable stream. * Always undefined in the browser. * * It will parse avor data returned by blob query. * * @readonly */ get readableStreamBody() { return coreUtil.isNode ? this.blobDownloadStream : undefined; } /** * The HTTP response. */ get _response() { return this.originalResponse._response; } /** * Creates an instance of BlobQueryResponse. * * @param originalResponse - * @param options - */ constructor(originalResponse, options = {}) { this.originalResponse = originalResponse; this.blobDownloadStream = new BlobQuickQueryStream(this.originalResponse.readableStreamBody, options); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * Represents the access tier on a blob. * For detailed information about block blob level tiering see {@link https://learn.microsoft.com/azure/storage/blobs/storage-blob-storage-tiers|Hot, cool and archive storage tiers.} */ exports.BlockBlobTier = void 0; (function (BlockBlobTier) { /** * Optimized for storing data that is accessed frequently. */ BlockBlobTier["Hot"] = "Hot"; /** * Optimized for storing data that is infrequently accessed and stored for at least 30 days. */ BlockBlobTier["Cool"] = "Cool"; /** * Optimized for storing data that is rarely accessed. */ BlockBlobTier["Cold"] = "Cold"; /** * Optimized for storing data that is rarely accessed and stored for at least 180 days * with flexible latency requirements (on the order of hours). */ BlockBlobTier["Archive"] = "Archive"; })(exports.BlockBlobTier || (exports.BlockBlobTier = {})); /** * Specifies the page blob tier to set the blob to. This is only applicable to page blobs on premium storage accounts. * Please see {@link https://learn.microsoft.com/azure/storage/storage-premium-storage#scalability-and-performance-targets|here} * for detailed information on the corresponding IOPS and throughput per PageBlobTier. */ exports.PremiumPageBlobTier = void 0; (function (PremiumPageBlobTier) { /** * P4 Tier. */ PremiumPageBlobTier["P4"] = "P4"; /** * P6 Tier. */ PremiumPageBlobTier["P6"] = "P6"; /** * P10 Tier. */ PremiumPageBlobTier["P10"] = "P10"; /** * P15 Tier. */ PremiumPageBlobTier["P15"] = "P15"; /** * P20 Tier. */ PremiumPageBlobTier["P20"] = "P20"; /** * P30 Tier. */ PremiumPageBlobTier["P30"] = "P30"; /** * P40 Tier. */ PremiumPageBlobTier["P40"] = "P40"; /** * P50 Tier. */ PremiumPageBlobTier["P50"] = "P50"; /** * P60 Tier. */ PremiumPageBlobTier["P60"] = "P60"; /** * P70 Tier. */ PremiumPageBlobTier["P70"] = "P70"; /** * P80 Tier. */ PremiumPageBlobTier["P80"] = "P80"; })(exports.PremiumPageBlobTier || (exports.PremiumPageBlobTier = {})); function toAccessTier(tier) { if (tier === undefined) { return undefined; } return tier; // No more check if string is a valid AccessTier, and left this to underlay logic to decide(service). } function ensureCpkIfSpecified(cpk, isHttps) { if (cpk && !isHttps) { throw new RangeError("Customer-provided encryption key must be used over HTTPS."); } if (cpk && !cpk.encryptionAlgorithm) { cpk.encryptionAlgorithm = EncryptionAlgorithmAES25; } } /** * Defines the known cloud audiences for Storage. */ exports.StorageBlobAudience = void 0; (function (StorageBlobAudience) { /** * The OAuth scope to use to retrieve an AAD token for Azure Storage. */ StorageBlobAudience["StorageOAuthScopes"] = "https://storage.azure.com/.default"; /** * The OAuth scope to use to retrieve an AAD token for Azure Disk. */ StorageBlobAudience["DiskComputeOAuthScopes"] = "https://disk.compute.azure.com/.default"; })(exports.StorageBlobAudience || (exports.StorageBlobAudience = {})); /** * * To get OAuth audience for a storage account for blob service. */ function getBlobServiceAccountAudience(storageAccountName) { return `https://${storageAccountName}.blob.core.windows.net/.default`; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * Function that converts PageRange and ClearRange to a common Range object. * PageRange and ClearRange have start and end while Range offset and count * this function normalizes to Range. * @param response - Model PageBlob Range response */ function rangeResponseFromModel(response) { const pageRange = (response._response.parsedBody.pageRange || []).map((x) => ({ offset: x.start, count: x.end - x.start, })); const clearRange = (response._response.parsedBody.clearRange || []).map((x) => ({ offset: x.start, count: x.end - x.start, })); return Object.assign(Object.assign({}, response), { pageRange, clearRange, _response: Object.assign(Object.assign({}, response._response), { parsedBody: { pageRange, clearRange, } }) }); } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * This is the poller returned by {@link BlobClient.beginCopyFromURL}. * This can not be instantiated directly outside of this package. * * @hidden */ class BlobBeginCopyFromUrlPoller extends coreLro.Poller { constructor(options) { const { blobClient, copySource, intervalInMs = 15000, onProgress, resumeFrom, startCopyFromURLOptions, } = options; let state; if (resumeFrom) { state = JSON.parse(resumeFrom).state; } const operation = makeBlobBeginCopyFromURLPollOperation(Object.assign(Object.assign({}, state), { blobClient, copySource, startCopyFromURLOptions })); super(operation); if (typeof onProgress === "function") { this.onProgress(onProgress); } this.intervalInMs = intervalInMs; } delay() { return coreUtil.delay(this.intervalInMs); } } /** * 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. * @hidden */ const cancel = async function cancel(options = {}) { const state = this.state; const { copyId } = state; if (state.isCompleted) { return makeBlobBeginCopyFromURLPollOperation(state); } if (!copyId) { state.isCancelled = true; return makeBlobBeginCopyFromURLPollOperation(state); } // if abortCopyFromURL throws, it will bubble up to user's poller.cancelOperation call await state.blobClient.abortCopyFromURL(copyId, { abortSignal: options.abortSignal, }); state.isCancelled = true; return makeBlobBeginCopyFromURLPollOperation(state); }; /** * 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. * @hidden */ const update = async function update(options = {}) { const state = this.state; const { blobClient, copySource, startCopyFromURLOptions } = state; if (!state.isStarted) { state.isStarted = true; const result = await blobClient.startCopyFromURL(copySource, startCopyFromURLOptions); // copyId is needed to abort state.copyId = result.copyId; if (result.copyStatus === "success") { state.result = result; state.isCompleted = true; } } else if (!state.isCompleted) { try { const result = await state.blobClient.getProperties({ abortSignal: options.abortSignal }); const { copyStatus, copyProgress } = result; const prevCopyProgress = state.copyProgress; if (copyProgress) { state.copyProgress = copyProgress; } if (copyStatus === "pending" && copyProgress !== prevCopyProgress && typeof options.fireProgress === "function") { // trigger in setTimeout, or swallow error? options.fireProgress(state); } else if (copyStatus === "success") { state.result = result; state.isCompleted = true; } else if (copyStatus === "failed") { state.error = new Error(`Blob copy failed with reason: "${result.copyStatusDescription || "unknown"}"`); state.isCompleted = true; } } catch (err) { state.error = err; state.isCompleted = true; } } return makeBlobBeginCopyFromURLPollOperation(state); }; /** * 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. * @hidden */ const toString = function toString() { return JSON.stringify({ state: this.state }, (key, value) => { // remove blobClient from serialized state since a client can't be hydrated from this info. if (key === "blobClient") { return undefined; } return value; }); }; /** * Creates a poll operation given the provided state. * @hidden */ function makeBlobBeginCopyFromURLPollOperation(state) { return { state: Object.assign({}, state), cancel, toString, update, }; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * Generate a range string. For example: * * "bytes=255-" or "bytes=0-511" * * @param iRange - */ function rangeToString(iRange) { if (iRange.offset < 0) { throw new RangeError(`Range.offset cannot be smaller than 0.`); } if (iRange.count && iRange.count <= 0) { throw new RangeError(`Range.count must be larger than 0. Leave it undefined if you want a range from offset to the end.`); } return iRange.count ? `bytes=${iRange.offset}-${iRange.offset + iRange.count - 1}` : `bytes=${iRange.offset}-`; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // In browser, during webpack or browserify bundling, this module will be replaced by 'events' // https://github.com/Gozala/events /** * States for Batch. */ var BatchStates; (function (BatchStates) { BatchStates[BatchStates["Good"] = 0] = "Good"; BatchStates[BatchStates["Error"] = 1] = "Error"; })(BatchStates || (BatchStates = {})); /** * Batch provides basic parallel execution with concurrency limits. * Will stop execute left operations when one of the executed operation throws an error. * But Batch cannot cancel ongoing operations, you need to cancel them by yourself. */ class Batch { /** * Creates an instance of Batch. * @param concurrency - */ constructor(concurrency = 5) { /** * Number of active operations under execution. */ this.actives = 0; /** * Number of completed operations under execution. */ this.completed = 0; /** * Offset of next operation to be executed. */ this.offset = 0; /** * Operation array to be executed. */ this.operations = []; /** * States of Batch. When an error happens, state will turn into error. * Batch will stop execute left operations. */ this.state = BatchStates.Good; if (concurrency < 1) { throw new RangeError("concurrency must be larger than 0"); } this.concurrency = concurrency; this.emitter = new events.EventEmitter(); } /** * Add a operation into queue. * * @param operation - */ addOperation(operation) { this.operations.push(async () => { try { this.actives++; await operation(); this.actives--; this.completed++; this.parallelExecute(); } catch (error) { this.emitter.emit("error", error); } }); } /** * Start execute operations in the queue. * */ async do() { if (this.operations.length === 0) { return Promise.resolve(); } this.parallelExecute(); return new Promise((resolve, reject) => { this.emitter.on("finish", resolve); this.emitter.on("error", (error) => { this.state = BatchStates.Error; reject(error); }); }); } /** * Get next operation to be executed. Return null when reaching ends. * */ nextOperation() { if (this.offset < this.operations.length) { return this.operations[this.offset++]; } return null; } /** * Start execute operations. One one the most important difference between * this method with do() is that do() wraps as an sync method. * */ parallelExecute() { if (this.state === BatchStates.Error) { return; } if (this.completed >= this.operations.length) { this.emitter.emit("finish"); return; } while (this.actives < this.concurrency) { const operation = this.nextOperation(); if (operation) { operation(); } else { return; } } } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * This class generates a readable stream from the data in an array of buffers. */ class BuffersStream extends stream.Readable { /** * Creates an instance of BuffersStream that will emit the data * contained in the array of buffers. * * @param buffers - Array of buffers containing the data * @param byteLength - The total length of data contained in the buffers */ constructor(buffers, byteLength, options) { super(options); this.buffers = buffers; this.byteLength = byteLength; this.byteOffsetInCurrentBuffer = 0; this.bufferIndex = 0; this.pushedBytesLength = 0; // check byteLength is no larger than buffers[] total length let buffersLength = 0; for (const buf of this.buffers) { buffersLength += buf.byteLength; } if (buffersLength < this.byteLength) { throw new Error("Data size shouldn't be larger than the total length of buffers."); } } /** * Internal _read() that will be called when the stream wants to pull more data in. * * @param size - Optional. The size of data to be read */ _read(size) { if (this.pushedBytesLength >= this.byteLength) { this.push(null); } if (!size) { size = this.readableHighWaterMark; } const outBuffers = []; let i = 0; while (i < size && this.pushedBytesLength < this.byteLength) { // The last buffer may be longer than the data it contains. const remainingDataInAllBuffers = this.byteLength - this.pushedBytesLength; const remainingCapacityInThisBuffer = this.buffers[this.bufferIndex].byteLength - this.byteOffsetInCurrentBuffer; const remaining = Math.min(remainingCapacityInThisBuffer, remainingDataInAllBuffers); if (remaining > size - i) { // chunkSize = size - i const end = this.byteOffsetInCurrentBuffer + size - i; outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end)); this.pushedBytesLength += size - i; this.byteOffsetInCurrentBuffer = end; i = size; break; } else { // chunkSize = remaining const end = this.byteOffsetInCurrentBuffer + remaining; outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end)); if (remaining === remainingCapacityInThisBuffer) { // this.buffers[this.bufferIndex] used up, shift to next one this.byteOffsetInCurrentBuffer = 0; this.bufferIndex++; } else { this.byteOffsetInCurrentBuffer = end; } this.pushedBytesLength += remaining; i += remaining; } } if (outBuffers.length > 1) { this.push(Buffer.concat(outBuffers)); } else if (outBuffers.length === 1) { this.push(outBuffers[0]); } } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. const maxBufferLength = buffer.constants.MAX_LENGTH; /** * This class provides a buffer container which conceptually has no hard size limit. * It accepts a capacity, an array of input buffers and the total length of input data. * It will allocate an internal "buffer" of the capacity and fill the data in the input buffers * into the internal "buffer" serially with respect to the total length. * Then by calling PooledBuffer.getReadableStream(), you can get a readable stream * assembled from all the data in the internal "buffer". */ class PooledBuffer { /** * The size of the data contained in the pooled buffers. */ get size() { return this._size; } constructor(capacity, buffers, totalLength) { /** * Internal buffers used to keep the data. * Each buffer has a length of the maxBufferLength except last one. */ this.buffers = []; this.capacity = capacity; this._size = 0; // allocate const bufferNum = Math.ceil(capacity / maxBufferLength); for (let i = 0; i < bufferNum; i++) { let len = i === bufferNum - 1 ? capacity % maxBufferLength : maxBufferLength; if (len === 0) { len = maxBufferLength; } this.buffers.push(Buffer.allocUnsafe(len)); } if (buffers) { this.fill(buffers, totalLength); } } /** * Fill the internal buffers with data in the input buffers serially * with respect to the total length and the total capacity of the internal buffers. * Data copied will be shift out of the input buffers. * * @param buffers - Input buffers containing the data to be filled in the pooled buffer * @param totalLength - Total length of the data to be filled in. * */ fill(buffers, totalLength) { this._size = Math.min(this.capacity, totalLength); let i = 0, j = 0, targetOffset = 0, sourceOffset = 0, totalCopiedNum = 0; while (totalCopiedNum < this._size) { const source = buffers[i]; const target = this.buffers[j]; const copiedNum = source.copy(target, targetOffset, sourceOffset); totalCopiedNum += copiedNum; sourceOffset += copiedNum; targetOffset += copiedNum; if (sourceOffset === source.length) { i++; sourceOffset = 0; } if (targetOffset === target.length) { j++; targetOffset = 0; } } // clear copied from source buffers buffers.splice(0, i); if (buffers.length > 0) { buffers[0] = buffers[0].slice(sourceOffset); } } /** * Get the readable stream assembled from all the data in the internal buffers. * */ getReadableStream() { return new BuffersStream(this.buffers, this.size); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * This class accepts a Node.js Readable stream as input, and keeps reading data * from the stream into the internal buffer structure, until it reaches maxBuffers. * Every available buffer will try to trigger outgoingHandler. * * The internal buffer structure includes an incoming buffer array, and a outgoing * buffer array. The incoming buffer array includes the "empty" buffers can be filled * with new incoming data. The outgoing array includes the filled buffers to be * handled by outgoingHandler. Every above buffer size is defined by parameter bufferSize. * * NUM_OF_ALL_BUFFERS = BUFFERS_IN_INCOMING + BUFFERS_IN_OUTGOING + BUFFERS_UNDER_HANDLING * * NUM_OF_ALL_BUFFERS lesser than or equal to maxBuffers * * PERFORMANCE IMPROVEMENT TIPS: * 1. Input stream highWaterMark is better to set a same value with bufferSize * parameter, which will avoid Buffer.concat() operations. * 2. concurrency should set a smaller value than maxBuffers, which is helpful to * reduce the possibility when a outgoing handler waits for the stream data. * in this situation, outgoing handlers are blocked. * Outgoing queue shouldn't be empty. */ class BufferScheduler { /** * Creates an instance of BufferScheduler. * * @param readable - A Node.js Readable stream * @param bufferSize - Buffer size of every maintained buffer * @param maxBuffers - How many buffers can be allocated * @param outgoingHandler - An async function scheduled to be * triggered when a buffer fully filled * with stream data * @param concurrency - Concurrency of executing outgoingHandlers (>0) * @param encoding - [Optional] Encoding of Readable stream when it's a string stream */ constructor(readable, bufferSize, maxBuffers, outgoingHandler, concurrency, encoding) { /** * An internal event emitter. */ this.emitter = new events.EventEmitter(); /** * An internal offset marker to track data offset in bytes of next outgoingHandler. */ this.offset = 0; /** * An internal marker to track whether stream is end. */ this.isStreamEnd = false; /** * An internal marker to track whether stream or outgoingHandler returns error. */ this.isError = false; /** * How many handlers are executing. */ this.executingOutgoingHandlers = 0; /** * How many buffers have been allocated. */ this.numBuffers = 0; /** * Because this class doesn't know how much data every time stream pops, which * is defined by highWaterMarker of the stream. So BufferScheduler will cache * data received from the stream, when data in unresolvedDataArray exceeds the * blockSize defined, it will try to concat a blockSize of buffer, fill into available * buffers from incoming and push to outgoing array. */ this.unresolvedDataArray = []; /** * How much data consisted in unresolvedDataArray. */ this.unresolvedLength = 0; /** * The array includes all the available buffers can be used to fill data from stream. */ this.incoming = []; /** * The array (queue) includes all the buffers filled from stream data. */ this.outgoing = []; if (bufferSize <= 0) { throw new RangeError(`bufferSize must be larger than 0, current is ${bufferSize}`); } if (maxBuffers <= 0) { throw new RangeError(`maxBuffers must be larger than 0, current is ${maxBuffers}`); } if (concurrency <= 0) { throw new RangeError(`concurrency must be larger than 0, current is ${concurrency}`); } this.bufferSize = bufferSize; this.maxBuffers = maxBuffers; this.readable = readable; this.outgoingHandler = outgoingHandler; this.concurrency = concurrency; this.encoding = encoding; } /** * Start the scheduler, will return error when stream of any of the outgoingHandlers * returns error. * */ async do() { return new Promise((resolve, reject) => { this.readable.on("data", (data) => { data = typeof data === "string" ? Buffer.from(data, this.encoding) : data; this.appendUnresolvedData(data); if (!this.resolveData()) { this.readable.pause(); } }); this.readable.on("error", (err) => { this.emitter.emit("error", err); }); this.readable.on("end", () => { this.isStreamEnd = true; this.emitter.emit("checkEnd"); }); this.emitter.on("error", (err) => { this.isError = true; this.readable.pause(); reject(err); }); this.emitter.on("checkEnd", () => { if (this.outgoing.length > 0) { this.triggerOutgoingHandlers(); return; } if (this.isStreamEnd && this.executingOutgoingHandlers === 0) { if (this.unresolvedLength > 0 && this.unresolvedLength < this.bufferSize) { const buffer = this.shiftBufferFromUnresolvedDataArray(); this.outgoingHandler(() => buffer.getReadableStream(), buffer.size, this.offset) .then(resolve) .catch(reject); } else if (this.unresolvedLength >= this.bufferSize) { return; } else { resolve(); } } }); }); } /** * Insert a new data into unresolved array. * * @param data - */ appendUnresolvedData(data) { this.unresolvedDataArray.push(data); this.unresolvedLength += data.length; } /** * Try to shift a buffer with size in blockSize. The buffer returned may be less * than blockSize when data in unresolvedDataArray is less than bufferSize. * */ shiftBufferFromUnresolvedDataArray(buffer) { if (!buffer) { buffer = new PooledBuffer(this.bufferSize, this.unresolvedDataArray, this.unresolvedLength); } else { buffer.fill(this.unresolvedDataArray, this.unresolvedLength); } this.unresolvedLength -= buffer.size; return buffer; } /** * Resolve data in unresolvedDataArray. For every buffer with size in blockSize * shifted, it will try to get (or allocate a buffer) from incoming, and fill it, * then push it into outgoing to be handled by outgoing handler. * * Return false when available buffers in incoming are not enough, else true. * * @returns Return false when buffers in incoming are not enough, else true. */ resolveData() { while (this.unresolvedLength >= this.bufferSize) { let buffer; if (this.incoming.length > 0) { buffer = this.incoming.shift(); this.shiftBufferFromUnresolvedDataArray(buffer); } else { if (this.numBuffers < this.maxBuffers) { buffer = this.shiftBufferFromUnresolvedDataArray(); this.numBuffers++; } else { // No available buffer, wait for buffer returned return false; } } this.outgoing.push(buffer); this.triggerOutgoingHandlers(); } return true; } /** * Try to trigger a outgoing handler for every buffer in outgoing. Stop when * concurrency reaches. */ async triggerOutgoingHandlers() { let buffer; do { if (this.executingOutgoingHandlers >= this.concurrency) { return; } buffer = this.outgoing.shift(); if (buffer) { this.triggerOutgoingHandler(buffer); } } while (buffer); } /** * Trigger a outgoing handler for a buffer shifted from outgoing. * * @param buffer - */ async triggerOutgoingHandler(buffer) { const bufferLength = buffer.size; this.executingOutgoingHandlers++; this.offset += bufferLength; try { await this.outgoingHandler(() => buffer.getReadableStream(), bufferLength, this.offset - bufferLength); } catch (err) { this.emitter.emit("error", err); return; } this.executingOutgoingHandlers--; this.reuseBuffer(buffer); this.emitter.emit("checkEnd"); } /** * Return buffer used by outgoing handler into incoming. * * @param buffer - */ reuseBuffer(buffer) { this.incoming.push(buffer); if (!this.isError && this.resolveData() && !this.isStreamEnd) { this.readable.resume(); } } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * Reads a readable stream into buffer. Fill the buffer from offset to end. * * @param stream - A Node.js Readable stream * @param buffer - Buffer to be filled, length must greater than or equal to offset * @param offset - From which position in the buffer to be filled, inclusive * @param end - To which position in the buffer to be filled, exclusive * @param encoding - Encoding of the Readable stream */ async function streamToBuffer(stream, buffer, offset, end, encoding) { let pos = 0; // Position in stream const count = end - offset; // Total amount of data needed in stream return new Promise((resolve, reject) => { const timeout = setTimeout(() => reject(new Error(`The operation cannot be completed in timeout.`)), REQUEST_TIMEOUT); stream.on("readable", () => { if (pos >= count) { clearTimeout(timeout); resolve(); return; } let chunk = stream.read(); if (!chunk) { return; } if (typeof chunk === "string") { chunk = Buffer.from(chunk, encoding); } // How much data needed in this chunk const chunkLength = pos + chunk.length > count ? count - pos : chunk.length; buffer.fill(chunk.slice(0, chunkLength), offset + pos, offset + pos + chunkLength); pos += chunkLength; }); stream.on("end", () => { clearTimeout(timeout); if (pos < count) { reject(new Error(`Stream drains before getting enough data needed. Data read: ${pos}, data need: ${count}`)); } resolve(); }); stream.on("error", (msg) => { clearTimeout(timeout); reject(msg); }); }); } /** * Reads a readable stream into buffer entirely. * * @param stream - A Node.js Readable stream * @param buffer - Buffer to be filled, length must greater than or equal to offset * @param encoding - Encoding of the Readable stream * @returns with the count of bytes read. * @throws `RangeError` If buffer size is not big enough. */ async function streamToBuffer2(stream, buffer, encoding) { let pos = 0; // Position in stream const bufferSize = buffer.length; return new Promise((resolve, reject) => { stream.on("readable", () => { let chunk = stream.read(); if (!chunk) { return; } if (typeof chunk === "string") { chunk = Buffer.from(chunk, encoding); } if (pos + chunk.length > bufferSize) { reject(new Error(`Stream exceeds buffer size. Buffer size: ${bufferSize}`)); return; } buffer.fill(chunk, pos, pos + chunk.length); pos += chunk.length; }); stream.on("end", () => { resolve(pos); }); stream.on("error", reject); }); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * Writes the content of a readstream to a local file. Returns a Promise which is completed after the file handle is closed. * * @param rs - The read stream. * @param file - Destination file path. */ async function readStreamToLocalFile(rs, file) { return new Promise((resolve, reject) => { const ws = fs__namespace.createWriteStream(file); rs.on("error", (err) => { reject(err); }); ws.on("error", (err) => { reject(err); }); ws.on("close", resolve); rs.pipe(ws); }); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * Promisified version of fs.stat(). */ const fsStat = util__namespace.promisify(fs__namespace.stat); const fsCreateReadStream = fs__namespace.createReadStream; // Copyright (c) Microsoft Corporation. // 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. */ class BlobClient extends StorageClient { /** * The name of the blob. */ get name() { return this._name; } /** * The name of the storage container the blob is associated with. */ get containerName() { return this._containerName; } constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, // Legacy, no fix for eslint error without breaking. Disable it for this interface. /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ options) { options = options || {}; let pipeline; let url; if (isPipelineLike(credentialOrPipelineOrContainerName)) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; } else if ((coreUtil.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreAuth.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; if (blobNameOrOptions && typeof blobNameOrOptions !== "string") { options = blobNameOrOptions; } pipeline = newPipeline(new AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string" && blobNameOrOptions && typeof blobNameOrOptions === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) const containerName = credentialOrPipelineOrContainerName; const blobName = blobNameOrOptions; const extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { if (coreUtil.isNode) { const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); if (!options.proxyOptions) { options.proxyOptions = coreRestPipeline.getDefaultProxySettings(extractedCreds.proxyUri); } pipeline = newPipeline(sharedKeyCredential, options); } else { throw new Error("Account connection string is only supported in Node.js environment"); } } 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"); } super(url, pipeline); ({ blobName: this._name, containerName: this._containerName } = this.getBlobAndContainerNamesFromUrl()); this.blobContext = this.storageClientContext.blob; this._snapshot = getURLParameter(this.url, URLConstants.Parameters.SNAPSHOT); this._versionId = getURLParameter(this.url, URLConstants.Parameters.VERSIONID); } /** * 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 snapshot - The snapshot timestamp. * @returns A new BlobClient object identical to the source but with the specified snapshot timestamp */ withSnapshot(snapshot) { return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); } /** * 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 versionId - The versionId. * @returns A new BlobClient object pointing to the version of this blob. */ withVersion(versionId) { return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.VERSIONID, versionId.length === 0 ? undefined : versionId), this.pipeline); } /** * Creates a AppendBlobClient object. * */ getAppendBlobClient() { return new AppendBlobClient(this.url, this.pipeline); } /** * Creates a BlockBlobClient object. * */ getBlockBlobClient() { return new BlockBlobClient(this.url, this.pipeline); } /** * Creates a PageBlobClient object. * */ getPageBlobClient() { return new PageBlobClient(this.url, this.pipeline); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/get-blob * * @param offset - From which position of the blob to download, greater than or equal to 0 * @param count - How much data to be downloaded, greater than 0. Will download to the end when undefined * @param options - Optional options to Blob Download operation. * * * 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(typeof data === "string" ? Buffer.from(data) : 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); * }); * } * ``` */ async download(offset = 0, count, options = {}) { options.conditions = options.conditions || {}; options.conditions = options.conditions || {}; ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return tracingClient.withSpan("BlobClient-download", options, async (updatedOptions) => { var _a; const res = assertResponse(await this.blobContext.download({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: { onDownloadProgress: coreUtil.isNode ? undefined : options.onProgress, // for Node.js, progress is reported by RetriableReadableStream }, range: offset === 0 && !count ? undefined : rangeToString({ offset, count }), rangeGetContentMD5: options.rangeGetContentMD5, rangeGetContentCRC64: options.rangeGetContentCrc64, snapshot: options.snapshot, cpkInfo: options.customerProvidedKey, tracingOptions: updatedOptions.tracingOptions, })); const wrappedRes = Object.assign(Object.assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) }); // Return browser response immediately if (!coreUtil.isNode) { return wrappedRes; } // 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.contentLength === undefined) { throw new RangeError(`File download response doesn't contain valid content length header`); } if (!res.etag) { throw new RangeError(`File download response doesn't contain valid etag header`); } return new BlobDownloadResponse(wrappedRes, async (start) => { var _a; const updatedDownloadOptions = { leaseAccessConditions: options.conditions, modifiedAccessConditions: { ifMatch: options.conditions.ifMatch || res.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.contentLength - start, offset: start, }), rangeGetContentMD5: options.rangeGetContentMD5, rangeGetContentCRC64: options.rangeGetContentCrc64, snapshot: options.snapshot, cpkInfo: options.customerProvidedKey, }; // Debug purpose only // console.log( // `Read from internal stream, range: ${ // updatedOptions.range // }, options: ${JSON.stringify(updatedOptions)}` // ); return (await this.blobContext.download(Object.assign({ abortSignal: options.abortSignal }, updatedDownloadOptions))).readableStreamBody; }, offset, res.contentLength, { maxRetryRequests: options.maxRetryRequests, onProgress: options.onProgress, }); }); } /** * 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 options - options to Exists operation. */ async exists(options = {}) { return tracingClient.withSpan("BlobClient-exists", options, async (updatedOptions) => { try { ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); await this.getProperties({ abortSignal: options.abortSignal, customerProvidedKey: options.customerProvidedKey, conditions: options.conditions, tracingOptions: updatedOptions.tracingOptions, }); return true; } catch (e) { if (e.statusCode === 404) { // Expected exception when checking blob existence return false; } else if (e.statusCode === 409 && (e.details.errorCode === BlobUsesCustomerSpecifiedEncryptionMsg || e.details.errorCode === BlobDoesNotUseCustomerSpecifiedEncryption)) { // Expected exception when checking blob existence return true; } throw e; } }); } /** * 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://learn.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. * * @param options - Optional options to Get Properties operation. */ async getProperties(options = {}) { options.conditions = options.conditions || {}; ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return tracingClient.withSpan("BlobClient-getProperties", options, async (updatedOptions) => { var _a; const res = assertResponse(await this.blobContext.getProperties({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, tracingOptions: updatedOptions.tracingOptions, })); return Object.assign(Object.assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) }); }); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/delete-blob * * @param options - Optional options to Blob Delete operation. */ async delete(options = {}) { options.conditions = options.conditions || {}; return tracingClient.withSpan("BlobClient-delete", options, async (updatedOptions) => { var _a; return assertResponse(await this.blobContext.delete({ abortSignal: options.abortSignal, deleteSnapshots: options.deleteSnapshots, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/delete-blob * * @param options - Optional options to Blob Delete operation. */ async deleteIfExists(options = {}) { return tracingClient.withSpan("BlobClient-deleteIfExists", options, async (updatedOptions) => { var _a, _b; try { const res = assertResponse(await this.delete(updatedOptions)); return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); } catch (e) { if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobNotFound") { return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); } throw e; } }); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/undelete-blob * * @param options - Optional options to Blob Undelete operation. */ async undelete(options = {}) { return tracingClient.withSpan("BlobClient-undelete", options, async (updatedOptions) => { return assertResponse(await this.blobContext.undelete({ abortSignal: options.abortSignal, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/set-blob-properties * * @param 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. * A common header to set is `blobContentType` * enabling the browser to provide functionality * based on file type. * @param options - Optional options to Blob Set HTTP Headers operation. */ async setHTTPHeaders(blobHTTPHeaders, options = {}) { options.conditions = options.conditions || {}; ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return tracingClient.withSpan("BlobClient-setHTTPHeaders", options, async (updatedOptions) => { var _a; return assertResponse(await this.blobContext.setHttpHeaders({ abortSignal: options.abortSignal, blobHttpHeaders: blobHTTPHeaders, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), // cpkInfo: options.customerProvidedKey, // CPK is not included in Swagger, should change this back when this issue is fixed in Swagger. tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/set-blob-metadata * * @param metadata - Replace existing metadata with this value. * If no value provided the existing metadata will be removed. * @param options - Optional options to Set Metadata operation. */ async setMetadata(metadata, options = {}) { options.conditions = options.conditions || {}; ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return tracingClient.withSpan("BlobClient-setMetadata", options, async (updatedOptions) => { var _a; return assertResponse(await this.blobContext.setMetadata({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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 - * @param options - */ async setTags(tags, options = {}) { return tracingClient.withSpan("BlobClient-setTags", options, async (updatedOptions) => { var _a; return assertResponse(await this.blobContext.setTags({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), tracingOptions: updatedOptions.tracingOptions, tags: toBlobTags(tags), })); }); } /** * Gets the tags associated with the underlying blob. * * @param options - */ async getTags(options = {}) { return tracingClient.withSpan("BlobClient-getTags", options, async (updatedOptions) => { var _a; const response = assertResponse(await this.blobContext.getTags({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), tracingOptions: updatedOptions.tracingOptions, })); const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, tags: toTags({ blobTagSet: response.blobTagSet }) || {} }); return wrappedResponse; }); } /** * Get a {@link BlobLeaseClient} that manages leases on the blob. * * @param proposeLeaseId - Initial proposed lease Id. * @returns A new BlobLeaseClient object for managing leases on the blob. */ getBlobLeaseClient(proposeLeaseId) { return new BlobLeaseClient(this, proposeLeaseId); } /** * Creates a read-only snapshot of a blob. * @see https://learn.microsoft.com/en-us/rest/api/storageservices/snapshot-blob * * @param options - Optional options to the Blob Create Snapshot operation. */ async createSnapshot(options = {}) { options.conditions = options.conditions || {}; ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return tracingClient.withSpan("BlobClient-createSnapshot", options, async (updatedOptions) => { var _a; return assertResponse(await this.blobContext.createSnapshot({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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://learn.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 copySource - url to the source Azure Blob/File. * @param options - Optional options to the Blob Start Copy From URL operation. */ async beginCopyFromURL(copySource, options = {}) { const client = { abortCopyFromURL: (...args) => this.abortCopyFromURL(...args), getProperties: (...args) => this.getProperties(...args), startCopyFromURL: (...args) => this.startCopyFromURL(...args), }; const poller = new BlobBeginCopyFromUrlPoller({ blobClient: client, 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. await poller.poll(); return poller; } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/abort-copy-blob * * @param copyId - Id of the Copy From URL operation. * @param options - Optional options to the Blob Abort Copy From URL operation. */ async abortCopyFromURL(copyId, options = {}) { return tracingClient.withSpan("BlobClient-abortCopyFromURL", options, async (updatedOptions) => { return assertResponse(await this.blobContext.abortCopyFromURL(copyId, { abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/copy-blob-from-url * * @param copySource - The source URL to copy from, Shared Access Signature(SAS) maybe needed for authentication * @param options - */ async syncCopyFromURL(copySource, options = {}) { options.conditions = options.conditions || {}; options.sourceConditions = options.sourceConditions || {}; return tracingClient.withSpan("BlobClient-syncCopyFromURL", options, async (updatedOptions) => { var _a, _b, _c, _d, _e, _f, _g; return assertResponse(await this.blobContext.copyFromURL(copySource, { abortSignal: options.abortSignal, metadata: options.metadata, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { sourceIfMatch: (_b = options.sourceConditions) === null || _b === void 0 ? void 0 : _b.ifMatch, sourceIfModifiedSince: (_c = options.sourceConditions) === null || _c === void 0 ? void 0 : _c.ifModifiedSince, sourceIfNoneMatch: (_d = options.sourceConditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch, sourceIfUnmodifiedSince: (_e = options.sourceConditions) === null || _e === void 0 ? void 0 : _e.ifUnmodifiedSince, }, sourceContentMD5: options.sourceContentMD5, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), immutabilityPolicyExpiry: (_f = options.immutabilityPolicy) === null || _f === void 0 ? void 0 : _f.expiriesOn, immutabilityPolicyMode: (_g = options.immutabilityPolicy) === null || _g === void 0 ? void 0 : _g.policyMode, legalHold: options.legalHold, encryptionScope: options.encryptionScope, copySourceTags: options.copySourceTags, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/set-blob-tier * * @param tier - The tier to be set on the blob. Valid values are Hot, Cool, or Archive. * @param options - Optional options to the Blob Set Tier operation. */ async setAccessTier(tier, options = {}) { return tracingClient.withSpan("BlobClient-setAccessTier", options, async (updatedOptions) => { var _a; return assertResponse(await this.blobContext.setTier(toAccessTier(tier), { abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), rehydratePriority: options.rehydratePriority, tracingOptions: updatedOptions.tracingOptions, })); }); } async downloadToBuffer(param1, param2, param3, param4 = {}) { var _a; let buffer; let offset = 0; let count = 0; let 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 || {}; } let blockSize = (_a = options.blockSize) !== null && _a !== void 0 ? _a : 0; if (blockSize < 0) { throw new RangeError("blockSize option must be >= 0"); } if (blockSize === 0) { 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 greater than 0"); } if (!options.conditions) { options.conditions = {}; } return tracingClient.withSpan("BlobClient-downloadToBuffer", options, async (updatedOptions) => { // Customer doesn't specify length, get it if (!count) { const response = await this.getProperties(Object.assign(Object.assign({}, options), { tracingOptions: updatedOptions.tracingOptions })); count = response.contentLength - offset; if (count < 0) { throw new RangeError(`offset ${offset} shouldn't be larger than blob size ${response.contentLength}`); } } // 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 (buffer.length < count) { throw new RangeError(`The buffer's size should be equal to or larger than the request count of bytes: ${count}`); } let transferProgress = 0; const batch = new Batch(options.concurrency); for (let off = offset; off < offset + count; off = off + blockSize) { batch.addOperation(async () => { // Exclusive chunk end position let chunkEnd = offset + count; if (off + blockSize < chunkEnd) { chunkEnd = off + blockSize; } const response = await this.download(off, chunkEnd - off, { abortSignal: options.abortSignal, conditions: options.conditions, maxRetryRequests: options.maxRetryRequestsPerBlock, customerProvidedKey: options.customerProvidedKey, tracingOptions: updatedOptions.tracingOptions, }); const stream = response.readableStreamBody; await streamToBuffer(stream, buffer, off - offset, chunkEnd - offset); // 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 += chunkEnd - off; if (options.onProgress) { options.onProgress({ loadedBytes: transferProgress }); } }); } await batch.do(); return buffer; }); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * 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 filePath - * @param offset - From which position of the block blob to download. * @param count - How much data to be downloaded. Will download to the end when passing undefined. * @param options - Options to Blob download options. * @returns 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. */ async downloadToFile(filePath, offset = 0, count, options = {}) { return tracingClient.withSpan("BlobClient-downloadToFile", options, async (updatedOptions) => { const response = await this.download(offset, count, Object.assign(Object.assign({}, options), { tracingOptions: updatedOptions.tracingOptions })); if (response.readableStreamBody) { await readStreamToLocalFile(response.readableStreamBody, filePath); } // The stream is no longer accessible so setting it to undefined. response.blobDownloadStream = undefined; return response; }); } getBlobAndContainerNamesFromUrl() { let containerName; let 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 const parsedUrl = new URL(this.url); if (parsedUrl.host.split(".")[1] === "blob") { // "https://myaccount.blob.core.windows.net/containername/blob". // .getPath() -> /containername/blob const pathComponents = parsedUrl.pathname.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 const pathComponents = parsedUrl.pathname.match("/([^/]*)/([^/]*)(/(.*))?"); containerName = pathComponents[2]; blobName = pathComponents[4]; } else { // "https://customdomain.com/containername/blob". // .getPath() -> /containername/blob const pathComponents = parsedUrl.pathname.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, 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://learn.microsoft.com/en-us/rest/api/storageservices/copy-blob * * @param copySource - url to the source Azure Blob/File. * @param options - Optional options to the Blob Start Copy From URL operation. */ async startCopyFromURL(copySource, options = {}) { return tracingClient.withSpan("BlobClient-startCopyFromURL", options, async (updatedOptions) => { var _a, _b, _c; options.conditions = options.conditions || {}; options.sourceConditions = options.sourceConditions || {}; return assertResponse(await this.blobContext.startCopyFromURL(copySource, { abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.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, }, immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold, rehydratePriority: options.rehydratePriority, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), sealBlob: options.sealBlob, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * * @param options - Optional parameters. * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ generateSasUrl(options) { return new Promise((resolve) => { if (!(this.credential instanceof StorageSharedKeyCredential)) { throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); } const sas = generateBlobSASQueryParameters(Object.assign({ containerName: this._containerName, blobName: this._name, snapshotTime: this._snapshot, versionId: this._versionId }, options), this.credential).toString(); resolve(appendToURLQuery(this.url, sas)); }); } /** * Only available for BlobClient constructed with a shared key credential. * * Generates string to sign for 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://learn.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * * @param options - Optional parameters. * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ generateSasStringToSign(options) { if (!(this.credential instanceof StorageSharedKeyCredential)) { throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); } return generateBlobSASQueryParametersInternal(Object.assign({ containerName: this._containerName, blobName: this._name, snapshotTime: this._snapshot, versionId: this._versionId }, options), this.credential).stringToSign; } /** * * Generates a Blob Service Shared Access Signature (SAS) URI based on * the client properties and parameters passed in. The SAS is signed by the input user delegation key. * * @see https://learn.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * * @param options - Optional parameters. * @param userDelegationKey - Return value of `blobServiceClient.getUserDelegationKey()` * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ generateUserDelegationSasUrl(options, userDelegationKey) { return new Promise((resolve) => { const sas = generateBlobSASQueryParameters(Object.assign({ containerName: this._containerName, blobName: this._name, snapshotTime: this._snapshot, versionId: this._versionId }, options), userDelegationKey, this.accountName).toString(); resolve(appendToURLQuery(this.url, sas)); }); } /** * Only available for BlobClient constructed with a shared key credential. * * Generates string to sign for a Blob Service Shared Access Signature (SAS) URI based on * the client properties and parameters passed in. The SAS is signed by the input user delegation key. * * @see https://learn.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * * @param options - Optional parameters. * @param userDelegationKey - Return value of `blobServiceClient.getUserDelegationKey()` * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ generateUserDelegationSasStringToSign(options, userDelegationKey) { return generateBlobSASQueryParametersInternal(Object.assign({ containerName: this._containerName, blobName: this._name, snapshotTime: this._snapshot, versionId: this._versionId }, options), userDelegationKey, this.accountName).stringToSign; } /** * Delete the immutablility policy on the blob. * * @param options - Optional options to delete immutability policy on the blob. */ async deleteImmutabilityPolicy(options = {}) { return tracingClient.withSpan("BlobClient-deleteImmutabilityPolicy", options, async (updatedOptions) => { return assertResponse(await this.blobContext.deleteImmutabilityPolicy({ tracingOptions: updatedOptions.tracingOptions, })); }); } /** * Set immutability policy on the blob. * * @param options - Optional options to set immutability policy on the blob. */ async setImmutabilityPolicy(immutabilityPolicy, options = {}) { return tracingClient.withSpan("BlobClient-setImmutabilityPolicy", options, async (updatedOptions) => { return assertResponse(await this.blobContext.setImmutabilityPolicy({ immutabilityPolicyExpiry: immutabilityPolicy.expiriesOn, immutabilityPolicyMode: immutabilityPolicy.policyMode, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * Set legal hold on the blob. * * @param options - Optional options to set legal hold on the blob. */ async setLegalHold(legalHoldEnabled, options = {}) { return tracingClient.withSpan("BlobClient-setLegalHold", options, async (updatedOptions) => { return assertResponse(await this.blobContext.setLegalHold(legalHoldEnabled, { tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/get-account-information * * @param options - Options to the Service Get Account Info operation. * @returns Response data for the Service Get Account Info operation. */ async getAccountInfo(options = {}) { return tracingClient.withSpan("BlobClient-getAccountInfo", options, async (updatedOptions) => { return assertResponse(await this.blobContext.getAccountInfo({ abortSignal: options.abortSignal, tracingOptions: updatedOptions.tracingOptions, })); }); } } /** * AppendBlobClient defines a set of operations applicable to append blobs. */ class AppendBlobClient extends BlobClient { constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, // Legacy, no fix for eslint error without breaking. Disable it for this interface. /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ options) { // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); let pipeline; let url; options = options || {}; if (isPipelineLike(credentialOrPipelineOrContainerName)) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; } else if ((coreUtil.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreAuth.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) const containerName = credentialOrPipelineOrContainerName; const blobName = blobNameOrOptions; const extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { if (coreUtil.isNode) { const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); if (!options.proxyOptions) { options.proxyOptions = coreRestPipeline.getDefaultProxySettings(extractedCreds.proxyUri); } pipeline = newPipeline(sharedKeyCredential, options); } else { throw new Error("Account connection string is only supported in Node.js environment"); } } 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"); } super(url, pipeline); this.appendBlobContext = this.storageClientContext.appendBlob; } /** * 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 snapshot - The snapshot timestamp. * @returns A new AppendBlobClient object identical to the source but with the specified snapshot timestamp. */ withSnapshot(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://learn.microsoft.com/rest/api/storageservices/put-blob * * @param options - Options to the Append Block Create operation. * * * Example usage: * * ```js * const appendBlobClient = containerClient.getAppendBlobClient(""); * await appendBlobClient.create(); * ``` */ async create(options = {}) { options.conditions = options.conditions || {}; ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return tracingClient.withSpan("AppendBlobClient-create", options, async (updatedOptions) => { var _a, _b, _c; return assertResponse(await this.appendBlobContext.create(0, { abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold, blobTagsString: toBlobTagsString(options.tags), tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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://learn.microsoft.com/rest/api/storageservices/put-blob * * @param options - */ async createIfNotExists(options = {}) { const conditions = { ifNoneMatch: ETagAny }; return tracingClient.withSpan("AppendBlobClient-createIfNotExists", options, async (updatedOptions) => { var _a, _b; try { const res = assertResponse(await this.create(Object.assign(Object.assign({}, updatedOptions), { conditions }))); return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); } catch (e) { if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); } throw e; } }); } /** * Seals the append blob, making it read only. * * @param options - */ async seal(options = {}) { options.conditions = options.conditions || {}; return tracingClient.withSpan("AppendBlobClient-seal", options, async (updatedOptions) => { var _a; return assertResponse(await this.appendBlobContext.seal({ abortSignal: options.abortSignal, appendPositionAccessConditions: options.conditions, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), tracingOptions: updatedOptions.tracingOptions, })); }); } /** * Commits a new block of data to the end of the existing append blob. * @see https://learn.microsoft.com/rest/api/storageservices/append-block * * @param body - Data to be appended. * @param contentLength - Length of the body in bytes. * @param options - Options to the Append Block operation. * * * 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); * ``` */ async appendBlock(body, contentLength, options = {}) { options.conditions = options.conditions || {}; ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return tracingClient.withSpan("AppendBlobClient-appendBlock", options, async (updatedOptions) => { var _a; return assertResponse(await this.appendBlobContext.appendBlock(contentLength, body, { abortSignal: options.abortSignal, appendPositionAccessConditions: options.conditions, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: { onUploadProgress: options.onProgress, }, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/append-block-from-url * * @param 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 sourceOffset - Offset in source to be appended * @param count - Number of bytes to be appended as a block * @param options - */ async appendBlockFromURL(sourceURL, sourceOffset, count, options = {}) { options.conditions = options.conditions || {}; options.sourceConditions = options.sourceConditions || {}; ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return tracingClient.withSpan("AppendBlobClient-appendBlockFromURL", options, async (updatedOptions) => { var _a, _b, _c, _d, _e; return assertResponse(await this.appendBlobContext.appendBlockFromUrl(sourceURL, 0, { abortSignal: options.abortSignal, sourceRange: rangeToString({ offset: sourceOffset, count }), sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, leaseAccessConditions: options.conditions, appendPositionAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { sourceIfMatch: (_b = options.sourceConditions) === null || _b === void 0 ? void 0 : _b.ifMatch, sourceIfModifiedSince: (_c = options.sourceConditions) === null || _c === void 0 ? void 0 : _c.ifModifiedSince, sourceIfNoneMatch: (_d = options.sourceConditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch, sourceIfUnmodifiedSince: (_e = options.sourceConditions) === null || _e === void 0 ? void 0 : _e.ifUnmodifiedSince, }, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, tracingOptions: updatedOptions.tracingOptions, })); }); } } /** * BlockBlobClient defines a set of operations applicable to block blobs. */ class BlockBlobClient extends BlobClient { constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, // Legacy, no fix for eslint error without breaking. Disable it for this interface. /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ options) { // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); let pipeline; let url; options = options || {}; if (isPipelineLike(credentialOrPipelineOrContainerName)) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; } else if ((coreUtil.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreAuth.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; if (blobNameOrOptions && typeof blobNameOrOptions !== "string") { options = blobNameOrOptions; } pipeline = newPipeline(new AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string" && blobNameOrOptions && typeof blobNameOrOptions === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) const containerName = credentialOrPipelineOrContainerName; const blobName = blobNameOrOptions; const extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { if (coreUtil.isNode) { const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); if (!options.proxyOptions) { options.proxyOptions = coreRestPipeline.getDefaultProxySettings(extractedCreds.proxyUri); } pipeline = newPipeline(sharedKeyCredential, options); } else { throw new Error("Account connection string is only supported in Node.js environment"); } } 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"); } super(url, pipeline); this.blockBlobContext = this.storageClientContext.blockBlob; this._blobContext = this.storageClientContext.blob; } /** * 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 snapshot - The snapshot timestamp. * @returns A new BlockBlobClient object identical to the source but with the specified snapshot timestamp. */ withSnapshot(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(typeof data === "string" ? Buffer.from(data) : data); * }); * readableStream.on("end", () => { * resolve(Buffer.concat(chunks)); * }); * readableStream.on("error", reject); * }); * } * ``` * * @param query - * @param options - */ async query(query, options = {}) { ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); if (!coreUtil.isNode) { throw new Error("This operation currently is only supported in Node.js."); } return tracingClient.withSpan("BlockBlobClient-query", options, async (updatedOptions) => { var _a; const response = assertResponse(await this._blobContext.query({ abortSignal: options.abortSignal, queryRequest: { queryType: "SQL", expression: query, inputSerialization: toQuerySerialization(options.inputTextConfiguration), outputSerialization: toQuerySerialization(options.outputTextConfiguration), }, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, tracingOptions: updatedOptions.tracingOptions, })); return new BlobQueryResponse(response, { abortSignal: options.abortSignal, onProgress: options.onProgress, onError: options.onError, }); }); } /** * 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://learn.microsoft.com/rest/api/storageservices/put-blob * * @param body - Blob, string, ArrayBuffer, ArrayBufferView or a function * which returns a new Readable stream whose offset is from data source beginning. * @param contentLength - Length of body in bytes. Use Buffer.byteLength() to calculate body length for a * string including non non-Base64/Hex-encoded characters. * @param options - Options to the Block Blob Upload operation. * @returns Response data for the Block Blob Upload operation. * * Example usage: * * ```js * const content = "Hello world!"; * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); * ``` */ async upload(body, contentLength, options = {}) { options.conditions = options.conditions || {}; ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return tracingClient.withSpan("BlockBlobClient-upload", options, async (updatedOptions) => { var _a, _b, _c; return assertResponse(await this.blockBlobContext.upload(contentLength, body, { abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: { onUploadProgress: options.onProgress, }, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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 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 options - Optional parameters. */ async syncUploadFromURL(sourceURL, options = {}) { options.conditions = options.conditions || {}; ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return tracingClient.withSpan("BlockBlobClient-syncUploadFromURL", options, async (updatedOptions) => { var _a, _b, _c, _d, _e, _f; return assertResponse(await this.blockBlobContext.putBlobFromUrl(0, sourceURL, Object.assign(Object.assign({}, options), { blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { sourceIfMatch: (_b = options.sourceConditions) === null || _b === void 0 ? void 0 : _b.ifMatch, sourceIfModifiedSince: (_c = options.sourceConditions) === null || _c === void 0 ? void 0 : _c.ifModifiedSince, sourceIfNoneMatch: (_d = options.sourceConditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch, sourceIfUnmodifiedSince: (_e = options.sourceConditions) === null || _e === void 0 ? void 0 : _e.ifUnmodifiedSince, sourceIfTags: (_f = options.sourceConditions) === null || _f === void 0 ? void 0 : _f.tagConditions, }, cpkInfo: options.customerProvidedKey, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), copySourceTags: options.copySourceTags, tracingOptions: updatedOptions.tracingOptions }))); }); } /** * Uploads the specified block to the block blob's "staging area" to be later * committed by a call to commitBlockList. * @see https://learn.microsoft.com/rest/api/storageservices/put-block * * @param blockId - A 64-byte value that is base64-encoded * @param body - Data to upload to the staging area. * @param contentLength - Number of bytes to upload. * @param options - Options to the Block Blob Stage Block operation. * @returns Response data for the Block Blob Stage Block operation. */ async stageBlock(blockId, body, contentLength, options = {}) { ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return tracingClient.withSpan("BlockBlobClient-stageBlock", options, async (updatedOptions) => { return assertResponse(await this.blockBlobContext.stageBlock(blockId, contentLength, body, { abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, requestOptions: { onUploadProgress: options.onProgress, }, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/put-block-from-url * * @param blockId - A 64-byte value that is base64-encoded * @param 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 offset - From which position of the blob to download, greater than or equal to 0 * @param count - How much data to be downloaded, greater than 0. Will download to the end when undefined * @param options - Options to the Block Blob Stage Block From URL operation. * @returns Response data for the Block Blob Stage Block From URL operation. */ async stageBlockFromURL(blockId, sourceURL, offset = 0, count, options = {}) { ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return tracingClient.withSpan("BlockBlobClient-stageBlockFromURL", options, async (updatedOptions) => { return assertResponse(await this.blockBlobContext.stageBlockFromURL(blockId, 0, sourceURL, { abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, sourceRange: offset === 0 && !count ? undefined : rangeToString({ offset, count }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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://learn.microsoft.com/rest/api/storageservices/put-block-list * * @param blocks - Array of 64-byte value that is base64-encoded * @param options - Options to the Block Blob Commit Block List operation. * @returns Response data for the Block Blob Commit Block List operation. */ async commitBlockList(blocks, options = {}) { options.conditions = options.conditions || {}; ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return tracingClient.withSpan("BlockBlobClient-commitBlockList", options, async (updatedOptions) => { var _a, _b, _c; return assertResponse(await this.blockBlobContext.commitBlockList({ latest: blocks }, { abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), tracingOptions: updatedOptions.tracingOptions, })); }); } /** * Returns the list of blocks that have been uploaded as part of a block blob * using the specified block list filter. * @see https://learn.microsoft.com/rest/api/storageservices/get-block-list * * @param listType - Specifies whether to return the list of committed blocks, * the list of uncommitted blocks, or both lists together. * @param options - Options to the Block Blob Get Block List operation. * @returns Response data for the Block Blob Get Block List operation. */ async getBlockList(listType, options = {}) { return tracingClient.withSpan("BlockBlobClient-getBlockList", options, async (updatedOptions) => { var _a; const res = assertResponse(await this.blockBlobContext.getBlockList(listType, { abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), tracingOptions: updatedOptions.tracingOptions, })); if (!res.committedBlocks) { res.committedBlocks = []; } if (!res.uncommittedBlocks) { res.uncommittedBlocks = []; } return res; }); } // 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. * * A common {@link BlockBlobParallelUploadOptions.blobHTTPHeaders} option to set is * `blobContentType`, enabling the browser to provide * functionality based on file type. * * @param data - Buffer(Node.js), Blob, ArrayBuffer or ArrayBufferView * @param options - */ async uploadData(data, options = {}) { return tracingClient.withSpan("BlockBlobClient-uploadData", options, async (updatedOptions) => { if (coreUtil.isNode) { let buffer; if (data instanceof Buffer) { buffer = data; } else if (data instanceof ArrayBuffer) { buffer = Buffer.from(data); } else { data = data; buffer = Buffer.from(data.buffer, data.byteOffset, data.byteLength); } return this.uploadSeekableInternal((offset, size) => buffer.slice(offset, offset + size), buffer.byteLength, updatedOptions); } else { const browserBlob = new Blob([data]); return this.uploadSeekableInternal((offset, size) => browserBlob.slice(offset, offset + size), browserBlob.size, updatedOptions); } }); } /** * ONLY AVAILABLE IN BROWSERS. * * Uploads a browser Blob/File/ArrayBuffer/ArrayBufferView object to block blob. * * When buffer length lesser than or equal to 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. * * A common {@link BlockBlobParallelUploadOptions.blobHTTPHeaders} option to set is * `blobContentType`, enabling the browser to provide * functionality based on file type. * * @deprecated Use {@link uploadData} instead. * * @param browserData - Blob, File, ArrayBuffer or ArrayBufferView * @param options - Options to upload browser data. * @returns Response data for the Blob Upload operation. */ async uploadBrowserData(browserData, options = {}) { return tracingClient.withSpan("BlockBlobClient-uploadBrowserData", options, async (updatedOptions) => { const browserBlob = new Blob([browserData]); return this.uploadSeekableInternal((offset, size) => browserBlob.slice(offset, offset + size), browserBlob.size, updatedOptions); }); } /** * * 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 specified {@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 bodyFactory - * @param size - size of the data to upload. * @param options - Options to Upload to Block Blob operation. * @returns Response data for the Blob Upload operation. */ async uploadSeekableInternal(bodyFactory, size, options = {}) { var _a, _b; let blockSize = (_a = options.blockSize) !== null && _a !== void 0 ? _a : 0; if (blockSize < 0 || blockSize > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES) { throw new RangeError(`blockSize option must be >= 0 and <= ${BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES}`); } const maxSingleShotSize = (_b = options.maxSingleShotSize) !== null && _b !== void 0 ? _b : BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES; if (maxSingleShotSize < 0 || maxSingleShotSize > BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES) { throw new RangeError(`maxSingleShotSize option must be >= 0 and <= ${BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}`); } if (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 > maxSingleShotSize) { blockSize = Math.ceil(size / BLOCK_BLOB_MAX_BLOCKS); if (blockSize < DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES) { blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; } } } if (!options.blobHTTPHeaders) { options.blobHTTPHeaders = {}; } if (!options.conditions) { options.conditions = {}; } return tracingClient.withSpan("BlockBlobClient-uploadSeekableInternal", options, async (updatedOptions) => { if (size <= maxSingleShotSize) { return assertResponse(await this.upload(bodyFactory(0, size), size, updatedOptions)); } const numBlocks = Math.floor((size - 1) / blockSize) + 1; if (numBlocks > 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}`); } const blockList = []; const blockIDPrefix = coreUtil.randomUUID(); let transferProgress = 0; const batch = new Batch(options.concurrency); for (let i = 0; i < numBlocks; i++) { batch.addOperation(async () => { const blockID = generateBlockID(blockIDPrefix, i); const start = blockSize * i; const end = i === numBlocks - 1 ? size : start + blockSize; const contentLength = end - start; blockList.push(blockID); await this.stageBlock(blockID, bodyFactory(start, contentLength), contentLength, { abortSignal: options.abortSignal, conditions: options.conditions, encryptionScope: options.encryptionScope, tracingOptions: updatedOptions.tracingOptions, }); // 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 += contentLength; if (options.onProgress) { options.onProgress({ loadedBytes: transferProgress, }); } }); } await batch.do(); return this.commitBlockList(blockList, updatedOptions); }); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * Uploads a local file in blocks to a block blob. * * When file size lesser than or equal to 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 filePath - Full path of local file * @param options - Options to Upload to Block Blob operation. * @returns Response data for the Blob Upload operation. */ async uploadFile(filePath, options = {}) { return tracingClient.withSpan("BlockBlobClient-uploadFile", options, async (updatedOptions) => { const size = (await fsStat(filePath)).size; return this.uploadSeekableInternal((offset, count) => { return () => fsCreateReadStream(filePath, { autoClose: true, end: count ? offset + count - 1 : Infinity, start: offset, }); }, size, Object.assign(Object.assign({}, options), { tracingOptions: updatedOptions.tracingOptions })); }); } /** * 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. * * @param stream - Node.js Readable stream * @param bufferSize - Size of every buffer allocated, also the block size in the uploaded block blob. Default value is 8MB * @param maxConcurrency - Max concurrency indicates the max number of buffers that can be allocated, * positive correlation with max uploading concurrency. Default value is 5 * @param options - Options to Upload Stream to Block Blob operation. * @returns Response data for the Blob Upload operation. */ async uploadStream(stream, bufferSize = DEFAULT_BLOCK_BUFFER_SIZE_BYTES, maxConcurrency = 5, options = {}) { if (!options.blobHTTPHeaders) { options.blobHTTPHeaders = {}; } if (!options.conditions) { options.conditions = {}; } return tracingClient.withSpan("BlockBlobClient-uploadStream", options, async (updatedOptions) => { let blockNum = 0; const blockIDPrefix = coreUtil.randomUUID(); let transferProgress = 0; const blockList = []; const scheduler = new BufferScheduler(stream, bufferSize, maxConcurrency, async (body, length) => { const blockID = generateBlockID(blockIDPrefix, blockNum); blockList.push(blockID); blockNum++; await this.stageBlock(blockID, body, length, { customerProvidedKey: options.customerProvidedKey, conditions: options.conditions, encryptionScope: options.encryptionScope, tracingOptions: updatedOptions.tracingOptions, }); // Update progress after block is successfully uploaded to server, in case of block trying transferProgress += length; if (options.onProgress) { options.onProgress({ loadedBytes: transferProgress }); } }, // 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)); await scheduler.do(); return assertResponse(await this.commitBlockList(blockList, Object.assign(Object.assign({}, options), { tracingOptions: updatedOptions.tracingOptions }))); }); } } /** * PageBlobClient defines a set of operations applicable to page blobs. */ class PageBlobClient extends BlobClient { constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, // Legacy, no fix for eslint error without breaking. Disable it for this interface. /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ options) { // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); let pipeline; let url; options = options || {}; if (isPipelineLike(credentialOrPipelineOrContainerName)) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; } else if ((coreUtil.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreAuth.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) const containerName = credentialOrPipelineOrContainerName; const blobName = blobNameOrOptions; const extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { if (coreUtil.isNode) { const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); if (!options.proxyOptions) { options.proxyOptions = coreRestPipeline.getDefaultProxySettings(extractedCreds.proxyUri); } pipeline = newPipeline(sharedKeyCredential, options); } else { throw new Error("Account connection string is only supported in Node.js environment"); } } 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"); } super(url, pipeline); this.pageBlobContext = this.storageClientContext.pageBlob; } /** * 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. * * @param snapshot - The snapshot timestamp. * @returns A new PageBlobClient object identical to the source but with the specified snapshot timestamp. */ withSnapshot(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://learn.microsoft.com/rest/api/storageservices/put-blob * * @param size - size of the page blob. * @param options - Options to the Page Blob Create operation. * @returns Response data for the Page Blob Create operation. */ async create(size, options = {}) { options.conditions = options.conditions || {}; ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return tracingClient.withSpan("PageBlobClient-create", options, async (updatedOptions) => { var _a, _b, _c; return assertResponse(await this.pageBlobContext.create(0, size, { abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, blobSequenceNumber: options.blobSequenceNumber, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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://learn.microsoft.com/rest/api/storageservices/put-blob * * @param size - size of the page blob. * @param options - */ async createIfNotExists(size, options = {}) { return tracingClient.withSpan("PageBlobClient-createIfNotExists", options, async (updatedOptions) => { var _a, _b; try { const conditions = { ifNoneMatch: ETagAny }; const res = assertResponse(await this.create(size, Object.assign(Object.assign({}, options), { conditions, tracingOptions: updatedOptions.tracingOptions }))); return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); } catch (e) { if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); } throw e; } }); } /** * Writes 1 or more pages to the page blob. The start and end offsets must be a multiple of 512. * @see https://learn.microsoft.com/rest/api/storageservices/put-page * * @param body - Data to upload * @param offset - Offset of destination page blob * @param count - Content length of the body, also number of bytes to be uploaded * @param options - Options to the Page Blob Upload Pages operation. * @returns Response data for the Page Blob Upload Pages operation. */ async uploadPages(body, offset, count, options = {}) { options.conditions = options.conditions || {}; ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return tracingClient.withSpan("PageBlobClient-uploadPages", options, async (updatedOptions) => { var _a; return assertResponse(await this.pageBlobContext.uploadPages(count, body, { abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: { onUploadProgress: options.onProgress, }, range: rangeToString({ offset, count }), sequenceNumberAccessConditions: options.conditions, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * The Upload Pages operation writes a range of pages to a page blob where the * contents are read from a URL. * @see https://learn.microsoft.com/en-us/rest/api/storageservices/put-page-from-url * * @param sourceURL - Specify a URL to the copy source, Shared Access Signature(SAS) maybe needed for authentication * @param sourceOffset - The source offset to copy from. Pass 0 to copy from the beginning of source page blob * @param destOffset - Offset of destination page blob * @param count - Number of bytes to be uploaded from source page blob * @param options - */ async uploadPagesFromURL(sourceURL, sourceOffset, destOffset, count, options = {}) { options.conditions = options.conditions || {}; options.sourceConditions = options.sourceConditions || {}; ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return tracingClient.withSpan("PageBlobClient-uploadPagesFromURL", options, async (updatedOptions) => { var _a, _b, _c, _d, _e; return assertResponse(await this.pageBlobContext.uploadPagesFromURL(sourceURL, rangeToString({ offset: sourceOffset, count }), 0, rangeToString({ offset: destOffset, count }), { abortSignal: options.abortSignal, sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, leaseAccessConditions: options.conditions, sequenceNumberAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { sourceIfMatch: (_b = options.sourceConditions) === null || _b === void 0 ? void 0 : _b.ifMatch, sourceIfModifiedSince: (_c = options.sourceConditions) === null || _c === void 0 ? void 0 : _c.ifModifiedSince, sourceIfNoneMatch: (_d = options.sourceConditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch, sourceIfUnmodifiedSince: (_e = options.sourceConditions) === null || _e === void 0 ? void 0 : _e.ifUnmodifiedSince, }, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), tracingOptions: updatedOptions.tracingOptions, })); }); } /** * Frees the specified pages from the page blob. * @see https://learn.microsoft.com/rest/api/storageservices/put-page * * @param offset - Starting byte position of the pages to clear. * @param count - Number of bytes to clear. * @param options - Options to the Page Blob Clear Pages operation. * @returns Response data for the Page Blob Clear Pages operation. */ async clearPages(offset = 0, count, options = {}) { options.conditions = options.conditions || {}; return tracingClient.withSpan("PageBlobClient-clearPages", options, async (updatedOptions) => { var _a; return assertResponse(await this.pageBlobContext.clearPages(0, { abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), range: rangeToString({ offset, count }), sequenceNumberAccessConditions: options.conditions, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * Returns the list of valid page ranges for a page blob or snapshot of a page blob. * @see https://learn.microsoft.com/rest/api/storageservices/get-page-ranges * * @param offset - Starting byte position of the page ranges. * @param count - Number of bytes to get. * @param options - Options to the Page Blob Get Ranges operation. * @returns Response data for the Page Blob Get Ranges operation. */ async getPageRanges(offset = 0, count, options = {}) { options.conditions = options.conditions || {}; return tracingClient.withSpan("PageBlobClient-getPageRanges", options, async (updatedOptions) => { var _a; const response = assertResponse(await this.pageBlobContext.getPageRanges({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), range: rangeToString({ offset, count }), tracingOptions: updatedOptions.tracingOptions, })); return rangeResponseFromModel(response); }); } /** * getPageRangesSegment returns a single segment of page ranges starting from the * specified Marker. Use an empty Marker to start enumeration from the beginning. * After getting a segment, process it, and then call getPageRangesSegment again * (passing the the previously-returned Marker) to get the next segment. * @see https://learn.microsoft.com/rest/api/storageservices/get-page-ranges * * @param offset - Starting byte position of the page ranges. * @param count - Number of bytes to get. * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. * @param options - Options to PageBlob Get Page Ranges Segment operation. */ async listPageRangesSegment(offset = 0, count, marker, options = {}) { return tracingClient.withSpan("PageBlobClient-getPageRangesSegment", options, async (updatedOptions) => { var _a; return assertResponse(await this.pageBlobContext.getPageRanges({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), range: rangeToString({ offset, count }), marker: marker, maxPageSize: options.maxPageSize, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * Returns an AsyncIterableIterator for {@link PageBlobGetPageRangesResponseModel} * * @param offset - Starting byte position of the page ranges. * @param count - Number of bytes to get. * @param marker - A string value that identifies the portion of * the get of page ranges to be returned with the next getting operation. The * operation returns the ContinuationToken value within the response body if the * getting operation did not return all page ranges remaining within 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 get * items. The marker value is opaque to the client. * @param options - Options to List Page Ranges operation. */ listPageRangeItemSegments() { return tslib.__asyncGenerator(this, arguments, function* listPageRangeItemSegments_1(offset = 0, count, marker, options = {}) { let getPageRangeItemSegmentsResponse; if (!!marker || marker === undefined) { do { getPageRangeItemSegmentsResponse = yield tslib.__await(this.listPageRangesSegment(offset, count, marker, options)); marker = getPageRangeItemSegmentsResponse.continuationToken; yield yield tslib.__await(yield tslib.__await(getPageRangeItemSegmentsResponse)); } while (marker); } }); } /** * Returns an AsyncIterableIterator of {@link PageRangeInfo} objects * * @param offset - Starting byte position of the page ranges. * @param count - Number of bytes to get. * @param options - Options to List Page Ranges operation. */ listPageRangeItems() { return tslib.__asyncGenerator(this, arguments, function* listPageRangeItems_1(offset = 0, count, options = {}) { var _a, e_1, _b, _c; let marker; try { for (var _d = true, _e = tslib.__asyncValues(this.listPageRangeItemSegments(offset, count, marker, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { _c = _f.value; _d = false; const getPageRangesSegment = _c; yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(ExtractPageRangeInfoItems(getPageRangesSegment)))); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); } finally { if (e_1) throw e_1.error; } } }); } /** * Returns an async iterable iterator to list of page ranges for a page blob. * @see https://learn.microsoft.com/rest/api/storageservices/get-page-ranges * * .byPage() returns an async iterable iterator to list of page ranges for a page blob. * * Example using `for await` syntax: * * ```js * // Get the pageBlobClient before you run these snippets, * // Can be obtained from `blobServiceClient.getContainerClient("").getPageBlobClient("");` * let i = 1; * for await (const pageRange of pageBlobClient.listPageRanges()) { * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); * } * ``` * * Example using `iter.next()`: * * ```js * let i = 1; * let iter = pageBlobClient.listPageRanges(); * let pageRangeItem = await iter.next(); * while (!pageRangeItem.done) { * console.log(`Page range ${i++}: ${pageRangeItem.value.start} - ${pageRangeItem.value.end}, IsClear: ${pageRangeItem.value.isClear}`); * pageRangeItem = await iter.next(); * } * ``` * * Example using `byPage()`: * * ```js * // passing optional maxPageSize in the page settings * let i = 1; * for await (const response of pageBlobClient.listPageRanges().byPage({ maxPageSize: 20 })) { * for (const pageRange of response) { * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); * } * } * ``` * * Example using paging with a marker: * * ```js * let i = 1; * let iterator = pageBlobClient.listPageRanges().byPage({ maxPageSize: 2 }); * let response = (await iterator.next()).value; * * // Prints 2 page ranges * for (const pageRange of response) { * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); * } * * // Gets next marker * let marker = response.continuationToken; * * // Passing next marker as continuationToken * * iterator = pageBlobClient.listPageRanges().byPage({ continuationToken: marker, maxPageSize: 10 }); * response = (await iterator.next()).value; * * // Prints 10 page ranges * for (const blob of response) { * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); * } * ``` * @param offset - Starting byte position of the page ranges. * @param count - Number of bytes to get. * @param options - Options to the Page Blob Get Ranges operation. * @returns An asyncIterableIterator that supports paging. */ listPageRanges(offset = 0, count, options = {}) { options.conditions = options.conditions || {}; // AsyncIterableIterator to iterate over blobs const iter = this.listPageRangeItems(offset, count, options); return { /** * The next method, part of the iteration protocol */ next() { return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ [Symbol.asyncIterator]() { return this; }, /** * Return an AsyncIterableIterator that works a page at a time */ byPage: (settings = {}) => { return this.listPageRangeItemSegments(offset, count, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, options)); }, }; } /** * Gets the collection of page ranges that differ between a specified snapshot and this page blob. * @see https://learn.microsoft.com/rest/api/storageservices/get-page-ranges * * @param offset - Starting byte position of the page blob * @param count - Number of bytes to get ranges diff. * @param prevSnapshot - Timestamp of snapshot to retrieve the difference. * @param options - Options to the Page Blob Get Page Ranges Diff operation. * @returns Response data for the Page Blob Get Page Range Diff operation. */ async getPageRangesDiff(offset, count, prevSnapshot, options = {}) { options.conditions = options.conditions || {}; return tracingClient.withSpan("PageBlobClient-getPageRangesDiff", options, async (updatedOptions) => { var _a; const result = assertResponse(await this.pageBlobContext.getPageRangesDiff({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), prevsnapshot: prevSnapshot, range: rangeToString({ offset, count }), tracingOptions: updatedOptions.tracingOptions, })); return rangeResponseFromModel(result); }); } /** * getPageRangesDiffSegment returns a single segment of page ranges starting from the * specified Marker for difference between previous snapshot and the target page blob. * Use an empty Marker to start enumeration from the beginning. * After getting a segment, process it, and then call getPageRangesDiffSegment again * (passing the the previously-returned Marker) to get the next segment. * @see https://learn.microsoft.com/rest/api/storageservices/get-page-ranges * * @param offset - Starting byte position of the page ranges. * @param count - Number of bytes to get. * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. * @param marker - A string value that identifies the portion of the get to be returned with the next get operation. * @param options - Options to the Page Blob Get Page Ranges Diff operation. */ async listPageRangesDiffSegment(offset, count, prevSnapshotOrUrl, marker, options = {}) { return tracingClient.withSpan("PageBlobClient-getPageRangesDiffSegment", options, async (updatedOptions) => { var _a; return assertResponse(await this.pageBlobContext.getPageRangesDiff({ abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal, leaseAccessConditions: options === null || options === void 0 ? void 0 : options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.conditions), { ifTags: (_a = options === null || options === void 0 ? void 0 : options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), prevsnapshot: prevSnapshotOrUrl, range: rangeToString({ offset: offset, count: count, }), marker: marker, maxPageSize: options === null || options === void 0 ? void 0 : options.maxPageSize, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * Returns an AsyncIterableIterator for {@link PageBlobGetPageRangesDiffResponseModel} * * * @param offset - Starting byte position of the page ranges. * @param count - Number of bytes to get. * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. * @param marker - A string value that identifies the portion of * the get of page ranges to be returned with the next getting operation. The * operation returns the ContinuationToken value within the response body if the * getting operation did not return all page ranges remaining within 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 get * items. The marker value is opaque to the client. * @param options - Options to the Page Blob Get Page Ranges Diff operation. */ listPageRangeDiffItemSegments(offset, count, prevSnapshotOrUrl, marker, options) { return tslib.__asyncGenerator(this, arguments, function* listPageRangeDiffItemSegments_1() { let getPageRangeItemSegmentsResponse; if (!!marker || marker === undefined) { do { getPageRangeItemSegmentsResponse = yield tslib.__await(this.listPageRangesDiffSegment(offset, count, prevSnapshotOrUrl, marker, options)); marker = getPageRangeItemSegmentsResponse.continuationToken; yield yield tslib.__await(yield tslib.__await(getPageRangeItemSegmentsResponse)); } while (marker); } }); } /** * Returns an AsyncIterableIterator of {@link PageRangeInfo} objects * * @param offset - Starting byte position of the page ranges. * @param count - Number of bytes to get. * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. * @param options - Options to the Page Blob Get Page Ranges Diff operation. */ listPageRangeDiffItems(offset, count, prevSnapshotOrUrl, options) { return tslib.__asyncGenerator(this, arguments, function* listPageRangeDiffItems_1() { var _a, e_2, _b, _c; let marker; try { for (var _d = true, _e = tslib.__asyncValues(this.listPageRangeDiffItemSegments(offset, count, prevSnapshotOrUrl, marker, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { _c = _f.value; _d = false; const getPageRangesSegment = _c; yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(ExtractPageRangeInfoItems(getPageRangesSegment)))); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); } finally { if (e_2) throw e_2.error; } } }); } /** * Returns an async iterable iterator to list of page ranges that differ between a specified snapshot and this page blob. * @see https://learn.microsoft.com/rest/api/storageservices/get-page-ranges * * .byPage() returns an async iterable iterator to list of page ranges that differ between a specified snapshot and this page blob. * * Example using `for await` syntax: * * ```js * // Get the pageBlobClient before you run these snippets, * // Can be obtained from `blobServiceClient.getContainerClient("").getPageBlobClient("");` * let i = 1; * for await (const pageRange of pageBlobClient.listPageRangesDiff()) { * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); * } * ``` * * Example using `iter.next()`: * * ```js * let i = 1; * let iter = pageBlobClient.listPageRangesDiff(); * let pageRangeItem = await iter.next(); * while (!pageRangeItem.done) { * console.log(`Page range ${i++}: ${pageRangeItem.value.start} - ${pageRangeItem.value.end}, IsClear: ${pageRangeItem.value.isClear}`); * pageRangeItem = await iter.next(); * } * ``` * * Example using `byPage()`: * * ```js * // passing optional maxPageSize in the page settings * let i = 1; * for await (const response of pageBlobClient.listPageRangesDiff().byPage({ maxPageSize: 20 })) { * for (const pageRange of response) { * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); * } * } * ``` * * Example using paging with a marker: * * ```js * let i = 1; * let iterator = pageBlobClient.listPageRangesDiff().byPage({ maxPageSize: 2 }); * let response = (await iterator.next()).value; * * // Prints 2 page ranges * for (const pageRange of response) { * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); * } * * // Gets next marker * let marker = response.continuationToken; * * // Passing next marker as continuationToken * * iterator = pageBlobClient.listPageRangesDiff().byPage({ continuationToken: marker, maxPageSize: 10 }); * response = (await iterator.next()).value; * * // Prints 10 page ranges * for (const blob of response) { * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); * } * ``` * @param offset - Starting byte position of the page ranges. * @param count - Number of bytes to get. * @param prevSnapshot - Timestamp of snapshot to retrieve the difference. * @param options - Options to the Page Blob Get Ranges operation. * @returns An asyncIterableIterator that supports paging. */ listPageRangesDiff(offset, count, prevSnapshot, options = {}) { options.conditions = options.conditions || {}; // AsyncIterableIterator to iterate over blobs const iter = this.listPageRangeDiffItems(offset, count, prevSnapshot, Object.assign({}, options)); return { /** * The next method, part of the iteration protocol */ next() { return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ [Symbol.asyncIterator]() { return this; }, /** * Return an AsyncIterableIterator that works a page at a time */ byPage: (settings = {}) => { return this.listPageRangeDiffItemSegments(offset, count, prevSnapshot, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, options)); }, }; } /** * Gets the collection of page ranges that differ between a specified snapshot and this page blob for managed disks. * @see https://learn.microsoft.com/rest/api/storageservices/get-page-ranges * * @param offset - Starting byte position of the page blob * @param count - Number of bytes to get ranges diff. * @param prevSnapshotUrl - URL of snapshot to retrieve the difference. * @param options - Options to the Page Blob Get Page Ranges Diff operation. * @returns Response data for the Page Blob Get Page Range Diff operation. */ async getPageRangesDiffForManagedDisks(offset, count, prevSnapshotUrl, options = {}) { options.conditions = options.conditions || {}; return tracingClient.withSpan("PageBlobClient-GetPageRangesDiffForManagedDisks", options, async (updatedOptions) => { var _a; const response = assertResponse(await this.pageBlobContext.getPageRangesDiff({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), prevSnapshotUrl, range: rangeToString({ offset, count }), tracingOptions: updatedOptions.tracingOptions, })); return rangeResponseFromModel(response); }); } /** * Resizes the page blob to the specified size (which must be a multiple of 512). * @see https://learn.microsoft.com/rest/api/storageservices/set-blob-properties * * @param size - Target size * @param options - Options to the Page Blob Resize operation. * @returns Response data for the Page Blob Resize operation. */ async resize(size, options = {}) { options.conditions = options.conditions || {}; return tracingClient.withSpan("PageBlobClient-resize", options, async (updatedOptions) => { var _a; return assertResponse(await this.pageBlobContext.resize(size, { abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), encryptionScope: options.encryptionScope, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * Sets a page blob's sequence number. * @see https://learn.microsoft.com/en-us/rest/api/storageservices/set-blob-properties * * @param sequenceNumberAction - Indicates how the service should modify the blob's sequence number. * @param sequenceNumber - Required if sequenceNumberAction is max or update * @param options - Options to the Page Blob Update Sequence Number operation. * @returns Response data for the Page Blob Update Sequence Number operation. */ async updateSequenceNumber(sequenceNumberAction, sequenceNumber, options = {}) { options.conditions = options.conditions || {}; return tracingClient.withSpan("PageBlobClient-updateSequenceNumber", options, async (updatedOptions) => { var _a; return assertResponse(await this.pageBlobContext.updateSequenceNumber(sequenceNumberAction, { abortSignal: options.abortSignal, blobSequenceNumber: sequenceNumber, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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://learn.microsoft.com/rest/api/storageservices/incremental-copy-blob * @see https://learn.microsoft.com/en-us/azure/virtual-machines/windows/incremental-snapshots * * @param copySource - Specifies the name of the source page blob snapshot. For example, * https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= * @param options - Options to the Page Blob Copy Incremental operation. * @returns Response data for the Page Blob Copy Incremental operation. */ async startCopyIncremental(copySource, options = {}) { return tracingClient.withSpan("PageBlobClient-startCopyIncremental", options, async (updatedOptions) => { var _a; return assertResponse(await this.pageBlobContext.copyIncremental(copySource, { abortSignal: options.abortSignal, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), tracingOptions: updatedOptions.tracingOptions, })); }); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. async function getBodyAsText(batchResponse) { let buffer = Buffer.alloc(BATCH_MAX_PAYLOAD_IN_BYTES); const responseLength = await streamToBuffer2(batchResponse.readableStreamBody, buffer); // Slice the buffer to trim the empty ending. buffer = buffer.slice(0, responseLength); return buffer.toString(); } function utf8ByteLength(str) { return Buffer.byteLength(str); } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. const HTTP_HEADER_DELIMITER = ": "; const SPACE_DELIMITER = " "; const NOT_FOUND = -1; /** * Util class for parsing batch response. */ class BatchResponseParser { constructor(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://learn.microsoft.com/en-us/rest/api/storageservices/blob-batch#response async parseBatchResponse() { // 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}'.`); } const responseBodyAsText = await getBodyAsText(this.batchResponse); const subResponses = responseBodyAsText .split(this.batchResponseEnding)[0] // string after ending is useless .split(this.perResponsePrefix) .slice(1); // string before first response boundary is useless const 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."); } const deserializedSubResponses = new Array(subResponseCount); let subResponsesSucceededCount = 0; let subResponsesFailedCount = 0; // Parse sub subResponses. for (let index = 0; index < subResponseCount; index++) { const subResponse = subResponses[index]; const deserializedSubResponse = {}; deserializedSubResponse.headers = coreHttpCompat.toHttpHeadersLike(coreRestPipeline.createHttpHeaders()); const responseLines = subResponse.split(`${HTTP_LINE_ENDING}`); let subRespHeaderStartFound = false; let subRespHeaderEndFound = false; let subRespFailed = false; let contentId = NOT_FOUND; for (const responseLine of responseLines) { 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; const 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}'.`); } // Parse headers of sub response. const 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 { subResponses: deserializedSubResponses, subResponsesSucceededCount: subResponsesSucceededCount, subResponsesFailedCount: subResponsesFailedCount, }; } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. var MutexLockStatus; (function (MutexLockStatus) { MutexLockStatus[MutexLockStatus["LOCKED"] = 0] = "LOCKED"; MutexLockStatus[MutexLockStatus["UNLOCKED"] = 1] = "UNLOCKED"; })(MutexLockStatus || (MutexLockStatus = {})); /** * An async mutex lock. */ class Mutex { /** * Lock for a specific key. If the lock has been acquired by another customer, then * will wait until getting the lock. * * @param key - lock key */ static async lock(key) { return new Promise((resolve) => { if (this.keys[key] === undefined || this.keys[key] === MutexLockStatus.UNLOCKED) { this.keys[key] = MutexLockStatus.LOCKED; resolve(); } else { this.onUnlockEvent(key, () => { this.keys[key] = MutexLockStatus.LOCKED; resolve(); }); } }); } /** * Unlock a key. * * @param key - */ static async unlock(key) { return new Promise((resolve) => { if (this.keys[key] === MutexLockStatus.LOCKED) { this.emitUnlockEvent(key); } delete this.keys[key]; resolve(); }); } static onUnlockEvent(key, handler) { if (this.listeners[key] === undefined) { this.listeners[key] = [handler]; } else { this.listeners[key].push(handler); } } static emitUnlockEvent(key) { if (this.listeners[key] !== undefined && this.listeners[key].length > 0) { const handler = this.listeners[key].shift(); setImmediate(() => { handler.call(this); }); } } } Mutex.keys = {}; Mutex.listeners = {}; // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * A BlobBatch represents an aggregated set of operations on blobs. * Currently, only `delete` and `setAccessTier` are supported. */ class BlobBatch { constructor() { 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 */ getMultiPartContentType() { return this.batchRequest.getMultipartContentType(); } /** * Get assembled HTTP request body for sub requests. */ getHttpRequestBody() { return this.batchRequest.getHttpRequestBody(); } /** * Get sub requests that are added into the batch request. */ getSubRequests() { return this.batchRequest.getSubRequests(); } async addSubRequestInternal(subRequest, assembleSubRequestFunc) { await Mutex.lock(this.batch); try { this.batchRequest.preAddSubRequest(subRequest); await assembleSubRequestFunc(); this.batchRequest.postAddSubRequest(subRequest); } finally { await Mutex.unlock(this.batch); } } setBatchType(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.`); } } async deleteBlob(urlOrBlobClient, credentialOrOptions, options) { let url; let credential; if (typeof urlOrBlobClient === "string" && ((coreUtil.isNode && credentialOrOptions instanceof StorageSharedKeyCredential) || credentialOrOptions instanceof AnonymousCredential || coreAuth.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 = {}; } return tracingClient.withSpan("BatchDeleteRequest-addSubRequest", options, async (updatedOptions) => { this.setBatchType("delete"); await this.addSubRequestInternal({ url: url, credential: credential, }, async () => { await new BlobClient(url, this.batchRequest.createPipeline(credential)).delete(updatedOptions); }); }); } async setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options) { let url; let credential; let tier; if (typeof urlOrBlobClient === "string" && ((coreUtil.isNode && credentialOrTier instanceof StorageSharedKeyCredential) || credentialOrTier instanceof AnonymousCredential || coreAuth.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 = {}; } return tracingClient.withSpan("BatchSetTierRequest-addSubRequest", options, async (updatedOptions) => { this.setBatchType("setAccessTier"); await this.addSubRequestInternal({ url: url, credential: credential, }, async () => { await new BlobClient(url, this.batchRequest.createPipeline(credential)).setAccessTier(tier, updatedOptions); }); }); } } /** * Inner batch request class which is responsible for assembling and serializing sub requests. * See https://learn.microsoft.com/en-us/rest/api/storageservices/blob-batch#request-body for how requests are assembled. */ class InnerBatchRequest { constructor() { this.operationCount = 0; this.body = ""; const tempGuid = coreUtil.randomUUID(); // 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 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. */ createPipeline(credential) { const corePipeline = coreRestPipeline.createEmptyPipeline(); corePipeline.addPolicy(coreClient.serializationPolicy({ stringifyXML: coreXml.stringifyXML, serializerOptions: { xml: { xmlCharKey: "#", }, }, }), { phase: "Serialize" }); // Use batch header filter policy to exclude unnecessary headers corePipeline.addPolicy(batchHeaderFilterPolicy()); // Use batch assemble policy to assemble request and intercept request from going to wire corePipeline.addPolicy(batchRequestAssemblePolicy(this), { afterPhase: "Sign" }); if (coreAuth.isTokenCredential(credential)) { corePipeline.addPolicy(coreRestPipeline.bearerTokenAuthenticationPolicy({ credential, scopes: StorageOAuthScopes, challengeCallbacks: { authorizeRequestOnChallenge: coreClient.authorizeRequestOnTenantChallenge }, }), { phase: "Sign" }); } else if (credential instanceof StorageSharedKeyCredential) { corePipeline.addPolicy(storageSharedKeyCredentialPolicy({ accountName: credential.accountName, accountKey: credential.accountKey, }), { phase: "Sign" }); } const pipeline = new Pipeline([]); // attach the v2 pipeline to this one pipeline._credential = credential; pipeline._corePipeline = corePipeline; return pipeline; } appendSubRequestToBody(request) { // Start to assemble sub request this.body += [ this.subRequestPrefix, // sub request constant prefix `${HeaderConstants.CONTENT_ID}: ${this.operationCount}`, // sub request's content ID "", // empty line after sub request's content ID `${request.method.toString()} ${getURLPathAndQuery(request.url)} ${HTTP_VERSION_1_1}${HTTP_LINE_ENDING}`, // sub request start line with method ].join(HTTP_LINE_ENDING); for (const [name, value] of request.headers) { this.body += `${name}: ${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 } preAddSubRequest(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 const path = getURLPath(subRequest.url); if (!path || path === "") { throw new RangeError(`Invalid url for sub request: '${subRequest.url}'`); } } postAddSubRequest(subRequest) { this.subRequests.set(this.operationCount, subRequest); this.operationCount++; } // Return the http request body with assembling the ending line to the sub request body. getHttpRequestBody() { return `${this.body}${this.batchRequestEnding}${HTTP_LINE_ENDING}`; } getMultipartContentType() { return this.multipartContentType; } getSubRequests() { return this.subRequests; } } function batchRequestAssemblePolicy(batchRequest) { return { name: "batchRequestAssemblePolicy", async sendRequest(request) { batchRequest.appendSubRequestToBody(request); return { request, status: 200, headers: coreRestPipeline.createHttpHeaders(), }; }, }; } function batchHeaderFilterPolicy() { return { name: "batchHeaderFilterPolicy", async sendRequest(request, next) { let xMsHeaderName = ""; for (const [name] of request.headers) { if (iEqual(name, HeaderConstants.X_MS_VERSION)) { xMsHeaderName = name; } } if (xMsHeaderName !== "") { request.headers.delete(xMsHeaderName); // The subrequests should not have the x-ms-version header. } return next(request); }, }; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * A BlobBatchClient allows you to make batched requests to the Azure Storage Blob service. * * @see https://learn.microsoft.com/en-us/rest/api/storageservices/blob-batch */ class BlobBatchClient { constructor(url, credentialOrPipeline, // Legacy, no fix for eslint error without breaking. Disable it for this interface. /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ options) { let pipeline; if (isPipelineLike(credentialOrPipeline)) { pipeline = credentialOrPipeline; } else if (!credentialOrPipeline) { // no credential provided pipeline = newPipeline(new AnonymousCredential(), options); } else { pipeline = newPipeline(credentialOrPipeline, options); } const storageClientContext = new StorageContextClient(url, getCoreClientOptions(pipeline)); const path = getURLPath(url); if (path && path !== "/") { // Container scoped. this.serviceOrContainerContext = storageClientContext.container; } else { this.serviceOrContainerContext = storageClientContext.service; } } /** * Creates a {@link BlobBatch}. * A BlobBatch represents an aggregated set of operations on blobs. */ createBatch() { return new BlobBatch(); } async deleteBlobs(urlsOrBlobClients, credentialOrOptions, // Legacy, no fix for eslint error without breaking. Disable it for this interface. /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ options) { const batch = new BlobBatch(); for (const urlOrBlobClient of urlsOrBlobClients) { if (typeof urlOrBlobClient === "string") { await batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options); } else { await batch.deleteBlob(urlOrBlobClient, credentialOrOptions); } } return this.submitBatch(batch); } async setBlobsAccessTier(urlsOrBlobClients, credentialOrTier, tierOrOptions, // Legacy, no fix for eslint error without breaking. Disable it for this interface. /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ options) { const batch = new BlobBatch(); for (const urlOrBlobClient of urlsOrBlobClients) { if (typeof urlOrBlobClient === "string") { await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options); } else { await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions); } } return this.submitBatch(batch); } /** * Submit batch request which consists of multiple subrequests. * * Get `blobBatchClient` and other details before running the snippets. * `blobServiceClient.getBlobBatchClient()` gives the `blobBatchClient` * * Example usage: * * ```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); * ``` * * Example using a lease: * * ```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); * ``` * * @see https://learn.microsoft.com/en-us/rest/api/storageservices/blob-batch * * @param batchRequest - A set of Delete or SetTier operations. * @param options - */ async submitBatch(batchRequest, options = {}) { if (!batchRequest || batchRequest.getSubRequests().size === 0) { throw new RangeError("Batch request should contain one or more sub requests."); } return tracingClient.withSpan("BlobBatchClient-submitBatch", options, async (updatedOptions) => { const batchRequestBody = batchRequest.getHttpRequestBody(); // ServiceSubmitBatchResponseModel and ContainerSubmitBatchResponse are compatible for now. const rawBatchResponse = assertResponse(await this.serviceOrContainerContext.submitBatch(utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), batchRequestBody, Object.assign({}, updatedOptions))); // Parse the sub responses result, if logic reaches here(i.e. the batch request succeeded with status code 202). const batchResponseParser = new BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests()); const responseSummary = await batchResponseParser.parseBatchResponse(); const 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 res; }); } } /** * A ContainerClient represents a URL to the Azure Storage container allowing you to manipulate its blobs. */ class ContainerClient extends StorageClient { /** * The name of the container. */ get containerName() { return this._containerName; } constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, // Legacy, no fix for eslint error without breaking. Disable it for this interface. /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ options) { let pipeline; let url; options = options || {}; if (isPipelineLike(credentialOrPipelineOrContainerName)) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; } else if ((coreUtil.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreAuth.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) const containerName = credentialOrPipelineOrContainerName; const extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { if (coreUtil.isNode) { const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); url = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)); if (!options.proxyOptions) { options.proxyOptions = coreRestPipeline.getDefaultProxySettings(extractedCreds.proxyUri); } pipeline = newPipeline(sharedKeyCredential, options); } else { throw new Error("Account connection string is only supported in Node.js environment"); } } 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"); } super(url, pipeline); this._containerName = this.getContainerNameFromUrl(); this.containerContext = this.storageClientContext.container; } /** * Creates a new container under the specified account. If the container with * the same name already exists, the operation fails. * @see https://learn.microsoft.com/en-us/rest/api/storageservices/create-container * Naming rules: @see https://learn.microsoft.com/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata * * @param options - Options to Container Create operation. * * * Example usage: * * ```js * const containerClient = blobServiceClient.getContainerClient(""); * const createContainerResponse = await containerClient.create(); * console.log("Container was created successfully", createContainerResponse.requestId); * ``` */ async create(options = {}) { return tracingClient.withSpan("ContainerClient-create", options, async (updatedOptions) => { return assertResponse(await this.containerContext.create(updatedOptions)); }); } /** * Creates a new container under the specified account. If the container with * the same name already exists, it is not changed. * @see https://learn.microsoft.com/en-us/rest/api/storageservices/create-container * Naming rules: @see https://learn.microsoft.com/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata * * @param options - */ async createIfNotExists(options = {}) { return tracingClient.withSpan("ContainerClient-createIfNotExists", options, async (updatedOptions) => { var _a, _b; try { const res = await this.create(updatedOptions); return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); } catch (e) { if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerAlreadyExists") { return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); } else { throw e; } } }); } /** * 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. * * @param options - */ async exists(options = {}) { return tracingClient.withSpan("ContainerClient-exists", options, async (updatedOptions) => { try { await this.getProperties({ abortSignal: options.abortSignal, tracingOptions: updatedOptions.tracingOptions, }); return true; } catch (e) { if (e.statusCode === 404) { return false; } throw e; } }); } /** * Creates a {@link BlobClient} * * @param blobName - A blob name * @returns A new BlobClient object for the given blob name. */ getBlobClient(blobName) { return new BlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); } /** * Creates an {@link AppendBlobClient} * * @param blobName - An append blob name */ getAppendBlobClient(blobName) { return new AppendBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); } /** * Creates a {@link BlockBlobClient} * * @param blobName - A block blob name * * * Example usage: * * ```js * const content = "Hello world!"; * * const blockBlobClient = containerClient.getBlockBlobClient(""); * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); * ``` */ getBlockBlobClient(blobName) { return new BlockBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); } /** * Creates a {@link PageBlobClient} * * @param blobName - A page blob name */ getPageBlobClient(blobName) { return new PageBlobClient(appendToURLPath(this.url, EscapePath(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://learn.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. * * @param options - Options to Container Get Properties operation. */ async getProperties(options = {}) { if (!options.conditions) { options.conditions = {}; } return tracingClient.withSpan("ContainerClient-getProperties", options, async (updatedOptions) => { return assertResponse(await this.containerContext.getProperties(Object.assign(Object.assign({ abortSignal: options.abortSignal }, options.conditions), { tracingOptions: updatedOptions.tracingOptions }))); }); } /** * Marks the specified container for deletion. The container and any blobs * contained within it are later deleted during garbage collection. * @see https://learn.microsoft.com/en-us/rest/api/storageservices/delete-container * * @param options - Options to Container Delete operation. */ async delete(options = {}) { if (!options.conditions) { options.conditions = {}; } return tracingClient.withSpan("ContainerClient-delete", options, async (updatedOptions) => { return assertResponse(await this.containerContext.delete({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: options.conditions, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/delete-container * * @param options - Options to Container Delete operation. */ async deleteIfExists(options = {}) { return tracingClient.withSpan("ContainerClient-deleteIfExists", options, async (updatedOptions) => { var _a, _b; try { const res = await this.delete(updatedOptions); return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); } catch (e) { if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerNotFound") { return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); } throw e; } }); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/set-container-metadata * * @param metadata - Replace existing metadata with this value. * If no value provided the existing metadata will be removed. * @param options - Options to Container Set Metadata operation. */ async setMetadata(metadata, options = {}) { 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"); } return tracingClient.withSpan("ContainerClient-setMetadata", options, async (updatedOptions) => { return assertResponse(await this.containerContext.setMetadata({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata, modifiedAccessConditions: options.conditions, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/get-container-acl * * @param options - Options to Container Get Access Policy operation. */ async getAccessPolicy(options = {}) { if (!options.conditions) { options.conditions = {}; } return tracingClient.withSpan("ContainerClient-getAccessPolicy", options, async (updatedOptions) => { const response = assertResponse(await this.containerContext.getAccessPolicy({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, tracingOptions: updatedOptions.tracingOptions, })); const 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 (const identifier of response) { let 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, id: identifier.id, }); } return res; }); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/set-container-acl * * @param access - The level of public access to data in the container. * @param containerAcl - Array of elements each having a unique Id and details of the access policy. * @param options - Options to Container Set Access Policy operation. */ async setAccessPolicy(access, containerAcl, options = {}) { options.conditions = options.conditions || {}; return tracingClient.withSpan("ContainerClient-setAccessPolicy", options, async (updatedOptions) => { const acl = []; for (const identifier of containerAcl || []) { 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 assertResponse(await this.containerContext.setAccessPolicy({ abortSignal: options.abortSignal, access, containerAcl: acl, leaseAccessConditions: options.conditions, modifiedAccessConditions: options.conditions, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * Get a {@link BlobLeaseClient} that manages leases on the container. * * @param proposeLeaseId - Initial proposed lease Id. * @returns A new BlobLeaseClient object for managing leases on the container. */ getBlobLeaseClient(proposeLeaseId) { return new BlobLeaseClient(this, proposeLeaseId); } /** * 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://learn.microsoft.com/rest/api/storageservices/put-blob * * @param blobName - Name of the block blob to create or update. * @param body - Blob, string, ArrayBuffer, ArrayBufferView or a function * which returns a new Readable stream whose offset is from data source beginning. * @param contentLength - Length of body in bytes. Use Buffer.byteLength() to calculate body length for a * string including non non-Base64/Hex-encoded characters. * @param options - Options to configure the Block Blob Upload operation. * @returns Block Blob upload response data and the corresponding BlockBlobClient instance. */ async uploadBlockBlob(blobName, body, contentLength, options = {}) { return tracingClient.withSpan("ContainerClient-uploadBlockBlob", options, async (updatedOptions) => { const blockBlobClient = this.getBlockBlobClient(blobName); const response = await blockBlobClient.upload(body, contentLength, updatedOptions); return { blockBlobClient, response, }; }); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/delete-blob * * @param blobName - * @param options - Options to Blob Delete operation. * @returns Block blob deletion response data. */ async deleteBlob(blobName, options = {}) { return tracingClient.withSpan("ContainerClient-deleteBlob", options, async (updatedOptions) => { let blobClient = this.getBlobClient(blobName); if (options.versionId) { blobClient = blobClient.withVersion(options.versionId); } return blobClient.delete(updatedOptions); }); } /** * 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://learn.microsoft.com/rest/api/storageservices/list-blobs * * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. * @param options - Options to Container List Blob Flat Segment operation. */ async listBlobFlatSegment(marker, options = {}) { return tracingClient.withSpan("ContainerClient-listBlobFlatSegment", options, async (updatedOptions) => { const response = assertResponse(await this.containerContext.listBlobFlatSegment(Object.assign(Object.assign({ marker }, options), { tracingOptions: updatedOptions.tracingOptions }))); const wrappedResponse = Object.assign(Object.assign({}, response), { _response: Object.assign(Object.assign({}, response._response), { parsedBody: ConvertInternalResponseOfListBlobFlat(response._response.parsedBody) }), segment: Object.assign(Object.assign({}, response.segment), { blobItems: response.segment.blobItems.map((blobItemInternal) => { const blobItem = Object.assign(Object.assign({}, blobItemInternal), { name: BlobNameToString(blobItemInternal.name), tags: toTags(blobItemInternal.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInternal.objectReplicationMetadata) }); return blobItem; }) }) }); return wrappedResponse; }); } /** * 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://learn.microsoft.com/rest/api/storageservices/list-blobs * * @param delimiter - The character or string used to define the virtual hierarchy * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. * @param options - Options to Container List Blob Hierarchy Segment operation. */ async listBlobHierarchySegment(delimiter, marker, options = {}) { return tracingClient.withSpan("ContainerClient-listBlobHierarchySegment", options, async (updatedOptions) => { var _a; const response = assertResponse(await this.containerContext.listBlobHierarchySegment(delimiter, Object.assign(Object.assign({ marker }, options), { tracingOptions: updatedOptions.tracingOptions }))); const wrappedResponse = Object.assign(Object.assign({}, response), { _response: Object.assign(Object.assign({}, response._response), { parsedBody: ConvertInternalResponseOfListBlobHierarchy(response._response.parsedBody) }), segment: Object.assign(Object.assign({}, response.segment), { blobItems: response.segment.blobItems.map((blobItemInternal) => { const blobItem = Object.assign(Object.assign({}, blobItemInternal), { name: BlobNameToString(blobItemInternal.name), tags: toTags(blobItemInternal.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInternal.objectReplicationMetadata) }); return blobItem; }), blobPrefixes: (_a = response.segment.blobPrefixes) === null || _a === void 0 ? void 0 : _a.map((blobPrefixInternal) => { const blobPrefix = Object.assign(Object.assign({}, blobPrefixInternal), { name: BlobNameToString(blobPrefixInternal.name) }); return blobPrefix; }) }) }); return wrappedResponse; }); } /** * Returns an AsyncIterableIterator for ContainerListBlobFlatSegmentResponse * * @param 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 options - Options to list blobs operation. */ listSegments(marker_1) { return tslib.__asyncGenerator(this, arguments, function* listSegments_1(marker, options = {}) { let listBlobsFlatSegmentResponse; if (!!marker || marker === undefined) { do { listBlobsFlatSegmentResponse = yield tslib.__await(this.listBlobFlatSegment(marker, options)); marker = listBlobsFlatSegmentResponse.continuationToken; yield yield tslib.__await(yield tslib.__await(listBlobsFlatSegmentResponse)); } while (marker); } }); } /** * Returns an AsyncIterableIterator of {@link BlobItem} objects * * @param options - Options to list blobs operation. */ listItems() { return tslib.__asyncGenerator(this, arguments, function* listItems_1(options = {}) { var _a, e_1, _b, _c; let marker; try { for (var _d = true, _e = tslib.__asyncValues(this.listSegments(marker, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { _c = _f.value; _d = false; const listBlobsFlatSegmentResponse = _c; yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(listBlobsFlatSegmentResponse.segment.blobItems))); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); } finally { if (e_1) throw e_1.error; } } }); } /** * 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 options - Options to list blobs. * @returns An asyncIterableIterator that supports paging. */ listBlobsFlat(options = {}) { const 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.includeDeletedWithVersions) { include.push("deletedwithversions"); } if (options.includeImmutabilityPolicy) { include.push("immutabilitypolicy"); } if (options.includeLegalHold) { include.push("legalhold"); } if (options.prefix === "") { options.prefix = undefined; } const updatedOptions = Object.assign(Object.assign({}, options), (include.length > 0 ? { include: include } : {})); // AsyncIterableIterator to iterate over blobs const iter = this.listItems(updatedOptions); return { /** * The next method, part of the iteration protocol */ next() { return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ [Symbol.asyncIterator]() { return this; }, /** * Return an AsyncIterableIterator that works a page at a time */ byPage: (settings = {}) => { return this.listSegments(settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); }, }; } /** * Returns an AsyncIterableIterator for ContainerListBlobHierarchySegmentResponse * * @param delimiter - The character or string used to define the virtual hierarchy * @param 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 options - Options to list blobs operation. */ listHierarchySegments(delimiter_1, marker_1) { return tslib.__asyncGenerator(this, arguments, function* listHierarchySegments_1(delimiter, marker, options = {}) { let listBlobsHierarchySegmentResponse; if (!!marker || marker === undefined) { do { listBlobsHierarchySegmentResponse = yield tslib.__await(this.listBlobHierarchySegment(delimiter, marker, options)); marker = listBlobsHierarchySegmentResponse.continuationToken; yield yield tslib.__await(yield tslib.__await(listBlobsHierarchySegmentResponse)); } while (marker); } }); } /** * Returns an AsyncIterableIterator for {@link BlobPrefix} and {@link BlobItem} objects. * * @param delimiter - The character or string used to define the virtual hierarchy * @param options - Options to list blobs operation. */ listItemsByHierarchy(delimiter_1) { return tslib.__asyncGenerator(this, arguments, function* listItemsByHierarchy_1(delimiter, options = {}) { var _a, e_2, _b, _c; let marker; try { for (var _d = true, _e = tslib.__asyncValues(this.listHierarchySegments(delimiter, marker, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { _c = _f.value; _d = false; const listBlobsHierarchySegmentResponse = _c; const segment = listBlobsHierarchySegmentResponse.segment; if (segment.blobPrefixes) { for (const prefix of segment.blobPrefixes) { yield yield tslib.__await(Object.assign({ kind: "prefix" }, prefix)); } } for (const blob of segment.blobItems) { yield yield tslib.__await(Object.assign({ kind: "blob" }, blob)); } } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); } finally { if (e_2) throw e_2.error; } } }); } /** * 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}`); * } * } * ``` * * 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}`); * } * entity = await iter.next(); * } * ``` * * 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}`); * } * } * ``` * * 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}`); * } * } * ``` * * @param delimiter - The character or string used to define the virtual hierarchy * @param options - Options to list blobs operation. */ listBlobsByHierarchy(delimiter, options = {}) { if (delimiter === "") { throw new RangeError("delimiter should contain one or more characters"); } const 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.includeDeletedWithVersions) { include.push("deletedwithversions"); } if (options.includeImmutabilityPolicy) { include.push("immutabilitypolicy"); } if (options.includeLegalHold) { include.push("legalhold"); } if (options.prefix === "") { options.prefix = undefined; } const updatedOptions = Object.assign(Object.assign({}, options), (include.length > 0 ? { include: include } : {})); // AsyncIterableIterator to iterate over blob prefixes and blobs const iter = this.listItemsByHierarchy(delimiter, updatedOptions); return { /** * The next method, part of the iteration protocol */ async next() { return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ [Symbol.asyncIterator]() { return this; }, /** * Return an AsyncIterableIterator that works a page at a time */ byPage: (settings = {}) => { return this.listHierarchySegments(delimiter, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); }, }; } /** * The Filter Blobs operation enables callers to list blobs in the container whose tags * match a given search expression. * * @param 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 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 options - Options to find blobs by tags. */ async findBlobsByTagsSegment(tagFilterSqlExpression, marker, options = {}) { return tracingClient.withSpan("ContainerClient-findBlobsByTagsSegment", options, async (updatedOptions) => { const response = assertResponse(await this.containerContext.filterBlobs({ abortSignal: options.abortSignal, where: tagFilterSqlExpression, marker, maxPageSize: options.maxPageSize, tracingOptions: updatedOptions.tracingOptions, })); const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, blobs: response.blobs.map((blob) => { var _a; let tagValue = ""; if (((_a = blob.tags) === null || _a === void 0 ? void 0 : _a.blobTagSet.length) === 1) { tagValue = blob.tags.blobTagSet[0].value; } return Object.assign(Object.assign({}, blob), { tags: toTags(blob.tags), tagValue }); }) }); return wrappedResponse; }); } /** * Returns an AsyncIterableIterator for ContainerFindBlobsByTagsSegmentResponse. * * @param 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 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 options - Options to find blobs by tags. */ findBlobsByTagsSegments(tagFilterSqlExpression_1, marker_1) { return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsSegments_1(tagFilterSqlExpression, marker, options = {}) { let response; if (!!marker || marker === undefined) { do { response = yield tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker, options)); response.blobs = response.blobs || []; marker = response.continuationToken; yield yield tslib.__await(response); } while (marker); } }); } /** * Returns an AsyncIterableIterator for blobs. * * @param 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 options - Options to findBlobsByTagsItems. */ findBlobsByTagsItems(tagFilterSqlExpression_1) { return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsItems_1(tagFilterSqlExpression, options = {}) { var _a, e_3, _b, _c; let marker; try { for (var _d = true, _e = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { _c = _f.value; _d = false; const segment = _c; yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs))); } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); } finally { if (e_3) throw e_3.error; } } }); } /** * Returns an async iterable iterator to find all blobs with specified tag * under the specified container. * * .byPage() returns an async iterable iterator to list the blobs in pages. * * Example using `for await` syntax: * * ```js * let i = 1; * for await (const blob of containerClient.findBlobsByTags("tagkey='tagvalue'")) { * console.log(`Blob ${i++}: ${blob.name}`); * } * ``` * * Example using `iter.next()`: * * ```js * let i = 1; * const iter = containerClient.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 containerClient.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 = containerClient.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 = containerClient * .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 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 options - Options to find blobs by tags. */ findBlobsByTags(tagFilterSqlExpression, options = {}) { // AsyncIterableIterator to iterate over blobs const listSegmentOptions = Object.assign({}, options); const iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); return { /** * The next method, part of the iteration protocol */ next() { return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ [Symbol.asyncIterator]() { return this; }, /** * Return an AsyncIterableIterator that works a page at a time */ byPage: (settings = {}) => { return this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); }, }; } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/get-account-information * * @param options - Options to the Service Get Account Info operation. * @returns Response data for the Service Get Account Info operation. */ async getAccountInfo(options = {}) { return tracingClient.withSpan("ContainerClient-getAccountInfo", options, async (updatedOptions) => { return assertResponse(await this.containerContext.getAccountInfo({ abortSignal: options.abortSignal, tracingOptions: updatedOptions.tracingOptions, })); }); } getContainerNameFromUrl() { let 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 const parsedUrl = new URL(this.url); if (parsedUrl.hostname.split(".")[1] === "blob") { // "https://myaccount.blob.core.windows.net/containername". // "https://customdomain.com/containername". // .getPath() -> /containername containerName = parsedUrl.pathname.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.pathname.split("/")[2]; } else { // "https://customdomain.com/containername". // .getPath() -> /containername containerName = parsedUrl.pathname.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."); } } /** * Only available for ContainerClient constructed with a shared key credential. * * 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. * * @see https://learn.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * * @param options - Optional parameters. * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ generateSasUrl(options) { return new Promise((resolve) => { if (!(this.credential instanceof StorageSharedKeyCredential)) { throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); } const sas = generateBlobSASQueryParameters(Object.assign({ containerName: this._containerName }, options), this.credential).toString(); resolve(appendToURLQuery(this.url, sas)); }); } /** * Only available for ContainerClient constructed with a shared key credential. * * Generates string to sign for 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. * * @see https://learn.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * * @param options - Optional parameters. * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ generateSasStringToSign(options) { if (!(this.credential instanceof StorageSharedKeyCredential)) { throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); } return generateBlobSASQueryParametersInternal(Object.assign({ containerName: this._containerName }, options), this.credential).stringToSign; } /** * 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 input user delegation key. * * @see https://learn.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * * @param options - Optional parameters. * @param userDelegationKey - Return value of `blobServiceClient.getUserDelegationKey()` * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ generateUserDelegationSasUrl(options, userDelegationKey) { return new Promise((resolve) => { const sas = generateBlobSASQueryParameters(Object.assign({ containerName: this._containerName }, options), userDelegationKey, this.accountName).toString(); resolve(appendToURLQuery(this.url, sas)); }); } /** * Generates string to sign for a Blob Container Service Shared Access Signature (SAS) URI * based on the client properties and parameters passed in. The SAS is signed by the input user delegation key. * * @see https://learn.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * * @param options - Optional parameters. * @param userDelegationKey - Return value of `blobServiceClient.getUserDelegationKey()` * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ generateUserDelegationSasStringToSign(options, userDelegationKey) { return generateBlobSASQueryParametersInternal(Object.assign({ containerName: this._containerName }, options), userDelegationKey, this.accountName).stringToSign; } /** * Creates a BlobBatchClient object to conduct batch operations. * * @see https://learn.microsoft.com/en-us/rest/api/storageservices/blob-batch * * @returns A new BlobBatchClient object for this container. */ getBlobBatchClient() { return new BlobBatchClient(this.url, this.pipeline); } } // Copyright (c) Microsoft Corporation. // 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 an AccountSAS. 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 an * {@link AccountSASSignatureValues} 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. */ class AccountSASPermissions { constructor() { /** * Permission to read resources and list queues and tables granted. */ this.read = false; /** * Permission to write resources granted. */ this.write = false; /** * Permission to delete blobs and files granted. */ this.delete = false; /** * Permission to delete versions granted. */ this.deleteVersion = false; /** * Permission to list blob containers, blobs, shares, directories, and files granted. */ this.list = false; /** * Permission to add messages, table entities, and append to blobs granted. */ this.add = false; /** * Permission to create blobs and files granted. */ this.create = false; /** * Permissions to update messages and table entities granted. */ this.update = false; /** * Permission to get and delete messages granted. */ this.process = false; /** * Specfies Tag access granted. */ this.tag = false; /** * Permission to filter blobs. */ this.filter = false; /** * Permission to set immutability policy. */ this.setImmutabilityPolicy = false; /** * Specifies that Permanent Delete is permitted. */ this.permanentDelete = false; } /** * Parse initializes the AccountSASPermissions fields from a string. * * @param permissions - */ static parse(permissions) { const accountSASPermissions = new AccountSASPermissions(); for (const c of permissions) { switch (c) { case "r": accountSASPermissions.read = true; break; case "w": accountSASPermissions.write = true; break; case "d": accountSASPermissions.delete = true; break; case "x": accountSASPermissions.deleteVersion = true; break; case "l": accountSASPermissions.list = true; break; case "a": accountSASPermissions.add = true; break; case "c": accountSASPermissions.create = true; break; case "u": accountSASPermissions.update = true; break; case "p": accountSASPermissions.process = true; break; case "t": accountSASPermissions.tag = true; break; case "f": accountSASPermissions.filter = true; break; case "i": accountSASPermissions.setImmutabilityPolicy = true; break; case "y": accountSASPermissions.permanentDelete = true; break; default: throw new RangeError(`Invalid permission character: ${c}`); } } return accountSASPermissions; } /** * Creates a {@link AccountSASPermissions} from a raw object which contains same keys as it * and boolean values for them. * * @param permissionLike - */ static from(permissionLike) { const 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; } if (permissionLike.setImmutabilityPolicy) { accountSASPermissions.setImmutabilityPolicy = true; } if (permissionLike.permanentDelete) { accountSASPermissions.permanentDelete = true; } return accountSASPermissions; } /** * Produces the SAS permissions string for an Azure Storage account. * Call this method to set AccountSASSignatureValues Permissions field. * * Using this method will guarantee the resource types are in * an order accepted by the service. * * @see https://learn.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas * */ toString() { // The order of the characters should be as specified here to ensure correctness: // https://learn.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas // Use a string array instead of string concatenating += operator for performance const permissions = []; if (this.read) { permissions.push("r"); } if (this.write) { permissions.push("w"); } if (this.delete) { permissions.push("d"); } if (this.deleteVersion) { permissions.push("x"); } if (this.filter) { permissions.push("f"); } if (this.tag) { permissions.push("t"); } if (this.list) { permissions.push("l"); } if (this.add) { permissions.push("a"); } if (this.create) { permissions.push("c"); } if (this.update) { permissions.push("u"); } if (this.process) { permissions.push("p"); } if (this.setImmutabilityPolicy) { permissions.push("i"); } if (this.permanentDelete) { permissions.push("y"); } return permissions.join(""); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * This is a helper class to construct a string representing the resources accessible by an AccountSAS. Setting a value * to true means that any SAS which uses these permissions will grant access to that resource type. Once all the * values are set, this should be serialized with toString and set as the resources field on an * {@link AccountSASSignatureValues} object. It is possible to construct the resources string without this class, but * the order of the resources is particular and this class guarantees correctness. */ class AccountSASResourceTypes { constructor() { /** * Permission to access service level APIs granted. */ this.service = false; /** * Permission to access container level APIs (Blob Containers, Tables, Queues, File Shares) granted. */ this.container = false; /** * Permission to access object level APIs (Blobs, Table Entities, Queue Messages, Files) granted. */ this.object = false; } /** * Creates an {@link AccountSASResourceTypes} from the specified resource types string. This method will throw an * Error if it encounters a character that does not correspond to a valid resource type. * * @param resourceTypes - */ static parse(resourceTypes) { const accountSASResourceTypes = new AccountSASResourceTypes(); for (const c of resourceTypes) { switch (c) { case "s": accountSASResourceTypes.service = true; break; case "c": accountSASResourceTypes.container = true; break; case "o": accountSASResourceTypes.object = true; break; default: throw new RangeError(`Invalid resource type: ${c}`); } } return accountSASResourceTypes; } /** * Converts the given resource types to a string. * * @see https://learn.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas * */ toString() { const resourceTypes = []; if (this.service) { resourceTypes.push("s"); } if (this.container) { resourceTypes.push("c"); } if (this.object) { resourceTypes.push("o"); } return resourceTypes.join(""); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * This is a helper class to construct a string representing the services accessible by an AccountSAS. Setting a value * to true means that any SAS which uses these permissions will grant access to that service. Once all the * values are set, this should be serialized with toString and set as the services field on an * {@link AccountSASSignatureValues} object. It is possible to construct the services string without this class, but * the order of the services is particular and this class guarantees correctness. */ class AccountSASServices { constructor() { /** * Permission to access blob resources granted. */ this.blob = false; /** * Permission to access file resources granted. */ this.file = false; /** * Permission to access queue resources granted. */ this.queue = false; /** * Permission to access table resources granted. */ this.table = false; } /** * Creates an {@link AccountSASServices} from the specified services string. This method will throw an * Error if it encounters a character that does not correspond to a valid service. * * @param services - */ static parse(services) { const accountSASServices = new AccountSASServices(); for (const c of services) { switch (c) { case "b": accountSASServices.blob = true; break; case "f": accountSASServices.file = true; break; case "q": accountSASServices.queue = true; break; case "t": accountSASServices.table = true; break; default: throw new RangeError(`Invalid service character: ${c}`); } } return accountSASServices; } /** * Converts the given services to a string. * */ toString() { const services = []; if (this.blob) { services.push("b"); } if (this.table) { services.push("t"); } if (this.queue) { services.push("q"); } if (this.file) { services.push("f"); } return services.join(""); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas * * @param accountSASSignatureValues - * @param sharedKeyCredential - */ function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { return generateAccountSASQueryParametersInternal(accountSASSignatureValues, sharedKeyCredential) .sasQueryParameters; } function generateAccountSASQueryParametersInternal(accountSASSignatureValues, sharedKeyCredential) { const version = accountSASSignatureValues.version ? accountSASSignatureValues.version : SERVICE_VERSION; if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.setImmutabilityPolicy && version < "2020-08-04") { throw RangeError("'version' must be >= '2020-08-04' when provided 'i' permission."); } 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.permanentDelete && version < "2019-10-10") { throw RangeError("'version' must be >= '2019-10-10' when provided 'y' 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."); } if (accountSASSignatureValues.encryptionScope && version < "2020-12-06") { throw RangeError("'version' must be >= '2020-12-06' when provided 'encryptionScope' in SAS."); } const parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); const parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); const parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); let stringToSign; if (version >= "2020-12-06") { 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, accountSASSignatureValues.encryptionScope ? accountSASSignatureValues.encryptionScope : "", "", // Account SAS requires an additional newline character ].join("\n"); } else { 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"); } const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); return { sasQueryParameters: new SASQueryParameters(version, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, accountSASSignatureValues.encryptionScope), stringToSign: stringToSign, }; } /** * A BlobServiceClient represents a Client to the Azure Storage Blob service allowing you * to manipulate blob containers. */ class BlobServiceClient extends StorageClient { /** * * Creates an instance of BlobServiceClient from connection string. * * @param 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 options - Optional. Options to configure the HTTP pipeline. */ static fromConnectionString(connectionString, // Legacy, no fix for eslint error without breaking. Disable it for this interface. /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ options) { options = options || {}; const extractedCreds = extractConnectionStringParts(connectionString); if (extractedCreds.kind === "AccountConnString") { if (coreUtil.isNode) { const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); if (!options.proxyOptions) { options.proxyOptions = coreRestPipeline.getDefaultProxySettings(extractedCreds.proxyUri); } const pipeline = newPipeline(sharedKeyCredential, options); return new BlobServiceClient(extractedCreds.url, pipeline); } else { throw new Error("Account connection string is only supported in Node.js environment"); } } else if (extractedCreds.kind === "SASConnString") { const 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"); } } constructor(url, credentialOrPipeline, // Legacy, no fix for eslint error without breaking. Disable it for this interface. /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ options) { let pipeline; if (isPipelineLike(credentialOrPipeline)) { pipeline = credentialOrPipeline; } else if ((coreUtil.isNode && credentialOrPipeline instanceof StorageSharedKeyCredential) || credentialOrPipeline instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrPipeline)) { pipeline = newPipeline(credentialOrPipeline, options); } else { // The second parameter is undefined. Use anonymous credential pipeline = newPipeline(new AnonymousCredential(), options); } super(url, pipeline); this.serviceContext = this.storageClientContext.service; } /** * Creates a {@link ContainerClient} object * * @param containerName - A container name * @returns A new ContainerClient object for the given container name. * * Example usage: * * ```js * const containerClient = blobServiceClient.getContainerClient(""); * ``` */ getContainerClient(containerName) { return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline); } /** * Create a Blob container. @see https://learn.microsoft.com/en-us/rest/api/storageservices/create-container * * @param containerName - Name of the container to create. * @param options - Options to configure Container Create operation. * @returns Container creation response and the corresponding container client. */ async createContainer(containerName, options = {}) { return tracingClient.withSpan("BlobServiceClient-createContainer", options, async (updatedOptions) => { const containerClient = this.getContainerClient(containerName); const containerCreateResponse = await containerClient.create(updatedOptions); return { containerClient, containerCreateResponse, }; }); } /** * Deletes a Blob container. * * @param containerName - Name of the container to delete. * @param options - Options to configure Container Delete operation. * @returns Container deletion response. */ async deleteContainer(containerName, options = {}) { return tracingClient.withSpan("BlobServiceClient-deleteContainer", options, async (updatedOptions) => { const containerClient = this.getContainerClient(containerName); return containerClient.delete(updatedOptions); }); } /** * 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 deletedContainerName - Name of the previously deleted container. * @param deletedContainerVersion - Version of the previously deleted container, used to uniquely identify the deleted container. * @param options - Options to configure Container Restore operation. * @returns Container deletion response. */ async undeleteContainer(deletedContainerName, deletedContainerVersion, options = {}) { return tracingClient.withSpan("BlobServiceClient-undeleteContainer", options, async (updatedOptions) => { const containerClient = this.getContainerClient(options.destinationContainerName || deletedContainerName); // Hack to access a protected member. const containerContext = containerClient["storageClientContext"].container; const containerUndeleteResponse = assertResponse(await containerContext.restore({ deletedContainerName, deletedContainerVersion, tracingOptions: updatedOptions.tracingOptions, })); return { containerClient, containerUndeleteResponse }; }); } /** * Rename an existing Blob Container. * * @param sourceContainerName - The name of the source container. * @param destinationContainerName - The new name of the container. * @param options - Options to configure Container Rename operation. */ /* eslint-disable-next-line @typescript-eslint/ban-ts-comment */ // @ts-ignore Need to hide this interface for now. Make it public and turn on the live tests for it when the service is ready. async renameContainer(sourceContainerName, destinationContainerName, options = {}) { return tracingClient.withSpan("BlobServiceClient-renameContainer", options, async (updatedOptions) => { var _a; const containerClient = this.getContainerClient(destinationContainerName); // Hack to access a protected member. const containerContext = containerClient["storageClientContext"].container; const containerRenameResponse = assertResponse(await containerContext.rename(sourceContainerName, Object.assign(Object.assign({}, updatedOptions), { sourceLeaseId: (_a = options.sourceCondition) === null || _a === void 0 ? void 0 : _a.leaseId }))); return { containerClient, containerRenameResponse }; }); } /** * Gets the properties of a storage account’s Blob service, including properties * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. * @see https://learn.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties * * @param options - Options to the Service Get Properties operation. * @returns Response data for the Service Get Properties operation. */ async getProperties(options = {}) { return tracingClient.withSpan("BlobServiceClient-getProperties", options, async (updatedOptions) => { return assertResponse(await this.serviceContext.getProperties({ abortSignal: options.abortSignal, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties * * @param properties - * @param options - Options to the Service Set Properties operation. * @returns Response data for the Service Set Properties operation. */ async setProperties(properties, options = {}) { return tracingClient.withSpan("BlobServiceClient-setProperties", options, async (updatedOptions) => { return assertResponse(await this.serviceContext.setProperties(properties, { abortSignal: options.abortSignal, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/get-blob-service-stats * * @param options - Options to the Service Get Statistics operation. * @returns Response data for the Service Get Statistics operation. */ async getStatistics(options = {}) { return tracingClient.withSpan("BlobServiceClient-getStatistics", options, async (updatedOptions) => { return assertResponse(await this.serviceContext.getStatistics({ abortSignal: options.abortSignal, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/get-account-information * * @param options - Options to the Service Get Account Info operation. * @returns Response data for the Service Get Account Info operation. */ async getAccountInfo(options = {}) { return tracingClient.withSpan("BlobServiceClient-getAccountInfo", options, async (updatedOptions) => { return assertResponse(await this.serviceContext.getAccountInfo({ abortSignal: options.abortSignal, tracingOptions: updatedOptions.tracingOptions, })); }); } /** * Returns a list of the containers under the specified account. * @see https://learn.microsoft.com/en-us/rest/api/storageservices/list-containers2 * * @param 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 options - Options to the Service List Container Segment operation. * @returns Response data for the Service List Container Segment operation. */ async listContainersSegment(marker, options = {}) { return tracingClient.withSpan("BlobServiceClient-listContainersSegment", options, async (updatedOptions) => { return assertResponse(await this.serviceContext.listContainersSegment(Object.assign(Object.assign({ abortSignal: options.abortSignal, marker }, options), { include: typeof options.include === "string" ? [options.include] : options.include, tracingOptions: updatedOptions.tracingOptions }))); }); } /** * 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. * * @param 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 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 options - Options to find blobs by tags. */ async findBlobsByTagsSegment(tagFilterSqlExpression, marker, options = {}) { return tracingClient.withSpan("BlobServiceClient-findBlobsByTagsSegment", options, async (updatedOptions) => { const response = assertResponse(await this.serviceContext.filterBlobs({ abortSignal: options.abortSignal, where: tagFilterSqlExpression, marker, maxPageSize: options.maxPageSize, tracingOptions: updatedOptions.tracingOptions, })); const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, blobs: response.blobs.map((blob) => { var _a; let tagValue = ""; if (((_a = blob.tags) === null || _a === void 0 ? void 0 : _a.blobTagSet.length) === 1) { tagValue = blob.tags.blobTagSet[0].value; } return Object.assign(Object.assign({}, blob), { tags: toTags(blob.tags), tagValue }); }) }); return wrappedResponse; }); } /** * Returns an AsyncIterableIterator for ServiceFindBlobsByTagsSegmentResponse. * * @param 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 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 options - Options to find blobs by tags. */ findBlobsByTagsSegments(tagFilterSqlExpression_1, marker_1) { return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsSegments_1(tagFilterSqlExpression, marker, options = {}) { let response; if (!!marker || marker === undefined) { do { response = yield tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker, options)); response.blobs = response.blobs || []; marker = response.continuationToken; yield yield tslib.__await(response); } while (marker); } }); } /** * Returns an AsyncIterableIterator for blobs. * * @param 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 options - Options to findBlobsByTagsItems. */ findBlobsByTagsItems(tagFilterSqlExpression_1) { return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsItems_1(tagFilterSqlExpression, options = {}) { var _a, e_1, _b, _c; let marker; try { for (var _d = true, _e = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { _c = _f.value; _d = false; const segment = _c; yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs))); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); } finally { if (e_1) throw e_1.error; } } }); } /** * 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://learn.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 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 options - Options to find blobs by tags. */ findBlobsByTags(tagFilterSqlExpression, options = {}) { // AsyncIterableIterator to iterate over blobs const listSegmentOptions = Object.assign({}, options); const iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); return { /** * The next method, part of the iteration protocol */ next() { return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ [Symbol.asyncIterator]() { return this; }, /** * Return an AsyncIterableIterator that works a page at a time */ byPage: (settings = {}) => { return this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); }, }; } /** * Returns an AsyncIterableIterator for ServiceListContainersSegmentResponses * * @param 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 options - Options to list containers operation. */ listSegments(marker_1) { return tslib.__asyncGenerator(this, arguments, function* listSegments_1(marker, options = {}) { let listContainersSegmentResponse; if (!!marker || marker === undefined) { do { listContainersSegmentResponse = yield tslib.__await(this.listContainersSegment(marker, options)); listContainersSegmentResponse.containerItems = listContainersSegmentResponse.containerItems || []; marker = listContainersSegmentResponse.continuationToken; yield yield tslib.__await(yield tslib.__await(listContainersSegmentResponse)); } while (marker); } }); } /** * Returns an AsyncIterableIterator for Container Items * * @param options - Options to list containers operation. */ listItems() { return tslib.__asyncGenerator(this, arguments, function* listItems_1(options = {}) { var _a, e_2, _b, _c; let marker; try { for (var _d = true, _e = tslib.__asyncValues(this.listSegments(marker, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { _c = _f.value; _d = false; const segment = _c; yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.containerItems))); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); } finally { if (e_2) throw e_2.error; } } }); } /** * 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()`: * * ```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 options - Options to list containers. * @returns An asyncIterableIterator that supports paging. */ listContainers(options = {}) { if (options.prefix === "") { options.prefix = undefined; } const include = []; if (options.includeDeleted) { include.push("deleted"); } if (options.includeMetadata) { include.push("metadata"); } if (options.includeSystem) { include.push("system"); } // AsyncIterableIterator to iterate over containers const listSegmentOptions = Object.assign(Object.assign({}, options), (include.length > 0 ? { include } : {})); const iter = this.listItems(listSegmentOptions); return { /** * The next method, part of the iteration protocol */ next() { return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ [Symbol.asyncIterator]() { return this; }, /** * Return an AsyncIterableIterator that works a page at a time */ byPage: (settings = {}) => { return this.listSegments(settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); }, }; } /** * 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://learn.microsoft.com/en-us/rest/api/storageservices/get-user-delegation-key * * @param startsOn - The start time for the user delegation SAS. Must be within 7 days of the current time * @param expiresOn - The end time for the user delegation SAS. Must be within 7 days of the current time */ async getUserDelegationKey(startsOn, expiresOn, options = {}) { return tracingClient.withSpan("BlobServiceClient-getUserDelegationKey", options, async (updatedOptions) => { const response = assertResponse(await this.serviceContext.getUserDelegationKey({ startsOn: truncatedISO8061Date(startsOn, false), expiresOn: truncatedISO8061Date(expiresOn, false), }, { abortSignal: options.abortSignal, tracingOptions: updatedOptions.tracingOptions, })); const 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, }; const res = Object.assign({ _response: response._response, requestId: response.requestId, clientRequestId: response.clientRequestId, version: response.version, date: response.date, errorCode: response.errorCode }, userDelegationKey); return res; }); } /** * Creates a BlobBatchClient object to conduct batch operations. * * @see https://learn.microsoft.com/en-us/rest/api/storageservices/blob-batch * * @returns A new BlobBatchClient object for this service. */ getBlobBatchClient() { return new BlobBatchClient(this.url, this.pipeline); } /** * Only available for BlobServiceClient constructed with a shared key credential. * * 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://learn.microsoft.com/en-us/rest/api/storageservices/create-account-sas * * @param expiresOn - Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not provided. * @param permissions - Specifies the list of permissions to be associated with the SAS. * @param resourceTypes - Specifies the resource types associated with the shared access signature. * @param options - Optional parameters. * @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ generateAccountSasUrl(expiresOn, permissions = AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) { if (!(this.credential instanceof StorageSharedKeyCredential)) { throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); } if (expiresOn === undefined) { const now = new Date(); expiresOn = new Date(now.getTime() + 3600 * 1000); } const sas = generateAccountSASQueryParameters(Object.assign({ permissions, expiresOn, resourceTypes, services: AccountSASServices.parse("b").toString() }, options), this.credential).toString(); return appendToURLQuery(this.url, sas); } /** * Only available for BlobServiceClient constructed with a shared key credential. * * Generates string to sign for 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://learn.microsoft.com/en-us/rest/api/storageservices/create-account-sas * * @param expiresOn - Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not provided. * @param permissions - Specifies the list of permissions to be associated with the SAS. * @param resourceTypes - Specifies the resource types associated with the shared access signature. * @param options - Optional parameters. * @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ generateSasStringToSign(expiresOn, permissions = AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) { if (!(this.credential instanceof StorageSharedKeyCredential)) { throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); } if (expiresOn === undefined) { const now = new Date(); expiresOn = new Date(now.getTime() + 3600 * 1000); } return generateAccountSASQueryParametersInternal(Object.assign({ permissions, expiresOn, resourceTypes, services: AccountSASServices.parse("b").toString() }, options), this.credential).stringToSign; } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** Known values of {@link EncryptionAlgorithmType} that the service accepts. */ exports.KnownEncryptionAlgorithmType = void 0; (function (KnownEncryptionAlgorithmType) { KnownEncryptionAlgorithmType["AES256"] = "AES256"; })(exports.KnownEncryptionAlgorithmType || (exports.KnownEncryptionAlgorithmType = {})); Object.defineProperty(exports, "RestError", ({ enumerable: true, get: function () { return coreRestPipeline.RestError; } })); exports.AccountSASPermissions = AccountSASPermissions; exports.AccountSASResourceTypes = AccountSASResourceTypes; exports.AccountSASServices = AccountSASServices; exports.AnonymousCredential = AnonymousCredential; exports.AnonymousCredentialPolicy = AnonymousCredentialPolicy; exports.AppendBlobClient = AppendBlobClient; exports.BaseRequestPolicy = BaseRequestPolicy; exports.BlobBatch = BlobBatch; exports.BlobBatchClient = BlobBatchClient; exports.BlobClient = BlobClient; exports.BlobLeaseClient = BlobLeaseClient; exports.BlobSASPermissions = BlobSASPermissions; exports.BlobServiceClient = BlobServiceClient; exports.BlockBlobClient = BlockBlobClient; exports.ContainerClient = ContainerClient; exports.ContainerSASPermissions = ContainerSASPermissions; exports.Credential = Credential; exports.CredentialPolicy = CredentialPolicy; exports.PageBlobClient = PageBlobClient; exports.Pipeline = Pipeline; exports.SASQueryParameters = SASQueryParameters; exports.StorageBrowserPolicy = StorageBrowserPolicy; exports.StorageBrowserPolicyFactory = StorageBrowserPolicyFactory; exports.StorageOAuthScopes = StorageOAuthScopes; exports.StorageRetryPolicy = StorageRetryPolicy; exports.StorageRetryPolicyFactory = StorageRetryPolicyFactory; exports.StorageSharedKeyCredential = StorageSharedKeyCredential; exports.StorageSharedKeyCredentialPolicy = StorageSharedKeyCredentialPolicy; exports.generateAccountSASQueryParameters = generateAccountSASQueryParameters; exports.generateBlobSASQueryParameters = generateBlobSASQueryParameters; exports.getBlobServiceAccountAudience = getBlobServiceAccountAudience; exports.isPipelineLike = isPipelineLike; exports.logger = logger; exports.newPipeline = newPipeline; //# sourceMappingURL=index.js.map /***/ }), /***/ 77864: /***/ ((module) => { "use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // pkg/dist-src/index.js var dist_src_exports = {}; __export(dist_src_exports, { createTokenAuth: () => createTokenAuth }); module.exports = __toCommonJS(dist_src_exports); // pkg/dist-src/auth.js var REGEX_IS_INSTALLATION_LEGACY = /^v1\./; var REGEX_IS_INSTALLATION = /^ghs_/; var REGEX_IS_USER_TO_SERVER = /^ghu_/; async function auth(token) { const isApp = token.split(/\./).length === 3; const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token); const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token); const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; return { type: "token", token, tokenType }; } // pkg/dist-src/with-authorization-prefix.js function withAuthorizationPrefix(token) { if (token.split(/\./).length === 3) { return `bearer ${token}`; } return `token ${token}`; } // pkg/dist-src/hook.js async function hook(token, request, route, parameters) { const endpoint = request.endpoint.merge( route, parameters ); endpoint.headers.authorization = withAuthorizationPrefix(token); return request(endpoint); } // pkg/dist-src/index.js var createTokenAuth = function createTokenAuth2(token) { if (!token) { throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); } if (typeof token !== "string") { throw new Error( "[@octokit/auth-token] Token passed to createTokenAuth is not a string" ); } token = token.replace(/^(token|bearer) +/i, ""); return Object.assign(auth.bind(null, token), { hook: hook.bind(null, token) }); }; // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 61897: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // pkg/dist-src/index.js var index_exports = {}; __export(index_exports, { Octokit: () => Octokit }); module.exports = __toCommonJS(index_exports); var import_universal_user_agent = __nccwpck_require__(33843); var import_before_after_hook = __nccwpck_require__(52732); var import_request = __nccwpck_require__(66255); var import_graphql = __nccwpck_require__(70007); var import_auth_token = __nccwpck_require__(77864); // pkg/dist-src/version.js var VERSION = "5.2.1"; // pkg/dist-src/index.js var noop = () => { }; var consoleWarn = console.warn.bind(console); var consoleError = console.error.bind(console); var userAgentTrail = `octokit-core.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; var Octokit = class { static { this.VERSION = VERSION; } static defaults(defaults) { const OctokitWithDefaults = class extends this { constructor(...args) { const options = args[0] || {}; if (typeof defaults === "function") { super(defaults(options)); return; } super( Object.assign( {}, defaults, options, options.userAgent && defaults.userAgent ? { userAgent: `${options.userAgent} ${defaults.userAgent}` } : null ) ); } }; return OctokitWithDefaults; } static { this.plugins = []; } /** * Attach a plugin (or many) to your Octokit instance. * * @example * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) */ static plugin(...newPlugins) { const currentPlugins = this.plugins; const NewOctokit = class extends this { static { this.plugins = currentPlugins.concat( newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) ); } }; return NewOctokit; } constructor(options = {}) { const hook = new import_before_after_hook.Collection(); const requestDefaults = { baseUrl: import_request.request.endpoint.DEFAULTS.baseUrl, headers: {}, request: Object.assign({}, options.request, { // @ts-ignore internal usage only, no need to type hook: hook.bind(null, "request") }), mediaType: { previews: [], format: "" } }; requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail; if (options.baseUrl) { requestDefaults.baseUrl = options.baseUrl; } if (options.previews) { requestDefaults.mediaType.previews = options.previews; } if (options.timeZone) { requestDefaults.headers["time-zone"] = options.timeZone; } this.request = import_request.request.defaults(requestDefaults); this.graphql = (0, import_graphql.withCustomRequest)(this.request).defaults(requestDefaults); this.log = Object.assign( { debug: noop, info: noop, warn: consoleWarn, error: consoleError }, options.log ); this.hook = hook; if (!options.authStrategy) { if (!options.auth) { this.auth = async () => ({ type: "unauthenticated" }); } else { const auth = (0, import_auth_token.createTokenAuth)(options.auth); hook.wrap("request", auth.hook); this.auth = auth; } } else { const { authStrategy, ...otherOptions } = options; const auth = authStrategy( Object.assign( { request: this.request, log: this.log, // we pass the current octokit instance as well as its constructor options // to allow for authentication strategies that return a new octokit instance // that shares the same internal state as the current one. The original // requirement for this was the "event-octokit" authentication strategy // of https://github.com/probot/octokit-auth-probot. octokit: this, octokitOptions: otherOptions }, options.auth ) ); hook.wrap("request", auth.hook); this.auth = auth; } const classConstructor = this.constructor; for (let i = 0; i < classConstructor.plugins.length; ++i) { Object.assign(this, classConstructor.plugins[i](this, options)); } } }; // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 54471: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // pkg/dist-src/index.js var dist_src_exports = {}; __export(dist_src_exports, { endpoint: () => endpoint }); module.exports = __toCommonJS(dist_src_exports); // pkg/dist-src/defaults.js var import_universal_user_agent = __nccwpck_require__(33843); // pkg/dist-src/version.js var VERSION = "9.0.6"; // pkg/dist-src/defaults.js var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; var DEFAULTS = { method: "GET", baseUrl: "https://api.github.com", headers: { accept: "application/vnd.github.v3+json", "user-agent": userAgent }, mediaType: { format: "" } }; // pkg/dist-src/util/lowercase-keys.js function lowercaseKeys(object) { if (!object) { return {}; } return Object.keys(object).reduce((newObj, key) => { newObj[key.toLowerCase()] = object[key]; return newObj; }, {}); } // pkg/dist-src/util/is-plain-object.js function isPlainObject(value) { if (typeof value !== "object" || value === null) return false; if (Object.prototype.toString.call(value) !== "[object Object]") return false; const proto = Object.getPrototypeOf(value); if (proto === null) return true; const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); } // pkg/dist-src/util/merge-deep.js function mergeDeep(defaults, options) { const result = Object.assign({}, defaults); Object.keys(options).forEach((key) => { if (isPlainObject(options[key])) { if (!(key in defaults)) Object.assign(result, { [key]: options[key] }); else result[key] = mergeDeep(defaults[key], options[key]); } else { Object.assign(result, { [key]: options[key] }); } }); return result; } // pkg/dist-src/util/remove-undefined-properties.js function removeUndefinedProperties(obj) { for (const key in obj) { if (obj[key] === void 0) { delete obj[key]; } } return obj; } // pkg/dist-src/merge.js function merge(defaults, route, options) { if (typeof route === "string") { let [method, url] = route.split(" "); options = Object.assign(url ? { method, url } : { url: method }, options); } else { options = Object.assign({}, route); } options.headers = lowercaseKeys(options.headers); removeUndefinedProperties(options); removeUndefinedProperties(options.headers); const mergedOptions = mergeDeep(defaults || {}, options); if (options.url === "/graphql") { if (defaults && defaults.mediaType.previews?.length) { mergedOptions.mediaType.previews = defaults.mediaType.previews.filter( (preview) => !mergedOptions.mediaType.previews.includes(preview) ).concat(mergedOptions.mediaType.previews); } mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); } return mergedOptions; } // pkg/dist-src/util/add-query-parameters.js function addQueryParameters(url, parameters) { const separator = /\?/.test(url) ? "&" : "?"; const names = Object.keys(parameters); if (names.length === 0) { return url; } return url + separator + names.map((name) => { if (name === "q") { return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); } return `${name}=${encodeURIComponent(parameters[name])}`; }).join("&"); } // pkg/dist-src/util/extract-url-variable-names.js var urlVariableRegex = /\{[^{}}]+\}/g; function removeNonChars(variableName) { return variableName.replace(/(?:^\W+)|(?:(? a.concat(b), []); } // pkg/dist-src/util/omit.js function omit(object, keysToOmit) { const result = { __proto__: null }; for (const key of Object.keys(object)) { if (keysToOmit.indexOf(key) === -1) { result[key] = object[key]; } } return result; } // pkg/dist-src/util/url-template.js function encodeReserved(str) { return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { if (!/%[0-9A-Fa-f]/.test(part)) { part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); } return part; }).join(""); } function encodeUnreserved(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return "%" + c.charCodeAt(0).toString(16).toUpperCase(); }); } function encodeValue(operator, value, key) { value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); if (key) { return encodeUnreserved(key) + "=" + value; } else { return value; } } function isDefined(value) { return value !== void 0 && value !== null; } function isKeyOperator(operator) { return operator === ";" || operator === "&" || operator === "?"; } function getValues(context, operator, key, modifier) { var value = context[key], result = []; if (isDefined(value) && value !== "") { if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { value = value.toString(); if (modifier && modifier !== "*") { value = value.substring(0, parseInt(modifier, 10)); } result.push( encodeValue(operator, value, isKeyOperator(operator) ? key : "") ); } else { if (modifier === "*") { if (Array.isArray(value)) { value.filter(isDefined).forEach(function(value2) { result.push( encodeValue(operator, value2, isKeyOperator(operator) ? key : "") ); }); } else { Object.keys(value).forEach(function(k) { if (isDefined(value[k])) { result.push(encodeValue(operator, value[k], k)); } }); } } else { const tmp = []; if (Array.isArray(value)) { value.filter(isDefined).forEach(function(value2) { tmp.push(encodeValue(operator, value2)); }); } else { Object.keys(value).forEach(function(k) { if (isDefined(value[k])) { tmp.push(encodeUnreserved(k)); tmp.push(encodeValue(operator, value[k].toString())); } }); } if (isKeyOperator(operator)) { result.push(encodeUnreserved(key) + "=" + tmp.join(",")); } else if (tmp.length !== 0) { result.push(tmp.join(",")); } } } } else { if (operator === ";") { if (isDefined(value)) { result.push(encodeUnreserved(key)); } } else if (value === "" && (operator === "&" || operator === "?")) { result.push(encodeUnreserved(key) + "="); } else if (value === "") { result.push(""); } } return result; } function parseUrl(template) { return { expand: expand.bind(null, template) }; } function expand(template, context) { var operators = ["+", "#", ".", "/", ";", "?", "&"]; template = template.replace( /\{([^\{\}]+)\}|([^\{\}]+)/g, function(_, expression, literal) { if (expression) { let operator = ""; const values = []; if (operators.indexOf(expression.charAt(0)) !== -1) { operator = expression.charAt(0); expression = expression.substr(1); } expression.split(/,/g).forEach(function(variable) { var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); }); if (operator && operator !== "+") { var separator = ","; if (operator === "?") { separator = "&"; } else if (operator !== "#") { separator = operator; } return (values.length !== 0 ? operator : "") + values.join(separator); } else { return values.join(","); } } else { return encodeReserved(literal); } } ); if (template === "/") { return template; } else { return template.replace(/\/$/, ""); } } // pkg/dist-src/parse.js function parse(options) { let method = options.method.toUpperCase(); let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); let headers = Object.assign({}, options.headers); let body; let parameters = omit(options, [ "method", "baseUrl", "url", "headers", "request", "mediaType" ]); const urlVariableNames = extractUrlVariableNames(url); url = parseUrl(url).expand(parameters); if (!/^http/.test(url)) { url = options.baseUrl + url; } const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); const remainingParameters = omit(parameters, omittedParameters); const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); if (!isBinaryRequest) { if (options.mediaType.format) { headers.accept = headers.accept.split(/,/).map( (format) => format.replace( /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}` ) ).join(","); } if (url.endsWith("/graphql")) { if (options.mediaType.previews?.length) { const previewsFromAcceptHeader = headers.accept.match(/(? { const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; return `application/vnd.github.${preview}-preview${format}`; }).join(","); } } } if (["GET", "HEAD"].includes(method)) { url = addQueryParameters(url, remainingParameters); } else { if ("data" in remainingParameters) { body = remainingParameters.data; } else { if (Object.keys(remainingParameters).length) { body = remainingParameters; } } } if (!headers["content-type"] && typeof body !== "undefined") { headers["content-type"] = "application/json; charset=utf-8"; } if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { body = ""; } return Object.assign( { method, url, headers }, typeof body !== "undefined" ? { body } : null, options.request ? { request: options.request } : null ); } // pkg/dist-src/endpoint-with-defaults.js function endpointWithDefaults(defaults, route, options) { return parse(merge(defaults, route, options)); } // pkg/dist-src/with-defaults.js function withDefaults(oldDefaults, newDefaults) { const DEFAULTS2 = merge(oldDefaults, newDefaults); const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); return Object.assign(endpoint2, { DEFAULTS: DEFAULTS2, defaults: withDefaults.bind(null, DEFAULTS2), merge: merge.bind(null, DEFAULTS2), parse }); } // pkg/dist-src/index.js var endpoint = withDefaults(null, DEFAULTS); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 70007: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // pkg/dist-src/index.js var index_exports = {}; __export(index_exports, { GraphqlResponseError: () => GraphqlResponseError, graphql: () => graphql2, withCustomRequest: () => withCustomRequest }); module.exports = __toCommonJS(index_exports); var import_request3 = __nccwpck_require__(66255); var import_universal_user_agent = __nccwpck_require__(33843); // pkg/dist-src/version.js var VERSION = "7.1.1"; // pkg/dist-src/with-defaults.js var import_request2 = __nccwpck_require__(66255); // pkg/dist-src/graphql.js var import_request = __nccwpck_require__(66255); // pkg/dist-src/error.js function _buildMessageForResponseErrors(data) { return `Request failed due to following response errors: ` + data.errors.map((e) => ` - ${e.message}`).join("\n"); } var GraphqlResponseError = class extends Error { constructor(request2, headers, response) { super(_buildMessageForResponseErrors(response)); this.request = request2; this.headers = headers; this.response = response; this.name = "GraphqlResponseError"; this.errors = response.errors; this.data = response.data; if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } }; // pkg/dist-src/graphql.js var NON_VARIABLE_OPTIONS = [ "method", "baseUrl", "url", "headers", "request", "query", "mediaType" ]; var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; function graphql(request2, query, options) { if (options) { if (typeof query === "string" && "query" in options) { return Promise.reject( new Error(`[@octokit/graphql] "query" cannot be used as variable name`) ); } for (const key in options) { if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue; return Promise.reject( new Error( `[@octokit/graphql] "${key}" cannot be used as variable name` ) ); } } const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query; const requestOptions = Object.keys( parsedOptions ).reduce((result, key) => { if (NON_VARIABLE_OPTIONS.includes(key)) { result[key] = parsedOptions[key]; return result; } if (!result.variables) { result.variables = {}; } result.variables[key] = parsedOptions[key]; return result; }, {}); const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); } return request2(requestOptions).then((response) => { if (response.data.errors) { const headers = {}; for (const key of Object.keys(response.headers)) { headers[key] = response.headers[key]; } throw new GraphqlResponseError( requestOptions, headers, response.data ); } return response.data.data; }); } // pkg/dist-src/with-defaults.js function withDefaults(request2, newDefaults) { const newRequest = request2.defaults(newDefaults); const newApi = (query, options) => { return graphql(newRequest, query, options); }; return Object.assign(newApi, { defaults: withDefaults.bind(null, newRequest), endpoint: newRequest.endpoint }); } // pkg/dist-src/index.js var graphql2 = withDefaults(import_request3.request, { headers: { "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` }, method: "POST", url: "/graphql" }); function withCustomRequest(customRequest) { return withDefaults(customRequest, { method: "POST", url: "/graphql" }); } // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 38082: /***/ ((module) => { "use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // pkg/dist-src/index.js var dist_src_exports = {}; __export(dist_src_exports, { composePaginateRest: () => composePaginateRest, isPaginatingEndpoint: () => isPaginatingEndpoint, paginateRest: () => paginateRest, paginatingEndpoints: () => paginatingEndpoints }); module.exports = __toCommonJS(dist_src_exports); // pkg/dist-src/version.js var VERSION = "9.2.2"; // pkg/dist-src/normalize-paginated-list-response.js function normalizePaginatedListResponse(response) { if (!response.data) { return { ...response, data: [] }; } const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); if (!responseNeedsNormalization) return response; const incompleteResults = response.data.incomplete_results; const repositorySelection = response.data.repository_selection; const totalCount = response.data.total_count; delete response.data.incomplete_results; delete response.data.repository_selection; delete response.data.total_count; const namespaceKey = Object.keys(response.data)[0]; const data = response.data[namespaceKey]; response.data = data; if (typeof incompleteResults !== "undefined") { response.data.incomplete_results = incompleteResults; } if (typeof repositorySelection !== "undefined") { response.data.repository_selection = repositorySelection; } response.data.total_count = totalCount; return response; } // pkg/dist-src/iterator.js function iterator(octokit, route, parameters) { const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); const requestMethod = typeof route === "function" ? route : octokit.request; const method = options.method; const headers = options.headers; let url = options.url; return { [Symbol.asyncIterator]: () => ({ async next() { if (!url) return { done: true }; try { const response = await requestMethod({ method, url, headers }); const normalizedResponse = normalizePaginatedListResponse(response); url = ((normalizedResponse.headers.link || "").match( /<([^<>]+)>;\s*rel="next"/ ) || [])[1]; return { value: normalizedResponse }; } catch (error) { if (error.status !== 409) throw error; url = ""; return { value: { status: 200, headers: {}, data: [] } }; } } }) }; } // pkg/dist-src/paginate.js function paginate(octokit, route, parameters, mapFn) { if (typeof parameters === "function") { mapFn = parameters; parameters = void 0; } return gather( octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn ); } function gather(octokit, results, iterator2, mapFn) { return iterator2.next().then((result) => { if (result.done) { return results; } let earlyExit = false; function done() { earlyExit = true; } results = results.concat( mapFn ? mapFn(result.value, done) : result.value.data ); if (earlyExit) { return results; } return gather(octokit, results, iterator2, mapFn); }); } // pkg/dist-src/compose-paginate.js var composePaginateRest = Object.assign(paginate, { iterator }); // pkg/dist-src/generated/paginating-endpoints.js var paginatingEndpoints = [ "GET /advisories", "GET /app/hook/deliveries", "GET /app/installation-requests", "GET /app/installations", "GET /assignments/{assignment_id}/accepted_assignments", "GET /classrooms", "GET /classrooms/{classroom_id}/assignments", "GET /enterprises/{enterprise}/dependabot/alerts", "GET /enterprises/{enterprise}/secret-scanning/alerts", "GET /events", "GET /gists", "GET /gists/public", "GET /gists/starred", "GET /gists/{gist_id}/comments", "GET /gists/{gist_id}/commits", "GET /gists/{gist_id}/forks", "GET /installation/repositories", "GET /issues", "GET /licenses", "GET /marketplace_listing/plans", "GET /marketplace_listing/plans/{plan_id}/accounts", "GET /marketplace_listing/stubbed/plans", "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", "GET /networks/{owner}/{repo}/events", "GET /notifications", "GET /organizations", "GET /orgs/{org}/actions/cache/usage-by-repository", "GET /orgs/{org}/actions/permissions/repositories", "GET /orgs/{org}/actions/runners", "GET /orgs/{org}/actions/secrets", "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", "GET /orgs/{org}/actions/variables", "GET /orgs/{org}/actions/variables/{name}/repositories", "GET /orgs/{org}/blocks", "GET /orgs/{org}/code-scanning/alerts", "GET /orgs/{org}/codespaces", "GET /orgs/{org}/codespaces/secrets", "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories", "GET /orgs/{org}/copilot/billing/seats", "GET /orgs/{org}/dependabot/alerts", "GET /orgs/{org}/dependabot/secrets", "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories", "GET /orgs/{org}/events", "GET /orgs/{org}/failed_invitations", "GET /orgs/{org}/hooks", "GET /orgs/{org}/hooks/{hook_id}/deliveries", "GET /orgs/{org}/installations", "GET /orgs/{org}/invitations", "GET /orgs/{org}/invitations/{invitation_id}/teams", "GET /orgs/{org}/issues", "GET /orgs/{org}/members", "GET /orgs/{org}/members/{username}/codespaces", "GET /orgs/{org}/migrations", "GET /orgs/{org}/migrations/{migration_id}/repositories", "GET /orgs/{org}/organization-roles/{role_id}/teams", "GET /orgs/{org}/organization-roles/{role_id}/users", "GET /orgs/{org}/outside_collaborators", "GET /orgs/{org}/packages", "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", "GET /orgs/{org}/personal-access-token-requests", "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories", "GET /orgs/{org}/personal-access-tokens", "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories", "GET /orgs/{org}/projects", "GET /orgs/{org}/properties/values", "GET /orgs/{org}/public_members", "GET /orgs/{org}/repos", "GET /orgs/{org}/rulesets", "GET /orgs/{org}/rulesets/rule-suites", "GET /orgs/{org}/secret-scanning/alerts", "GET /orgs/{org}/security-advisories", "GET /orgs/{org}/teams", "GET /orgs/{org}/teams/{team_slug}/discussions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/invitations", "GET /orgs/{org}/teams/{team_slug}/members", "GET /orgs/{org}/teams/{team_slug}/projects", "GET /orgs/{org}/teams/{team_slug}/repos", "GET /orgs/{org}/teams/{team_slug}/teams", "GET /projects/columns/{column_id}/cards", "GET /projects/{project_id}/collaborators", "GET /projects/{project_id}/columns", "GET /repos/{owner}/{repo}/actions/artifacts", "GET /repos/{owner}/{repo}/actions/caches", "GET /repos/{owner}/{repo}/actions/organization-secrets", "GET /repos/{owner}/{repo}/actions/organization-variables", "GET /repos/{owner}/{repo}/actions/runners", "GET /repos/{owner}/{repo}/actions/runs", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", "GET /repos/{owner}/{repo}/actions/secrets", "GET /repos/{owner}/{repo}/actions/variables", "GET /repos/{owner}/{repo}/actions/workflows", "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", "GET /repos/{owner}/{repo}/activity", "GET /repos/{owner}/{repo}/assignees", "GET /repos/{owner}/{repo}/branches", "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", "GET /repos/{owner}/{repo}/code-scanning/alerts", "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", "GET /repos/{owner}/{repo}/code-scanning/analyses", "GET /repos/{owner}/{repo}/codespaces", "GET /repos/{owner}/{repo}/codespaces/devcontainers", "GET /repos/{owner}/{repo}/codespaces/secrets", "GET /repos/{owner}/{repo}/collaborators", "GET /repos/{owner}/{repo}/comments", "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/commits", "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", "GET /repos/{owner}/{repo}/commits/{ref}/status", "GET /repos/{owner}/{repo}/commits/{ref}/statuses", "GET /repos/{owner}/{repo}/contributors", "GET /repos/{owner}/{repo}/dependabot/alerts", "GET /repos/{owner}/{repo}/dependabot/secrets", "GET /repos/{owner}/{repo}/deployments", "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", "GET /repos/{owner}/{repo}/environments", "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies", "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps", "GET /repos/{owner}/{repo}/events", "GET /repos/{owner}/{repo}/forks", "GET /repos/{owner}/{repo}/hooks", "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", "GET /repos/{owner}/{repo}/invitations", "GET /repos/{owner}/{repo}/issues", "GET /repos/{owner}/{repo}/issues/comments", "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/issues/events", "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", "GET /repos/{owner}/{repo}/issues/{issue_number}/events", "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", "GET /repos/{owner}/{repo}/keys", "GET /repos/{owner}/{repo}/labels", "GET /repos/{owner}/{repo}/milestones", "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", "GET /repos/{owner}/{repo}/notifications", "GET /repos/{owner}/{repo}/pages/builds", "GET /repos/{owner}/{repo}/projects", "GET /repos/{owner}/{repo}/pulls", "GET /repos/{owner}/{repo}/pulls/comments", "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", "GET /repos/{owner}/{repo}/releases", "GET /repos/{owner}/{repo}/releases/{release_id}/assets", "GET /repos/{owner}/{repo}/releases/{release_id}/reactions", "GET /repos/{owner}/{repo}/rules/branches/{branch}", "GET /repos/{owner}/{repo}/rulesets", "GET /repos/{owner}/{repo}/rulesets/rule-suites", "GET /repos/{owner}/{repo}/secret-scanning/alerts", "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations", "GET /repos/{owner}/{repo}/security-advisories", "GET /repos/{owner}/{repo}/stargazers", "GET /repos/{owner}/{repo}/subscribers", "GET /repos/{owner}/{repo}/tags", "GET /repos/{owner}/{repo}/teams", "GET /repos/{owner}/{repo}/topics", "GET /repositories", "GET /repositories/{repository_id}/environments/{environment_name}/secrets", "GET /repositories/{repository_id}/environments/{environment_name}/variables", "GET /search/code", "GET /search/commits", "GET /search/issues", "GET /search/labels", "GET /search/repositories", "GET /search/topics", "GET /search/users", "GET /teams/{team_id}/discussions", "GET /teams/{team_id}/discussions/{discussion_number}/comments", "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", "GET /teams/{team_id}/discussions/{discussion_number}/reactions", "GET /teams/{team_id}/invitations", "GET /teams/{team_id}/members", "GET /teams/{team_id}/projects", "GET /teams/{team_id}/repos", "GET /teams/{team_id}/teams", "GET /user/blocks", "GET /user/codespaces", "GET /user/codespaces/secrets", "GET /user/emails", "GET /user/followers", "GET /user/following", "GET /user/gpg_keys", "GET /user/installations", "GET /user/installations/{installation_id}/repositories", "GET /user/issues", "GET /user/keys", "GET /user/marketplace_purchases", "GET /user/marketplace_purchases/stubbed", "GET /user/memberships/orgs", "GET /user/migrations", "GET /user/migrations/{migration_id}/repositories", "GET /user/orgs", "GET /user/packages", "GET /user/packages/{package_type}/{package_name}/versions", "GET /user/public_emails", "GET /user/repos", "GET /user/repository_invitations", "GET /user/social_accounts", "GET /user/ssh_signing_keys", "GET /user/starred", "GET /user/subscriptions", "GET /user/teams", "GET /users", "GET /users/{username}/events", "GET /users/{username}/events/orgs/{org}", "GET /users/{username}/events/public", "GET /users/{username}/followers", "GET /users/{username}/following", "GET /users/{username}/gists", "GET /users/{username}/gpg_keys", "GET /users/{username}/keys", "GET /users/{username}/orgs", "GET /users/{username}/packages", "GET /users/{username}/projects", "GET /users/{username}/received_events", "GET /users/{username}/received_events/public", "GET /users/{username}/repos", "GET /users/{username}/social_accounts", "GET /users/{username}/ssh_signing_keys", "GET /users/{username}/starred", "GET /users/{username}/subscriptions" ]; // pkg/dist-src/paginating-endpoints.js function isPaginatingEndpoint(arg) { if (typeof arg === "string") { return paginatingEndpoints.includes(arg); } else { return false; } } // pkg/dist-src/index.js function paginateRest(octokit) { return { paginate: Object.assign(paginate.bind(null, octokit), { iterator: iterator.bind(null, octokit) }) }; } paginateRest.VERSION = VERSION; // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 93708: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // pkg/dist-src/index.js var dist_src_exports = {}; __export(dist_src_exports, { RequestError: () => RequestError }); module.exports = __toCommonJS(dist_src_exports); var import_deprecation = __nccwpck_require__(14150); var import_once = __toESM(__nccwpck_require__(55560)); var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); var RequestError = class extends Error { constructor(message, statusCode, options) { super(message); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } this.name = "HttpError"; this.status = statusCode; let headers; if ("headers" in options && typeof options.headers !== "undefined") { headers = options.headers; } if ("response" in options) { this.response = options.response; headers = options.response.headers; } const requestCopy = Object.assign({}, options.request); if (options.request.headers.authorization) { requestCopy.headers = Object.assign({}, options.request.headers, { authorization: options.request.headers.authorization.replace( /(? { "use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // pkg/dist-src/index.js var dist_src_exports = {}; __export(dist_src_exports, { request: () => request }); module.exports = __toCommonJS(dist_src_exports); var import_endpoint = __nccwpck_require__(54471); var import_universal_user_agent = __nccwpck_require__(33843); // pkg/dist-src/version.js var VERSION = "8.4.1"; // pkg/dist-src/is-plain-object.js function isPlainObject(value) { if (typeof value !== "object" || value === null) return false; if (Object.prototype.toString.call(value) !== "[object Object]") return false; const proto = Object.getPrototypeOf(value); if (proto === null) return true; const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); } // pkg/dist-src/fetch-wrapper.js var import_request_error = __nccwpck_require__(93708); // pkg/dist-src/get-buffer-response.js function getBufferResponse(response) { return response.arrayBuffer(); } // pkg/dist-src/fetch-wrapper.js function fetchWrapper(requestOptions) { var _a, _b, _c, _d; const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { requestOptions.body = JSON.stringify(requestOptions.body); } let headers = {}; let status; let url; let { fetch } = globalThis; if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { fetch = requestOptions.request.fetch; } if (!fetch) { throw new Error( "fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing" ); } return fetch(requestOptions.url, { method: requestOptions.method, body: requestOptions.body, redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, headers: requestOptions.headers, signal: (_d = requestOptions.request) == null ? void 0 : _d.signal, // duplex must be set if request.body is ReadableStream or Async Iterables. // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. ...requestOptions.body && { duplex: "half" } }).then(async (response) => { url = response.url; status = response.status; for (const keyAndValue of response.headers) { headers[keyAndValue[0]] = keyAndValue[1]; } if ("deprecation" in headers) { const matches = headers.link && headers.link.match(/<([^<>]+)>; rel="deprecation"/); const deprecationLink = matches && matches.pop(); log.warn( `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` ); } if (status === 204 || status === 205) { return; } if (requestOptions.method === "HEAD") { if (status < 400) { return; } throw new import_request_error.RequestError(response.statusText, status, { response: { url, status, headers, data: void 0 }, request: requestOptions }); } if (status === 304) { throw new import_request_error.RequestError("Not modified", status, { response: { url, status, headers, data: await getResponseData(response) }, request: requestOptions }); } if (status >= 400) { const data = await getResponseData(response); const error = new import_request_error.RequestError(toErrorMessage(data), status, { response: { url, status, headers, data }, request: requestOptions }); throw error; } return parseSuccessResponseBody ? await getResponseData(response) : response.body; }).then((data) => { return { status, url, headers, data }; }).catch((error) => { if (error instanceof import_request_error.RequestError) throw error; else if (error.name === "AbortError") throw error; let message = error.message; if (error.name === "TypeError" && "cause" in error) { if (error.cause instanceof Error) { message = error.cause.message; } else if (typeof error.cause === "string") { message = error.cause; } } throw new import_request_error.RequestError(message, 500, { request: requestOptions }); }); } async function getResponseData(response) { const contentType = response.headers.get("content-type"); if (/application\/json/.test(contentType)) { return response.json().catch(() => response.text()).catch(() => ""); } if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { return response.text(); } return getBufferResponse(response); } function toErrorMessage(data) { if (typeof data === "string") return data; let suffix; if ("documentation_url" in data) { suffix = ` - ${data.documentation_url}`; } else { suffix = ""; } if ("message" in data) { if (Array.isArray(data.errors)) { return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; } return `${data.message}${suffix}`; } return `Unknown error: ${JSON.stringify(data)}`; } // pkg/dist-src/with-defaults.js function withDefaults(oldEndpoint, newDefaults) { const endpoint2 = oldEndpoint.defaults(newDefaults); const newApi = function(route, parameters) { const endpointOptions = endpoint2.merge(route, parameters); if (!endpointOptions.request || !endpointOptions.request.hook) { return fetchWrapper(endpoint2.parse(endpointOptions)); } const request2 = (route2, parameters2) => { return fetchWrapper( endpoint2.parse(endpoint2.merge(route2, parameters2)) ); }; Object.assign(request2, { endpoint: endpoint2, defaults: withDefaults.bind(null, endpoint2) }); return endpointOptions.request.hook(request2, endpointOptions); }; return Object.assign(newApi, { endpoint: endpoint2, defaults: withDefaults.bind(null, endpoint2) }); } // pkg/dist-src/index.js var request = withDefaults(import_endpoint.endpoint, { headers: { "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` } }); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 37889: /***/ (function(__unused_webpack_module, exports) { "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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ClientStreamingCall = void 0; /** * A client streaming RPC call. This means that the clients sends 0, 1, or * more messages to the server, and the server replies with exactly one * message. */ class ClientStreamingCall { constructor(method, requestHeaders, request, headers, response, status, trailers) { this.method = method; this.requestHeaders = requestHeaders; this.requests = request; this.headers = headers; this.response = response; this.status = status; this.trailers = trailers; } /** * Instead of awaiting the response status and trailers, you can * just as well await this call itself to receive the server outcome. * Note that it may still be valid to send more request messages. */ then(onfulfilled, onrejected) { return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); } promiseFinished() { return __awaiter(this, void 0, void 0, function* () { let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); return { method: this.method, requestHeaders: this.requestHeaders, headers, response, status, trailers }; }); } } exports.ClientStreamingCall = ClientStreamingCall; /***/ }), /***/ 71409: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Deferred = exports.DeferredState = void 0; var DeferredState; (function (DeferredState) { DeferredState[DeferredState["PENDING"] = 0] = "PENDING"; DeferredState[DeferredState["REJECTED"] = 1] = "REJECTED"; DeferredState[DeferredState["RESOLVED"] = 2] = "RESOLVED"; })(DeferredState = exports.DeferredState || (exports.DeferredState = {})); /** * A deferred promise. This is a "controller" for a promise, which lets you * pass a promise around and reject or resolve it from the outside. * * Warning: This class is to be used with care. Using it can make code very * difficult to read. It is intended for use in library code that exposes * promises, not for regular business logic. */ class Deferred { /** * @param preventUnhandledRejectionWarning - prevents the warning * "Unhandled Promise rejection" by adding a noop rejection handler. * Working with calls returned from the runtime-rpc package in an * async function usually means awaiting one call property after * the other. This means that the "status" is not being awaited when * an earlier await for the "headers" is rejected. This causes the * "unhandled promise reject" warning. A more correct behaviour for * calls might be to become aware whether at least one of the * promises is handled and swallow the rejection warning for the * others. */ constructor(preventUnhandledRejectionWarning = true) { this._state = DeferredState.PENDING; this._promise = new Promise((resolve, reject) => { this._resolve = resolve; this._reject = reject; }); if (preventUnhandledRejectionWarning) { this._promise.catch(_ => { }); } } /** * Get the current state of the promise. */ get state() { return this._state; } /** * Get the deferred promise. */ get promise() { return this._promise; } /** * Resolve the promise. Throws if the promise is already resolved or rejected. */ resolve(value) { if (this.state !== DeferredState.PENDING) throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`); this._resolve(value); this._state = DeferredState.RESOLVED; } /** * Reject the promise. Throws if the promise is already resolved or rejected. */ reject(reason) { if (this.state !== DeferredState.PENDING) throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`); this._reject(reason); this._state = DeferredState.REJECTED; } /** * Resolve the promise. Ignore if not pending. */ resolvePending(val) { if (this._state === DeferredState.PENDING) this.resolve(val); } /** * Reject the promise. Ignore if not pending. */ rejectPending(reason) { if (this._state === DeferredState.PENDING) this.reject(reason); } } exports.Deferred = Deferred; /***/ }), /***/ 36826: /***/ (function(__unused_webpack_module, exports) { "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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DuplexStreamingCall = void 0; /** * A duplex streaming RPC call. This means that the clients sends an * arbitrary amount of messages to the server, while at the same time, * the server sends an arbitrary amount of messages to the client. */ class DuplexStreamingCall { constructor(method, requestHeaders, request, headers, response, status, trailers) { this.method = method; this.requestHeaders = requestHeaders; this.requests = request; this.headers = headers; this.responses = response; this.status = status; this.trailers = trailers; } /** * Instead of awaiting the response status and trailers, you can * just as well await this call itself to receive the server outcome. * Note that it may still be valid to send more request messages. */ then(onfulfilled, onrejected) { return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); } promiseFinished() { return __awaiter(this, void 0, void 0, function* () { let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); return { method: this.method, requestHeaders: this.requestHeaders, headers, status, trailers, }; }); } } exports.DuplexStreamingCall = DuplexStreamingCall; /***/ }), /***/ 44420: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Public API of the rpc runtime. // Note: we do not use `export * from ...` to help tree shakers, // webpack verbose output hints that this should be useful Object.defineProperty(exports, "__esModule", ({ value: true })); var service_type_1 = __nccwpck_require__(56892); Object.defineProperty(exports, "ServiceType", ({ enumerable: true, get: function () { return service_type_1.ServiceType; } })); var reflection_info_1 = __nccwpck_require__(62496); Object.defineProperty(exports, "readMethodOptions", ({ enumerable: true, get: function () { return reflection_info_1.readMethodOptions; } })); Object.defineProperty(exports, "readMethodOption", ({ enumerable: true, get: function () { return reflection_info_1.readMethodOption; } })); Object.defineProperty(exports, "readServiceOption", ({ enumerable: true, get: function () { return reflection_info_1.readServiceOption; } })); var rpc_error_1 = __nccwpck_require__(78636); Object.defineProperty(exports, "RpcError", ({ enumerable: true, get: function () { return rpc_error_1.RpcError; } })); var rpc_options_1 = __nccwpck_require__(28576); Object.defineProperty(exports, "mergeRpcOptions", ({ enumerable: true, get: function () { return rpc_options_1.mergeRpcOptions; } })); var rpc_output_stream_1 = __nccwpck_require__(72726); Object.defineProperty(exports, "RpcOutputStreamController", ({ enumerable: true, get: function () { return rpc_output_stream_1.RpcOutputStreamController; } })); var test_transport_1 = __nccwpck_require__(79122); Object.defineProperty(exports, "TestTransport", ({ enumerable: true, get: function () { return test_transport_1.TestTransport; } })); var deferred_1 = __nccwpck_require__(71409); Object.defineProperty(exports, "Deferred", ({ enumerable: true, get: function () { return deferred_1.Deferred; } })); Object.defineProperty(exports, "DeferredState", ({ enumerable: true, get: function () { return deferred_1.DeferredState; } })); var duplex_streaming_call_1 = __nccwpck_require__(36826); Object.defineProperty(exports, "DuplexStreamingCall", ({ enumerable: true, get: function () { return duplex_streaming_call_1.DuplexStreamingCall; } })); var client_streaming_call_1 = __nccwpck_require__(37889); Object.defineProperty(exports, "ClientStreamingCall", ({ enumerable: true, get: function () { return client_streaming_call_1.ClientStreamingCall; } })); var server_streaming_call_1 = __nccwpck_require__(46173); Object.defineProperty(exports, "ServerStreamingCall", ({ enumerable: true, get: function () { return server_streaming_call_1.ServerStreamingCall; } })); var unary_call_1 = __nccwpck_require__(29288); Object.defineProperty(exports, "UnaryCall", ({ enumerable: true, get: function () { return unary_call_1.UnaryCall; } })); var rpc_interceptor_1 = __nccwpck_require__(52849); Object.defineProperty(exports, "stackIntercept", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackIntercept; } })); Object.defineProperty(exports, "stackDuplexStreamingInterceptors", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackDuplexStreamingInterceptors; } })); Object.defineProperty(exports, "stackClientStreamingInterceptors", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackClientStreamingInterceptors; } })); Object.defineProperty(exports, "stackServerStreamingInterceptors", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackServerStreamingInterceptors; } })); Object.defineProperty(exports, "stackUnaryInterceptors", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackUnaryInterceptors; } })); var server_call_context_1 = __nccwpck_require__(43352); Object.defineProperty(exports, "ServerCallContextController", ({ enumerable: true, get: function () { return server_call_context_1.ServerCallContextController; } })); /***/ }), /***/ 62496: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readServiceOption = exports.readMethodOption = exports.readMethodOptions = exports.normalizeMethodInfo = void 0; const runtime_1 = __nccwpck_require__(68886); /** * Turns PartialMethodInfo into MethodInfo. */ function normalizeMethodInfo(method, service) { var _a, _b, _c; let m = method; m.service = service; m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name); // noinspection PointlessBooleanExpressionJS m.serverStreaming = !!m.serverStreaming; // noinspection PointlessBooleanExpressionJS m.clientStreaming = !!m.clientStreaming; m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : undefined; return m; } exports.normalizeMethodInfo = normalizeMethodInfo; /** * Read custom method options from a generated service client. * * @deprecated use readMethodOption() */ function readMethodOptions(service, methodName, extensionName, extensionType) { var _a; const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : undefined; } exports.readMethodOptions = readMethodOptions; function readMethodOption(service, methodName, extensionName, extensionType) { var _a; const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; if (!options) { return undefined; } const optionVal = options[extensionName]; if (optionVal === undefined) { return optionVal; } return extensionType ? extensionType.fromJson(optionVal) : optionVal; } exports.readMethodOption = readMethodOption; function readServiceOption(service, extensionName, extensionType) { const options = service.options; if (!options) { return undefined; } const optionVal = options[extensionName]; if (optionVal === undefined) { return optionVal; } return extensionType ? extensionType.fromJson(optionVal) : optionVal; } exports.readServiceOption = readServiceOption; /***/ }), /***/ 78636: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RpcError = void 0; /** * An error that occurred while calling a RPC method. */ class RpcError extends Error { constructor(message, code = 'UNKNOWN', meta) { super(message); this.name = 'RpcError'; // see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#example Object.setPrototypeOf(this, new.target.prototype); this.code = code; this.meta = meta !== null && meta !== void 0 ? meta : {}; } toString() { const l = [this.name + ': ' + this.message]; if (this.code) { l.push(''); l.push('Code: ' + this.code); } if (this.serviceName && this.methodName) { l.push('Method: ' + this.serviceName + '/' + this.methodName); } let m = Object.entries(this.meta); if (m.length) { l.push(''); l.push('Meta:'); for (let [k, v] of m) { l.push(` ${k}: ${v}`); } } return l.join('\n'); } } exports.RpcError = RpcError; /***/ }), /***/ 52849: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.stackDuplexStreamingInterceptors = exports.stackClientStreamingInterceptors = exports.stackServerStreamingInterceptors = exports.stackUnaryInterceptors = exports.stackIntercept = void 0; const runtime_1 = __nccwpck_require__(68886); /** * Creates a "stack" of of all interceptors specified in the given `RpcOptions`. * Used by generated client implementations. * @internal */ function stackIntercept(kind, transport, method, options, input) { var _a, _b, _c, _d; if (kind == "unary") { let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter(i => i.interceptUnary).reverse()) { const next = tail; tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); } return tail(method, input, options); } if (kind == "serverStreaming") { let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter(i => i.interceptServerStreaming).reverse()) { const next = tail; tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); } return tail(method, input, options); } if (kind == "clientStreaming") { let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter(i => i.interceptClientStreaming).reverse()) { const next = tail; tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); } return tail(method, options); } if (kind == "duplex") { let tail = (mtd, opt) => transport.duplex(mtd, opt); for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter(i => i.interceptDuplex).reverse()) { const next = tail; tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); } return tail(method, options); } runtime_1.assertNever(kind); } exports.stackIntercept = stackIntercept; /** * @deprecated replaced by `stackIntercept()`, still here to support older generated code */ function stackUnaryInterceptors(transport, method, input, options) { return stackIntercept("unary", transport, method, options, input); } exports.stackUnaryInterceptors = stackUnaryInterceptors; /** * @deprecated replaced by `stackIntercept()`, still here to support older generated code */ function stackServerStreamingInterceptors(transport, method, input, options) { return stackIntercept("serverStreaming", transport, method, options, input); } exports.stackServerStreamingInterceptors = stackServerStreamingInterceptors; /** * @deprecated replaced by `stackIntercept()`, still here to support older generated code */ function stackClientStreamingInterceptors(transport, method, options) { return stackIntercept("clientStreaming", transport, method, options); } exports.stackClientStreamingInterceptors = stackClientStreamingInterceptors; /** * @deprecated replaced by `stackIntercept()`, still here to support older generated code */ function stackDuplexStreamingInterceptors(transport, method, options) { return stackIntercept("duplex", transport, method, options); } exports.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; /***/ }), /***/ 28576: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.mergeRpcOptions = void 0; const runtime_1 = __nccwpck_require__(68886); /** * Merges custom RPC options with defaults. Returns a new instance and keeps * the "defaults" and the "options" unmodified. * * Merges `RpcMetadata` "meta", overwriting values from "defaults" with * values from "options". Does not append values to existing entries. * * Merges "jsonOptions", including "jsonOptions.typeRegistry", by creating * a new array that contains types from "options.jsonOptions.typeRegistry" * first, then types from "defaults.jsonOptions.typeRegistry". * * Merges "binaryOptions". * * Merges "interceptors" by creating a new array that contains interceptors * from "defaults" first, then interceptors from "options". * * Works with objects that extend `RpcOptions`, but only if the added * properties are of type Date, primitive like string, boolean, or Array * of primitives. If you have other property types, you have to merge them * yourself. */ function mergeRpcOptions(defaults, options) { if (!options) return defaults; let o = {}; copy(defaults, o); copy(options, o); for (let key of Object.keys(options)) { let val = options[key]; switch (key) { case "jsonOptions": o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions); break; case "binaryOptions": o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions); break; case "meta": o.meta = {}; copy(defaults.meta, o.meta); copy(options.meta, o.meta); break; case "interceptors": o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val) : val.concat(); break; } } return o; } exports.mergeRpcOptions = mergeRpcOptions; function copy(a, into) { if (!a) return; let c = into; for (let [k, v] of Object.entries(a)) { if (v instanceof Date) c[k] = new Date(v.getTime()); else if (Array.isArray(v)) c[k] = v.concat(); else c[k] = v; } } /***/ }), /***/ 72726: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RpcOutputStreamController = void 0; const deferred_1 = __nccwpck_require__(71409); const runtime_1 = __nccwpck_require__(68886); /** * A `RpcOutputStream` that you control. */ class RpcOutputStreamController { constructor() { this._lis = { nxt: [], msg: [], err: [], cmp: [], }; this._closed = false; } // --- RpcOutputStream callback API onNext(callback) { return this.addLis(callback, this._lis.nxt); } onMessage(callback) { return this.addLis(callback, this._lis.msg); } onError(callback) { return this.addLis(callback, this._lis.err); } onComplete(callback) { return this.addLis(callback, this._lis.cmp); } addLis(callback, list) { list.push(callback); return () => { let i = list.indexOf(callback); if (i >= 0) list.splice(i, 1); }; } // remove all listeners clearLis() { for (let l of Object.values(this._lis)) l.splice(0, l.length); } // --- Controller API /** * Is this stream already closed by a completion or error? */ get closed() { return this._closed !== false; } /** * Emit message, close with error, or close successfully, but only one * at a time. * Can be used to wrap a stream by using the other stream's `onNext`. */ notifyNext(message, error, complete) { runtime_1.assert((message ? 1 : 0) + (error ? 1 : 0) + (complete ? 1 : 0) <= 1, 'only one emission at a time'); if (message) this.notifyMessage(message); if (error) this.notifyError(error); if (complete) this.notifyComplete(); } /** * Emits a new message. Throws if stream is closed. * * Triggers onNext and onMessage callbacks. */ notifyMessage(message) { runtime_1.assert(!this.closed, 'stream is closed'); this.pushIt({ value: message, done: false }); this._lis.msg.forEach(l => l(message)); this._lis.nxt.forEach(l => l(message, undefined, false)); } /** * Closes the stream with an error. Throws if stream is closed. * * Triggers onNext and onError callbacks. */ notifyError(error) { runtime_1.assert(!this.closed, 'stream is closed'); this._closed = error; this.pushIt(error); this._lis.err.forEach(l => l(error)); this._lis.nxt.forEach(l => l(undefined, error, false)); this.clearLis(); } /** * Closes the stream successfully. Throws if stream is closed. * * Triggers onNext and onComplete callbacks. */ notifyComplete() { runtime_1.assert(!this.closed, 'stream is closed'); this._closed = true; this.pushIt({ value: null, done: true }); this._lis.cmp.forEach(l => l()); this._lis.nxt.forEach(l => l(undefined, undefined, true)); this.clearLis(); } /** * Creates an async iterator (that can be used with `for await {...}`) * to consume the stream. * * Some things to note: * - If an error occurs, the `for await` will throw it. * - If an error occurred before the `for await` was started, `for await` * will re-throw it. * - If the stream is already complete, the `for await` will be empty. * - If your `for await` consumes slower than the stream produces, * for example because you are relaying messages in a slow operation, * messages are queued. */ [Symbol.asyncIterator]() { // init the iterator state, enabling pushIt() if (!this._itState) { this._itState = { q: [] }; } // if we are closed, we are definitely not receiving any more messages. // but we can't let the iterator get stuck. we want to either: // a) finish the new iterator immediately, because we are completed // b) reject the new iterator, because we errored if (this._closed === true) this.pushIt({ value: null, done: true }); else if (this._closed !== false) this.pushIt(this._closed); // the async iterator return { next: () => { let state = this._itState; runtime_1.assert(state, "bad state"); // if we don't have a state here, code is broken // there should be no pending result. // did the consumer call next() before we resolved our previous result promise? runtime_1.assert(!state.p, "iterator contract broken"); // did we produce faster than the iterator consumed? // return the oldest result from the queue. let first = state.q.shift(); if (first) return ("value" in first) ? Promise.resolve(first) : Promise.reject(first); // we have no result ATM, but we promise one. // as soon as we have a result, we must resolve promise. state.p = new deferred_1.Deferred(); return state.p.promise; }, }; } // "push" a new iterator result. // this either resolves a pending promise, or enqueues the result. pushIt(result) { let state = this._itState; if (!state) return; // is the consumer waiting for us? if (state.p) { // yes, consumer is waiting for this promise. const p = state.p; runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken"); // resolve the promise ("value" in result) ? p.resolve(result) : p.reject(result); // must cleanup, otherwise iterator.next() would pick it up again. delete state.p; } else { // we are producing faster than the iterator consumes. // push result onto queue. state.q.push(result); } } } exports.RpcOutputStreamController = RpcOutputStreamController; /***/ }), /***/ 43352: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ServerCallContextController = void 0; class ServerCallContextController { constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: 'OK', detail: '' }) { this._cancelled = false; this._listeners = []; this.method = method; this.headers = headers; this.deadline = deadline; this.trailers = {}; this._sendRH = sendResponseHeadersFn; this.status = defaultStatus; } /** * Set the call cancelled. * * Invokes all callbacks registered with onCancel() and * sets `cancelled = true`. */ notifyCancelled() { if (!this._cancelled) { this._cancelled = true; for (let l of this._listeners) { l(); } } } /** * Send response headers. */ sendResponseHeaders(data) { this._sendRH(data); } /** * Is the call cancelled? * * When the client closes the connection before the server * is done, the call is cancelled. * * If you want to cancel a request on the server, throw a * RpcError with the CANCELLED status code. */ get cancelled() { return this._cancelled; } /** * Add a callback for cancellation. */ onCancel(callback) { const l = this._listeners; l.push(callback); return () => { let i = l.indexOf(callback); if (i >= 0) l.splice(i, 1); }; } } exports.ServerCallContextController = ServerCallContextController; /***/ }), /***/ 46173: /***/ (function(__unused_webpack_module, exports) { "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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ServerStreamingCall = void 0; /** * A server streaming RPC call. The client provides exactly one input message * but the server may respond with 0, 1, or more messages. */ class ServerStreamingCall { constructor(method, requestHeaders, request, headers, response, status, trailers) { this.method = method; this.requestHeaders = requestHeaders; this.request = request; this.headers = headers; this.responses = response; this.status = status; this.trailers = trailers; } /** * Instead of awaiting the response status and trailers, you can * just as well await this call itself to receive the server outcome. * You should first setup some listeners to the `request` to * see the actual messages the server replied with. */ then(onfulfilled, onrejected) { return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); } promiseFinished() { return __awaiter(this, void 0, void 0, function* () { let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); return { method: this.method, requestHeaders: this.requestHeaders, request: this.request, headers, status, trailers, }; }); } } exports.ServerStreamingCall = ServerStreamingCall; /***/ }), /***/ 56892: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ServiceType = void 0; const reflection_info_1 = __nccwpck_require__(62496); class ServiceType { constructor(typeName, methods, options) { this.typeName = typeName; this.methods = methods.map(i => reflection_info_1.normalizeMethodInfo(i, this)); this.options = options !== null && options !== void 0 ? options : {}; } } exports.ServiceType = ServiceType; /***/ }), /***/ 79122: /***/ (function(__unused_webpack_module, exports, __nccwpck_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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TestTransport = void 0; const rpc_error_1 = __nccwpck_require__(78636); const runtime_1 = __nccwpck_require__(68886); const rpc_output_stream_1 = __nccwpck_require__(72726); const rpc_options_1 = __nccwpck_require__(28576); const unary_call_1 = __nccwpck_require__(29288); const server_streaming_call_1 = __nccwpck_require__(46173); const client_streaming_call_1 = __nccwpck_require__(37889); const duplex_streaming_call_1 = __nccwpck_require__(36826); /** * Transport for testing. */ class TestTransport { /** * Initialize with mock data. Omitted fields have default value. */ constructor(data) { /** * Suppress warning / error about uncaught rejections of * "status" and "trailers". */ this.suppressUncaughtRejections = true; this.headerDelay = 10; this.responseDelay = 50; this.betweenResponseDelay = 10; this.afterResponseDelay = 10; this.data = data !== null && data !== void 0 ? data : {}; } /** * Sent message(s) during the last operation. */ get sentMessages() { if (this.lastInput instanceof TestInputStream) { return this.lastInput.sent; } else if (typeof this.lastInput == "object") { return [this.lastInput.single]; } return []; } /** * Sending message(s) completed? */ get sendComplete() { if (this.lastInput instanceof TestInputStream) { return this.lastInput.completed; } else if (typeof this.lastInput == "object") { return true; } return false; } // Creates a promise for response headers from the mock data. promiseHeaders() { var _a; const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : TestTransport.defaultHeaders; return headers instanceof rpc_error_1.RpcError ? Promise.reject(headers) : Promise.resolve(headers); } // Creates a promise for a single, valid, message from the mock data. promiseSingleResponse(method) { if (this.data.response instanceof rpc_error_1.RpcError) { return Promise.reject(this.data.response); } let r; if (Array.isArray(this.data.response)) { runtime_1.assert(this.data.response.length > 0); r = this.data.response[0]; } else if (this.data.response !== undefined) { r = this.data.response; } else { r = method.O.create(); } runtime_1.assert(method.O.is(r)); return Promise.resolve(r); } /** * Pushes response messages from the mock data to the output stream. * If an error response, status or trailers are mocked, the stream is * closed with the respective error. * Otherwise, stream is completed successfully. * * The returned promise resolves when the stream is closed. It should * not reject. If it does, code is broken. */ streamResponses(method, stream, abort) { return __awaiter(this, void 0, void 0, function* () { // normalize "data.response" into an array of valid output messages const messages = []; if (this.data.response === undefined) { messages.push(method.O.create()); } else if (Array.isArray(this.data.response)) { for (let msg of this.data.response) { runtime_1.assert(method.O.is(msg)); messages.push(msg); } } else if (!(this.data.response instanceof rpc_error_1.RpcError)) { runtime_1.assert(method.O.is(this.data.response)); messages.push(this.data.response); } // start the stream with an initial delay. // if the request is cancelled, notify() error and exit. try { yield delay(this.responseDelay, abort)(undefined); } catch (error) { stream.notifyError(error); return; } // if error response was mocked, notify() error (stream is now closed with error) and exit. if (this.data.response instanceof rpc_error_1.RpcError) { stream.notifyError(this.data.response); return; } // regular response messages were mocked. notify() them. for (let msg of messages) { stream.notifyMessage(msg); // add a short delay between responses // if the request is cancelled, notify() error and exit. try { yield delay(this.betweenResponseDelay, abort)(undefined); } catch (error) { stream.notifyError(error); return; } } // error status was mocked, notify() error (stream is now closed with error) and exit. if (this.data.status instanceof rpc_error_1.RpcError) { stream.notifyError(this.data.status); return; } // error trailers were mocked, notify() error (stream is now closed with error) and exit. if (this.data.trailers instanceof rpc_error_1.RpcError) { stream.notifyError(this.data.trailers); return; } // stream completed successfully stream.notifyComplete(); }); } // Creates a promise for response status from the mock data. promiseStatus() { var _a; const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : TestTransport.defaultStatus; return status instanceof rpc_error_1.RpcError ? Promise.reject(status) : Promise.resolve(status); } // Creates a promise for response trailers from the mock data. promiseTrailers() { var _a; const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : TestTransport.defaultTrailers; return trailers instanceof rpc_error_1.RpcError ? Promise.reject(trailers) : Promise.resolve(trailers); } maybeSuppressUncaught(...promise) { if (this.suppressUncaughtRejections) { for (let p of promise) { p.catch(() => { }); } } } mergeOptions(options) { return rpc_options_1.mergeRpcOptions({}, options); } unary(method, input, options) { var _a; const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders() .then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise .catch(_ => { }) .then(delay(this.responseDelay, options.abort)) .then(_ => this.promiseSingleResponse(method)), statusPromise = responsePromise .catch(_ => { }) .then(delay(this.afterResponseDelay, options.abort)) .then(_ => this.promiseStatus()), trailersPromise = responsePromise .catch(_ => { }) .then(delay(this.afterResponseDelay, options.abort)) .then(_ => this.promiseTrailers()); this.maybeSuppressUncaught(statusPromise, trailersPromise); this.lastInput = { single: input }; return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); } serverStreaming(method, input, options) { var _a; const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders() .then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise .then(delay(this.responseDelay, options.abort)) .catch(() => { }) .then(() => this.streamResponses(method, outputStream, options.abort)) .then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise .then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise .then(() => this.promiseTrailers()); this.maybeSuppressUncaught(statusPromise, trailersPromise); this.lastInput = { single: input }; return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); } clientStreaming(method, options) { var _a; const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders() .then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise .catch(_ => { }) .then(delay(this.responseDelay, options.abort)) .then(_ => this.promiseSingleResponse(method)), statusPromise = responsePromise .catch(_ => { }) .then(delay(this.afterResponseDelay, options.abort)) .then(_ => this.promiseStatus()), trailersPromise = responsePromise .catch(_ => { }) .then(delay(this.afterResponseDelay, options.abort)) .then(_ => this.promiseTrailers()); this.maybeSuppressUncaught(statusPromise, trailersPromise); this.lastInput = new TestInputStream(this.data, options.abort); return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); } duplex(method, options) { var _a; const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders() .then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise .then(delay(this.responseDelay, options.abort)) .catch(() => { }) .then(() => this.streamResponses(method, outputStream, options.abort)) .then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise .then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise .then(() => this.promiseTrailers()); this.maybeSuppressUncaught(statusPromise, trailersPromise); this.lastInput = new TestInputStream(this.data, options.abort); return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise); } } exports.TestTransport = TestTransport; TestTransport.defaultHeaders = { responseHeader: "test" }; TestTransport.defaultStatus = { code: "OK", detail: "all good" }; TestTransport.defaultTrailers = { responseTrailer: "test" }; function delay(ms, abort) { return (v) => new Promise((resolve, reject) => { if (abort === null || abort === void 0 ? void 0 : abort.aborted) { reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); } else { const id = setTimeout(() => resolve(v), ms); if (abort) { abort.addEventListener("abort", ev => { clearTimeout(id); reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); }); } } }); } class TestInputStream { constructor(data, abort) { this._completed = false; this._sent = []; this.data = data; this.abort = abort; } get sent() { return this._sent; } get completed() { return this._completed; } send(message) { if (this.data.inputMessage instanceof rpc_error_1.RpcError) { return Promise.reject(this.data.inputMessage); } const delayMs = this.data.inputMessage === undefined ? 10 : this.data.inputMessage; return Promise.resolve(undefined) .then(() => { this._sent.push(message); }) .then(delay(delayMs, this.abort)); } complete() { if (this.data.inputComplete instanceof rpc_error_1.RpcError) { return Promise.reject(this.data.inputComplete); } const delayMs = this.data.inputComplete === undefined ? 10 : this.data.inputComplete; return Promise.resolve(undefined) .then(() => { this._completed = true; }) .then(delay(delayMs, this.abort)); } } /***/ }), /***/ 29288: /***/ (function(__unused_webpack_module, exports) { "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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnaryCall = void 0; /** * A unary RPC call. Unary means there is exactly one input message and * exactly one output message unless an error occurred. */ class UnaryCall { constructor(method, requestHeaders, request, headers, response, status, trailers) { this.method = method; this.requestHeaders = requestHeaders; this.request = request; this.headers = headers; this.response = response; this.status = status; this.trailers = trailers; } /** * If you are only interested in the final outcome of this call, * you can await it to receive a `FinishedUnaryCall`. */ then(onfulfilled, onrejected) { return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); } promiseFinished() { return __awaiter(this, void 0, void 0, function* () { let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); return { method: this.method, requestHeaders: this.requestHeaders, request: this.request, headers, response, status, trailers }; }); } } exports.UnaryCall = UnaryCall; /***/ }), /***/ 8602: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.assertFloat32 = exports.assertUInt32 = exports.assertInt32 = exports.assertNever = exports.assert = void 0; /** * assert that condition is true or throw error (with message) */ function assert(condition, msg) { if (!condition) { throw new Error(msg); } } exports.assert = assert; /** * assert that value cannot exist = type `never`. throw runtime error if it does. */ function assertNever(value, msg) { throw new Error(msg !== null && msg !== void 0 ? msg : 'Unexpected object: ' + value); } exports.assertNever = assertNever; const FLOAT32_MAX = 3.4028234663852886e+38, FLOAT32_MIN = -3.4028234663852886e+38, UINT32_MAX = 0xFFFFFFFF, INT32_MAX = 0X7FFFFFFF, INT32_MIN = -0X80000000; function assertInt32(arg) { if (typeof arg !== "number") throw new Error('invalid int 32: ' + typeof arg); if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) throw new Error('invalid int 32: ' + arg); } exports.assertInt32 = assertInt32; function assertUInt32(arg) { if (typeof arg !== "number") throw new Error('invalid uint 32: ' + typeof arg); if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) throw new Error('invalid uint 32: ' + arg); } exports.assertUInt32 = assertUInt32; function assertFloat32(arg) { if (typeof arg !== "number") throw new Error('invalid float 32: ' + typeof arg); if (!Number.isFinite(arg)) return; if (arg > FLOAT32_MAX || arg < FLOAT32_MIN) throw new Error('invalid float 32: ' + arg); } exports.assertFloat32 = assertFloat32; /***/ }), /***/ 26335: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.base64encode = exports.base64decode = void 0; // lookup table from base64 character to byte let encTable = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); // lookup table from base64 character *code* to byte because lookup by number is fast let decTable = []; for (let i = 0; i < encTable.length; i++) decTable[encTable[i].charCodeAt(0)] = i; // support base64url variants decTable["-".charCodeAt(0)] = encTable.indexOf("+"); decTable["_".charCodeAt(0)] = encTable.indexOf("/"); /** * Decodes a base64 string to a byte array. * * - ignores white-space, including line breaks and tabs * - allows inner padding (can decode concatenated base64 strings) * - does not require padding * - understands base64url encoding: * "-" instead of "+", * "_" instead of "/", * no padding */ function base64decode(base64Str) { // estimate byte size, not accounting for inner padding and whitespace let es = base64Str.length * 3 / 4; // if (es % 3 !== 0) // throw new Error('invalid base64 string'); if (base64Str[base64Str.length - 2] == '=') es -= 2; else if (base64Str[base64Str.length - 1] == '=') es -= 1; let bytes = new Uint8Array(es), bytePos = 0, // position in byte array groupPos = 0, // position in base64 group b, // current byte p = 0 // previous byte ; for (let i = 0; i < base64Str.length; i++) { b = decTable[base64Str.charCodeAt(i)]; if (b === undefined) { // noinspection FallThroughInSwitchStatementJS switch (base64Str[i]) { case '=': groupPos = 0; // reset state when padding found case '\n': case '\r': case '\t': case ' ': continue; // skip white-space, and padding default: throw Error(`invalid base64 string.`); } } switch (groupPos) { case 0: p = b; groupPos = 1; break; case 1: bytes[bytePos++] = p << 2 | (b & 48) >> 4; p = b; groupPos = 2; break; case 2: bytes[bytePos++] = (p & 15) << 4 | (b & 60) >> 2; p = b; groupPos = 3; break; case 3: bytes[bytePos++] = (p & 3) << 6 | b; groupPos = 0; break; } } if (groupPos == 1) throw Error(`invalid base64 string.`); return bytes.subarray(0, bytePos); } exports.base64decode = base64decode; /** * Encodes a byte array to a base64 string. * Adds padding at the end. * Does not insert newlines. */ function base64encode(bytes) { let base64 = '', groupPos = 0, // position in base64 group b, // current byte p = 0; // carry over from previous byte for (let i = 0; i < bytes.length; i++) { b = bytes[i]; switch (groupPos) { case 0: base64 += encTable[b >> 2]; p = (b & 3) << 4; groupPos = 1; break; case 1: base64 += encTable[p | b >> 4]; p = (b & 15) << 2; groupPos = 2; break; case 2: base64 += encTable[p | b >> 6]; base64 += encTable[b & 63]; groupPos = 0; break; } } // padding required? if (groupPos) { base64 += encTable[p]; base64 += '='; if (groupPos == 1) base64 += '='; } return base64; } exports.base64encode = base64encode; /***/ }), /***/ 54816: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WireType = exports.mergeBinaryOptions = exports.UnknownFieldHandler = void 0; /** * This handler implements the default behaviour for unknown fields. * When reading data, unknown fields are stored on the message, in a * symbol property. * When writing data, the symbol property is queried and unknown fields * are serialized into the output again. */ var UnknownFieldHandler; (function (UnknownFieldHandler) { /** * The symbol used to store unknown fields for a message. * The property must conform to `UnknownFieldContainer`. */ UnknownFieldHandler.symbol = Symbol.for("protobuf-ts/unknown"); /** * Store an unknown field during binary read directly on the message. * This method is compatible with `BinaryReadOptions.readUnknownField`. */ UnknownFieldHandler.onRead = (typeName, message, fieldNo, wireType, data) => { let container = is(message) ? message[UnknownFieldHandler.symbol] : message[UnknownFieldHandler.symbol] = []; container.push({ no: fieldNo, wireType, data }); }; /** * Write unknown fields stored for the message to the writer. * This method is compatible with `BinaryWriteOptions.writeUnknownFields`. */ UnknownFieldHandler.onWrite = (typeName, message, writer) => { for (let { no, wireType, data } of UnknownFieldHandler.list(message)) writer.tag(no, wireType).raw(data); }; /** * List unknown fields stored for the message. * Note that there may be multiples fields with the same number. */ UnknownFieldHandler.list = (message, fieldNo) => { if (is(message)) { let all = message[UnknownFieldHandler.symbol]; return fieldNo ? all.filter(uf => uf.no == fieldNo) : all; } return []; }; /** * Returns the last unknown field by field number. */ UnknownFieldHandler.last = (message, fieldNo) => UnknownFieldHandler.list(message, fieldNo).slice(-1)[0]; const is = (message) => message && Array.isArray(message[UnknownFieldHandler.symbol]); })(UnknownFieldHandler = exports.UnknownFieldHandler || (exports.UnknownFieldHandler = {})); /** * Merges binary write or read options. Later values override earlier values. */ function mergeBinaryOptions(a, b) { return Object.assign(Object.assign({}, a), b); } exports.mergeBinaryOptions = mergeBinaryOptions; /** * Protobuf binary format wire types. * * A wire type provides just enough information to find the length of the * following value. * * See https://developers.google.com/protocol-buffers/docs/encoding#structure */ var WireType; (function (WireType) { /** * Used for int32, int64, uint32, uint64, sint32, sint64, bool, enum */ WireType[WireType["Varint"] = 0] = "Varint"; /** * Used for fixed64, sfixed64, double. * Always 8 bytes with little-endian byte order. */ WireType[WireType["Bit64"] = 1] = "Bit64"; /** * Used for string, bytes, embedded messages, packed repeated fields * * Only repeated numeric types (types which use the varint, 32-bit, * or 64-bit wire types) can be packed. In proto3, such fields are * packed by default. */ WireType[WireType["LengthDelimited"] = 2] = "LengthDelimited"; /** * Used for groups * @deprecated */ WireType[WireType["StartGroup"] = 3] = "StartGroup"; /** * Used for groups * @deprecated */ WireType[WireType["EndGroup"] = 4] = "EndGroup"; /** * Used for fixed32, sfixed32, float. * Always 4 bytes with little-endian byte order. */ WireType[WireType["Bit32"] = 5] = "Bit32"; })(WireType = exports.WireType || (exports.WireType = {})); /***/ }), /***/ 92889: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BinaryReader = exports.binaryReadOptions = void 0; const binary_format_contract_1 = __nccwpck_require__(54816); const pb_long_1 = __nccwpck_require__(61753); const goog_varint_1 = __nccwpck_require__(93223); const defaultsRead = { readUnknownField: true, readerFactory: bytes => new BinaryReader(bytes), }; /** * Make options for reading binary data form partial options. */ function binaryReadOptions(options) { return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; } exports.binaryReadOptions = binaryReadOptions; class BinaryReader { constructor(buf, textDecoder) { this.varint64 = goog_varint_1.varint64read; // dirty cast for `this` /** * Read a `uint32` field, an unsigned 32 bit varint. */ this.uint32 = goog_varint_1.varint32read; // dirty cast for `this` and access to protected `buf` this.buf = buf; this.len = buf.length; this.pos = 0; this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); this.textDecoder = textDecoder !== null && textDecoder !== void 0 ? textDecoder : new TextDecoder("utf-8", { fatal: true, ignoreBOM: true, }); } /** * Reads a tag - field number and wire type. */ tag() { let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7; if (fieldNo <= 0 || wireType < 0 || wireType > 5) throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType); return [fieldNo, wireType]; } /** * Skip one element on the wire and return the skipped data. * Supports WireType.StartGroup since v2.0.0-alpha.23. */ skip(wireType) { let start = this.pos; // noinspection FallThroughInSwitchStatementJS switch (wireType) { case binary_format_contract_1.WireType.Varint: while (this.buf[this.pos++] & 0x80) { // ignore } break; case binary_format_contract_1.WireType.Bit64: this.pos += 4; case binary_format_contract_1.WireType.Bit32: this.pos += 4; break; case binary_format_contract_1.WireType.LengthDelimited: let len = this.uint32(); this.pos += len; break; case binary_format_contract_1.WireType.StartGroup: // From descriptor.proto: Group type is deprecated, not supported in proto3. // But we must still be able to parse and treat as unknown. let t; while ((t = this.tag()[1]) !== binary_format_contract_1.WireType.EndGroup) { this.skip(t); } break; default: throw new Error("cant skip wire type " + wireType); } this.assertBounds(); return this.buf.subarray(start, this.pos); } /** * Throws error if position in byte array is out of range. */ assertBounds() { if (this.pos > this.len) throw new RangeError("premature EOF"); } /** * Read a `int32` field, a signed 32 bit varint. */ int32() { return this.uint32() | 0; } /** * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint. */ sint32() { let zze = this.uint32(); // decode zigzag return (zze >>> 1) ^ -(zze & 1); } /** * Read a `int64` field, a signed 64-bit varint. */ int64() { return new pb_long_1.PbLong(...this.varint64()); } /** * Read a `uint64` field, an unsigned 64-bit varint. */ uint64() { return new pb_long_1.PbULong(...this.varint64()); } /** * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint. */ sint64() { let [lo, hi] = this.varint64(); // decode zig zag let s = -(lo & 1); lo = ((lo >>> 1 | (hi & 1) << 31) ^ s); hi = (hi >>> 1 ^ s); return new pb_long_1.PbLong(lo, hi); } /** * Read a `bool` field, a variant. */ bool() { let [lo, hi] = this.varint64(); return lo !== 0 || hi !== 0; } /** * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer. */ fixed32() { return this.view.getUint32((this.pos += 4) - 4, true); } /** * Read a `sfixed32` field, a signed, fixed-length 32-bit integer. */ sfixed32() { return this.view.getInt32((this.pos += 4) - 4, true); } /** * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer. */ fixed64() { return new pb_long_1.PbULong(this.sfixed32(), this.sfixed32()); } /** * Read a `fixed64` field, a signed, fixed-length 64-bit integer. */ sfixed64() { return new pb_long_1.PbLong(this.sfixed32(), this.sfixed32()); } /** * Read a `float` field, 32-bit floating point number. */ float() { return this.view.getFloat32((this.pos += 4) - 4, true); } /** * Read a `double` field, a 64-bit floating point number. */ double() { return this.view.getFloat64((this.pos += 8) - 8, true); } /** * Read a `bytes` field, length-delimited arbitrary data. */ bytes() { let len = this.uint32(); let start = this.pos; this.pos += len; this.assertBounds(); return this.buf.subarray(start, start + len); } /** * Read a `string` field, length-delimited data converted to UTF-8 text. */ string() { return this.textDecoder.decode(this.bytes()); } } exports.BinaryReader = BinaryReader; /***/ }), /***/ 23957: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BinaryWriter = exports.binaryWriteOptions = void 0; const pb_long_1 = __nccwpck_require__(61753); const goog_varint_1 = __nccwpck_require__(93223); const assert_1 = __nccwpck_require__(8602); const defaultsWrite = { writeUnknownFields: true, writerFactory: () => new BinaryWriter(), }; /** * Make options for writing binary data form partial options. */ function binaryWriteOptions(options) { return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; } exports.binaryWriteOptions = binaryWriteOptions; class BinaryWriter { constructor(textEncoder) { /** * Previous fork states. */ this.stack = []; this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder(); this.chunks = []; this.buf = []; } /** * Return all bytes written and reset this writer. */ finish() { this.chunks.push(new Uint8Array(this.buf)); // flush the buffer let len = 0; for (let i = 0; i < this.chunks.length; i++) len += this.chunks[i].length; let bytes = new Uint8Array(len); let offset = 0; for (let i = 0; i < this.chunks.length; i++) { bytes.set(this.chunks[i], offset); offset += this.chunks[i].length; } this.chunks = []; return bytes; } /** * Start a new fork for length-delimited data like a message * or a packed repeated field. * * Must be joined later with `join()`. */ fork() { this.stack.push({ chunks: this.chunks, buf: this.buf }); this.chunks = []; this.buf = []; return this; } /** * Join the last fork. Write its length and bytes, then * return to the previous state. */ join() { // get chunk of fork let chunk = this.finish(); // restore previous state let prev = this.stack.pop(); if (!prev) throw new Error('invalid state, fork stack empty'); this.chunks = prev.chunks; this.buf = prev.buf; // write length of chunk as varint this.uint32(chunk.byteLength); return this.raw(chunk); } /** * Writes a tag (field number and wire type). * * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. * * Generated code should compute the tag ahead of time and call `uint32()`. */ tag(fieldNo, type) { return this.uint32((fieldNo << 3 | type) >>> 0); } /** * Write a chunk of raw bytes. */ raw(chunk) { if (this.buf.length) { this.chunks.push(new Uint8Array(this.buf)); this.buf = []; } this.chunks.push(chunk); return this; } /** * Write a `uint32` value, an unsigned 32 bit varint. */ uint32(value) { assert_1.assertUInt32(value); // write value as varint 32, inlined for speed while (value > 0x7f) { this.buf.push((value & 0x7f) | 0x80); value = value >>> 7; } this.buf.push(value); return this; } /** * Write a `int32` value, a signed 32 bit varint. */ int32(value) { assert_1.assertInt32(value); goog_varint_1.varint32write(value, this.buf); return this; } /** * Write a `bool` value, a variant. */ bool(value) { this.buf.push(value ? 1 : 0); return this; } /** * Write a `bytes` value, length-delimited arbitrary data. */ bytes(value) { this.uint32(value.byteLength); // write length of chunk as varint return this.raw(value); } /** * Write a `string` value, length-delimited data converted to UTF-8 text. */ string(value) { let chunk = this.textEncoder.encode(value); this.uint32(chunk.byteLength); // write length of chunk as varint return this.raw(chunk); } /** * Write a `float` value, 32-bit floating point number. */ float(value) { assert_1.assertFloat32(value); let chunk = new Uint8Array(4); new DataView(chunk.buffer).setFloat32(0, value, true); return this.raw(chunk); } /** * Write a `double` value, a 64-bit floating point number. */ double(value) { let chunk = new Uint8Array(8); new DataView(chunk.buffer).setFloat64(0, value, true); return this.raw(chunk); } /** * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. */ fixed32(value) { assert_1.assertUInt32(value); let chunk = new Uint8Array(4); new DataView(chunk.buffer).setUint32(0, value, true); return this.raw(chunk); } /** * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. */ sfixed32(value) { assert_1.assertInt32(value); let chunk = new Uint8Array(4); new DataView(chunk.buffer).setInt32(0, value, true); return this.raw(chunk); } /** * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. */ sint32(value) { assert_1.assertInt32(value); // zigzag encode value = ((value << 1) ^ (value >> 31)) >>> 0; goog_varint_1.varint32write(value, this.buf); return this; } /** * Write a `fixed64` value, a signed, fixed-length 64-bit integer. */ sfixed64(value) { let chunk = new Uint8Array(8); let view = new DataView(chunk.buffer); let long = pb_long_1.PbLong.from(value); view.setInt32(0, long.lo, true); view.setInt32(4, long.hi, true); return this.raw(chunk); } /** * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. */ fixed64(value) { let chunk = new Uint8Array(8); let view = new DataView(chunk.buffer); let long = pb_long_1.PbULong.from(value); view.setInt32(0, long.lo, true); view.setInt32(4, long.hi, true); return this.raw(chunk); } /** * Write a `int64` value, a signed 64-bit varint. */ int64(value) { let long = pb_long_1.PbLong.from(value); goog_varint_1.varint64write(long.lo, long.hi, this.buf); return this; } /** * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. */ sint64(value) { let long = pb_long_1.PbLong.from(value), // zigzag encode sign = long.hi >> 31, lo = (long.lo << 1) ^ sign, hi = ((long.hi << 1) | (long.lo >>> 31)) ^ sign; goog_varint_1.varint64write(lo, hi, this.buf); return this; } /** * Write a `uint64` value, an unsigned 64-bit varint. */ uint64(value) { let long = pb_long_1.PbULong.from(value); goog_varint_1.varint64write(long.lo, long.hi, this.buf); return this; } } exports.BinaryWriter = BinaryWriter; /***/ }), /***/ 70257: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.listEnumNumbers = exports.listEnumNames = exports.listEnumValues = exports.isEnumObject = void 0; /** * Is this a lookup object generated by Typescript, for a Typescript enum * generated by protobuf-ts? * * - No `const enum` (enum must not be inlined, we need reverse mapping). * - No string enum (we need int32 for protobuf). * - Must have a value for 0 (otherwise, we would need to support custom default values). */ function isEnumObject(arg) { if (typeof arg != 'object' || arg === null) { return false; } if (!arg.hasOwnProperty(0)) { return false; } for (let k of Object.keys(arg)) { let num = parseInt(k); if (!Number.isNaN(num)) { // is there a name for the number? let nam = arg[num]; if (nam === undefined) return false; // does the name resolve back to the number? if (arg[nam] !== num) return false; } else { // is there a number for the name? let num = arg[k]; if (num === undefined) return false; // is it a string enum? if (typeof num !== 'number') return false; // do we know the number? if (arg[num] === undefined) return false; } } return true; } exports.isEnumObject = isEnumObject; /** * Lists all values of a Typescript enum, as an array of objects with a "name" * property and a "number" property. * * Note that it is possible that a number appears more than once, because it is * possible to have aliases in an enum. * * Throws if the enum does not adhere to the rules of enums generated by * protobuf-ts. See `isEnumObject()`. */ function listEnumValues(enumObject) { if (!isEnumObject(enumObject)) throw new Error("not a typescript enum object"); let values = []; for (let [name, number] of Object.entries(enumObject)) if (typeof number == "number") values.push({ name, number }); return values; } exports.listEnumValues = listEnumValues; /** * Lists the names of a Typescript enum. * * Throws if the enum does not adhere to the rules of enums generated by * protobuf-ts. See `isEnumObject()`. */ function listEnumNames(enumObject) { return listEnumValues(enumObject).map(val => val.name); } exports.listEnumNames = listEnumNames; /** * Lists the numbers of a Typescript enum. * * Throws if the enum does not adhere to the rules of enums generated by * protobuf-ts. See `isEnumObject()`. */ function listEnumNumbers(enumObject) { return listEnumValues(enumObject) .map(val => val.number) .filter((num, index, arr) => arr.indexOf(num) == index); } exports.listEnumNumbers = listEnumNumbers; /***/ }), /***/ 93223: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright 2008 Google Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Code generated by the Protocol Buffer compiler is owned by the owner // of the input file used when generating it. This code is not // standalone and requires a support library to be linked with it. This // support library is itself covered by the above license. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.varint32read = exports.varint32write = exports.int64toString = exports.int64fromString = exports.varint64write = exports.varint64read = void 0; /** * Read a 64 bit varint as two JS numbers. * * Returns tuple: * [0]: low bits * [0]: high bits * * Copyright 2008 Google Inc. All rights reserved. * * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L175 */ function varint64read() { let lowBits = 0; let highBits = 0; for (let shift = 0; shift < 28; shift += 7) { let b = this.buf[this.pos++]; lowBits |= (b & 0x7F) << shift; if ((b & 0x80) == 0) { this.assertBounds(); return [lowBits, highBits]; } } let middleByte = this.buf[this.pos++]; // last four bits of the first 32 bit number lowBits |= (middleByte & 0x0F) << 28; // 3 upper bits are part of the next 32 bit number highBits = (middleByte & 0x70) >> 4; if ((middleByte & 0x80) == 0) { this.assertBounds(); return [lowBits, highBits]; } for (let shift = 3; shift <= 31; shift += 7) { let b = this.buf[this.pos++]; highBits |= (b & 0x7F) << shift; if ((b & 0x80) == 0) { this.assertBounds(); return [lowBits, highBits]; } } throw new Error('invalid varint'); } exports.varint64read = varint64read; /** * Write a 64 bit varint, given as two JS numbers, to the given bytes array. * * Copyright 2008 Google Inc. All rights reserved. * * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/writer.js#L344 */ function varint64write(lo, hi, bytes) { for (let i = 0; i < 28; i = i + 7) { const shift = lo >>> i; const hasNext = !((shift >>> 7) == 0 && hi == 0); const byte = (hasNext ? shift | 0x80 : shift) & 0xFF; bytes.push(byte); if (!hasNext) { return; } } const splitBits = ((lo >>> 28) & 0x0F) | ((hi & 0x07) << 4); const hasMoreBits = !((hi >> 3) == 0); bytes.push((hasMoreBits ? splitBits | 0x80 : splitBits) & 0xFF); if (!hasMoreBits) { return; } for (let i = 3; i < 31; i = i + 7) { const shift = hi >>> i; const hasNext = !((shift >>> 7) == 0); const byte = (hasNext ? shift | 0x80 : shift) & 0xFF; bytes.push(byte); if (!hasNext) { return; } } bytes.push((hi >>> 31) & 0x01); } exports.varint64write = varint64write; // constants for binary math const TWO_PWR_32_DBL = (1 << 16) * (1 << 16); /** * Parse decimal string of 64 bit integer value as two JS numbers. * * Returns tuple: * [0]: minus sign? * [1]: low bits * [2]: high bits * * Copyright 2008 Google Inc. */ function int64fromString(dec) { // Check for minus sign. let minus = dec[0] == '-'; if (minus) dec = dec.slice(1); // Work 6 decimal digits at a time, acting like we're converting base 1e6 // digits to binary. This is safe to do with floating point math because // Number.isSafeInteger(ALL_32_BITS * 1e6) == true. const base = 1e6; let lowBits = 0; let highBits = 0; function add1e6digit(begin, end) { // Note: Number('') is 0. const digit1e6 = Number(dec.slice(begin, end)); highBits *= base; lowBits = lowBits * base + digit1e6; // Carry bits from lowBits to highBits if (lowBits >= TWO_PWR_32_DBL) { highBits = highBits + ((lowBits / TWO_PWR_32_DBL) | 0); lowBits = lowBits % TWO_PWR_32_DBL; } } add1e6digit(-24, -18); add1e6digit(-18, -12); add1e6digit(-12, -6); add1e6digit(-6); return [minus, lowBits, highBits]; } exports.int64fromString = int64fromString; /** * Format 64 bit integer value (as two JS numbers) to decimal string. * * Copyright 2008 Google Inc. */ function int64toString(bitsLow, bitsHigh) { // Skip the expensive conversion if the number is small enough to use the // built-in conversions. if ((bitsHigh >>> 0) <= 0x1FFFFF) { return '' + (TWO_PWR_32_DBL * bitsHigh + (bitsLow >>> 0)); } // What this code is doing is essentially converting the input number from // base-2 to base-1e7, which allows us to represent the 64-bit range with // only 3 (very large) digits. Those digits are then trivial to convert to // a base-10 string. // The magic numbers used here are - // 2^24 = 16777216 = (1,6777216) in base-1e7. // 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7. // Split 32:32 representation into 16:24:24 representation so our // intermediate digits don't overflow. let low = bitsLow & 0xFFFFFF; let mid = (((bitsLow >>> 24) | (bitsHigh << 8)) >>> 0) & 0xFFFFFF; let high = (bitsHigh >> 16) & 0xFFFF; // Assemble our three base-1e7 digits, ignoring carries. The maximum // value in a digit at this step is representable as a 48-bit integer, which // can be stored in a 64-bit floating point number. let digitA = low + (mid * 6777216) + (high * 6710656); let digitB = mid + (high * 8147497); let digitC = (high * 2); // Apply carries from A to B and from B to C. let base = 10000000; if (digitA >= base) { digitB += Math.floor(digitA / base); digitA %= base; } if (digitB >= base) { digitC += Math.floor(digitB / base); digitB %= base; } // Convert base-1e7 digits to base-10, with optional leading zeroes. function decimalFrom1e7(digit1e7, needLeadingZeros) { let partial = digit1e7 ? String(digit1e7) : ''; if (needLeadingZeros) { return '0000000'.slice(partial.length) + partial; } return partial; } return decimalFrom1e7(digitC, /*needLeadingZeros=*/ 0) + decimalFrom1e7(digitB, /*needLeadingZeros=*/ digitC) + // If the final 1e7 digit didn't need leading zeros, we would have // returned via the trivial code path at the top. decimalFrom1e7(digitA, /*needLeadingZeros=*/ 1); } exports.int64toString = int64toString; /** * Write a 32 bit varint, signed or unsigned. Same as `varint64write(0, value, bytes)` * * Copyright 2008 Google Inc. All rights reserved. * * See https://github.com/protocolbuffers/protobuf/blob/1b18833f4f2a2f681f4e4a25cdf3b0a43115ec26/js/binary/encoder.js#L144 */ function varint32write(value, bytes) { if (value >= 0) { // write value as varint 32 while (value > 0x7f) { bytes.push((value & 0x7f) | 0x80); value = value >>> 7; } bytes.push(value); } else { for (let i = 0; i < 9; i++) { bytes.push(value & 127 | 128); value = value >> 7; } bytes.push(1); } } exports.varint32write = varint32write; /** * Read an unsigned 32 bit varint. * * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L220 */ function varint32read() { let b = this.buf[this.pos++]; let result = b & 0x7F; if ((b & 0x80) == 0) { this.assertBounds(); return result; } b = this.buf[this.pos++]; result |= (b & 0x7F) << 7; if ((b & 0x80) == 0) { this.assertBounds(); return result; } b = this.buf[this.pos++]; result |= (b & 0x7F) << 14; if ((b & 0x80) == 0) { this.assertBounds(); return result; } b = this.buf[this.pos++]; result |= (b & 0x7F) << 21; if ((b & 0x80) == 0) { this.assertBounds(); return result; } // Extract only last 4 bits b = this.buf[this.pos++]; result |= (b & 0x0F) << 28; for (let readBytes = 5; ((b & 0x80) !== 0) && readBytes < 10; readBytes++) b = this.buf[this.pos++]; if ((b & 0x80) != 0) throw new Error('invalid varint'); this.assertBounds(); // Result can have 32 bits, convert it to unsigned return result >>> 0; } exports.varint32read = varint32read; /***/ }), /***/ 68886: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Public API of the protobuf-ts runtime. // Note: we do not use `export * from ...` to help tree shakers, // webpack verbose output hints that this should be useful Object.defineProperty(exports, "__esModule", ({ value: true })); // Convenience JSON typings and corresponding type guards var json_typings_1 = __nccwpck_require__(49999); Object.defineProperty(exports, "typeofJsonValue", ({ enumerable: true, get: function () { return json_typings_1.typeofJsonValue; } })); Object.defineProperty(exports, "isJsonObject", ({ enumerable: true, get: function () { return json_typings_1.isJsonObject; } })); // Base 64 encoding var base64_1 = __nccwpck_require__(26335); Object.defineProperty(exports, "base64decode", ({ enumerable: true, get: function () { return base64_1.base64decode; } })); Object.defineProperty(exports, "base64encode", ({ enumerable: true, get: function () { return base64_1.base64encode; } })); // UTF8 encoding var protobufjs_utf8_1 = __nccwpck_require__(58950); Object.defineProperty(exports, "utf8read", ({ enumerable: true, get: function () { return protobufjs_utf8_1.utf8read; } })); // Binary format contracts, options for reading and writing, for example var binary_format_contract_1 = __nccwpck_require__(54816); Object.defineProperty(exports, "WireType", ({ enumerable: true, get: function () { return binary_format_contract_1.WireType; } })); Object.defineProperty(exports, "mergeBinaryOptions", ({ enumerable: true, get: function () { return binary_format_contract_1.mergeBinaryOptions; } })); Object.defineProperty(exports, "UnknownFieldHandler", ({ enumerable: true, get: function () { return binary_format_contract_1.UnknownFieldHandler; } })); // Standard IBinaryReader implementation var binary_reader_1 = __nccwpck_require__(92889); Object.defineProperty(exports, "BinaryReader", ({ enumerable: true, get: function () { return binary_reader_1.BinaryReader; } })); Object.defineProperty(exports, "binaryReadOptions", ({ enumerable: true, get: function () { return binary_reader_1.binaryReadOptions; } })); // Standard IBinaryWriter implementation var binary_writer_1 = __nccwpck_require__(23957); Object.defineProperty(exports, "BinaryWriter", ({ enumerable: true, get: function () { return binary_writer_1.BinaryWriter; } })); Object.defineProperty(exports, "binaryWriteOptions", ({ enumerable: true, get: function () { return binary_writer_1.binaryWriteOptions; } })); // Int64 and UInt64 implementations required for the binary format var pb_long_1 = __nccwpck_require__(61753); Object.defineProperty(exports, "PbLong", ({ enumerable: true, get: function () { return pb_long_1.PbLong; } })); Object.defineProperty(exports, "PbULong", ({ enumerable: true, get: function () { return pb_long_1.PbULong; } })); // JSON format contracts, options for reading and writing, for example var json_format_contract_1 = __nccwpck_require__(29367); Object.defineProperty(exports, "jsonReadOptions", ({ enumerable: true, get: function () { return json_format_contract_1.jsonReadOptions; } })); Object.defineProperty(exports, "jsonWriteOptions", ({ enumerable: true, get: function () { return json_format_contract_1.jsonWriteOptions; } })); Object.defineProperty(exports, "mergeJsonOptions", ({ enumerable: true, get: function () { return json_format_contract_1.mergeJsonOptions; } })); // Message type contract var message_type_contract_1 = __nccwpck_require__(43785); Object.defineProperty(exports, "MESSAGE_TYPE", ({ enumerable: true, get: function () { return message_type_contract_1.MESSAGE_TYPE; } })); // Message type implementation via reflection var message_type_1 = __nccwpck_require__(15106); Object.defineProperty(exports, "MessageType", ({ enumerable: true, get: function () { return message_type_1.MessageType; } })); // Reflection info, generated by the plugin, exposed to the user, used by reflection ops var reflection_info_1 = __nccwpck_require__(67910); Object.defineProperty(exports, "ScalarType", ({ enumerable: true, get: function () { return reflection_info_1.ScalarType; } })); Object.defineProperty(exports, "LongType", ({ enumerable: true, get: function () { return reflection_info_1.LongType; } })); Object.defineProperty(exports, "RepeatType", ({ enumerable: true, get: function () { return reflection_info_1.RepeatType; } })); Object.defineProperty(exports, "normalizeFieldInfo", ({ enumerable: true, get: function () { return reflection_info_1.normalizeFieldInfo; } })); Object.defineProperty(exports, "readFieldOptions", ({ enumerable: true, get: function () { return reflection_info_1.readFieldOptions; } })); Object.defineProperty(exports, "readFieldOption", ({ enumerable: true, get: function () { return reflection_info_1.readFieldOption; } })); Object.defineProperty(exports, "readMessageOption", ({ enumerable: true, get: function () { return reflection_info_1.readMessageOption; } })); // Message operations via reflection var reflection_type_check_1 = __nccwpck_require__(25167); Object.defineProperty(exports, "ReflectionTypeCheck", ({ enumerable: true, get: function () { return reflection_type_check_1.ReflectionTypeCheck; } })); var reflection_create_1 = __nccwpck_require__(53345); Object.defineProperty(exports, "reflectionCreate", ({ enumerable: true, get: function () { return reflection_create_1.reflectionCreate; } })); var reflection_scalar_default_1 = __nccwpck_require__(19526); Object.defineProperty(exports, "reflectionScalarDefault", ({ enumerable: true, get: function () { return reflection_scalar_default_1.reflectionScalarDefault; } })); var reflection_merge_partial_1 = __nccwpck_require__(98044); Object.defineProperty(exports, "reflectionMergePartial", ({ enumerable: true, get: function () { return reflection_merge_partial_1.reflectionMergePartial; } })); var reflection_equals_1 = __nccwpck_require__(4827); Object.defineProperty(exports, "reflectionEquals", ({ enumerable: true, get: function () { return reflection_equals_1.reflectionEquals; } })); var reflection_binary_reader_1 = __nccwpck_require__(89611); Object.defineProperty(exports, "ReflectionBinaryReader", ({ enumerable: true, get: function () { return reflection_binary_reader_1.ReflectionBinaryReader; } })); var reflection_binary_writer_1 = __nccwpck_require__(66907); Object.defineProperty(exports, "ReflectionBinaryWriter", ({ enumerable: true, get: function () { return reflection_binary_writer_1.ReflectionBinaryWriter; } })); var reflection_json_reader_1 = __nccwpck_require__(46790); Object.defineProperty(exports, "ReflectionJsonReader", ({ enumerable: true, get: function () { return reflection_json_reader_1.ReflectionJsonReader; } })); var reflection_json_writer_1 = __nccwpck_require__(11094); Object.defineProperty(exports, "ReflectionJsonWriter", ({ enumerable: true, get: function () { return reflection_json_writer_1.ReflectionJsonWriter; } })); var reflection_contains_message_type_1 = __nccwpck_require__(59946); Object.defineProperty(exports, "containsMessageType", ({ enumerable: true, get: function () { return reflection_contains_message_type_1.containsMessageType; } })); // Oneof helpers var oneof_1 = __nccwpck_require__(18063); Object.defineProperty(exports, "isOneofGroup", ({ enumerable: true, get: function () { return oneof_1.isOneofGroup; } })); Object.defineProperty(exports, "setOneofValue", ({ enumerable: true, get: function () { return oneof_1.setOneofValue; } })); Object.defineProperty(exports, "getOneofValue", ({ enumerable: true, get: function () { return oneof_1.getOneofValue; } })); Object.defineProperty(exports, "clearOneofValue", ({ enumerable: true, get: function () { return oneof_1.clearOneofValue; } })); Object.defineProperty(exports, "getSelectedOneofValue", ({ enumerable: true, get: function () { return oneof_1.getSelectedOneofValue; } })); // Enum object type guard and reflection util, may be interesting to the user. var enum_object_1 = __nccwpck_require__(70257); Object.defineProperty(exports, "listEnumValues", ({ enumerable: true, get: function () { return enum_object_1.listEnumValues; } })); Object.defineProperty(exports, "listEnumNames", ({ enumerable: true, get: function () { return enum_object_1.listEnumNames; } })); Object.defineProperty(exports, "listEnumNumbers", ({ enumerable: true, get: function () { return enum_object_1.listEnumNumbers; } })); Object.defineProperty(exports, "isEnumObject", ({ enumerable: true, get: function () { return enum_object_1.isEnumObject; } })); // lowerCamelCase() is exported for plugin, rpc-runtime and other rpc packages var lower_camel_case_1 = __nccwpck_require__(4073); Object.defineProperty(exports, "lowerCamelCase", ({ enumerable: true, get: function () { return lower_camel_case_1.lowerCamelCase; } })); // assertion functions are exported for plugin, may also be useful to user var assert_1 = __nccwpck_require__(8602); Object.defineProperty(exports, "assert", ({ enumerable: true, get: function () { return assert_1.assert; } })); Object.defineProperty(exports, "assertNever", ({ enumerable: true, get: function () { return assert_1.assertNever; } })); Object.defineProperty(exports, "assertInt32", ({ enumerable: true, get: function () { return assert_1.assertInt32; } })); Object.defineProperty(exports, "assertUInt32", ({ enumerable: true, get: function () { return assert_1.assertUInt32; } })); Object.defineProperty(exports, "assertFloat32", ({ enumerable: true, get: function () { return assert_1.assertFloat32; } })); /***/ }), /***/ 29367: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.mergeJsonOptions = exports.jsonWriteOptions = exports.jsonReadOptions = void 0; const defaultsWrite = { emitDefaultValues: false, enumAsInteger: false, useProtoFieldName: false, prettySpaces: 0, }, defaultsRead = { ignoreUnknownFields: false, }; /** * Make options for reading JSON data from partial options. */ function jsonReadOptions(options) { return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; } exports.jsonReadOptions = jsonReadOptions; /** * Make options for writing JSON data from partial options. */ function jsonWriteOptions(options) { return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; } exports.jsonWriteOptions = jsonWriteOptions; /** * Merges JSON write or read options. Later values override earlier values. Type registries are merged. */ function mergeJsonOptions(a, b) { var _a, _b; let c = Object.assign(Object.assign({}, a), b); c.typeRegistry = [...((_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : []), ...((_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : [])]; return c; } exports.mergeJsonOptions = mergeJsonOptions; /***/ }), /***/ 49999: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isJsonObject = exports.typeofJsonValue = void 0; /** * Get the type of a JSON value. * Distinguishes between array, null and object. */ function typeofJsonValue(value) { let t = typeof value; if (t == "object") { if (Array.isArray(value)) return "array"; if (value === null) return "null"; } return t; } exports.typeofJsonValue = typeofJsonValue; /** * Is this a JSON object (instead of an array or null)? */ function isJsonObject(value) { return value !== null && typeof value == "object" && !Array.isArray(value); } exports.isJsonObject = isJsonObject; /***/ }), /***/ 4073: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.lowerCamelCase = void 0; /** * Converts snake_case to lowerCamelCase. * * Should behave like protoc: * https://github.com/protocolbuffers/protobuf/blob/e8ae137c96444ea313485ed1118c5e43b2099cf1/src/google/protobuf/compiler/java/java_helpers.cc#L118 */ function lowerCamelCase(snakeCase) { let capNext = false; const sb = []; for (let i = 0; i < snakeCase.length; i++) { let next = snakeCase.charAt(i); if (next == '_') { capNext = true; } else if (/\d/.test(next)) { sb.push(next); capNext = true; } else if (capNext) { sb.push(next.toUpperCase()); capNext = false; } else if (i == 0) { sb.push(next.toLowerCase()); } else { sb.push(next); } } return sb.join(''); } exports.lowerCamelCase = lowerCamelCase; /***/ }), /***/ 43785: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MESSAGE_TYPE = void 0; /** * The symbol used as a key on message objects to store the message type. * * Note that this is an experimental feature - it is here to stay, but * implementation details may change without notice. */ exports.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); /***/ }), /***/ 15106: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MessageType = void 0; const message_type_contract_1 = __nccwpck_require__(43785); const reflection_info_1 = __nccwpck_require__(67910); const reflection_type_check_1 = __nccwpck_require__(25167); const reflection_json_reader_1 = __nccwpck_require__(46790); const reflection_json_writer_1 = __nccwpck_require__(11094); const reflection_binary_reader_1 = __nccwpck_require__(89611); const reflection_binary_writer_1 = __nccwpck_require__(66907); const reflection_create_1 = __nccwpck_require__(53345); const reflection_merge_partial_1 = __nccwpck_require__(98044); const json_typings_1 = __nccwpck_require__(49999); const json_format_contract_1 = __nccwpck_require__(29367); const reflection_equals_1 = __nccwpck_require__(4827); const binary_writer_1 = __nccwpck_require__(23957); const binary_reader_1 = __nccwpck_require__(92889); const baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})); /** * This standard message type provides reflection-based * operations to work with a message. */ class MessageType { constructor(name, fields, options) { this.defaultCheckDepth = 16; this.typeName = name; this.fields = fields.map(reflection_info_1.normalizeFieldInfo); this.options = options !== null && options !== void 0 ? options : {}; this.messagePrototype = Object.create(null, Object.assign(Object.assign({}, baseDescriptors), { [message_type_contract_1.MESSAGE_TYPE]: { value: this } })); this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this); this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this); this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this); this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this); this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this); } create(value) { let message = reflection_create_1.reflectionCreate(this); if (value !== undefined) { reflection_merge_partial_1.reflectionMergePartial(this, message, value); } return message; } /** * Clone the message. * * Unknown fields are discarded. */ clone(message) { let copy = this.create(); reflection_merge_partial_1.reflectionMergePartial(this, copy, message); return copy; } /** * Determines whether two message of the same type have the same field values. * Checks for deep equality, traversing repeated fields, oneof groups, maps * and messages recursively. * Will also return true if both messages are `undefined`. */ equals(a, b) { return reflection_equals_1.reflectionEquals(this, a, b); } /** * Is the given value assignable to our message type * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? */ is(arg, depth = this.defaultCheckDepth) { return this.refTypeCheck.is(arg, depth, false); } /** * Is the given value assignable to our message type, * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? */ isAssignable(arg, depth = this.defaultCheckDepth) { return this.refTypeCheck.is(arg, depth, true); } /** * Copy partial data into the target message. */ mergePartial(target, source) { reflection_merge_partial_1.reflectionMergePartial(this, target, source); } /** * Create a new message from binary format. */ fromBinary(data, options) { let opt = binary_reader_1.binaryReadOptions(options); return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt); } /** * Read a new message from a JSON value. */ fromJson(json, options) { return this.internalJsonRead(json, json_format_contract_1.jsonReadOptions(options)); } /** * Read a new message from a JSON string. * This is equivalent to `T.fromJson(JSON.parse(json))`. */ fromJsonString(json, options) { let value = JSON.parse(json); return this.fromJson(value, options); } /** * Write the message to canonical JSON value. */ toJson(message, options) { return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options)); } /** * Convert the message to canonical JSON string. * This is equivalent to `JSON.stringify(T.toJson(t))` */ toJsonString(message, options) { var _a; let value = this.toJson(message, options); return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0); } /** * Write the message to binary format. */ toBinary(message, options) { let opt = binary_writer_1.binaryWriteOptions(options); return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish(); } /** * This is an internal method. If you just want to read a message from * JSON, use `fromJson()` or `fromJsonString()`. * * Reads JSON value and merges the fields into the target * according to protobuf rules. If the target is omitted, * a new instance is created first. */ internalJsonRead(json, options, target) { if (json !== null && typeof json == "object" && !Array.isArray(json)) { let message = target !== null && target !== void 0 ? target : this.create(); this.refJsonReader.read(json, message, options); return message; } throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json)}.`); } /** * This is an internal method. If you just want to write a message * to JSON, use `toJson()` or `toJsonString(). * * Writes JSON value and returns it. */ internalJsonWrite(message, options) { return this.refJsonWriter.write(message, options); } /** * This is an internal method. If you just want to write a message * in binary format, use `toBinary()`. * * Serializes the message in binary format and appends it to the given * writer. Returns passed writer. */ internalBinaryWrite(message, writer, options) { this.refBinWriter.write(message, writer, options); return writer; } /** * This is an internal method. If you just want to read a message from * binary data, use `fromBinary()`. * * Reads data from binary format and merges the fields into * the target according to protobuf rules. If the target is * omitted, a new instance is created first. */ internalBinaryRead(reader, length, options, target) { let message = target !== null && target !== void 0 ? target : this.create(); this.refBinReader.read(reader, message, options, length); return message; } } exports.MessageType = MessageType; /***/ }), /***/ 18063: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getSelectedOneofValue = exports.clearOneofValue = exports.setUnknownOneofValue = exports.setOneofValue = exports.getOneofValue = exports.isOneofGroup = void 0; /** * Is the given value a valid oneof group? * * We represent protobuf `oneof` as algebraic data types (ADT) in generated * code. But when working with messages of unknown type, the ADT does not * help us. * * This type guard checks if the given object adheres to the ADT rules, which * are as follows: * * 1) Must be an object. * * 2) Must have a "oneofKind" discriminator property. * * 3) If "oneofKind" is `undefined`, no member field is selected. The object * must not have any other properties. * * 4) If "oneofKind" is a `string`, the member field with this name is * selected. * * 5) If a member field is selected, the object must have a second property * with this name. The property must not be `undefined`. * * 6) No extra properties are allowed. The object has either one property * (no selection) or two properties (selection). * */ function isOneofGroup(any) { if (typeof any != 'object' || any === null || !any.hasOwnProperty('oneofKind')) { return false; } switch (typeof any.oneofKind) { case "string": if (any[any.oneofKind] === undefined) return false; return Object.keys(any).length == 2; case "undefined": return Object.keys(any).length == 1; default: return false; } } exports.isOneofGroup = isOneofGroup; /** * Returns the value of the given field in a oneof group. */ function getOneofValue(oneof, kind) { return oneof[kind]; } exports.getOneofValue = getOneofValue; function setOneofValue(oneof, kind, value) { if (oneof.oneofKind !== undefined) { delete oneof[oneof.oneofKind]; } oneof.oneofKind = kind; if (value !== undefined) { oneof[kind] = value; } } exports.setOneofValue = setOneofValue; function setUnknownOneofValue(oneof, kind, value) { if (oneof.oneofKind !== undefined) { delete oneof[oneof.oneofKind]; } oneof.oneofKind = kind; if (value !== undefined && kind !== undefined) { oneof[kind] = value; } } exports.setUnknownOneofValue = setUnknownOneofValue; /** * Removes the selected field in a oneof group. * * Note that the recommended way to modify a oneof group is to set * a new object: * * ```ts * message.result = { oneofKind: undefined }; * ``` */ function clearOneofValue(oneof) { if (oneof.oneofKind !== undefined) { delete oneof[oneof.oneofKind]; } oneof.oneofKind = undefined; } exports.clearOneofValue = clearOneofValue; /** * Returns the selected value of the given oneof group. * * Not that the recommended way to access a oneof group is to check * the "oneofKind" property and let TypeScript narrow down the union * type for you: * * ```ts * if (message.result.oneofKind === "error") { * message.result.error; // string * } * ``` * * In the rare case you just need the value, and do not care about * which protobuf field is selected, you can use this function * for convenience. */ function getSelectedOneofValue(oneof) { if (oneof.oneofKind === undefined) { return undefined; } return oneof[oneof.oneofKind]; } exports.getSelectedOneofValue = getSelectedOneofValue; /***/ }), /***/ 61753: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PbLong = exports.PbULong = exports.detectBi = void 0; const goog_varint_1 = __nccwpck_require__(93223); let BI; function detectBi() { const dv = new DataView(new ArrayBuffer(8)); const ok = globalThis.BigInt !== undefined && typeof dv.getBigInt64 === "function" && typeof dv.getBigUint64 === "function" && typeof dv.setBigInt64 === "function" && typeof dv.setBigUint64 === "function"; BI = ok ? { MIN: BigInt("-9223372036854775808"), MAX: BigInt("9223372036854775807"), UMIN: BigInt("0"), UMAX: BigInt("18446744073709551615"), C: BigInt, V: dv, } : undefined; } exports.detectBi = detectBi; detectBi(); function assertBi(bi) { if (!bi) throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support"); } // used to validate from(string) input (when bigint is unavailable) const RE_DECIMAL_STR = /^-?[0-9]+$/; // constants for binary math const TWO_PWR_32_DBL = 0x100000000; const HALF_2_PWR_32 = 0x080000000; // base class for PbLong and PbULong provides shared code class SharedPbLong { /** * Create a new instance with the given bits. */ constructor(lo, hi) { this.lo = lo | 0; this.hi = hi | 0; } /** * Is this instance equal to 0? */ isZero() { return this.lo == 0 && this.hi == 0; } /** * Convert to a native number. */ toNumber() { let result = this.hi * TWO_PWR_32_DBL + (this.lo >>> 0); if (!Number.isSafeInteger(result)) throw new Error("cannot convert to safe number"); return result; } } /** * 64-bit unsigned integer as two 32-bit values. * Converts between `string`, `number` and `bigint` representations. */ class PbULong extends SharedPbLong { /** * Create instance from a `string`, `number` or `bigint`. */ static from(value) { if (BI) // noinspection FallThroughInSwitchStatementJS switch (typeof value) { case "string": if (value == "0") return this.ZERO; if (value == "") throw new Error('string is no integer'); value = BI.C(value); case "number": if (value === 0) return this.ZERO; value = BI.C(value); case "bigint": if (!value) return this.ZERO; if (value < BI.UMIN) throw new Error('signed value for ulong'); if (value > BI.UMAX) throw new Error('ulong too large'); BI.V.setBigUint64(0, value, true); return new PbULong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); } else switch (typeof value) { case "string": if (value == "0") return this.ZERO; value = value.trim(); if (!RE_DECIMAL_STR.test(value)) throw new Error('string is no integer'); let [minus, lo, hi] = goog_varint_1.int64fromString(value); if (minus) throw new Error('signed value for ulong'); return new PbULong(lo, hi); case "number": if (value == 0) return this.ZERO; if (!Number.isSafeInteger(value)) throw new Error('number is no integer'); if (value < 0) throw new Error('signed value for ulong'); return new PbULong(value, value / TWO_PWR_32_DBL); } throw new Error('unknown value ' + typeof value); } /** * Convert to decimal string. */ toString() { return BI ? this.toBigInt().toString() : goog_varint_1.int64toString(this.lo, this.hi); } /** * Convert to native bigint. */ toBigInt() { assertBi(BI); BI.V.setInt32(0, this.lo, true); BI.V.setInt32(4, this.hi, true); return BI.V.getBigUint64(0, true); } } exports.PbULong = PbULong; /** * ulong 0 singleton. */ PbULong.ZERO = new PbULong(0, 0); /** * 64-bit signed integer as two 32-bit values. * Converts between `string`, `number` and `bigint` representations. */ class PbLong extends SharedPbLong { /** * Create instance from a `string`, `number` or `bigint`. */ static from(value) { if (BI) // noinspection FallThroughInSwitchStatementJS switch (typeof value) { case "string": if (value == "0") return this.ZERO; if (value == "") throw new Error('string is no integer'); value = BI.C(value); case "number": if (value === 0) return this.ZERO; value = BI.C(value); case "bigint": if (!value) return this.ZERO; if (value < BI.MIN) throw new Error('signed long too small'); if (value > BI.MAX) throw new Error('signed long too large'); BI.V.setBigInt64(0, value, true); return new PbLong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); } else switch (typeof value) { case "string": if (value == "0") return this.ZERO; value = value.trim(); if (!RE_DECIMAL_STR.test(value)) throw new Error('string is no integer'); let [minus, lo, hi] = goog_varint_1.int64fromString(value); if (minus) { if (hi > HALF_2_PWR_32 || (hi == HALF_2_PWR_32 && lo != 0)) throw new Error('signed long too small'); } else if (hi >= HALF_2_PWR_32) throw new Error('signed long too large'); let pbl = new PbLong(lo, hi); return minus ? pbl.negate() : pbl; case "number": if (value == 0) return this.ZERO; if (!Number.isSafeInteger(value)) throw new Error('number is no integer'); return value > 0 ? new PbLong(value, value / TWO_PWR_32_DBL) : new PbLong(-value, -value / TWO_PWR_32_DBL).negate(); } throw new Error('unknown value ' + typeof value); } /** * Do we have a minus sign? */ isNegative() { return (this.hi & HALF_2_PWR_32) !== 0; } /** * Negate two's complement. * Invert all the bits and add one to the result. */ negate() { let hi = ~this.hi, lo = this.lo; if (lo) lo = ~lo + 1; else hi += 1; return new PbLong(lo, hi); } /** * Convert to decimal string. */ toString() { if (BI) return this.toBigInt().toString(); if (this.isNegative()) { let n = this.negate(); return '-' + goog_varint_1.int64toString(n.lo, n.hi); } return goog_varint_1.int64toString(this.lo, this.hi); } /** * Convert to native bigint. */ toBigInt() { assertBi(BI); BI.V.setInt32(0, this.lo, true); BI.V.setInt32(4, this.hi, true); return BI.V.getBigInt64(0, true); } } exports.PbLong = PbLong; /** * long 0 singleton. */ PbLong.ZERO = new PbLong(0, 0); /***/ }), /***/ 58950: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) 2016, Daniel Wirtz All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of its author, nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.utf8read = void 0; const fromCharCodes = (chunk) => String.fromCharCode.apply(String, chunk); /** * @deprecated This function will no longer be exported with the next major * release, since protobuf-ts has switch to TextDecoder API. If you need this * function, please migrate to @protobufjs/utf8. For context, see * https://github.com/timostamm/protobuf-ts/issues/184 * * Reads UTF8 bytes as a string. * * See [protobufjs / utf8](https://github.com/protobufjs/protobuf.js/blob/9893e35b854621cce64af4bf6be2cff4fb892796/lib/utf8/index.js#L40) * * Copyright (c) 2016, Daniel Wirtz */ function utf8read(bytes) { if (bytes.length < 1) return ""; let pos = 0, // position in bytes parts = [], chunk = [], i = 0, // char offset t; // temporary let len = bytes.length; while (pos < len) { t = bytes[pos++]; if (t < 128) chunk[i++] = t; else if (t > 191 && t < 224) chunk[i++] = (t & 31) << 6 | bytes[pos++] & 63; else if (t > 239 && t < 365) { t = ((t & 7) << 18 | (bytes[pos++] & 63) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63) - 0x10000; chunk[i++] = 0xD800 + (t >> 10); chunk[i++] = 0xDC00 + (t & 1023); } else chunk[i++] = (t & 15) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63; if (i > 8191) { parts.push(fromCharCodes(chunk)); i = 0; } } if (parts.length) { if (i) parts.push(fromCharCodes(chunk.slice(0, i))); return parts.join(""); } return fromCharCodes(chunk.slice(0, i)); } exports.utf8read = utf8read; /***/ }), /***/ 89611: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReflectionBinaryReader = void 0; const binary_format_contract_1 = __nccwpck_require__(54816); const reflection_info_1 = __nccwpck_require__(67910); const reflection_long_convert_1 = __nccwpck_require__(63402); const reflection_scalar_default_1 = __nccwpck_require__(19526); /** * Reads proto3 messages in binary format using reflection information. * * https://developers.google.com/protocol-buffers/docs/encoding */ class ReflectionBinaryReader { constructor(info) { this.info = info; } prepare() { var _a; if (!this.fieldNoToField) { const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; this.fieldNoToField = new Map(fieldsInput.map(field => [field.no, field])); } } /** * Reads a message from binary format into the target message. * * Repeated fields are appended. Map entries are added, overwriting * existing keys. * * If a message field is already present, it will be merged with the * new data. */ read(reader, message, options, length) { this.prepare(); const end = length === undefined ? reader.len : reader.pos + length; while (reader.pos < end) { // read the tag and find the field const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo); if (!field) { let u = options.readUnknownField; if (u == "throw") throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d); continue; } // target object for the field we are reading let target = message, repeated = field.repeat, localName = field.localName; // if field is member of oneof ADT, use ADT as target if (field.oneof) { target = target[field.oneof]; // if other oneof member selected, set new ADT if (target.oneofKind !== localName) target = message[field.oneof] = { oneofKind: localName }; } // we have handled oneof above, we just have read the value into `target[localName]` switch (field.kind) { case "scalar": case "enum": let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; let L = field.kind == "scalar" ? field.L : undefined; if (repeated) { let arr = target[localName]; // safe to assume presence of array, oneof cannot contain repeated values if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) { let e = reader.uint32() + reader.pos; while (reader.pos < e) arr.push(this.scalar(reader, T, L)); } else arr.push(this.scalar(reader, T, L)); } else target[localName] = this.scalar(reader, T, L); break; case "message": if (repeated) { let arr = target[localName]; // safe to assume presence of array, oneof cannot contain repeated values let msg = field.T().internalBinaryRead(reader, reader.uint32(), options); arr.push(msg); } else target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]); break; case "map": let [mapKey, mapVal] = this.mapEntry(field, reader, options); // safe to assume presence of map object, oneof cannot contain repeated values target[localName][mapKey] = mapVal; break; } } } /** * Read a map field, expecting key field = 1, value field = 2 */ mapEntry(field, reader, options) { let length = reader.uint32(); let end = reader.pos + length; let key = undefined; // javascript only allows number or string for object properties let val = undefined; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case 1: if (field.K == reflection_info_1.ScalarType.BOOL) key = reader.bool().toString(); else // long types are read as string, number types are okay as number key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING); break; case 2: switch (field.V.kind) { case "scalar": val = this.scalar(reader, field.V.T, field.V.L); break; case "enum": val = reader.int32(); break; case "message": val = field.V.T().internalBinaryRead(reader, reader.uint32(), options); break; } break; default: throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`); } } if (key === undefined) { let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K); key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw; } if (val === undefined) switch (field.V.kind) { case "scalar": val = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L); break; case "enum": val = 0; break; case "message": val = field.V.T().create(); break; } return [key, val]; } scalar(reader, type, longType) { switch (type) { case reflection_info_1.ScalarType.INT32: return reader.int32(); case reflection_info_1.ScalarType.STRING: return reader.string(); case reflection_info_1.ScalarType.BOOL: return reader.bool(); case reflection_info_1.ScalarType.DOUBLE: return reader.double(); case reflection_info_1.ScalarType.FLOAT: return reader.float(); case reflection_info_1.ScalarType.INT64: return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType); case reflection_info_1.ScalarType.UINT64: return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType); case reflection_info_1.ScalarType.FIXED64: return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType); case reflection_info_1.ScalarType.FIXED32: return reader.fixed32(); case reflection_info_1.ScalarType.BYTES: return reader.bytes(); case reflection_info_1.ScalarType.UINT32: return reader.uint32(); case reflection_info_1.ScalarType.SFIXED32: return reader.sfixed32(); case reflection_info_1.ScalarType.SFIXED64: return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType); case reflection_info_1.ScalarType.SINT32: return reader.sint32(); case reflection_info_1.ScalarType.SINT64: return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType); } } } exports.ReflectionBinaryReader = ReflectionBinaryReader; /***/ }), /***/ 66907: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReflectionBinaryWriter = void 0; const binary_format_contract_1 = __nccwpck_require__(54816); const reflection_info_1 = __nccwpck_require__(67910); const assert_1 = __nccwpck_require__(8602); const pb_long_1 = __nccwpck_require__(61753); /** * Writes proto3 messages in binary format using reflection information. * * https://developers.google.com/protocol-buffers/docs/encoding */ class ReflectionBinaryWriter { constructor(info) { this.info = info; } prepare() { if (!this.fields) { const fieldsInput = this.info.fields ? this.info.fields.concat() : []; this.fields = fieldsInput.sort((a, b) => a.no - b.no); } } /** * Writes the message to binary format. */ write(message, writer, options) { this.prepare(); for (const field of this.fields) { let value, // this will be our field value, whether it is member of a oneof or not emitDefault, // whether we emit the default value (only true for oneof members) repeated = field.repeat, localName = field.localName; // handle oneof ADT if (field.oneof) { const group = message[field.oneof]; if (group.oneofKind !== localName) continue; // if field is not selected, skip value = group[localName]; emitDefault = true; } else { value = message[localName]; emitDefault = false; } // we have handled oneof above. we just have to honor `emitDefault`. switch (field.kind) { case "scalar": case "enum": let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; if (repeated) { assert_1.assert(Array.isArray(value)); if (repeated == reflection_info_1.RepeatType.PACKED) this.packed(writer, T, field.no, value); else for (const item of value) this.scalar(writer, T, field.no, item, true); } else if (value === undefined) assert_1.assert(field.opt); else this.scalar(writer, T, field.no, value, emitDefault || field.opt); break; case "message": if (repeated) { assert_1.assert(Array.isArray(value)); for (const item of value) this.message(writer, options, field.T(), field.no, item); } else { this.message(writer, options, field.T(), field.no, value); } break; case "map": assert_1.assert(typeof value == 'object' && value !== null); for (const [key, val] of Object.entries(value)) this.mapEntry(writer, options, field, key, val); break; } } let u = options.writeUnknownFields; if (u !== false) (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer); } mapEntry(writer, options, field, key, value) { writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited); writer.fork(); // javascript only allows number or string for object properties // we convert from our representation to the protobuf type let keyValue = key; switch (field.K) { case reflection_info_1.ScalarType.INT32: case reflection_info_1.ScalarType.FIXED32: case reflection_info_1.ScalarType.UINT32: case reflection_info_1.ScalarType.SFIXED32: case reflection_info_1.ScalarType.SINT32: keyValue = Number.parseInt(key); break; case reflection_info_1.ScalarType.BOOL: assert_1.assert(key == 'true' || key == 'false'); keyValue = key == 'true'; break; } // write key, expecting key field number = 1 this.scalar(writer, field.K, 1, keyValue, true); // write value, expecting value field number = 2 switch (field.V.kind) { case 'scalar': this.scalar(writer, field.V.T, 2, value, true); break; case 'enum': this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true); break; case 'message': this.message(writer, options, field.V.T(), 2, value); break; } writer.join(); } message(writer, options, handler, fieldNo, value) { if (value === undefined) return; handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options); writer.join(); } /** * Write a single scalar value. */ scalar(writer, type, fieldNo, value, emitDefault) { let [wireType, method, isDefault] = this.scalarInfo(type, value); if (!isDefault || emitDefault) { writer.tag(fieldNo, wireType); writer[method](value); } } /** * Write an array of scalar values in packed format. */ packed(writer, type, fieldNo, value) { if (!value.length) return; assert_1.assert(type !== reflection_info_1.ScalarType.BYTES && type !== reflection_info_1.ScalarType.STRING); // write tag writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited); // begin length-delimited writer.fork(); // write values without tags let [, method,] = this.scalarInfo(type); for (let i = 0; i < value.length; i++) writer[method](value[i]); // end length delimited writer.join(); } /** * Get information for writing a scalar value. * * Returns tuple: * [0]: appropriate WireType * [1]: name of the appropriate method of IBinaryWriter * [2]: whether the given value is a default value * * If argument `value` is omitted, [2] is always false. */ scalarInfo(type, value) { let t = binary_format_contract_1.WireType.Varint; let m; let i = value === undefined; let d = value === 0; switch (type) { case reflection_info_1.ScalarType.INT32: m = "int32"; break; case reflection_info_1.ScalarType.STRING: d = i || !value.length; t = binary_format_contract_1.WireType.LengthDelimited; m = "string"; break; case reflection_info_1.ScalarType.BOOL: d = value === false; m = "bool"; break; case reflection_info_1.ScalarType.UINT32: m = "uint32"; break; case reflection_info_1.ScalarType.DOUBLE: t = binary_format_contract_1.WireType.Bit64; m = "double"; break; case reflection_info_1.ScalarType.FLOAT: t = binary_format_contract_1.WireType.Bit32; m = "float"; break; case reflection_info_1.ScalarType.INT64: d = i || pb_long_1.PbLong.from(value).isZero(); m = "int64"; break; case reflection_info_1.ScalarType.UINT64: d = i || pb_long_1.PbULong.from(value).isZero(); m = "uint64"; break; case reflection_info_1.ScalarType.FIXED64: d = i || pb_long_1.PbULong.from(value).isZero(); t = binary_format_contract_1.WireType.Bit64; m = "fixed64"; break; case reflection_info_1.ScalarType.BYTES: d = i || !value.byteLength; t = binary_format_contract_1.WireType.LengthDelimited; m = "bytes"; break; case reflection_info_1.ScalarType.FIXED32: t = binary_format_contract_1.WireType.Bit32; m = "fixed32"; break; case reflection_info_1.ScalarType.SFIXED32: t = binary_format_contract_1.WireType.Bit32; m = "sfixed32"; break; case reflection_info_1.ScalarType.SFIXED64: d = i || pb_long_1.PbLong.from(value).isZero(); t = binary_format_contract_1.WireType.Bit64; m = "sfixed64"; break; case reflection_info_1.ScalarType.SINT32: m = "sint32"; break; case reflection_info_1.ScalarType.SINT64: d = i || pb_long_1.PbLong.from(value).isZero(); m = "sint64"; break; } return [t, m, i || d]; } } exports.ReflectionBinaryWriter = ReflectionBinaryWriter; /***/ }), /***/ 59946: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.containsMessageType = void 0; const message_type_contract_1 = __nccwpck_require__(43785); /** * Check if the provided object is a proto message. * * Note that this is an experimental feature - it is here to stay, but * implementation details may change without notice. */ function containsMessageType(msg) { return msg[message_type_contract_1.MESSAGE_TYPE] != null; } exports.containsMessageType = containsMessageType; /***/ }), /***/ 53345: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.reflectionCreate = void 0; const reflection_scalar_default_1 = __nccwpck_require__(19526); const message_type_contract_1 = __nccwpck_require__(43785); /** * Creates an instance of the generic message, using the field * information. */ function reflectionCreate(type) { /** * This ternary can be removed in the next major version. * The `Object.create()` code path utilizes a new `messagePrototype` * property on the `IMessageType` which has this same `MESSAGE_TYPE` * non-enumerable property on it. Doing it this way means that we only * pay the cost of `Object.defineProperty()` once per `IMessageType` * class of once per "instance". The falsy code path is only provided * for backwards compatibility in cases where the runtime library is * updated without also updating the generated code. */ const msg = type.messagePrototype ? Object.create(type.messagePrototype) : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type }); for (let field of type.fields) { let name = field.localName; if (field.opt) continue; if (field.oneof) msg[field.oneof] = { oneofKind: undefined }; else if (field.repeat) msg[name] = []; else switch (field.kind) { case "scalar": msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L); break; case "enum": // we require 0 to be default value for all enums msg[name] = 0; break; case "map": msg[name] = {}; break; } } return msg; } exports.reflectionCreate = reflectionCreate; /***/ }), /***/ 4827: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.reflectionEquals = void 0; const reflection_info_1 = __nccwpck_require__(67910); /** * Determines whether two message of the same type have the same field values. * Checks for deep equality, traversing repeated fields, oneof groups, maps * and messages recursively. * Will also return true if both messages are `undefined`. */ function reflectionEquals(info, a, b) { if (a === b) return true; if (!a || !b) return false; for (let field of info.fields) { let localName = field.localName; let val_a = field.oneof ? a[field.oneof][localName] : a[localName]; let val_b = field.oneof ? b[field.oneof][localName] : b[localName]; switch (field.kind) { case "enum": case "scalar": let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; if (!(field.repeat ? repeatedPrimitiveEq(t, val_a, val_b) : primitiveEq(t, val_a, val_b))) return false; break; case "map": if (!(field.V.kind == "message" ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b)))) return false; break; case "message": let T = field.T(); if (!(field.repeat ? repeatedMsgEq(T, val_a, val_b) : T.equals(val_a, val_b))) return false; break; } } return true; } exports.reflectionEquals = reflectionEquals; const objectValues = Object.values; function primitiveEq(type, a, b) { if (a === b) return true; if (type !== reflection_info_1.ScalarType.BYTES) return false; let ba = a; let bb = b; if (ba.length !== bb.length) return false; for (let i = 0; i < ba.length; i++) if (ba[i] != bb[i]) return false; return true; } function repeatedPrimitiveEq(type, a, b) { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) if (!primitiveEq(type, a[i], b[i])) return false; return true; } function repeatedMsgEq(type, a, b) { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) if (!type.equals(a[i], b[i])) return false; return true; } /***/ }), /***/ 67910: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readMessageOption = exports.readFieldOption = exports.readFieldOptions = exports.normalizeFieldInfo = exports.RepeatType = exports.LongType = exports.ScalarType = void 0; const lower_camel_case_1 = __nccwpck_require__(4073); /** * Scalar value types. This is a subset of field types declared by protobuf * enum google.protobuf.FieldDescriptorProto.Type The types GROUP and MESSAGE * are omitted, but the numerical values are identical. */ var ScalarType; (function (ScalarType) { // 0 is reserved for errors. // Order is weird for historical reasons. ScalarType[ScalarType["DOUBLE"] = 1] = "DOUBLE"; ScalarType[ScalarType["FLOAT"] = 2] = "FLOAT"; // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if // negative values are likely. ScalarType[ScalarType["INT64"] = 3] = "INT64"; ScalarType[ScalarType["UINT64"] = 4] = "UINT64"; // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if // negative values are likely. ScalarType[ScalarType["INT32"] = 5] = "INT32"; ScalarType[ScalarType["FIXED64"] = 6] = "FIXED64"; ScalarType[ScalarType["FIXED32"] = 7] = "FIXED32"; ScalarType[ScalarType["BOOL"] = 8] = "BOOL"; ScalarType[ScalarType["STRING"] = 9] = "STRING"; // Tag-delimited aggregate. // Group type is deprecated and not supported in proto3. However, Proto3 // implementations should still be able to parse the group wire format and // treat group fields as unknown fields. // TYPE_GROUP = 10, // TYPE_MESSAGE = 11, // Length-delimited aggregate. // New in version 2. ScalarType[ScalarType["BYTES"] = 12] = "BYTES"; ScalarType[ScalarType["UINT32"] = 13] = "UINT32"; // TYPE_ENUM = 14, ScalarType[ScalarType["SFIXED32"] = 15] = "SFIXED32"; ScalarType[ScalarType["SFIXED64"] = 16] = "SFIXED64"; ScalarType[ScalarType["SINT32"] = 17] = "SINT32"; ScalarType[ScalarType["SINT64"] = 18] = "SINT64"; })(ScalarType = exports.ScalarType || (exports.ScalarType = {})); /** * JavaScript representation of 64 bit integral types. Equivalent to the * field option "jstype". * * By default, protobuf-ts represents 64 bit types as `bigint`. * * You can change the default behaviour by enabling the plugin parameter * `long_type_string`, which will represent 64 bit types as `string`. * * Alternatively, you can change the behaviour for individual fields * with the field option "jstype": * * ```protobuf * uint64 my_field = 1 [jstype = JS_STRING]; * uint64 other_field = 2 [jstype = JS_NUMBER]; * ``` */ var LongType; (function (LongType) { /** * Use JavaScript `bigint`. * * Field option `[jstype = JS_NORMAL]`. */ LongType[LongType["BIGINT"] = 0] = "BIGINT"; /** * Use JavaScript `string`. * * Field option `[jstype = JS_STRING]`. */ LongType[LongType["STRING"] = 1] = "STRING"; /** * Use JavaScript `number`. * * Large values will loose precision. * * Field option `[jstype = JS_NUMBER]`. */ LongType[LongType["NUMBER"] = 2] = "NUMBER"; })(LongType = exports.LongType || (exports.LongType = {})); /** * Protobuf 2.1.0 introduced packed repeated fields. * Setting the field option `[packed = true]` enables packing. * * In proto3, all repeated fields are packed by default. * Setting the field option `[packed = false]` disables packing. * * Packed repeated fields are encoded with a single tag, * then a length-delimiter, then the element values. * * Unpacked repeated fields are encoded with a tag and * value for each element. * * `bytes` and `string` cannot be packed. */ var RepeatType; (function (RepeatType) { /** * The field is not repeated. */ RepeatType[RepeatType["NO"] = 0] = "NO"; /** * The field is repeated and should be packed. * Invalid for `bytes` and `string`, they cannot be packed. */ RepeatType[RepeatType["PACKED"] = 1] = "PACKED"; /** * The field is repeated but should not be packed. * The only valid repeat type for repeated `bytes` and `string`. */ RepeatType[RepeatType["UNPACKED"] = 2] = "UNPACKED"; })(RepeatType = exports.RepeatType || (exports.RepeatType = {})); /** * Turns PartialFieldInfo into FieldInfo. */ function normalizeFieldInfo(field) { var _a, _b, _c, _d; field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name); field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : (field.repeat ? false : field.oneof ? false : field.kind == "message"); return field; } exports.normalizeFieldInfo = normalizeFieldInfo; /** * Read custom field options from a generated message type. * * @deprecated use readFieldOption() */ function readFieldOptions(messageType, fieldName, extensionName, extensionType) { var _a; const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : undefined; } exports.readFieldOptions = readFieldOptions; function readFieldOption(messageType, fieldName, extensionName, extensionType) { var _a; const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; if (!options) { return undefined; } const optionVal = options[extensionName]; if (optionVal === undefined) { return optionVal; } return extensionType ? extensionType.fromJson(optionVal) : optionVal; } exports.readFieldOption = readFieldOption; function readMessageOption(messageType, extensionName, extensionType) { const options = messageType.options; const optionVal = options[extensionName]; if (optionVal === undefined) { return optionVal; } return extensionType ? extensionType.fromJson(optionVal) : optionVal; } exports.readMessageOption = readMessageOption; /***/ }), /***/ 46790: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReflectionJsonReader = void 0; const json_typings_1 = __nccwpck_require__(49999); const base64_1 = __nccwpck_require__(26335); const reflection_info_1 = __nccwpck_require__(67910); const pb_long_1 = __nccwpck_require__(61753); const assert_1 = __nccwpck_require__(8602); const reflection_long_convert_1 = __nccwpck_require__(63402); /** * Reads proto3 messages in canonical JSON format using reflection information. * * https://developers.google.com/protocol-buffers/docs/proto3#json */ class ReflectionJsonReader { constructor(info) { this.info = info; } prepare() { var _a; if (this.fMap === undefined) { this.fMap = {}; const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; for (const field of fieldsInput) { this.fMap[field.name] = field; this.fMap[field.jsonName] = field; this.fMap[field.localName] = field; } } } // Cannot parse JSON for #. assert(condition, fieldName, jsonValue) { if (!condition) { let what = json_typings_1.typeofJsonValue(jsonValue); if (what == "number" || what == "boolean") what = jsonValue.toString(); throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`); } } /** * Reads a message from canonical JSON format into the target message. * * Repeated fields are appended. Map entries are added, overwriting * existing keys. * * If a message field is already present, it will be merged with the * new data. */ read(input, message, options) { this.prepare(); const oneofsHandled = []; for (const [jsonKey, jsonValue] of Object.entries(input)) { const field = this.fMap[jsonKey]; if (!field) { if (!options.ignoreUnknownFields) throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`); continue; } const localName = field.localName; // handle oneof ADT let target; // this will be the target for the field value, whether it is member of a oneof or not if (field.oneof) { if (jsonValue === null && (field.kind !== 'enum' || field.T()[0] !== 'google.protobuf.NullValue')) { continue; } // since json objects are unordered by specification, it is not possible to take the last of multiple oneofs if (oneofsHandled.includes(field.oneof)) throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`); oneofsHandled.push(field.oneof); target = message[field.oneof] = { oneofKind: localName }; } else { target = message; } // we have handled oneof above. we just have read the value into `target`. if (field.kind == 'map') { if (jsonValue === null) { continue; } // check input this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue); // our target to put map entries into const fieldObj = target[localName]; // read entries for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) { this.assert(jsonObjValue !== null, field.name + " map value", null); // read value let val; switch (field.V.kind) { case "message": val = field.V.T().internalJsonRead(jsonObjValue, options); break; case "enum": val = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields); if (val === false) continue; break; case "scalar": val = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name); break; } this.assert(val !== undefined, field.name + " map value", jsonObjValue); // read key let key = jsonObjKey; if (field.K == reflection_info_1.ScalarType.BOOL) key = key == "true" ? true : key == "false" ? false : key; key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString(); fieldObj[key] = val; } } else if (field.repeat) { if (jsonValue === null) continue; // check input this.assert(Array.isArray(jsonValue), field.name, jsonValue); // our target to put array entries into const fieldArr = target[localName]; // read array entries for (const jsonItem of jsonValue) { this.assert(jsonItem !== null, field.name, null); let val; switch (field.kind) { case "message": val = field.T().internalJsonRead(jsonItem, options); break; case "enum": val = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields); if (val === false) continue; break; case "scalar": val = this.scalar(jsonItem, field.T, field.L, field.name); break; } this.assert(val !== undefined, field.name, jsonValue); fieldArr.push(val); } } else { switch (field.kind) { case "message": if (jsonValue === null && field.T().typeName != 'google.protobuf.Value') { this.assert(field.oneof === undefined, field.name + " (oneof member)", null); continue; } target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]); break; case "enum": if (jsonValue === null) continue; let val = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields); if (val === false) continue; target[localName] = val; break; case "scalar": if (jsonValue === null) continue; target[localName] = this.scalar(jsonValue, field.T, field.L, field.name); break; } } } } /** * Returns `false` for unrecognized string representations. * * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). */ enum(type, json, fieldName, ignoreUnknownFields) { if (type[0] == 'google.protobuf.NullValue') assert_1.assert(json === null || json === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type[0]} only accepts null.`); if (json === null) // we require 0 to be default value for all enums return 0; switch (typeof json) { case "number": assert_1.assert(Number.isInteger(json), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json}.`); return json; case "string": let localEnumName = json; if (type[2] && json.substring(0, type[2].length) === type[2]) // lookup without the shared prefix localEnumName = json.substring(type[2].length); let enumNumber = type[1][localEnumName]; if (typeof enumNumber === 'undefined' && ignoreUnknownFields) { return false; } assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type[0]} has no value for "${json}".`); return enumNumber; } assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json}".`); } scalar(json, type, longType, fieldName) { let e; try { switch (type) { // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". // Either numbers or strings are accepted. Exponent notation is also accepted. case reflection_info_1.ScalarType.DOUBLE: case reflection_info_1.ScalarType.FLOAT: if (json === null) return .0; if (json === "NaN") return Number.NaN; if (json === "Infinity") return Number.POSITIVE_INFINITY; if (json === "-Infinity") return Number.NEGATIVE_INFINITY; if (json === "") { e = "empty string"; break; } if (typeof json == "string" && json.trim().length !== json.length) { e = "extra whitespace"; break; } if (typeof json != "string" && typeof json != "number") { break; } let float = Number(json); if (Number.isNaN(float)) { e = "not a number"; break; } if (!Number.isFinite(float)) { // infinity and -infinity are handled by string representation above, so this is an error e = "too large or small"; break; } if (type == reflection_info_1.ScalarType.FLOAT) assert_1.assertFloat32(float); return float; // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. case reflection_info_1.ScalarType.INT32: case reflection_info_1.ScalarType.FIXED32: case reflection_info_1.ScalarType.SFIXED32: case reflection_info_1.ScalarType.SINT32: case reflection_info_1.ScalarType.UINT32: if (json === null) return 0; let int32; if (typeof json == "number") int32 = json; else if (json === "") e = "empty string"; else if (typeof json == "string") { if (json.trim().length !== json.length) e = "extra whitespace"; else int32 = Number(json); } if (int32 === undefined) break; if (type == reflection_info_1.ScalarType.UINT32) assert_1.assertUInt32(int32); else assert_1.assertInt32(int32); return int32; // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted. case reflection_info_1.ScalarType.INT64: case reflection_info_1.ScalarType.SFIXED64: case reflection_info_1.ScalarType.SINT64: if (json === null) return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); if (typeof json != "number" && typeof json != "string") break; return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json), longType); case reflection_info_1.ScalarType.FIXED64: case reflection_info_1.ScalarType.UINT64: if (json === null) return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); if (typeof json != "number" && typeof json != "string") break; return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json), longType); // bool: case reflection_info_1.ScalarType.BOOL: if (json === null) return false; if (typeof json !== "boolean") break; return json; // string: case reflection_info_1.ScalarType.STRING: if (json === null) return ""; if (typeof json !== "string") { e = "extra whitespace"; break; } try { encodeURIComponent(json); } catch (e) { e = "invalid UTF8"; break; } return json; // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. // Either standard or URL-safe base64 encoding with/without paddings are accepted. case reflection_info_1.ScalarType.BYTES: if (json === null || json === "") return new Uint8Array(0); if (typeof json !== 'string') break; return base64_1.base64decode(json); } } catch (error) { e = error.message; } this.assert(false, fieldName + (e ? " - " + e : ""), json); } } exports.ReflectionJsonReader = ReflectionJsonReader; /***/ }), /***/ 11094: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReflectionJsonWriter = void 0; const base64_1 = __nccwpck_require__(26335); const pb_long_1 = __nccwpck_require__(61753); const reflection_info_1 = __nccwpck_require__(67910); const assert_1 = __nccwpck_require__(8602); /** * Writes proto3 messages in canonical JSON format using reflection * information. * * https://developers.google.com/protocol-buffers/docs/proto3#json */ class ReflectionJsonWriter { constructor(info) { var _a; this.fields = (_a = info.fields) !== null && _a !== void 0 ? _a : []; } /** * Converts the message to a JSON object, based on the field descriptors. */ write(message, options) { const json = {}, source = message; for (const field of this.fields) { // field is not part of a oneof, simply write as is if (!field.oneof) { let jsonValue = this.field(field, source[field.localName], options); if (jsonValue !== undefined) json[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; continue; } // field is part of a oneof const group = source[field.oneof]; if (group.oneofKind !== field.localName) continue; // not selected, skip const opt = field.kind == 'scalar' || field.kind == 'enum' ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options; let jsonValue = this.field(field, group[field.localName], opt); assert_1.assert(jsonValue !== undefined); json[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; } return json; } field(field, value, options) { let jsonValue = undefined; if (field.kind == 'map') { assert_1.assert(typeof value == "object" && value !== null); const jsonObj = {}; switch (field.V.kind) { case "scalar": for (const [entryKey, entryValue] of Object.entries(value)) { const val = this.scalar(field.V.T, entryValue, field.name, false, true); assert_1.assert(val !== undefined); jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key } break; case "message": const messageType = field.V.T(); for (const [entryKey, entryValue] of Object.entries(value)) { const val = this.message(messageType, entryValue, field.name, options); assert_1.assert(val !== undefined); jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key } break; case "enum": const enumInfo = field.V.T(); for (const [entryKey, entryValue] of Object.entries(value)) { assert_1.assert(entryValue === undefined || typeof entryValue == 'number'); const val = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger); assert_1.assert(val !== undefined); jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key } break; } if (options.emitDefaultValues || Object.keys(jsonObj).length > 0) jsonValue = jsonObj; } else if (field.repeat) { assert_1.assert(Array.isArray(value)); const jsonArr = []; switch (field.kind) { case "scalar": for (let i = 0; i < value.length; i++) { const val = this.scalar(field.T, value[i], field.name, field.opt, true); assert_1.assert(val !== undefined); jsonArr.push(val); } break; case "enum": const enumInfo = field.T(); for (let i = 0; i < value.length; i++) { assert_1.assert(value[i] === undefined || typeof value[i] == 'number'); const val = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger); assert_1.assert(val !== undefined); jsonArr.push(val); } break; case "message": const messageType = field.T(); for (let i = 0; i < value.length; i++) { const val = this.message(messageType, value[i], field.name, options); assert_1.assert(val !== undefined); jsonArr.push(val); } break; } // add converted array to json output if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues) jsonValue = jsonArr; } else { switch (field.kind) { case "scalar": jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues); break; case "enum": jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger); break; case "message": jsonValue = this.message(field.T(), value, field.name, options); break; } } return jsonValue; } /** * Returns `null` as the default for google.protobuf.NullValue. */ enum(type, value, fieldName, optional, emitDefaultValues, enumAsInteger) { if (type[0] == 'google.protobuf.NullValue') return !emitDefaultValues && !optional ? undefined : null; if (value === undefined) { assert_1.assert(optional); return undefined; } if (value === 0 && !emitDefaultValues && !optional) // we require 0 to be default value for all enums return undefined; assert_1.assert(typeof value == 'number'); assert_1.assert(Number.isInteger(value)); if (enumAsInteger || !type[1].hasOwnProperty(value)) // if we don't now the enum value, just return the number return value; if (type[2]) // restore the dropped prefix return type[2] + type[1][value]; return type[1][value]; } message(type, value, fieldName, options) { if (value === undefined) return options.emitDefaultValues ? null : undefined; return type.internalJsonWrite(value, options); } scalar(type, value, fieldName, optional, emitDefaultValues) { if (value === undefined) { assert_1.assert(optional); return undefined; } const ed = emitDefaultValues || optional; // noinspection FallThroughInSwitchStatementJS switch (type) { // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. case reflection_info_1.ScalarType.INT32: case reflection_info_1.ScalarType.SFIXED32: case reflection_info_1.ScalarType.SINT32: if (value === 0) return ed ? 0 : undefined; assert_1.assertInt32(value); return value; case reflection_info_1.ScalarType.FIXED32: case reflection_info_1.ScalarType.UINT32: if (value === 0) return ed ? 0 : undefined; assert_1.assertUInt32(value); return value; // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". // Either numbers or strings are accepted. Exponent notation is also accepted. case reflection_info_1.ScalarType.FLOAT: assert_1.assertFloat32(value); case reflection_info_1.ScalarType.DOUBLE: if (value === 0) return ed ? 0 : undefined; assert_1.assert(typeof value == 'number'); if (Number.isNaN(value)) return 'NaN'; if (value === Number.POSITIVE_INFINITY) return 'Infinity'; if (value === Number.NEGATIVE_INFINITY) return '-Infinity'; return value; // string: case reflection_info_1.ScalarType.STRING: if (value === "") return ed ? '' : undefined; assert_1.assert(typeof value == 'string'); return value; // bool: case reflection_info_1.ScalarType.BOOL: if (value === false) return ed ? false : undefined; assert_1.assert(typeof value == 'boolean'); return value; // JSON value will be a decimal string. Either numbers or strings are accepted. case reflection_info_1.ScalarType.UINT64: case reflection_info_1.ScalarType.FIXED64: assert_1.assert(typeof value == 'number' || typeof value == 'string' || typeof value == 'bigint'); let ulong = pb_long_1.PbULong.from(value); if (ulong.isZero() && !ed) return undefined; return ulong.toString(); // JSON value will be a decimal string. Either numbers or strings are accepted. case reflection_info_1.ScalarType.INT64: case reflection_info_1.ScalarType.SFIXED64: case reflection_info_1.ScalarType.SINT64: assert_1.assert(typeof value == 'number' || typeof value == 'string' || typeof value == 'bigint'); let long = pb_long_1.PbLong.from(value); if (long.isZero() && !ed) return undefined; return long.toString(); // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. // Either standard or URL-safe base64 encoding with/without paddings are accepted. case reflection_info_1.ScalarType.BYTES: assert_1.assert(value instanceof Uint8Array); if (!value.byteLength) return ed ? "" : undefined; return base64_1.base64encode(value); } } } exports.ReflectionJsonWriter = ReflectionJsonWriter; /***/ }), /***/ 63402: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.reflectionLongConvert = void 0; const reflection_info_1 = __nccwpck_require__(67910); /** * Utility method to convert a PbLong or PbUlong to a JavaScript * representation during runtime. * * Works with generated field information, `undefined` is equivalent * to `STRING`. */ function reflectionLongConvert(long, type) { switch (type) { case reflection_info_1.LongType.BIGINT: return long.toBigInt(); case reflection_info_1.LongType.NUMBER: return long.toNumber(); default: // case undefined: // case LongType.STRING: return long.toString(); } } exports.reflectionLongConvert = reflectionLongConvert; /***/ }), /***/ 98044: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.reflectionMergePartial = void 0; /** * Copy partial data into the target message. * * If a singular scalar or enum field is present in the source, it * replaces the field in the target. * * If a singular message field is present in the source, it is merged * with the target field by calling mergePartial() of the responsible * message type. * * If a repeated field is present in the source, its values replace * all values in the target array, removing extraneous values. * Repeated message fields are copied, not merged. * * If a map field is present in the source, entries are added to the * target map, replacing entries with the same key. Entries that only * exist in the target remain. Entries with message values are copied, * not merged. * * Note that this function differs from protobuf merge semantics, * which appends repeated fields. */ function reflectionMergePartial(info, target, source) { let fieldValue, // the field value we are working with input = source, output; // where we want our field value to go for (let field of info.fields) { let name = field.localName; if (field.oneof) { const group = input[field.oneof]; // this is the oneof`s group in the source if ((group === null || group === void 0 ? void 0 : group.oneofKind) == undefined) { // the user is free to omit continue; // we skip this field, and all other members too } fieldValue = group[name]; // our value comes from the the oneof group of the source output = target[field.oneof]; // and our output is the oneof group of the target output.oneofKind = group.oneofKind; // always update discriminator if (fieldValue == undefined) { delete output[name]; // remove any existing value continue; // skip further work on field } } else { fieldValue = input[name]; // we are using the source directly output = target; // we want our field value to go directly into the target if (fieldValue == undefined) { continue; // skip further work on field, existing value is used as is } } if (field.repeat) output[name].length = fieldValue.length; // resize target array to match source array // now we just work with `fieldValue` and `output` to merge the value switch (field.kind) { case "scalar": case "enum": if (field.repeat) for (let i = 0; i < fieldValue.length; i++) output[name][i] = fieldValue[i]; // not a reference type else output[name] = fieldValue; // not a reference type break; case "message": let T = field.T(); if (field.repeat) for (let i = 0; i < fieldValue.length; i++) output[name][i] = T.create(fieldValue[i]); else if (output[name] === undefined) output[name] = T.create(fieldValue); // nothing to merge with else T.mergePartial(output[name], fieldValue); break; case "map": // Map and repeated fields are simply overwritten, not appended or merged switch (field.V.kind) { case "scalar": case "enum": Object.assign(output[name], fieldValue); // elements are not reference types break; case "message": let T = field.V.T(); for (let k of Object.keys(fieldValue)) output[name][k] = T.create(fieldValue[k]); break; } break; } } } exports.reflectionMergePartial = reflectionMergePartial; /***/ }), /***/ 19526: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.reflectionScalarDefault = void 0; const reflection_info_1 = __nccwpck_require__(67910); const reflection_long_convert_1 = __nccwpck_require__(63402); const pb_long_1 = __nccwpck_require__(61753); /** * Creates the default value for a scalar type. */ function reflectionScalarDefault(type, longType = reflection_info_1.LongType.STRING) { switch (type) { case reflection_info_1.ScalarType.BOOL: return false; case reflection_info_1.ScalarType.UINT64: case reflection_info_1.ScalarType.FIXED64: return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); case reflection_info_1.ScalarType.INT64: case reflection_info_1.ScalarType.SFIXED64: case reflection_info_1.ScalarType.SINT64: return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); case reflection_info_1.ScalarType.DOUBLE: case reflection_info_1.ScalarType.FLOAT: return 0.0; case reflection_info_1.ScalarType.BYTES: return new Uint8Array(0); case reflection_info_1.ScalarType.STRING: return ""; default: // case ScalarType.INT32: // case ScalarType.UINT32: // case ScalarType.SINT32: // case ScalarType.FIXED32: // case ScalarType.SFIXED32: return 0; } } exports.reflectionScalarDefault = reflectionScalarDefault; /***/ }), /***/ 25167: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReflectionTypeCheck = void 0; const reflection_info_1 = __nccwpck_require__(67910); const oneof_1 = __nccwpck_require__(18063); // noinspection JSMethodCanBeStatic class ReflectionTypeCheck { constructor(info) { var _a; this.fields = (_a = info.fields) !== null && _a !== void 0 ? _a : []; } prepare() { if (this.data) return; const req = [], known = [], oneofs = []; for (let field of this.fields) { if (field.oneof) { if (!oneofs.includes(field.oneof)) { oneofs.push(field.oneof); req.push(field.oneof); known.push(field.oneof); } } else { known.push(field.localName); switch (field.kind) { case "scalar": case "enum": if (!field.opt || field.repeat) req.push(field.localName); break; case "message": if (field.repeat) req.push(field.localName); break; case "map": req.push(field.localName); break; } } } this.data = { req, known, oneofs: Object.values(oneofs) }; } /** * Is the argument a valid message as specified by the * reflection information? * * Checks all field types recursively. The `depth` * specifies how deep into the structure the check will be. * * With a depth of 0, only the presence of fields * is checked. * * With a depth of 1 or more, the field types are checked. * * With a depth of 2 or more, the members of map, repeated * and message fields are checked. * * Message fields will be checked recursively with depth - 1. * * The number of map entries / repeated values being checked * is < depth. */ is(message, depth, allowExcessProperties = false) { if (depth < 0) return true; if (message === null || message === undefined || typeof message != 'object') return false; this.prepare(); let keys = Object.keys(message), data = this.data; // if a required field is missing in arg, this cannot be a T if (keys.length < data.req.length || data.req.some(n => !keys.includes(n))) return false; if (!allowExcessProperties) { // if the arg contains a key we dont know, this is not a literal T if (keys.some(k => !data.known.includes(k))) return false; } // "With a depth of 0, only the presence and absence of fields is checked." // "With a depth of 1 or more, the field types are checked." if (depth < 1) { return true; } // check oneof group for (const name of data.oneofs) { const group = message[name]; if (!oneof_1.isOneofGroup(group)) return false; if (group.oneofKind === undefined) continue; const field = this.fields.find(f => f.localName === group.oneofKind); if (!field) return false; // we found no field, but have a kind, something is wrong if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth)) return false; } // check types for (const field of this.fields) { if (field.oneof !== undefined) continue; if (!this.field(message[field.localName], field, allowExcessProperties, depth)) return false; } return true; } field(arg, field, allowExcessProperties, depth) { let repeated = field.repeat; switch (field.kind) { case "scalar": if (arg === undefined) return field.opt; if (repeated) return this.scalars(arg, field.T, depth, field.L); return this.scalar(arg, field.T, field.L); case "enum": if (arg === undefined) return field.opt; if (repeated) return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth); return this.scalar(arg, reflection_info_1.ScalarType.INT32); case "message": if (arg === undefined) return true; if (repeated) return this.messages(arg, field.T(), allowExcessProperties, depth); return this.message(arg, field.T(), allowExcessProperties, depth); case "map": if (typeof arg != 'object' || arg === null) return false; if (depth < 2) return true; if (!this.mapKeys(arg, field.K, depth)) return false; switch (field.V.kind) { case "scalar": return this.scalars(Object.values(arg), field.V.T, depth, field.V.L); case "enum": return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth); case "message": return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth); } break; } return true; } message(arg, type, allowExcessProperties, depth) { if (allowExcessProperties) { return type.isAssignable(arg, depth); } return type.is(arg, depth); } messages(arg, type, allowExcessProperties, depth) { if (!Array.isArray(arg)) return false; if (depth < 2) return true; if (allowExcessProperties) { for (let i = 0; i < arg.length && i < depth; i++) if (!type.isAssignable(arg[i], depth - 1)) return false; } else { for (let i = 0; i < arg.length && i < depth; i++) if (!type.is(arg[i], depth - 1)) return false; } return true; } scalar(arg, type, longType) { let argType = typeof arg; switch (type) { case reflection_info_1.ScalarType.UINT64: case reflection_info_1.ScalarType.FIXED64: case reflection_info_1.ScalarType.INT64: case reflection_info_1.ScalarType.SFIXED64: case reflection_info_1.ScalarType.SINT64: switch (longType) { case reflection_info_1.LongType.BIGINT: return argType == "bigint"; case reflection_info_1.LongType.NUMBER: return argType == "number" && !isNaN(arg); default: return argType == "string"; } case reflection_info_1.ScalarType.BOOL: return argType == 'boolean'; case reflection_info_1.ScalarType.STRING: return argType == 'string'; case reflection_info_1.ScalarType.BYTES: return arg instanceof Uint8Array; case reflection_info_1.ScalarType.DOUBLE: case reflection_info_1.ScalarType.FLOAT: return argType == 'number' && !isNaN(arg); default: // case ScalarType.UINT32: // case ScalarType.FIXED32: // case ScalarType.INT32: // case ScalarType.SINT32: // case ScalarType.SFIXED32: return argType == 'number' && Number.isInteger(arg); } } scalars(arg, type, depth, longType) { if (!Array.isArray(arg)) return false; if (depth < 2) return true; if (Array.isArray(arg)) for (let i = 0; i < arg.length && i < depth; i++) if (!this.scalar(arg[i], type, longType)) return false; return true; } mapKeys(map, type, depth) { let keys = Object.keys(map); switch (type) { case reflection_info_1.ScalarType.INT32: case reflection_info_1.ScalarType.FIXED32: case reflection_info_1.ScalarType.SFIXED32: case reflection_info_1.ScalarType.SINT32: case reflection_info_1.ScalarType.UINT32: return this.scalars(keys.slice(0, depth).map(k => parseInt(k)), type, depth); case reflection_info_1.ScalarType.BOOL: return this.scalars(keys.slice(0, depth).map(k => k == 'true' ? true : k == 'false' ? false : k), type, depth); default: return this.scalars(keys, type, depth, reflection_info_1.LongType.STRING); } } } exports.ReflectionTypeCheck = ReflectionTypeCheck; /***/ }), /***/ 15183: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.req = exports.json = exports.toBuffer = void 0; const http = __importStar(__nccwpck_require__(58611)); const https = __importStar(__nccwpck_require__(65692)); async function toBuffer(stream) { let length = 0; const chunks = []; for await (const chunk of stream) { length += chunk.length; chunks.push(chunk); } return Buffer.concat(chunks, length); } exports.toBuffer = toBuffer; // eslint-disable-next-line @typescript-eslint/no-explicit-any async function json(stream) { const buf = await toBuffer(stream); const str = buf.toString('utf8'); try { return JSON.parse(str); } catch (_err) { const err = _err; err.message += ` (input: ${str})`; throw err; } } exports.json = json; function req(url, opts = {}) { const href = typeof url === 'string' ? url : url.href; const req = (href.startsWith('https:') ? https : http).request(url, opts); const promise = new Promise((resolve, reject) => { req .once('response', resolve) .once('error', reject) .end(); }); req.then = promise.then.bind(promise); return req; } exports.req = req; //# sourceMappingURL=helpers.js.map /***/ }), /***/ 98894: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Agent = void 0; const net = __importStar(__nccwpck_require__(69278)); const http = __importStar(__nccwpck_require__(58611)); const https_1 = __nccwpck_require__(65692); __exportStar(__nccwpck_require__(15183), exports); const INTERNAL = Symbol('AgentBaseInternalState'); class Agent extends http.Agent { constructor(opts) { super(opts); this[INTERNAL] = {}; } /** * Determine whether this is an `http` or `https` request. */ isSecureEndpoint(options) { if (options) { // First check the `secureEndpoint` property explicitly, since this // means that a parent `Agent` is "passing through" to this instance. // eslint-disable-next-line @typescript-eslint/no-explicit-any if (typeof options.secureEndpoint === 'boolean') { return options.secureEndpoint; } // If no explicit `secure` endpoint, check if `protocol` property is // set. This will usually be the case since using a full string URL // or `URL` instance should be the most common usage. if (typeof options.protocol === 'string') { return options.protocol === 'https:'; } } // Finally, if no `protocol` property was set, then fall back to // checking the stack trace of the current call stack, and try to // detect the "https" module. const { stack } = new Error(); if (typeof stack !== 'string') return false; return stack .split('\n') .some((l) => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); } // In order to support async signatures in `connect()` and Node's native // connection pooling in `http.Agent`, the array of sockets for each origin // has to be updated synchronously. This is so the length of the array is // accurate when `addRequest()` is next called. We achieve this by creating a // fake socket and adding it to `sockets[origin]` and incrementing // `totalSocketCount`. incrementSockets(name) { // If `maxSockets` and `maxTotalSockets` are both Infinity then there is no // need to create a fake socket because Node.js native connection pooling // will never be invoked. if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { return null; } // All instances of `sockets` are expected TypeScript errors. The // alternative is to add it as a private property of this class but that // will break TypeScript subclassing. if (!this.sockets[name]) { // @ts-expect-error `sockets` is readonly in `@types/node` this.sockets[name] = []; } const fakeSocket = new net.Socket({ writable: false }); this.sockets[name].push(fakeSocket); // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` this.totalSocketCount++; return fakeSocket; } decrementSockets(name, socket) { if (!this.sockets[name] || socket === null) { return; } const sockets = this.sockets[name]; const index = sockets.indexOf(socket); if (index !== -1) { sockets.splice(index, 1); // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` this.totalSocketCount--; if (sockets.length === 0) { // @ts-expect-error `sockets` is readonly in `@types/node` delete this.sockets[name]; } } } // In order to properly update the socket pool, we need to call `getName()` on // the core `https.Agent` if it is a secureEndpoint. getName(options) { const secureEndpoint = typeof options.secureEndpoint === 'boolean' ? options.secureEndpoint : this.isSecureEndpoint(options); if (secureEndpoint) { // @ts-expect-error `getName()` isn't defined in `@types/node` return https_1.Agent.prototype.getName.call(this, options); } // @ts-expect-error `getName()` isn't defined in `@types/node` return super.getName(options); } createSocket(req, options, cb) { const connectOpts = { ...options, secureEndpoint: this.isSecureEndpoint(options), }; const name = this.getName(connectOpts); const fakeSocket = this.incrementSockets(name); Promise.resolve() .then(() => this.connect(req, connectOpts)) .then((socket) => { this.decrementSockets(name, fakeSocket); if (socket instanceof http.Agent) { try { // @ts-expect-error `addRequest()` isn't defined in `@types/node` return socket.addRequest(req, connectOpts); } catch (err) { return cb(err); } } this[INTERNAL].currentSocket = socket; // @ts-expect-error `createSocket()` isn't defined in `@types/node` super.createSocket(req, options, cb); }, (err) => { this.decrementSockets(name, fakeSocket); cb(err); }); } createConnection() { const socket = this[INTERNAL].currentSocket; this[INTERNAL].currentSocket = undefined; if (!socket) { throw new Error('No socket was returned in the `connect()` function'); } return socket; } get defaultPort() { return (this[INTERNAL].defaultPort ?? (this.protocol === 'https:' ? 443 : 80)); } set defaultPort(v) { if (this[INTERNAL]) { this[INTERNAL].defaultPort = v; } } get protocol() { return (this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? 'https:' : 'http:')); } set protocol(v) { if (this[INTERNAL]) { this[INTERNAL].protocol = v; } } } exports.Agent = Agent; //# sourceMappingURL=index.js.map /***/ }), /***/ 59380: /***/ ((module) => { "use strict"; module.exports = balanced; function balanced(a, b, str) { if (a instanceof RegExp) a = maybeMatch(a, str); if (b instanceof RegExp) b = maybeMatch(b, str); var r = range(a, b, str); return r && { start: r[0], end: r[1], pre: str.slice(0, r[0]), body: str.slice(r[0] + a.length, r[1]), post: str.slice(r[1] + b.length) }; } function maybeMatch(reg, str) { var m = str.match(reg); return m ? m[0] : null; } balanced.range = range; function range(a, b, str) { var begs, beg, left, right, result; var ai = str.indexOf(a); var bi = str.indexOf(b, ai + 1); var i = ai; if (ai >= 0 && bi > 0) { if(a===b) { return [ai, bi]; } begs = []; left = str.length; while (i >= 0 && !result) { if (i == ai) { begs.push(i); ai = str.indexOf(a, i + 1); } else if (begs.length == 1) { result = [ begs.pop(), bi ]; } else { beg = begs.pop(); if (beg < left) { left = beg; right = bi; } bi = str.indexOf(b, i + 1); } i = ai < bi && ai >= 0 ? ai : bi; } if (begs.length) { result = [ left, right ]; } } return result; } /***/ }), /***/ 52732: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var register = __nccwpck_require__(11063); var addHook = __nccwpck_require__(22027); var removeHook = __nccwpck_require__(59934); // bind with array of arguments: https://stackoverflow.com/a/21792913 var bind = Function.bind; var bindable = bind.bind(bind); function bindApi(hook, state, name) { var removeHookRef = bindable(removeHook, null).apply( null, name ? [state, name] : [state] ); hook.api = { remove: removeHookRef }; hook.remove = removeHookRef; ["before", "error", "after", "wrap"].forEach(function (kind) { var args = name ? [state, kind, name] : [state, kind]; hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); }); } function HookSingular() { var singularHookName = "h"; var singularHookState = { registry: {}, }; var singularHook = register.bind(null, singularHookState, singularHookName); bindApi(singularHook, singularHookState, singularHookName); return singularHook; } function HookCollection() { var state = { registry: {}, }; var hook = register.bind(null, state); bindApi(hook, state); return hook; } var collectionHookDeprecationMessageDisplayed = false; function Hook() { if (!collectionHookDeprecationMessageDisplayed) { console.warn( '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' ); collectionHookDeprecationMessageDisplayed = true; } return HookCollection(); } Hook.Singular = HookSingular.bind(); Hook.Collection = HookCollection.bind(); module.exports = Hook; // expose constructors as a named property for TypeScript module.exports.Hook = Hook; module.exports.Singular = Hook.Singular; module.exports.Collection = Hook.Collection; /***/ }), /***/ 22027: /***/ ((module) => { module.exports = addHook; function addHook(state, kind, name, hook) { var orig = hook; if (!state.registry[name]) { state.registry[name] = []; } if (kind === "before") { hook = function (method, options) { return Promise.resolve() .then(orig.bind(null, options)) .then(method.bind(null, options)); }; } if (kind === "after") { hook = function (method, options) { var result; return Promise.resolve() .then(method.bind(null, options)) .then(function (result_) { result = result_; return orig(result, options); }) .then(function () { return result; }); }; } if (kind === "error") { hook = function (method, options) { return Promise.resolve() .then(method.bind(null, options)) .catch(function (error) { return orig(error, options); }); }; } state.registry[name].push({ hook: hook, orig: orig, }); } /***/ }), /***/ 11063: /***/ ((module) => { module.exports = register; function register(state, name, method, options) { if (typeof method !== "function") { throw new Error("method for before hook must be a function"); } if (!options) { options = {}; } if (Array.isArray(name)) { return name.reverse().reduce(function (callback, name) { return register.bind(null, state, name, callback, options); }, method)(); } return Promise.resolve().then(function () { if (!state.registry[name]) { return method(options); } return state.registry[name].reduce(function (method, registered) { return registered.hook.bind(null, method, options); }, method)(); }); } /***/ }), /***/ 59934: /***/ ((module) => { module.exports = removeHook; function removeHook(state, name, method) { if (!state.registry[name]) { return; } var index = state.registry[name] .map(function (registered) { return registered.orig; }) .indexOf(method); if (index === -1) { return; } state.registry[name].splice(index, 1); } /***/ }), /***/ 45265: /***/ ((module) => { module.exports = { trueFunc: function trueFunc(){ return true; }, falseFunc: function falseFunc(){ return false; } }; /***/ }), /***/ 94691: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var concatMap = __nccwpck_require__(97087); var balanced = __nccwpck_require__(59380); module.exports = expandTop; var escSlash = '\0SLASH'+Math.random()+'\0'; var escOpen = '\0OPEN'+Math.random()+'\0'; var escClose = '\0CLOSE'+Math.random()+'\0'; var escComma = '\0COMMA'+Math.random()+'\0'; var escPeriod = '\0PERIOD'+Math.random()+'\0'; function numeric(str) { return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); } function escapeBraces(str) { return str.split('\\\\').join(escSlash) .split('\\{').join(escOpen) .split('\\}').join(escClose) .split('\\,').join(escComma) .split('\\.').join(escPeriod); } function unescapeBraces(str) { return str.split(escSlash).join('\\') .split(escOpen).join('{') .split(escClose).join('}') .split(escComma).join(',') .split(escPeriod).join('.'); } // Basically just str.split(","), but handling cases // where we have nested braced sections, which should be // treated as individual members, like {a,{b,c},d} function parseCommaParts(str) { if (!str) return ['']; var parts = []; var m = balanced('{', '}', str); if (!m) return str.split(','); var pre = m.pre; var body = m.body; var post = m.post; var p = pre.split(','); p[p.length-1] += '{' + body + '}'; var postParts = parseCommaParts(post); if (post.length) { p[p.length-1] += postParts.shift(); p.push.apply(p, postParts); } parts.push.apply(parts, p); return parts; } function expandTop(str) { if (!str) return []; // I don't know why Bash 4.3 does this, but it does. // Anything starting with {} will have the first two bytes preserved // but *only* at the top level, so {},a}b will not expand to anything, // but a{},b}c will be expanded to [a}c,abc]. // One could argue that this is a bug in Bash, but since the goal of // this module is to match Bash's rules, we escape a leading {} if (str.substr(0, 2) === '{}') { str = '\\{\\}' + str.substr(2); } return expand(escapeBraces(str), true).map(unescapeBraces); } function identity(e) { return e; } function embrace(str) { return '{' + str + '}'; } function isPadded(el) { return /^-?0\d/.test(el); } function lte(i, y) { return i <= y; } function gte(i, y) { return i >= y; } function expand(str, isTop) { var expansions = []; var m = balanced('{', '}', str); if (!m || /\$$/.test(m.pre)) return [str]; var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(',') >= 0; if (!isSequence && !isOptions) { // {a},b} if (m.post.match(/,.*\}/)) { str = m.pre + '{' + m.body + escClose + m.post; return expand(str); } return [str]; } var n; if (isSequence) { n = m.body.split(/\.\./); } else { n = parseCommaParts(m.body); if (n.length === 1) { // x{{a,b}}y ==> x{a}y x{b}y n = expand(n[0], false).map(embrace); if (n.length === 1) { var post = m.post.length ? expand(m.post, false) : ['']; return post.map(function(p) { return m.pre + n[0] + p; }); } } } // at this point, n is the parts, and we know it's not a comma set // with a single entry. // no need to expand pre, since it is guaranteed to be free of brace-sets var pre = m.pre; var post = m.post.length ? expand(m.post, false) : ['']; var N; if (isSequence) { var x = numeric(n[0]); var y = numeric(n[1]); var width = Math.max(n[0].length, n[1].length) var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1; var test = lte; var reverse = y < x; if (reverse) { incr *= -1; test = gte; } var pad = n.some(isPadded); N = []; for (var i = x; test(i, y); i += incr) { var c; if (isAlphaSequence) { c = String.fromCharCode(i); if (c === '\\') c = ''; } else { c = String(i); if (pad) { var need = width - c.length; if (need > 0) { var z = new Array(need + 1).join('0'); if (i < 0) c = '-' + z + c.slice(1); else c = z + c; } } } N.push(c); } } else { N = concatMap(n, function(el) { return expand(el, false) }); } for (var j = 0; j < N.length; j++) { for (var k = 0; k < post.length; k++) { var expansion = pre + N[j] + post[k]; if (!isTop || isSequence || expansion) expansions.push(expansion); } } return expansions; } /***/ }), /***/ 70561: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.groupSelectors = exports.getDocumentRoot = void 0; var positionals_js_1 = __nccwpck_require__(69863); function getDocumentRoot(node) { while (node.parent) node = node.parent; return node; } exports.getDocumentRoot = getDocumentRoot; function groupSelectors(selectors) { var filteredSelectors = []; var plainSelectors = []; for (var _i = 0, selectors_1 = selectors; _i < selectors_1.length; _i++) { var selector = selectors_1[_i]; if (selector.some(positionals_js_1.isFilter)) { filteredSelectors.push(selector); } else { plainSelectors.push(selector); } } return [plainSelectors, filteredSelectors]; } exports.groupSelectors = groupSelectors; //# sourceMappingURL=helpers.js.map /***/ }), /***/ 21012: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __assign = (this && this.__assign) || function () { __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; }; return __assign.apply(this, arguments); }; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.select = exports.filter = exports.some = exports.is = exports.aliases = exports.pseudos = exports.filters = void 0; var css_what_1 = __nccwpck_require__(75667); var css_select_1 = __nccwpck_require__(32842); var DomUtils = __importStar(__nccwpck_require__(92357)); var boolbase = __importStar(__nccwpck_require__(45265)); var helpers_js_1 = __nccwpck_require__(70561); var positionals_js_1 = __nccwpck_require__(69863); // Re-export pseudo extension points var css_select_2 = __nccwpck_require__(32842); Object.defineProperty(exports, "filters", ({ enumerable: true, get: function () { return css_select_2.filters; } })); Object.defineProperty(exports, "pseudos", ({ enumerable: true, get: function () { return css_select_2.pseudos; } })); Object.defineProperty(exports, "aliases", ({ enumerable: true, get: function () { return css_select_2.aliases; } })); var UNIVERSAL_SELECTOR = { type: css_what_1.SelectorType.Universal, namespace: null, }; var SCOPE_PSEUDO = { type: css_what_1.SelectorType.Pseudo, name: "scope", data: null, }; function is(element, selector, options) { if (options === void 0) { options = {}; } return some([element], selector, options); } exports.is = is; function some(elements, selector, options) { if (options === void 0) { options = {}; } if (typeof selector === "function") return elements.some(selector); var _a = (0, helpers_js_1.groupSelectors)((0, css_what_1.parse)(selector)), plain = _a[0], filtered = _a[1]; return ((plain.length > 0 && elements.some((0, css_select_1._compileToken)(plain, options))) || filtered.some(function (sel) { return filterBySelector(sel, elements, options).length > 0; })); } exports.some = some; function filterByPosition(filter, elems, data, options) { var num = typeof data === "string" ? parseInt(data, 10) : NaN; switch (filter) { case "first": case "lt": // Already done in `getLimit` return elems; case "last": return elems.length > 0 ? [elems[elems.length - 1]] : elems; case "nth": case "eq": return isFinite(num) && Math.abs(num) < elems.length ? [num < 0 ? elems[elems.length + num] : elems[num]] : []; case "gt": return isFinite(num) ? elems.slice(num + 1) : []; case "even": return elems.filter(function (_, i) { return i % 2 === 0; }); case "odd": return elems.filter(function (_, i) { return i % 2 === 1; }); case "not": { var filtered_1 = new Set(filterParsed(data, elems, options)); return elems.filter(function (e) { return !filtered_1.has(e); }); } } } function filter(selector, elements, options) { if (options === void 0) { options = {}; } return filterParsed((0, css_what_1.parse)(selector), elements, options); } exports.filter = filter; /** * Filter a set of elements by a selector. * * Will return elements in the original order. * * @param selector Selector to filter by. * @param elements Elements to filter. * @param options Options for selector. */ function filterParsed(selector, elements, options) { if (elements.length === 0) return []; var _a = (0, helpers_js_1.groupSelectors)(selector), plainSelectors = _a[0], filteredSelectors = _a[1]; var found; if (plainSelectors.length) { var filtered = filterElements(elements, plainSelectors, options); // If there are no filters, just return if (filteredSelectors.length === 0) { return filtered; } // Otherwise, we have to do some filtering if (filtered.length) { found = new Set(filtered); } } for (var i = 0; i < filteredSelectors.length && (found === null || found === void 0 ? void 0 : found.size) !== elements.length; i++) { var filteredSelector = filteredSelectors[i]; var missing = found ? elements.filter(function (e) { return DomUtils.isTag(e) && !found.has(e); }) : elements; if (missing.length === 0) break; var filtered = filterBySelector(filteredSelector, elements, options); if (filtered.length) { if (!found) { /* * If we haven't found anything before the last selector, * just return what we found now. */ if (i === filteredSelectors.length - 1) { return filtered; } found = new Set(filtered); } else { filtered.forEach(function (el) { return found.add(el); }); } } } return typeof found !== "undefined" ? (found.size === elements.length ? elements : // Filter elements to preserve order elements.filter(function (el) { return found.has(el); })) : []; } function filterBySelector(selector, elements, options) { var _a; if (selector.some(css_what_1.isTraversal)) { /* * Get root node, run selector with the scope * set to all of our nodes. */ var root = (_a = options.root) !== null && _a !== void 0 ? _a : (0, helpers_js_1.getDocumentRoot)(elements[0]); var opts = __assign(__assign({}, options), { context: elements, relativeSelector: false }); selector.push(SCOPE_PSEUDO); return findFilterElements(root, selector, opts, true, elements.length); } // Performance optimization: If we don't have to traverse, just filter set. return findFilterElements(elements, selector, options, false, elements.length); } function select(selector, root, options, limit) { if (options === void 0) { options = {}; } if (limit === void 0) { limit = Infinity; } if (typeof selector === "function") { return find(root, selector); } var _a = (0, helpers_js_1.groupSelectors)((0, css_what_1.parse)(selector)), plain = _a[0], filtered = _a[1]; var results = filtered.map(function (sel) { return findFilterElements(root, sel, options, true, limit); }); // Plain selectors can be queried in a single go if (plain.length) { results.push(findElements(root, plain, options, limit)); } if (results.length === 0) { return []; } // If there was only a single selector, just return the result if (results.length === 1) { return results[0]; } // Sort results, filtering for duplicates return DomUtils.uniqueSort(results.reduce(function (a, b) { return __spreadArray(__spreadArray([], a, true), b, true); })); } exports.select = select; /** * * @param root Element(s) to search from. * @param selector Selector to look for. * @param options Options for querying. * @param queryForSelector Query multiple levels deep for the initial selector, even if it doesn't contain a traversal. */ function findFilterElements(root, selector, options, queryForSelector, totalLimit) { var filterIndex = selector.findIndex(positionals_js_1.isFilter); var sub = selector.slice(0, filterIndex); var filter = selector[filterIndex]; // If we are at the end of the selector, we can limit the number of elements to retrieve. var partLimit = selector.length - 1 === filterIndex ? totalLimit : Infinity; /* * Set the number of elements to retrieve. * Eg. for :first, we only have to get a single element. */ var limit = (0, positionals_js_1.getLimit)(filter.name, filter.data, partLimit); if (limit === 0) return []; /* * Skip `findElements` call if our selector starts with a positional * pseudo. */ var elemsNoLimit = sub.length === 0 && !Array.isArray(root) ? DomUtils.getChildren(root).filter(DomUtils.isTag) : sub.length === 0 ? (Array.isArray(root) ? root : [root]).filter(DomUtils.isTag) : queryForSelector || sub.some(css_what_1.isTraversal) ? findElements(root, [sub], options, limit) : filterElements(root, [sub], options); var elems = elemsNoLimit.slice(0, limit); var result = filterByPosition(filter.name, elems, filter.data, options); if (result.length === 0 || selector.length === filterIndex + 1) { return result; } var remainingSelector = selector.slice(filterIndex + 1); var remainingHasTraversal = remainingSelector.some(css_what_1.isTraversal); if (remainingHasTraversal) { if ((0, css_what_1.isTraversal)(remainingSelector[0])) { var type = remainingSelector[0].type; if (type === css_what_1.SelectorType.Sibling || type === css_what_1.SelectorType.Adjacent) { // If we have a sibling traversal, we need to also look at the siblings. result = (0, css_select_1.prepareContext)(result, DomUtils, true); } // Avoid a traversal-first selector error. remainingSelector.unshift(UNIVERSAL_SELECTOR); } options = __assign(__assign({}, options), { // Avoid absolutizing the selector relativeSelector: false, /* * Add a custom root func, to make sure traversals don't match elements * that aren't a part of the considered tree. */ rootFunc: function (el) { return result.includes(el); } }); } else if (options.rootFunc && options.rootFunc !== boolbase.trueFunc) { options = __assign(__assign({}, options), { rootFunc: boolbase.trueFunc }); } /* * If we have another filter, recursively call `findFilterElements`, * with the `recursive` flag disabled. We only have to look for more * elements when we see a traversal. * * Otherwise, */ return remainingSelector.some(positionals_js_1.isFilter) ? findFilterElements(result, remainingSelector, options, false, totalLimit) : remainingHasTraversal ? // Query existing elements to resolve traversal. findElements(result, [remainingSelector], options, totalLimit) : // If we don't have any more traversals, simply filter elements. filterElements(result, [remainingSelector], options); } function findElements(root, sel, options, limit) { var query = (0, css_select_1._compileToken)(sel, options, root); return find(root, query, limit); } function find(root, query, limit) { if (limit === void 0) { limit = Infinity; } var elems = (0, css_select_1.prepareContext)(root, DomUtils, query.shouldTestNextSiblings); return DomUtils.find(function (node) { return DomUtils.isTag(node) && query(node); }, elems, true, limit); } function filterElements(elements, sel, options) { var els = (Array.isArray(elements) ? elements : [elements]).filter(DomUtils.isTag); if (els.length === 0) return els; var query = (0, css_select_1._compileToken)(sel, options); return query === boolbase.trueFunc ? els : els.filter(query); } //# sourceMappingURL=index.js.map /***/ }), /***/ 69863: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getLimit = exports.isFilter = exports.filterNames = void 0; exports.filterNames = new Set([ "first", "last", "eq", "gt", "nth", "lt", "even", "odd", ]); function isFilter(s) { if (s.type !== "pseudo") return false; if (exports.filterNames.has(s.name)) return true; if (s.name === "not" && Array.isArray(s.data)) { // Only consider `:not` with embedded filters return s.data.some(function (s) { return s.some(isFilter); }); } return false; } exports.isFilter = isFilter; function getLimit(filter, data, partLimit) { var num = data != null ? parseInt(data, 10) : NaN; switch (filter) { case "first": return 1; case "nth": case "eq": return isFinite(num) ? (num >= 0 ? num + 1 : Infinity) : 0; case "lt": return isFinite(num) ? num >= 0 ? Math.min(num, partLimit) : Infinity : 0; case "gt": return isFinite(num) ? Infinity : 0; case "odd": return 2 * partLimit; case "even": return 2 * partLimit - 1; case "last": case "not": return Infinity; } } exports.getLimit = getLimit; //# sourceMappingURL=positionals.js.map /***/ }), /***/ 96325: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Client = __nccwpck_require__(56716) const Dispatcher = __nccwpck_require__(24350) const Pool = __nccwpck_require__(74561) const BalancedPool = __nccwpck_require__(18422) const Agent = __nccwpck_require__(11538) const ProxyAgent = __nccwpck_require__(7851) const EnvHttpProxyAgent = __nccwpck_require__(60592) const RetryAgent = __nccwpck_require__(489) const H2CClient = __nccwpck_require__(77046) const errors = __nccwpck_require__(21158) const util = __nccwpck_require__(46425) const { InvalidArgumentError } = errors const api = __nccwpck_require__(97558) const buildConnector = __nccwpck_require__(50815) const MockClient = __nccwpck_require__(20274) const { MockCallHistory, MockCallHistoryLog } = __nccwpck_require__(96376) const MockAgent = __nccwpck_require__(82980) const MockPool = __nccwpck_require__(82319) const mockErrors = __nccwpck_require__(63534) const RetryHandler = __nccwpck_require__(90093) const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(14266) const DecoratorHandler = __nccwpck_require__(11158) const RedirectHandler = __nccwpck_require__(28733) Object.assign(Dispatcher.prototype, api) module.exports.Dispatcher = Dispatcher module.exports.Client = Client module.exports.Pool = Pool module.exports.BalancedPool = BalancedPool module.exports.Agent = Agent module.exports.ProxyAgent = ProxyAgent module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent module.exports.RetryAgent = RetryAgent module.exports.H2CClient = H2CClient module.exports.RetryHandler = RetryHandler module.exports.DecoratorHandler = DecoratorHandler module.exports.RedirectHandler = RedirectHandler module.exports.interceptors = { redirect: __nccwpck_require__(92553), responseError: __nccwpck_require__(93577), retry: __nccwpck_require__(72895), dump: __nccwpck_require__(92295), dns: __nccwpck_require__(8374), cache: __nccwpck_require__(74455) } module.exports.cacheStores = { MemoryCacheStore: __nccwpck_require__(92434) } const SqliteCacheStore = __nccwpck_require__(82005) module.exports.cacheStores.SqliteCacheStore = SqliteCacheStore module.exports.buildConnector = buildConnector module.exports.errors = errors module.exports.util = { parseHeaders: util.parseHeaders, headerNameToString: util.headerNameToString } function makeDispatcher (fn) { return (url, opts, handler) => { if (typeof opts === 'function') { handler = opts opts = null } if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { throw new InvalidArgumentError('invalid url') } if (opts != null && typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } if (opts && opts.path != null) { if (typeof opts.path !== 'string') { throw new InvalidArgumentError('invalid opts.path') } let path = opts.path if (!opts.path.startsWith('/')) { path = `/${path}` } url = new URL(util.parseOrigin(url).origin + path) } else { if (!opts) { opts = typeof url === 'object' ? url : {} } url = util.parseURL(url) } const { agent, dispatcher = getGlobalDispatcher() } = opts if (agent) { throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') } return fn.call(dispatcher, { ...opts, origin: url.origin, path: url.search ? `${url.pathname}${url.search}` : url.pathname, method: opts.method || (opts.body ? 'PUT' : 'GET') }, handler) } } module.exports.setGlobalDispatcher = setGlobalDispatcher module.exports.getGlobalDispatcher = getGlobalDispatcher const fetchImpl = (__nccwpck_require__(25071).fetch) module.exports.fetch = async function fetch (init, options = undefined) { try { return await fetchImpl(init, options) } catch (err) { if (err && typeof err === 'object') { Error.captureStackTrace(err) } throw err } } module.exports.Headers = __nccwpck_require__(289).Headers module.exports.Response = __nccwpck_require__(46632).Response module.exports.Request = __nccwpck_require__(7622).Request module.exports.FormData = __nccwpck_require__(30717).FormData const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(53072) module.exports.setGlobalOrigin = setGlobalOrigin module.exports.getGlobalOrigin = getGlobalOrigin const { CacheStorage } = __nccwpck_require__(39886) const { kConstruct } = __nccwpck_require__(83112) // Cache & CacheStorage are tightly coupled with fetch. Even if it may run // in an older version of Node, it doesn't have any use without fetch. module.exports.caches = new CacheStorage(kConstruct) const { deleteCookie, getCookies, getSetCookies, setCookie, parseCookie } = __nccwpck_require__(17236) module.exports.deleteCookie = deleteCookie module.exports.getCookies = getCookies module.exports.getSetCookies = getSetCookies module.exports.setCookie = setCookie module.exports.parseCookie = parseCookie const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(38675) module.exports.parseMIMEType = parseMIMEType module.exports.serializeAMimeType = serializeAMimeType const { CloseEvent, ErrorEvent, MessageEvent } = __nccwpck_require__(91979) const { WebSocket, ping } = __nccwpck_require__(52279) module.exports.WebSocket = WebSocket module.exports.CloseEvent = CloseEvent module.exports.ErrorEvent = ErrorEvent module.exports.MessageEvent = MessageEvent module.exports.ping = ping module.exports.WebSocketStream = __nccwpck_require__(10794).WebSocketStream module.exports.WebSocketError = __nccwpck_require__(60446).WebSocketError module.exports.request = makeDispatcher(api.request) module.exports.stream = makeDispatcher(api.stream) module.exports.pipeline = makeDispatcher(api.pipeline) module.exports.connect = makeDispatcher(api.connect) module.exports.upgrade = makeDispatcher(api.upgrade) module.exports.MockClient = MockClient module.exports.MockCallHistory = MockCallHistory module.exports.MockCallHistoryLog = MockCallHistoryLog module.exports.MockPool = MockPool module.exports.MockAgent = MockAgent module.exports.mockErrors = mockErrors const { EventSource } = __nccwpck_require__(303) module.exports.EventSource = EventSource function install () { globalThis.fetch = module.exports.fetch globalThis.Headers = module.exports.Headers globalThis.Response = module.exports.Response globalThis.Request = module.exports.Request globalThis.FormData = module.exports.FormData globalThis.WebSocket = module.exports.WebSocket globalThis.CloseEvent = module.exports.CloseEvent globalThis.ErrorEvent = module.exports.ErrorEvent globalThis.MessageEvent = module.exports.MessageEvent globalThis.EventSource = module.exports.EventSource } module.exports.install = install /***/ }), /***/ 73853: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { addAbortListener } = __nccwpck_require__(46425) const { RequestAbortedError } = __nccwpck_require__(21158) const kListener = Symbol('kListener') const kSignal = Symbol('kSignal') function abort (self) { if (self.abort) { self.abort(self[kSignal]?.reason) } else { self.reason = self[kSignal]?.reason ?? new RequestAbortedError() } removeSignal(self) } function addSignal (self, signal) { self.reason = null self[kSignal] = null self[kListener] = null if (!signal) { return } if (signal.aborted) { abort(self) return } self[kSignal] = signal self[kListener] = () => { abort(self) } addAbortListener(self[kSignal], self[kListener]) } function removeSignal (self) { if (!self[kSignal]) { return } if ('removeEventListener' in self[kSignal]) { self[kSignal].removeEventListener('abort', self[kListener]) } else { self[kSignal].removeListener('abort', self[kListener]) } self[kSignal] = null self[kListener] = null } module.exports = { addSignal, removeSignal } /***/ }), /***/ 305: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(34589) const { AsyncResource } = __nccwpck_require__(16698) const { InvalidArgumentError, SocketError } = __nccwpck_require__(21158) const util = __nccwpck_require__(46425) const { addSignal, removeSignal } = __nccwpck_require__(73853) class ConnectHandler extends AsyncResource { constructor (opts, callback) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } const { signal, opaque, responseHeaders } = opts if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } super('UNDICI_CONNECT') this.opaque = opaque || null this.responseHeaders = responseHeaders || null this.callback = callback this.abort = null addSignal(this, signal) } onConnect (abort, context) { if (this.reason) { abort(this.reason) return } assert(this.callback) this.abort = abort this.context = context } onHeaders () { throw new SocketError('bad connect', null) } onUpgrade (statusCode, rawHeaders, socket) { const { callback, opaque, context } = this removeSignal(this) this.callback = null let headers = rawHeaders // Indicates is an HTTP2Session if (headers != null) { headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) } this.runInAsyncScope(callback, null, null, { statusCode, headers, socket, opaque, context }) } onError (err) { const { callback, opaque } = this removeSignal(this) if (callback) { this.callback = null queueMicrotask(() => { this.runInAsyncScope(callback, null, err, { opaque }) }) } } } function connect (opts, callback) { if (callback === undefined) { return new Promise((resolve, reject) => { connect.call(this, opts, (err, data) => { return err ? reject(err) : resolve(data) }) }) } try { const connectHandler = new ConnectHandler(opts, callback) const connectOptions = { ...opts, method: 'CONNECT' } this.dispatch(connectOptions, connectHandler) } catch (err) { if (typeof callback !== 'function') { throw err } const opaque = opts?.opaque queueMicrotask(() => callback(err, { opaque })) } } module.exports = connect /***/ }), /***/ 59993: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Readable, Duplex, PassThrough } = __nccwpck_require__(57075) const assert = __nccwpck_require__(34589) const { AsyncResource } = __nccwpck_require__(16698) const { InvalidArgumentError, InvalidReturnValueError, RequestAbortedError } = __nccwpck_require__(21158) const util = __nccwpck_require__(46425) const { addSignal, removeSignal } = __nccwpck_require__(73853) function noop () {} const kResume = Symbol('resume') class PipelineRequest extends Readable { constructor () { super({ autoDestroy: true }) this[kResume] = null } _read () { const { [kResume]: resume } = this if (resume) { this[kResume] = null resume() } } _destroy (err, callback) { this._read() callback(err) } } class PipelineResponse extends Readable { constructor (resume) { super({ autoDestroy: true }) this[kResume] = resume } _read () { this[kResume]() } _destroy (err, callback) { if (!err && !this._readableState.endEmitted) { err = new RequestAbortedError() } callback(err) } } class PipelineHandler extends AsyncResource { constructor (opts, handler) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } if (typeof handler !== 'function') { throw new InvalidArgumentError('invalid handler') } const { signal, method, opaque, onInfo, responseHeaders } = opts if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } if (method === 'CONNECT') { throw new InvalidArgumentError('invalid method') } if (onInfo && typeof onInfo !== 'function') { throw new InvalidArgumentError('invalid onInfo callback') } super('UNDICI_PIPELINE') this.opaque = opaque || null this.responseHeaders = responseHeaders || null this.handler = handler this.abort = null this.context = null this.onInfo = onInfo || null this.req = new PipelineRequest().on('error', noop) this.ret = new Duplex({ readableObjectMode: opts.objectMode, autoDestroy: true, read: () => { const { body } = this if (body?.resume) { body.resume() } }, write: (chunk, encoding, callback) => { const { req } = this if (req.push(chunk, encoding) || req._readableState.destroyed) { callback() } else { req[kResume] = callback } }, destroy: (err, callback) => { const { body, req, res, ret, abort } = this if (!err && !ret._readableState.endEmitted) { err = new RequestAbortedError() } if (abort && err) { abort() } util.destroy(body, err) util.destroy(req, err) util.destroy(res, err) removeSignal(this) callback(err) } }).on('prefinish', () => { const { req } = this // Node < 15 does not call _final in same tick. req.push(null) }) this.res = null addSignal(this, signal) } onConnect (abort, context) { const { res } = this if (this.reason) { abort(this.reason) return } assert(!res, 'pipeline cannot be retried') this.abort = abort this.context = context } onHeaders (statusCode, rawHeaders, resume) { const { opaque, handler, context } = this if (statusCode < 200) { if (this.onInfo) { const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) this.onInfo({ statusCode, headers }) } return } this.res = new PipelineResponse(resume) let body try { this.handler = null const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) body = this.runInAsyncScope(handler, null, { statusCode, headers, opaque, body: this.res, context }) } catch (err) { this.res.on('error', noop) throw err } if (!body || typeof body.on !== 'function') { throw new InvalidReturnValueError('expected Readable') } body .on('data', (chunk) => { const { ret, body } = this if (!ret.push(chunk) && body.pause) { body.pause() } }) .on('error', (err) => { const { ret } = this util.destroy(ret, err) }) .on('end', () => { const { ret } = this ret.push(null) }) .on('close', () => { const { ret } = this if (!ret._readableState.ended) { util.destroy(ret, new RequestAbortedError()) } }) this.body = body } onData (chunk) { const { res } = this return res.push(chunk) } onComplete (trailers) { const { res } = this res.push(null) } onError (err) { const { ret } = this this.handler = null util.destroy(ret, err) } } function pipeline (opts, handler) { try { const pipelineHandler = new PipelineHandler(opts, handler) this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler) return pipelineHandler.ret } catch (err) { return new PassThrough().destroy(err) } } module.exports = pipeline /***/ }), /***/ 20482: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(34589) const { AsyncResource } = __nccwpck_require__(16698) const { Readable } = __nccwpck_require__(84220) const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(21158) const util = __nccwpck_require__(46425) function noop () {} class RequestHandler extends AsyncResource { constructor (opts, callback) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } const { signal, method, opaque, body, onInfo, responseHeaders, highWaterMark } = opts try { if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { throw new InvalidArgumentError('invalid highWaterMark') } if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } if (method === 'CONNECT') { throw new InvalidArgumentError('invalid method') } if (onInfo && typeof onInfo !== 'function') { throw new InvalidArgumentError('invalid onInfo callback') } super('UNDICI_REQUEST') } catch (err) { if (util.isStream(body)) { util.destroy(body.on('error', noop), err) } throw err } this.method = method this.responseHeaders = responseHeaders || null this.opaque = opaque || null this.callback = callback this.res = null this.abort = null this.body = body this.trailers = {} this.context = null this.onInfo = onInfo || null this.highWaterMark = highWaterMark this.reason = null this.removeAbortListener = null if (signal?.aborted) { this.reason = signal.reason ?? new RequestAbortedError() } else if (signal) { this.removeAbortListener = util.addAbortListener(signal, () => { this.reason = signal.reason ?? new RequestAbortedError() if (this.res) { util.destroy(this.res.on('error', noop), this.reason) } else if (this.abort) { this.abort(this.reason) } }) } } onConnect (abort, context) { if (this.reason) { abort(this.reason) return } assert(this.callback) this.abort = abort this.context = context } onHeaders (statusCode, rawHeaders, resume, statusMessage) { const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) if (statusCode < 200) { if (this.onInfo) { this.onInfo({ statusCode, headers }) } return } const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers const contentType = parsedHeaders['content-type'] const contentLength = parsedHeaders['content-length'] const res = new Readable({ resume, abort, contentType, contentLength: this.method !== 'HEAD' && contentLength ? Number(contentLength) : null, highWaterMark }) if (this.removeAbortListener) { res.on('close', this.removeAbortListener) this.removeAbortListener = null } this.callback = null this.res = res if (callback !== null) { this.runInAsyncScope(callback, null, null, { statusCode, headers, trailers: this.trailers, opaque, body: res, context }) } } onData (chunk) { return this.res.push(chunk) } onComplete (trailers) { util.parseHeaders(trailers, this.trailers) this.res.push(null) } onError (err) { const { res, callback, body, opaque } = this if (callback) { // TODO: Does this need queueMicrotask? this.callback = null queueMicrotask(() => { this.runInAsyncScope(callback, null, err, { opaque }) }) } if (res) { this.res = null // Ensure all queued handlers are invoked before destroying res. queueMicrotask(() => { util.destroy(res.on('error', noop), err) }) } if (body) { this.body = null if (util.isStream(body)) { body.on('error', noop) util.destroy(body, err) } } if (this.removeAbortListener) { this.removeAbortListener() this.removeAbortListener = null } } } function request (opts, callback) { if (callback === undefined) { return new Promise((resolve, reject) => { request.call(this, opts, (err, data) => { return err ? reject(err) : resolve(data) }) }) } try { const handler = new RequestHandler(opts, callback) this.dispatch(opts, handler) } catch (err) { if (typeof callback !== 'function') { throw err } const opaque = opts?.opaque queueMicrotask(() => callback(err, { opaque })) } } module.exports = request module.exports.RequestHandler = RequestHandler /***/ }), /***/ 36103: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(34589) const { finished } = __nccwpck_require__(57075) const { AsyncResource } = __nccwpck_require__(16698) const { InvalidArgumentError, InvalidReturnValueError } = __nccwpck_require__(21158) const util = __nccwpck_require__(46425) const { addSignal, removeSignal } = __nccwpck_require__(73853) function noop () {} class StreamHandler extends AsyncResource { constructor (opts, factory, callback) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } const { signal, method, opaque, body, onInfo, responseHeaders } = opts try { if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } if (typeof factory !== 'function') { throw new InvalidArgumentError('invalid factory') } if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } if (method === 'CONNECT') { throw new InvalidArgumentError('invalid method') } if (onInfo && typeof onInfo !== 'function') { throw new InvalidArgumentError('invalid onInfo callback') } super('UNDICI_STREAM') } catch (err) { if (util.isStream(body)) { util.destroy(body.on('error', noop), err) } throw err } this.responseHeaders = responseHeaders || null this.opaque = opaque || null this.factory = factory this.callback = callback this.res = null this.abort = null this.context = null this.trailers = null this.body = body this.onInfo = onInfo || null if (util.isStream(body)) { body.on('error', (err) => { this.onError(err) }) } addSignal(this, signal) } onConnect (abort, context) { if (this.reason) { abort(this.reason) return } assert(this.callback) this.abort = abort this.context = context } onHeaders (statusCode, rawHeaders, resume, statusMessage) { const { factory, opaque, context, responseHeaders } = this const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) if (statusCode < 200) { if (this.onInfo) { this.onInfo({ statusCode, headers }) } return } this.factory = null if (factory === null) { return } const res = this.runInAsyncScope(factory, null, { statusCode, headers, opaque, context }) if ( !res || typeof res.write !== 'function' || typeof res.end !== 'function' || typeof res.on !== 'function' ) { throw new InvalidReturnValueError('expected Writable') } // TODO: Avoid finished. It registers an unnecessary amount of listeners. finished(res, { readable: false }, (err) => { const { callback, res, opaque, trailers, abort } = this this.res = null if (err || !res?.readable) { util.destroy(res, err) } this.callback = null this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) if (err) { abort() } }) res.on('drain', resume) this.res = res const needDrain = res.writableNeedDrain !== undefined ? res.writableNeedDrain : res._writableState?.needDrain return needDrain !== true } onData (chunk) { const { res } = this return res ? res.write(chunk) : true } onComplete (trailers) { const { res } = this removeSignal(this) if (!res) { return } this.trailers = util.parseHeaders(trailers) res.end() } onError (err) { const { res, callback, opaque, body } = this removeSignal(this) this.factory = null if (res) { this.res = null util.destroy(res, err) } else if (callback) { this.callback = null queueMicrotask(() => { this.runInAsyncScope(callback, null, err, { opaque }) }) } if (body) { this.body = null util.destroy(body, err) } } } function stream (opts, factory, callback) { if (callback === undefined) { return new Promise((resolve, reject) => { stream.call(this, opts, factory, (err, data) => { return err ? reject(err) : resolve(data) }) }) } try { const handler = new StreamHandler(opts, factory, callback) this.dispatch(opts, handler) } catch (err) { if (typeof callback !== 'function') { throw err } const opaque = opts?.opaque queueMicrotask(() => callback(err, { opaque })) } } module.exports = stream /***/ }), /***/ 67035: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { InvalidArgumentError, SocketError } = __nccwpck_require__(21158) const { AsyncResource } = __nccwpck_require__(16698) const assert = __nccwpck_require__(34589) const util = __nccwpck_require__(46425) const { addSignal, removeSignal } = __nccwpck_require__(73853) class UpgradeHandler extends AsyncResource { constructor (opts, callback) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } const { signal, opaque, responseHeaders } = opts if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } super('UNDICI_UPGRADE') this.responseHeaders = responseHeaders || null this.opaque = opaque || null this.callback = callback this.abort = null this.context = null addSignal(this, signal) } onConnect (abort, context) { if (this.reason) { abort(this.reason) return } assert(this.callback) this.abort = abort this.context = null } onHeaders () { throw new SocketError('bad upgrade', null) } onUpgrade (statusCode, rawHeaders, socket) { assert(statusCode === 101) const { callback, opaque, context } = this removeSignal(this) this.callback = null const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) this.runInAsyncScope(callback, null, null, { headers, socket, opaque, context }) } onError (err) { const { callback, opaque } = this removeSignal(this) if (callback) { this.callback = null queueMicrotask(() => { this.runInAsyncScope(callback, null, err, { opaque }) }) } } } function upgrade (opts, callback) { if (callback === undefined) { return new Promise((resolve, reject) => { upgrade.call(this, opts, (err, data) => { return err ? reject(err) : resolve(data) }) }) } try { const upgradeHandler = new UpgradeHandler(opts, callback) const upgradeOpts = { ...opts, method: opts.method || 'GET', upgrade: opts.protocol || 'Websocket' } this.dispatch(upgradeOpts, upgradeHandler) } catch (err) { if (typeof callback !== 'function') { throw err } const opaque = opts?.opaque queueMicrotask(() => callback(err, { opaque })) } } module.exports = upgrade /***/ }), /***/ 97558: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports.request = __nccwpck_require__(20482) module.exports.stream = __nccwpck_require__(36103) module.exports.pipeline = __nccwpck_require__(59993) module.exports.upgrade = __nccwpck_require__(67035) module.exports.connect = __nccwpck_require__(305) /***/ }), /***/ 84220: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Ported from https://github.com/nodejs/undici/pull/907 const assert = __nccwpck_require__(34589) const { Readable } = __nccwpck_require__(57075) const { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = __nccwpck_require__(21158) const util = __nccwpck_require__(46425) const { ReadableStreamFrom } = __nccwpck_require__(46425) const kConsume = Symbol('kConsume') const kReading = Symbol('kReading') const kBody = Symbol('kBody') const kAbort = Symbol('kAbort') const kContentType = Symbol('kContentType') const kContentLength = Symbol('kContentLength') const kUsed = Symbol('kUsed') const kBytesRead = Symbol('kBytesRead') const noop = () => {} /** * @class * @extends {Readable} * @see https://fetch.spec.whatwg.org/#body */ class BodyReadable extends Readable { /** * @param {object} opts * @param {(this: Readable, size: number) => void} opts.resume * @param {() => (void | null)} opts.abort * @param {string} [opts.contentType = ''] * @param {number} [opts.contentLength] * @param {number} [opts.highWaterMark = 64 * 1024] */ constructor ({ resume, abort, contentType = '', contentLength, highWaterMark = 64 * 1024 // Same as nodejs fs streams. }) { super({ autoDestroy: true, read: resume, highWaterMark }) this._readableState.dataEmitted = false this[kAbort] = abort /** * @type {Consume | null} */ this[kConsume] = null this[kBytesRead] = 0 /** * @type {ReadableStream|null} */ this[kBody] = null this[kUsed] = false this[kContentType] = contentType this[kContentLength] = Number.isFinite(contentLength) ? contentLength : null // Is stream being consumed through Readable API? // This is an optimization so that we avoid checking // for 'data' and 'readable' listeners in the hot path // inside push(). this[kReading] = false } /** * @param {Error|null} err * @param {(error:(Error|null)) => void} callback * @returns {void} */ _destroy (err, callback) { if (!err && !this._readableState.endEmitted) { err = new RequestAbortedError() } if (err) { this[kAbort]() } // Workaround for Node "bug". If the stream is destroyed in same // tick as it is created, then a user who is waiting for a // promise (i.e micro tick) for installing an 'error' listener will // never get a chance and will always encounter an unhandled exception. if (!this[kUsed]) { setImmediate(callback, err) } else { callback(err) } } /** * @param {string} event * @param {(...args: any[]) => void} listener * @returns {this} */ on (event, listener) { if (event === 'data' || event === 'readable') { this[kReading] = true this[kUsed] = true } return super.on(event, listener) } /** * @param {string} event * @param {(...args: any[]) => void} listener * @returns {this} */ addListener (event, listener) { return this.on(event, listener) } /** * @param {string|symbol} event * @param {(...args: any[]) => void} listener * @returns {this} */ off (event, listener) { const ret = super.off(event, listener) if (event === 'data' || event === 'readable') { this[kReading] = ( this.listenerCount('data') > 0 || this.listenerCount('readable') > 0 ) } return ret } /** * @param {string|symbol} event * @param {(...args: any[]) => void} listener * @returns {this} */ removeListener (event, listener) { return this.off(event, listener) } /** * @param {Buffer|null} chunk * @returns {boolean} */ push (chunk) { this[kBytesRead] += chunk ? chunk.length : 0 if (this[kConsume] && chunk !== null) { consumePush(this[kConsume], chunk) return this[kReading] ? super.push(chunk) : true } return super.push(chunk) } /** * Consumes and returns the body as a string. * * @see https://fetch.spec.whatwg.org/#dom-body-text * @returns {Promise} */ text () { return consume(this, 'text') } /** * Consumes and returns the body as a JavaScript Object. * * @see https://fetch.spec.whatwg.org/#dom-body-json * @returns {Promise} */ json () { return consume(this, 'json') } /** * Consumes and returns the body as a Blob * * @see https://fetch.spec.whatwg.org/#dom-body-blob * @returns {Promise} */ blob () { return consume(this, 'blob') } /** * Consumes and returns the body as an Uint8Array. * * @see https://fetch.spec.whatwg.org/#dom-body-bytes * @returns {Promise} */ bytes () { return consume(this, 'bytes') } /** * Consumes and returns the body as an ArrayBuffer. * * @see https://fetch.spec.whatwg.org/#dom-body-arraybuffer * @returns {Promise} */ arrayBuffer () { return consume(this, 'arrayBuffer') } /** * Not implemented * * @see https://fetch.spec.whatwg.org/#dom-body-formdata * @throws {NotSupportedError} */ async formData () { // TODO: Implement. throw new NotSupportedError() } /** * Returns true if the body is not null and the body has been consumed. * Otherwise, returns false. * * @see https://fetch.spec.whatwg.org/#dom-body-bodyused * @readonly * @returns {boolean} */ get bodyUsed () { return util.isDisturbed(this) } /** * @see https://fetch.spec.whatwg.org/#dom-body-body * @readonly * @returns {ReadableStream} */ get body () { if (!this[kBody]) { this[kBody] = ReadableStreamFrom(this) if (this[kConsume]) { // TODO: Is this the best way to force a lock? this[kBody].getReader() // Ensure stream is locked. assert(this[kBody].locked) } } return this[kBody] } /** * Dumps the response body by reading `limit` number of bytes. * @param {object} opts * @param {number} [opts.limit = 131072] Number of bytes to read. * @param {AbortSignal} [opts.signal] An AbortSignal to cancel the dump. * @returns {Promise} */ async dump (opts) { const signal = opts?.signal if (signal != null && (typeof signal !== 'object' || !('aborted' in signal))) { throw new InvalidArgumentError('signal must be an AbortSignal') } const limit = opts?.limit && Number.isFinite(opts.limit) ? opts.limit : 128 * 1024 signal?.throwIfAborted() if (this._readableState.closeEmitted) { return null } return await new Promise((resolve, reject) => { if ( (this[kContentLength] && (this[kContentLength] > limit)) || this[kBytesRead] > limit ) { this.destroy(new AbortError()) } if (signal) { const onAbort = () => { this.destroy(signal.reason ?? new AbortError()) } signal.addEventListener('abort', onAbort) this .on('close', function () { signal.removeEventListener('abort', onAbort) if (signal.aborted) { reject(signal.reason ?? new AbortError()) } else { resolve(null) } }) } else { this.on('close', resolve) } this .on('error', noop) .on('data', () => { if (this[kBytesRead] > limit) { this.destroy() } }) .resume() }) } /** * @param {BufferEncoding} encoding * @returns {this} */ setEncoding (encoding) { if (Buffer.isEncoding(encoding)) { this._readableState.encoding = encoding } return this } } /** * @see https://streams.spec.whatwg.org/#readablestream-locked * @param {BodyReadable} bodyReadable * @returns {boolean} */ function isLocked (bodyReadable) { // Consume is an implicit lock. return bodyReadable[kBody]?.locked === true || bodyReadable[kConsume] !== null } /** * @see https://fetch.spec.whatwg.org/#body-unusable * @param {BodyReadable} bodyReadable * @returns {boolean} */ function isUnusable (bodyReadable) { return util.isDisturbed(bodyReadable) || isLocked(bodyReadable) } /** * @typedef {object} Consume * @property {string} type * @property {BodyReadable} stream * @property {((value?: any) => void)} resolve * @property {((err: Error) => void)} reject * @property {number} length * @property {Buffer[]} body */ /** * @param {BodyReadable} stream * @param {string} type * @returns {Promise} */ function consume (stream, type) { assert(!stream[kConsume]) return new Promise((resolve, reject) => { if (isUnusable(stream)) { const rState = stream._readableState if (rState.destroyed && rState.closeEmitted === false) { stream .on('error', err => { reject(err) }) .on('close', () => { reject(new TypeError('unusable')) }) } else { reject(rState.errored ?? new TypeError('unusable')) } } else { queueMicrotask(() => { stream[kConsume] = { type, stream, resolve, reject, length: 0, body: [] } stream .on('error', function (err) { consumeFinish(this[kConsume], err) }) .on('close', function () { if (this[kConsume].body !== null) { consumeFinish(this[kConsume], new RequestAbortedError()) } }) consumeStart(stream[kConsume]) }) } }) } /** * @param {Consume} consume * @returns {void} */ function consumeStart (consume) { if (consume.body === null) { return } const { _readableState: state } = consume.stream if (state.bufferIndex) { const start = state.bufferIndex const end = state.buffer.length for (let n = start; n < end; n++) { consumePush(consume, state.buffer[n]) } } else { for (const chunk of state.buffer) { consumePush(consume, chunk) } } if (state.endEmitted) { consumeEnd(this[kConsume], this._readableState.encoding) } else { consume.stream.on('end', function () { consumeEnd(this[kConsume], this._readableState.encoding) }) } consume.stream.resume() while (consume.stream.read() != null) { // Loop } } /** * @param {Buffer[]} chunks * @param {number} length * @param {BufferEncoding} encoding * @returns {string} */ function chunksDecode (chunks, length, encoding) { if (chunks.length === 0 || length === 0) { return '' } const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length) const bufferLength = buffer.length // Skip BOM. const start = bufferLength > 2 && buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf ? 3 : 0 if (!encoding || encoding === 'utf8' || encoding === 'utf-8') { return buffer.utf8Slice(start, bufferLength) } else { return buffer.subarray(start, bufferLength).toString(encoding) } } /** * @param {Buffer[]} chunks * @param {number} length * @returns {Uint8Array} */ function chunksConcat (chunks, length) { if (chunks.length === 0 || length === 0) { return new Uint8Array(0) } if (chunks.length === 1) { // fast-path return new Uint8Array(chunks[0]) } const buffer = new Uint8Array(Buffer.allocUnsafeSlow(length).buffer) let offset = 0 for (let i = 0; i < chunks.length; ++i) { const chunk = chunks[i] buffer.set(chunk, offset) offset += chunk.length } return buffer } /** * @param {Consume} consume * @param {BufferEncoding} encoding * @returns {void} */ function consumeEnd (consume, encoding) { const { type, body, resolve, stream, length } = consume try { if (type === 'text') { resolve(chunksDecode(body, length, encoding)) } else if (type === 'json') { resolve(JSON.parse(chunksDecode(body, length, encoding))) } else if (type === 'arrayBuffer') { resolve(chunksConcat(body, length).buffer) } else if (type === 'blob') { resolve(new Blob(body, { type: stream[kContentType] })) } else if (type === 'bytes') { resolve(chunksConcat(body, length)) } consumeFinish(consume) } catch (err) { stream.destroy(err) } } /** * @param {Consume} consume * @param {Buffer} chunk * @returns {void} */ function consumePush (consume, chunk) { consume.length += chunk.length consume.body.push(chunk) } /** * @param {Consume} consume * @param {Error} [err] * @returns {void} */ function consumeFinish (consume, err) { if (consume.body === null) { return } if (err) { consume.reject(err) } else { consume.resolve() } // Reset the consume object to allow for garbage collection. consume.type = null consume.stream = null consume.resolve = null consume.reject = null consume.length = 0 consume.body = null } module.exports = { Readable: BodyReadable, chunksDecode } /***/ }), /***/ 92434: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Writable } = __nccwpck_require__(57075) const { EventEmitter } = __nccwpck_require__(78474) const { assertCacheKey, assertCacheValue } = __nccwpck_require__(27128) /** * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheKey} CacheKey * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheValue} CacheValue * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheStore} CacheStore * @typedef {import('../../types/cache-interceptor.d.ts').default.GetResult} GetResult */ /** * @implements {CacheStore} * @extends {EventEmitter} */ class MemoryCacheStore extends EventEmitter { #maxCount = 1024 #maxSize = 104857600 // 100MB #maxEntrySize = 5242880 // 5MB #size = 0 #count = 0 #entries = new Map() #hasEmittedMaxSizeEvent = false /** * @param {import('../../types/cache-interceptor.d.ts').default.MemoryCacheStoreOpts | undefined} [opts] */ constructor (opts) { super() if (opts) { if (typeof opts !== 'object') { throw new TypeError('MemoryCacheStore options must be an object') } if (opts.maxCount !== undefined) { if ( typeof opts.maxCount !== 'number' || !Number.isInteger(opts.maxCount) || opts.maxCount < 0 ) { throw new TypeError('MemoryCacheStore options.maxCount must be a non-negative integer') } this.#maxCount = opts.maxCount } if (opts.maxSize !== undefined) { if ( typeof opts.maxSize !== 'number' || !Number.isInteger(opts.maxSize) || opts.maxSize < 0 ) { throw new TypeError('MemoryCacheStore options.maxSize must be a non-negative integer') } this.#maxSize = opts.maxSize } if (opts.maxEntrySize !== undefined) { if ( typeof opts.maxEntrySize !== 'number' || !Number.isInteger(opts.maxEntrySize) || opts.maxEntrySize < 0 ) { throw new TypeError('MemoryCacheStore options.maxEntrySize must be a non-negative integer') } this.#maxEntrySize = opts.maxEntrySize } } } /** * Get the current size of the cache in bytes * @returns {number} The current size of the cache in bytes */ get size () { return this.#size } /** * Check if the cache is full (either max size or max count reached) * @returns {boolean} True if the cache is full, false otherwise */ isFull () { return this.#size >= this.#maxSize || this.#count >= this.#maxCount } /** * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} req * @returns {import('../../types/cache-interceptor.d.ts').default.GetResult | undefined} */ get (key) { assertCacheKey(key) const topLevelKey = `${key.origin}:${key.path}` const now = Date.now() const entries = this.#entries.get(topLevelKey) const entry = entries ? findEntry(key, entries, now) : null return entry == null ? undefined : { statusMessage: entry.statusMessage, statusCode: entry.statusCode, headers: entry.headers, body: entry.body, vary: entry.vary ? entry.vary : undefined, etag: entry.etag, cacheControlDirectives: entry.cacheControlDirectives, cachedAt: entry.cachedAt, staleAt: entry.staleAt, deleteAt: entry.deleteAt } } /** * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} val * @returns {Writable | undefined} */ createWriteStream (key, val) { assertCacheKey(key) assertCacheValue(val) const topLevelKey = `${key.origin}:${key.path}` const store = this const entry = { ...key, ...val, body: [], size: 0 } return new Writable({ write (chunk, encoding, callback) { if (typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding) } entry.size += chunk.byteLength if (entry.size >= store.#maxEntrySize) { this.destroy() } else { entry.body.push(chunk) } callback(null) }, final (callback) { let entries = store.#entries.get(topLevelKey) if (!entries) { entries = [] store.#entries.set(topLevelKey, entries) } const previousEntry = findEntry(key, entries, Date.now()) if (previousEntry) { const index = entries.indexOf(previousEntry) entries.splice(index, 1, entry) store.#size -= previousEntry.size } else { entries.push(entry) store.#count += 1 } store.#size += entry.size // Check if cache is full and emit event if needed if (store.#size > store.#maxSize || store.#count > store.#maxCount) { // Emit maxSizeExceeded event if we haven't already if (!store.#hasEmittedMaxSizeEvent) { store.emit('maxSizeExceeded', { size: store.#size, maxSize: store.#maxSize, count: store.#count, maxCount: store.#maxCount }) store.#hasEmittedMaxSizeEvent = true } // Perform eviction for (const [key, entries] of store.#entries) { for (const entry of entries.splice(0, entries.length / 2)) { store.#size -= entry.size store.#count -= 1 } if (entries.length === 0) { store.#entries.delete(key) } } // Reset the event flag after eviction if (store.#size < store.#maxSize && store.#count < store.#maxCount) { store.#hasEmittedMaxSizeEvent = false } } callback(null) } }) } /** * @param {CacheKey} key */ delete (key) { if (typeof key !== 'object') { throw new TypeError(`expected key to be object, got ${typeof key}`) } const topLevelKey = `${key.origin}:${key.path}` for (const entry of this.#entries.get(topLevelKey) ?? []) { this.#size -= entry.size this.#count -= 1 } this.#entries.delete(topLevelKey) } } function findEntry (key, entries, now) { return entries.find((entry) => ( entry.deleteAt > now && entry.method === key.method && (entry.vary == null || Object.keys(entry.vary).every(headerName => { if (entry.vary[headerName] === null) { return key.headers[headerName] === undefined } return entry.vary[headerName] === key.headers[headerName] })) )) } module.exports = MemoryCacheStore /***/ }), /***/ 82005: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Writable } = __nccwpck_require__(57075) const { assertCacheKey, assertCacheValue } = __nccwpck_require__(27128) let DatabaseSync const VERSION = 3 // 2gb const MAX_ENTRY_SIZE = 2 * 1000 * 1000 * 1000 /** * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheStore} CacheStore * @implements {CacheStore} * * @typedef {{ * id: Readonly, * body?: Uint8Array * statusCode: number * statusMessage: string * headers?: string * vary?: string * etag?: string * cacheControlDirectives?: string * cachedAt: number * staleAt: number * deleteAt: number * }} SqliteStoreValue */ module.exports = class SqliteCacheStore { #maxEntrySize = MAX_ENTRY_SIZE #maxCount = Infinity /** * @type {import('node:sqlite').DatabaseSync} */ #db /** * @type {import('node:sqlite').StatementSync} */ #getValuesQuery /** * @type {import('node:sqlite').StatementSync} */ #updateValueQuery /** * @type {import('node:sqlite').StatementSync} */ #insertValueQuery /** * @type {import('node:sqlite').StatementSync} */ #deleteExpiredValuesQuery /** * @type {import('node:sqlite').StatementSync} */ #deleteByUrlQuery /** * @type {import('node:sqlite').StatementSync} */ #countEntriesQuery /** * @type {import('node:sqlite').StatementSync | null} */ #deleteOldValuesQuery /** * @param {import('../../types/cache-interceptor.d.ts').default.SqliteCacheStoreOpts | undefined} opts */ constructor (opts) { if (opts) { if (typeof opts !== 'object') { throw new TypeError('SqliteCacheStore options must be an object') } if (opts.maxEntrySize !== undefined) { if ( typeof opts.maxEntrySize !== 'number' || !Number.isInteger(opts.maxEntrySize) || opts.maxEntrySize < 0 ) { throw new TypeError('SqliteCacheStore options.maxEntrySize must be a non-negative integer') } if (opts.maxEntrySize > MAX_ENTRY_SIZE) { throw new TypeError('SqliteCacheStore options.maxEntrySize must be less than 2gb') } this.#maxEntrySize = opts.maxEntrySize } if (opts.maxCount !== undefined) { if ( typeof opts.maxCount !== 'number' || !Number.isInteger(opts.maxCount) || opts.maxCount < 0 ) { throw new TypeError('SqliteCacheStore options.maxCount must be a non-negative integer') } this.#maxCount = opts.maxCount } } if (!DatabaseSync) { DatabaseSync = (__nccwpck_require__(80099).DatabaseSync) } this.#db = new DatabaseSync(opts?.location ?? ':memory:') this.#db.exec(` PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA temp_store = memory; PRAGMA optimize; CREATE TABLE IF NOT EXISTS cacheInterceptorV${VERSION} ( -- Data specific to us id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL, method TEXT NOT NULL, -- Data returned to the interceptor body BUF NULL, deleteAt INTEGER NOT NULL, statusCode INTEGER NOT NULL, statusMessage TEXT NOT NULL, headers TEXT NULL, cacheControlDirectives TEXT NULL, etag TEXT NULL, vary TEXT NULL, cachedAt INTEGER NOT NULL, staleAt INTEGER NOT NULL ); CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION}_getValuesQuery ON cacheInterceptorV${VERSION}(url, method, deleteAt); CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION}_deleteByUrlQuery ON cacheInterceptorV${VERSION}(deleteAt); `) this.#getValuesQuery = this.#db.prepare(` SELECT id, body, deleteAt, statusCode, statusMessage, headers, etag, cacheControlDirectives, vary, cachedAt, staleAt FROM cacheInterceptorV${VERSION} WHERE url = ? AND method = ? ORDER BY deleteAt ASC `) this.#updateValueQuery = this.#db.prepare(` UPDATE cacheInterceptorV${VERSION} SET body = ?, deleteAt = ?, statusCode = ?, statusMessage = ?, headers = ?, etag = ?, cacheControlDirectives = ?, cachedAt = ?, staleAt = ? WHERE id = ? `) this.#insertValueQuery = this.#db.prepare(` INSERT INTO cacheInterceptorV${VERSION} ( url, method, body, deleteAt, statusCode, statusMessage, headers, etag, cacheControlDirectives, vary, cachedAt, staleAt ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `) this.#deleteByUrlQuery = this.#db.prepare( `DELETE FROM cacheInterceptorV${VERSION} WHERE url = ?` ) this.#countEntriesQuery = this.#db.prepare( `SELECT COUNT(*) AS total FROM cacheInterceptorV${VERSION}` ) this.#deleteExpiredValuesQuery = this.#db.prepare( `DELETE FROM cacheInterceptorV${VERSION} WHERE deleteAt <= ?` ) this.#deleteOldValuesQuery = this.#maxCount === Infinity ? null : this.#db.prepare(` DELETE FROM cacheInterceptorV${VERSION} WHERE id IN ( SELECT id FROM cacheInterceptorV${VERSION} ORDER BY cachedAt DESC LIMIT ? ) `) } close () { this.#db.close() } /** * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key * @returns {(import('../../types/cache-interceptor.d.ts').default.GetResult & { body?: Buffer }) | undefined} */ get (key) { assertCacheKey(key) const value = this.#findValue(key) return value ? { body: value.body ? Buffer.from(value.body.buffer, value.body.byteOffset, value.body.byteLength) : undefined, statusCode: value.statusCode, statusMessage: value.statusMessage, headers: value.headers ? JSON.parse(value.headers) : undefined, etag: value.etag ? value.etag : undefined, vary: value.vary ? JSON.parse(value.vary) : undefined, cacheControlDirectives: value.cacheControlDirectives ? JSON.parse(value.cacheControlDirectives) : undefined, cachedAt: value.cachedAt, staleAt: value.staleAt, deleteAt: value.deleteAt } : undefined } /** * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue & { body: null | Buffer | Array}} value */ set (key, value) { assertCacheKey(key) const url = this.#makeValueUrl(key) const body = Array.isArray(value.body) ? Buffer.concat(value.body) : value.body const size = body?.byteLength if (size && size > this.#maxEntrySize) { return } const existingValue = this.#findValue(key, true) if (existingValue) { // Updating an existing response, let's overwrite it this.#updateValueQuery.run( body, value.deleteAt, value.statusCode, value.statusMessage, value.headers ? JSON.stringify(value.headers) : null, value.etag ? value.etag : null, value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null, value.cachedAt, value.staleAt, existingValue.id ) } else { this.#prune() // New response, let's insert it this.#insertValueQuery.run( url, key.method, body, value.deleteAt, value.statusCode, value.statusMessage, value.headers ? JSON.stringify(value.headers) : null, value.etag ? value.etag : null, value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null, value.vary ? JSON.stringify(value.vary) : null, value.cachedAt, value.staleAt ) } } /** * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} value * @returns {Writable | undefined} */ createWriteStream (key, value) { assertCacheKey(key) assertCacheValue(value) let size = 0 /** * @type {Buffer[] | null} */ const body = [] const store = this return new Writable({ decodeStrings: true, write (chunk, encoding, callback) { size += chunk.byteLength if (size < store.#maxEntrySize) { body.push(chunk) } else { this.destroy() } callback() }, final (callback) { store.set(key, { ...value, body }) callback() } }) } /** * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key */ delete (key) { if (typeof key !== 'object') { throw new TypeError(`expected key to be object, got ${typeof key}`) } this.#deleteByUrlQuery.run(this.#makeValueUrl(key)) } #prune () { if (Number.isFinite(this.#maxCount) && this.size <= this.#maxCount) { return 0 } { const removed = this.#deleteExpiredValuesQuery.run(Date.now()).changes if (removed) { return removed } } { const removed = this.#deleteOldValuesQuery?.run(Math.max(Math.floor(this.#maxCount * 0.1), 1)).changes if (removed) { return removed } } return 0 } /** * Counts the number of rows in the cache * @returns {Number} */ get size () { const { total } = this.#countEntriesQuery.get() return total } /** * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key * @returns {string} */ #makeValueUrl (key) { return `${key.origin}/${key.path}` } /** * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key * @param {boolean} [canBeExpired=false] * @returns {SqliteStoreValue | undefined} */ #findValue (key, canBeExpired = false) { const url = this.#makeValueUrl(key) const { headers, method } = key /** * @type {SqliteStoreValue[]} */ const values = this.#getValuesQuery.all(url, method) if (values.length === 0) { return undefined } const now = Date.now() for (const value of values) { if (now >= value.deleteAt && !canBeExpired) { return undefined } let matches = true if (value.vary) { const vary = JSON.parse(value.vary) for (const header in vary) { if (!headerValueEquals(headers[header], vary[header])) { matches = false break } } } if (matches) { return value } } return undefined } } /** * @param {string|string[]|null|undefined} lhs * @param {string|string[]|null|undefined} rhs * @returns {boolean} */ function headerValueEquals (lhs, rhs) { if (lhs == null && rhs == null) { return true } if ((lhs == null && rhs != null) || (lhs != null && rhs == null)) { return false } if (Array.isArray(lhs) && Array.isArray(rhs)) { if (lhs.length !== rhs.length) { return false } return lhs.every((x, i) => x === rhs[i]) } return lhs === rhs } /***/ }), /***/ 50815: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const net = __nccwpck_require__(77030) const assert = __nccwpck_require__(34589) const util = __nccwpck_require__(46425) const { InvalidArgumentError } = __nccwpck_require__(21158) let tls // include tls conditionally since it is not always available // TODO: session re-use does not wait for the first // connection to resolve the session and might therefore // resolve the same servername multiple times even when // re-use is enabled. const SessionCache = class WeakSessionCache { constructor (maxCachedSessions) { this._maxCachedSessions = maxCachedSessions this._sessionCache = new Map() this._sessionRegistry = new FinalizationRegistry((key) => { if (this._sessionCache.size < this._maxCachedSessions) { return } const ref = this._sessionCache.get(key) if (ref !== undefined && ref.deref() === undefined) { this._sessionCache.delete(key) } }) } get (sessionKey) { const ref = this._sessionCache.get(sessionKey) return ref ? ref.deref() : null } set (sessionKey, session) { if (this._maxCachedSessions === 0) { return } this._sessionCache.set(sessionKey, new WeakRef(session)) this._sessionRegistry.register(session, sessionKey) } } function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, session: customSession, ...opts }) { if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) { throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero') } const options = { path: socketPath, ...opts } const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions) timeout = timeout == null ? 10e3 : timeout allowH2 = allowH2 != null ? allowH2 : false return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { let socket if (protocol === 'https:') { if (!tls) { tls = __nccwpck_require__(41692) } servername = servername || options.servername || util.getServerName(host) || null const sessionKey = servername || hostname assert(sessionKey) const session = customSession || sessionCache.get(sessionKey) || null port = port || 443 socket = tls.connect({ highWaterMark: 16384, // TLS in node can't have bigger HWM anyway... ...options, servername, session, localAddress, ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'], socket: httpSocket, // upgrade socket connection port, host: hostname }) socket .on('session', function (session) { // TODO (fix): Can a session become invalid once established? Don't think so? sessionCache.set(sessionKey, session) }) } else { assert(!httpSocket, 'httpSocket can only be sent on TLS update') port = port || 80 socket = net.connect({ highWaterMark: 64 * 1024, // Same as nodejs fs streams. ...options, localAddress, port, host: hostname }) } // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket if (options.keepAlive == null || options.keepAlive) { const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay socket.setKeepAlive(true, keepAliveInitialDelay) } const clearConnectTimeout = util.setupConnectTimeout(new WeakRef(socket), { timeout, hostname, port }) socket .setNoDelay(true) .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { queueMicrotask(clearConnectTimeout) if (callback) { const cb = callback callback = null cb(null, this) } }) .on('error', function (err) { queueMicrotask(clearConnectTimeout) if (callback) { const cb = callback callback = null cb(err) } }) return socket } } module.exports = buildConnector /***/ }), /***/ 77432: /***/ ((module) => { "use strict"; /** * @see https://developer.mozilla.org/docs/Web/HTTP/Headers */ const wellknownHeaderNames = /** @type {const} */ ([ 'Accept', 'Accept-Encoding', 'Accept-Language', 'Accept-Ranges', 'Access-Control-Allow-Credentials', 'Access-Control-Allow-Headers', 'Access-Control-Allow-Methods', 'Access-Control-Allow-Origin', 'Access-Control-Expose-Headers', 'Access-Control-Max-Age', 'Access-Control-Request-Headers', 'Access-Control-Request-Method', 'Age', 'Allow', 'Alt-Svc', 'Alt-Used', 'Authorization', 'Cache-Control', 'Clear-Site-Data', 'Connection', 'Content-Disposition', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-Location', 'Content-Range', 'Content-Security-Policy', 'Content-Security-Policy-Report-Only', 'Content-Type', 'Cookie', 'Cross-Origin-Embedder-Policy', 'Cross-Origin-Opener-Policy', 'Cross-Origin-Resource-Policy', 'Date', 'Device-Memory', 'Downlink', 'ECT', 'ETag', 'Expect', 'Expect-CT', 'Expires', 'Forwarded', 'From', 'Host', 'If-Match', 'If-Modified-Since', 'If-None-Match', 'If-Range', 'If-Unmodified-Since', 'Keep-Alive', 'Last-Modified', 'Link', 'Location', 'Max-Forwards', 'Origin', 'Permissions-Policy', 'Pragma', 'Proxy-Authenticate', 'Proxy-Authorization', 'RTT', 'Range', 'Referer', 'Referrer-Policy', 'Refresh', 'Retry-After', 'Sec-WebSocket-Accept', 'Sec-WebSocket-Extensions', 'Sec-WebSocket-Key', 'Sec-WebSocket-Protocol', 'Sec-WebSocket-Version', 'Server', 'Server-Timing', 'Service-Worker-Allowed', 'Service-Worker-Navigation-Preload', 'Set-Cookie', 'SourceMap', 'Strict-Transport-Security', 'Supports-Loading-Mode', 'TE', 'Timing-Allow-Origin', 'Trailer', 'Transfer-Encoding', 'Upgrade', 'Upgrade-Insecure-Requests', 'User-Agent', 'Vary', 'Via', 'WWW-Authenticate', 'X-Content-Type-Options', 'X-DNS-Prefetch-Control', 'X-Frame-Options', 'X-Permitted-Cross-Domain-Policies', 'X-Powered-By', 'X-Requested-With', 'X-XSS-Protection' ]) /** @type {Record, string>} */ const headerNameLowerCasedRecord = {} // Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. Object.setPrototypeOf(headerNameLowerCasedRecord, null) /** * @type {Record, Buffer>} */ const wellknownHeaderNameBuffers = {} // Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. Object.setPrototypeOf(wellknownHeaderNameBuffers, null) /** * @param {string} header Lowercased header * @returns {Buffer} */ function getHeaderNameAsBuffer (header) { let buffer = wellknownHeaderNameBuffers[header] if (buffer === undefined) { buffer = Buffer.from(header) } return buffer } for (let i = 0; i < wellknownHeaderNames.length; ++i) { const key = wellknownHeaderNames[i] const lowerCasedKey = key.toLowerCase() headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = lowerCasedKey } module.exports = { wellknownHeaderNames, headerNameLowerCasedRecord, getHeaderNameAsBuffer } /***/ }), /***/ 69709: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const diagnosticsChannel = __nccwpck_require__(53053) const util = __nccwpck_require__(57975) const undiciDebugLog = util.debuglog('undici') const fetchDebuglog = util.debuglog('fetch') const websocketDebuglog = util.debuglog('websocket') const channels = { // Client beforeConnect: diagnosticsChannel.channel('undici:client:beforeConnect'), connected: diagnosticsChannel.channel('undici:client:connected'), connectError: diagnosticsChannel.channel('undici:client:connectError'), sendHeaders: diagnosticsChannel.channel('undici:client:sendHeaders'), // Request create: diagnosticsChannel.channel('undici:request:create'), bodySent: diagnosticsChannel.channel('undici:request:bodySent'), bodyChunkSent: diagnosticsChannel.channel('undici:request:bodyChunkSent'), bodyChunkReceived: diagnosticsChannel.channel('undici:request:bodyChunkReceived'), headers: diagnosticsChannel.channel('undici:request:headers'), trailers: diagnosticsChannel.channel('undici:request:trailers'), error: diagnosticsChannel.channel('undici:request:error'), // WebSocket open: diagnosticsChannel.channel('undici:websocket:open'), close: diagnosticsChannel.channel('undici:websocket:close'), socketError: diagnosticsChannel.channel('undici:websocket:socket_error'), ping: diagnosticsChannel.channel('undici:websocket:ping'), pong: diagnosticsChannel.channel('undici:websocket:pong') } let isTrackingClientEvents = false function trackClientEvents (debugLog = undiciDebugLog) { if (isTrackingClientEvents) { return } isTrackingClientEvents = true diagnosticsChannel.subscribe('undici:client:beforeConnect', evt => { const { connectParams: { version, protocol, port, host } } = evt debugLog( 'connecting to %s%s using %s%s', host, port ? `:${port}` : '', protocol, version ) }) diagnosticsChannel.subscribe('undici:client:connected', evt => { const { connectParams: { version, protocol, port, host } } = evt debugLog( 'connected to %s%s using %s%s', host, port ? `:${port}` : '', protocol, version ) }) diagnosticsChannel.subscribe('undici:client:connectError', evt => { const { connectParams: { version, protocol, port, host }, error } = evt debugLog( 'connection to %s%s using %s%s errored - %s', host, port ? `:${port}` : '', protocol, version, error.message ) }) diagnosticsChannel.subscribe('undici:client:sendHeaders', evt => { const { request: { method, path, origin } } = evt debugLog('sending request to %s %s%s', method, origin, path) }) } let isTrackingRequestEvents = false function trackRequestEvents (debugLog = undiciDebugLog) { if (isTrackingRequestEvents) { return } isTrackingRequestEvents = true diagnosticsChannel.subscribe('undici:request:headers', evt => { const { request: { method, path, origin }, response: { statusCode } } = evt debugLog( 'received response to %s %s%s - HTTP %d', method, origin, path, statusCode ) }) diagnosticsChannel.subscribe('undici:request:trailers', evt => { const { request: { method, path, origin } } = evt debugLog('trailers received from %s %s%s', method, origin, path) }) diagnosticsChannel.subscribe('undici:request:error', evt => { const { request: { method, path, origin }, error } = evt debugLog( 'request to %s %s%s errored - %s', method, origin, path, error.message ) }) } let isTrackingWebSocketEvents = false function trackWebSocketEvents (debugLog = websocketDebuglog) { if (isTrackingWebSocketEvents) { return } isTrackingWebSocketEvents = true diagnosticsChannel.subscribe('undici:websocket:open', evt => { const { address: { address, port } } = evt debugLog('connection opened %s%s', address, port ? `:${port}` : '') }) diagnosticsChannel.subscribe('undici:websocket:close', evt => { const { websocket, code, reason } = evt debugLog( 'closed connection to %s - %s %s', websocket.url, code, reason ) }) diagnosticsChannel.subscribe('undici:websocket:socket_error', err => { debugLog('connection errored - %s', err.message) }) diagnosticsChannel.subscribe('undici:websocket:ping', evt => { debugLog('ping received') }) diagnosticsChannel.subscribe('undici:websocket:pong', evt => { debugLog('pong received') }) } if (undiciDebugLog.enabled || fetchDebuglog.enabled) { trackClientEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog) trackRequestEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog) } if (websocketDebuglog.enabled) { trackClientEvents(undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog) trackWebSocketEvents(websocketDebuglog) } module.exports = { channels } /***/ }), /***/ 21158: /***/ ((module) => { "use strict"; class UndiciError extends Error { constructor (message, options) { super(message, options) this.name = 'UndiciError' this.code = 'UND_ERR' } } class ConnectTimeoutError extends UndiciError { constructor (message) { super(message) this.name = 'ConnectTimeoutError' this.message = message || 'Connect Timeout Error' this.code = 'UND_ERR_CONNECT_TIMEOUT' } } class HeadersTimeoutError extends UndiciError { constructor (message) { super(message) this.name = 'HeadersTimeoutError' this.message = message || 'Headers Timeout Error' this.code = 'UND_ERR_HEADERS_TIMEOUT' } } class HeadersOverflowError extends UndiciError { constructor (message) { super(message) this.name = 'HeadersOverflowError' this.message = message || 'Headers Overflow Error' this.code = 'UND_ERR_HEADERS_OVERFLOW' } } class BodyTimeoutError extends UndiciError { constructor (message) { super(message) this.name = 'BodyTimeoutError' this.message = message || 'Body Timeout Error' this.code = 'UND_ERR_BODY_TIMEOUT' } } class ResponseStatusCodeError extends UndiciError { constructor (message, statusCode, headers, body) { super(message) this.name = 'ResponseStatusCodeError' this.message = message || 'Response Status Code Error' this.code = 'UND_ERR_RESPONSE_STATUS_CODE' this.body = body this.status = statusCode this.statusCode = statusCode this.headers = headers } } class InvalidArgumentError extends UndiciError { constructor (message) { super(message) this.name = 'InvalidArgumentError' this.message = message || 'Invalid Argument Error' this.code = 'UND_ERR_INVALID_ARG' } } class InvalidReturnValueError extends UndiciError { constructor (message) { super(message) this.name = 'InvalidReturnValueError' this.message = message || 'Invalid Return Value Error' this.code = 'UND_ERR_INVALID_RETURN_VALUE' } } class AbortError extends UndiciError { constructor (message) { super(message) this.name = 'AbortError' this.message = message || 'The operation was aborted' } } class RequestAbortedError extends AbortError { constructor (message) { super(message) this.name = 'AbortError' this.message = message || 'Request aborted' this.code = 'UND_ERR_ABORTED' } } class InformationalError extends UndiciError { constructor (message) { super(message) this.name = 'InformationalError' this.message = message || 'Request information' this.code = 'UND_ERR_INFO' } } class RequestContentLengthMismatchError extends UndiciError { constructor (message) { super(message) this.name = 'RequestContentLengthMismatchError' this.message = message || 'Request body length does not match content-length header' this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' } } class ResponseContentLengthMismatchError extends UndiciError { constructor (message) { super(message) this.name = 'ResponseContentLengthMismatchError' this.message = message || 'Response body length does not match content-length header' this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' } } class ClientDestroyedError extends UndiciError { constructor (message) { super(message) this.name = 'ClientDestroyedError' this.message = message || 'The client is destroyed' this.code = 'UND_ERR_DESTROYED' } } class ClientClosedError extends UndiciError { constructor (message) { super(message) this.name = 'ClientClosedError' this.message = message || 'The client is closed' this.code = 'UND_ERR_CLOSED' } } class SocketError extends UndiciError { constructor (message, socket) { super(message) this.name = 'SocketError' this.message = message || 'Socket error' this.code = 'UND_ERR_SOCKET' this.socket = socket } } class NotSupportedError extends UndiciError { constructor (message) { super(message) this.name = 'NotSupportedError' this.message = message || 'Not supported error' this.code = 'UND_ERR_NOT_SUPPORTED' } } class BalancedPoolMissingUpstreamError extends UndiciError { constructor (message) { super(message) this.name = 'MissingUpstreamError' this.message = message || 'No upstream has been added to the BalancedPool' this.code = 'UND_ERR_BPL_MISSING_UPSTREAM' } } class HTTPParserError extends Error { constructor (message, code, data) { super(message) this.name = 'HTTPParserError' this.code = code ? `HPE_${code}` : undefined this.data = data ? data.toString() : undefined } } class ResponseExceededMaxSizeError extends UndiciError { constructor (message) { super(message) this.name = 'ResponseExceededMaxSizeError' this.message = message || 'Response content exceeded max size' this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE' } } class RequestRetryError extends UndiciError { constructor (message, code, { headers, data }) { super(message) this.name = 'RequestRetryError' this.message = message || 'Request retry error' this.code = 'UND_ERR_REQ_RETRY' this.statusCode = code this.data = data this.headers = headers } } class ResponseError extends UndiciError { constructor (message, code, { headers, body }) { super(message) this.name = 'ResponseError' this.message = message || 'Response error' this.code = 'UND_ERR_RESPONSE' this.statusCode = code this.body = body this.headers = headers } } class SecureProxyConnectionError extends UndiciError { constructor (cause, message, options = {}) { super(message, { cause, ...options }) this.name = 'SecureProxyConnectionError' this.message = message || 'Secure Proxy Connection failed' this.code = 'UND_ERR_PRX_TLS' this.cause = cause } } module.exports = { AbortError, HTTPParserError, UndiciError, HeadersTimeoutError, HeadersOverflowError, BodyTimeoutError, RequestContentLengthMismatchError, ConnectTimeoutError, ResponseStatusCodeError, InvalidArgumentError, InvalidReturnValueError, RequestAbortedError, ClientDestroyedError, ClientClosedError, InformationalError, SocketError, NotSupportedError, ResponseContentLengthMismatchError, BalancedPoolMissingUpstreamError, ResponseExceededMaxSizeError, RequestRetryError, ResponseError, SecureProxyConnectionError } /***/ }), /***/ 53172: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { InvalidArgumentError, NotSupportedError } = __nccwpck_require__(21158) const assert = __nccwpck_require__(34589) const { isValidHTTPToken, isValidHeaderValue, isStream, destroy, isBuffer, isFormDataLike, isIterable, isBlobLike, serializePathWithQuery, assertRequestHandler, getServerName, normalizedMethodRecords } = __nccwpck_require__(46425) const { channels } = __nccwpck_require__(69709) const { headerNameLowerCasedRecord } = __nccwpck_require__(77432) // Verifies that a given path is valid does not contain control chars \x00 to \x20 const invalidPathRegex = /[^\u0021-\u00ff]/ const kHandler = Symbol('handler') class Request { constructor (origin, { path, method, body, headers, query, idempotent, blocking, upgrade, headersTimeout, bodyTimeout, reset, expectContinue, servername, throwOnError, maxRedirections }, handler) { if (typeof path !== 'string') { throw new InvalidArgumentError('path must be a string') } else if ( path[0] !== '/' && !(path.startsWith('http://') || path.startsWith('https://')) && method !== 'CONNECT' ) { throw new InvalidArgumentError('path must be an absolute URL or start with a slash') } else if (invalidPathRegex.test(path)) { throw new InvalidArgumentError('invalid request path') } if (typeof method !== 'string') { throw new InvalidArgumentError('method must be a string') } else if (normalizedMethodRecords[method] === undefined && !isValidHTTPToken(method)) { throw new InvalidArgumentError('invalid request method') } if (upgrade && typeof upgrade !== 'string') { throw new InvalidArgumentError('upgrade must be a string') } if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { throw new InvalidArgumentError('invalid headersTimeout') } if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { throw new InvalidArgumentError('invalid bodyTimeout') } if (reset != null && typeof reset !== 'boolean') { throw new InvalidArgumentError('invalid reset') } if (expectContinue != null && typeof expectContinue !== 'boolean') { throw new InvalidArgumentError('invalid expectContinue') } if (throwOnError != null) { throw new InvalidArgumentError('invalid throwOnError') } if (maxRedirections != null && maxRedirections !== 0) { throw new InvalidArgumentError('maxRedirections is not supported, use the redirect interceptor') } this.headersTimeout = headersTimeout this.bodyTimeout = bodyTimeout this.method = method this.abort = null if (body == null) { this.body = null } else if (isStream(body)) { this.body = body const rState = this.body._readableState if (!rState || !rState.autoDestroy) { this.endHandler = function autoDestroy () { destroy(this) } this.body.on('end', this.endHandler) } this.errorHandler = err => { if (this.abort) { this.abort(err) } else { this.error = err } } this.body.on('error', this.errorHandler) } else if (isBuffer(body)) { this.body = body.byteLength ? body : null } else if (ArrayBuffer.isView(body)) { this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null } else if (body instanceof ArrayBuffer) { this.body = body.byteLength ? Buffer.from(body) : null } else if (typeof body === 'string') { this.body = body.length ? Buffer.from(body) : null } else if (isFormDataLike(body) || isIterable(body) || isBlobLike(body)) { this.body = body } else { throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable') } this.completed = false this.aborted = false this.upgrade = upgrade || null this.path = query ? serializePathWithQuery(path, query) : path this.origin = origin this.idempotent = idempotent == null ? method === 'HEAD' || method === 'GET' : idempotent this.blocking = blocking ?? this.method !== 'HEAD' this.reset = reset == null ? null : reset this.host = null this.contentLength = null this.contentType = null this.headers = [] // Only for H2 this.expectContinue = expectContinue != null ? expectContinue : false if (Array.isArray(headers)) { if (headers.length % 2 !== 0) { throw new InvalidArgumentError('headers array must be even') } for (let i = 0; i < headers.length; i += 2) { processHeader(this, headers[i], headers[i + 1]) } } else if (headers && typeof headers === 'object') { if (headers[Symbol.iterator]) { for (const header of headers) { if (!Array.isArray(header) || header.length !== 2) { throw new InvalidArgumentError('headers must be in key-value pair format') } processHeader(this, header[0], header[1]) } } else { const keys = Object.keys(headers) for (let i = 0; i < keys.length; ++i) { processHeader(this, keys[i], headers[keys[i]]) } } } else if (headers != null) { throw new InvalidArgumentError('headers must be an object or an array') } assertRequestHandler(handler, method, upgrade) this.servername = servername || getServerName(this.host) || null this[kHandler] = handler if (channels.create.hasSubscribers) { channels.create.publish({ request: this }) } } onBodySent (chunk) { if (channels.bodyChunkSent.hasSubscribers) { channels.bodyChunkSent.publish({ request: this, chunk }) } if (this[kHandler].onBodySent) { try { return this[kHandler].onBodySent(chunk) } catch (err) { this.abort(err) } } } onRequestSent () { if (channels.bodySent.hasSubscribers) { channels.bodySent.publish({ request: this }) } if (this[kHandler].onRequestSent) { try { return this[kHandler].onRequestSent() } catch (err) { this.abort(err) } } } onConnect (abort) { assert(!this.aborted) assert(!this.completed) if (this.error) { abort(this.error) } else { this.abort = abort return this[kHandler].onConnect(abort) } } onResponseStarted () { return this[kHandler].onResponseStarted?.() } onHeaders (statusCode, headers, resume, statusText) { assert(!this.aborted) assert(!this.completed) if (channels.headers.hasSubscribers) { channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) } try { return this[kHandler].onHeaders(statusCode, headers, resume, statusText) } catch (err) { this.abort(err) } } onData (chunk) { assert(!this.aborted) assert(!this.completed) if (channels.bodyChunkReceived.hasSubscribers) { channels.bodyChunkReceived.publish({ request: this, chunk }) } try { return this[kHandler].onData(chunk) } catch (err) { this.abort(err) return false } } onUpgrade (statusCode, headers, socket) { assert(!this.aborted) assert(!this.completed) return this[kHandler].onUpgrade(statusCode, headers, socket) } onComplete (trailers) { this.onFinally() assert(!this.aborted) assert(!this.completed) this.completed = true if (channels.trailers.hasSubscribers) { channels.trailers.publish({ request: this, trailers }) } try { return this[kHandler].onComplete(trailers) } catch (err) { // TODO (fix): This might be a bad idea? this.onError(err) } } onError (error) { this.onFinally() if (channels.error.hasSubscribers) { channels.error.publish({ request: this, error }) } if (this.aborted) { return } this.aborted = true return this[kHandler].onError(error) } onFinally () { if (this.errorHandler) { this.body.off('error', this.errorHandler) this.errorHandler = null } if (this.endHandler) { this.body.off('end', this.endHandler) this.endHandler = null } } addHeader (key, value) { processHeader(this, key, value) return this } } function processHeader (request, key, val) { if (val && (typeof val === 'object' && !Array.isArray(val))) { throw new InvalidArgumentError(`invalid ${key} header`) } else if (val === undefined) { return } let headerName = headerNameLowerCasedRecord[key] if (headerName === undefined) { headerName = key.toLowerCase() if (headerNameLowerCasedRecord[headerName] === undefined && !isValidHTTPToken(headerName)) { throw new InvalidArgumentError('invalid header key') } } if (Array.isArray(val)) { const arr = [] for (let i = 0; i < val.length; i++) { if (typeof val[i] === 'string') { if (!isValidHeaderValue(val[i])) { throw new InvalidArgumentError(`invalid ${key} header`) } arr.push(val[i]) } else if (val[i] === null) { arr.push('') } else if (typeof val[i] === 'object') { throw new InvalidArgumentError(`invalid ${key} header`) } else { arr.push(`${val[i]}`) } } val = arr } else if (typeof val === 'string') { if (!isValidHeaderValue(val)) { throw new InvalidArgumentError(`invalid ${key} header`) } } else if (val === null) { val = '' } else { val = `${val}` } if (request.host === null && headerName === 'host') { if (typeof val !== 'string') { throw new InvalidArgumentError('invalid host header') } // Consumed by Client request.host = val } else if (request.contentLength === null && headerName === 'content-length') { request.contentLength = parseInt(val, 10) if (!Number.isFinite(request.contentLength)) { throw new InvalidArgumentError('invalid content-length header') } } else if (request.contentType === null && headerName === 'content-type') { request.contentType = val request.headers.push(key, val) } else if (headerName === 'transfer-encoding' || headerName === 'keep-alive' || headerName === 'upgrade') { throw new InvalidArgumentError(`invalid ${headerName} header`) } else if (headerName === 'connection') { const value = typeof val === 'string' ? val.toLowerCase() : null if (value !== 'close' && value !== 'keep-alive') { throw new InvalidArgumentError('invalid connection header') } if (value === 'close') { request.reset = true } } else if (headerName === 'expect') { throw new NotSupportedError('expect header not supported') } else { request.headers.push(key, val) } } module.exports = Request /***/ }), /***/ 83112: /***/ ((module) => { "use strict"; module.exports = { kClose: Symbol('close'), kDestroy: Symbol('destroy'), kDispatch: Symbol('dispatch'), kUrl: Symbol('url'), kWriting: Symbol('writing'), kResuming: Symbol('resuming'), kQueue: Symbol('queue'), kConnect: Symbol('connect'), kConnecting: Symbol('connecting'), kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), kKeepAliveTimeoutValue: Symbol('keep alive timeout'), kKeepAlive: Symbol('keep alive'), kHeadersTimeout: Symbol('headers timeout'), kBodyTimeout: Symbol('body timeout'), kServerName: Symbol('server name'), kLocalAddress: Symbol('local address'), kHost: Symbol('host'), kNoRef: Symbol('no ref'), kBodyUsed: Symbol('used'), kBody: Symbol('abstracted request body'), kRunning: Symbol('running'), kBlocking: Symbol('blocking'), kPending: Symbol('pending'), kSize: Symbol('size'), kBusy: Symbol('busy'), kQueued: Symbol('queued'), kFree: Symbol('free'), kConnected: Symbol('connected'), kClosed: Symbol('closed'), kNeedDrain: Symbol('need drain'), kReset: Symbol('reset'), kDestroyed: Symbol.for('nodejs.stream.destroyed'), kResume: Symbol('resume'), kOnError: Symbol('on error'), kMaxHeadersSize: Symbol('max headers size'), kRunningIdx: Symbol('running index'), kPendingIdx: Symbol('pending index'), kError: Symbol('error'), kClients: Symbol('clients'), kClient: Symbol('client'), kParser: Symbol('parser'), kOnDestroyed: Symbol('destroy callbacks'), kPipelining: Symbol('pipelining'), kSocket: Symbol('socket'), kHostHeader: Symbol('host header'), kConnector: Symbol('connector'), kStrictContentLength: Symbol('strict content length'), kMaxRedirections: Symbol('maxRedirections'), kMaxRequests: Symbol('maxRequestsPerClient'), kProxy: Symbol('proxy agent options'), kCounter: Symbol('socket request counter'), kMaxResponseSize: Symbol('max response size'), kHTTP2Session: Symbol('http2Session'), kHTTP2SessionState: Symbol('http2Session state'), kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), kConstruct: Symbol('constructable'), kListeners: Symbol('listeners'), kHTTPContext: Symbol('http context'), kMaxConcurrentStreams: Symbol('max concurrent streams'), kNoProxyAgent: Symbol('no proxy agent'), kHttpProxyAgent: Symbol('http proxy agent'), kHttpsProxyAgent: Symbol('https proxy agent') } /***/ }), /***/ 53105: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { wellknownHeaderNames, headerNameLowerCasedRecord } = __nccwpck_require__(77432) class TstNode { /** @type {any} */ value = null /** @type {null | TstNode} */ left = null /** @type {null | TstNode} */ middle = null /** @type {null | TstNode} */ right = null /** @type {number} */ code /** * @param {string} key * @param {any} value * @param {number} index */ constructor (key, value, index) { if (index === undefined || index >= key.length) { throw new TypeError('Unreachable') } const code = this.code = key.charCodeAt(index) // check code is ascii string if (code > 0x7F) { throw new TypeError('key must be ascii string') } if (key.length !== ++index) { this.middle = new TstNode(key, value, index) } else { this.value = value } } /** * @param {string} key * @param {any} value * @returns {void} */ add (key, value) { const length = key.length if (length === 0) { throw new TypeError('Unreachable') } let index = 0 /** * @type {TstNode} */ let node = this while (true) { const code = key.charCodeAt(index) // check code is ascii string if (code > 0x7F) { throw new TypeError('key must be ascii string') } if (node.code === code) { if (length === ++index) { node.value = value break } else if (node.middle !== null) { node = node.middle } else { node.middle = new TstNode(key, value, index) break } } else if (node.code < code) { if (node.left !== null) { node = node.left } else { node.left = new TstNode(key, value, index) break } } else if (node.right !== null) { node = node.right } else { node.right = new TstNode(key, value, index) break } } } /** * @param {Uint8Array} key * @returns {TstNode | null} */ search (key) { const keylength = key.length let index = 0 /** * @type {TstNode|null} */ let node = this while (node !== null && index < keylength) { let code = key[index] // A-Z // First check if it is bigger than 0x5a. // Lowercase letters have higher char codes than uppercase ones. // Also we assume that headers will mostly contain lowercase characters. if (code <= 0x5a && code >= 0x41) { // Lowercase for uppercase. code |= 32 } while (node !== null) { if (code === node.code) { if (keylength === ++index) { // Returns Node since it is the last key. return node } node = node.middle break } node = node.code < code ? node.left : node.right } } return null } } class TernarySearchTree { /** @type {TstNode | null} */ node = null /** * @param {string} key * @param {any} value * @returns {void} * */ insert (key, value) { if (this.node === null) { this.node = new TstNode(key, value, 0) } else { this.node.add(key, value) } } /** * @param {Uint8Array} key * @returns {any} */ lookup (key) { return this.node?.search(key)?.value ?? null } } const tree = new TernarySearchTree() for (let i = 0; i < wellknownHeaderNames.length; ++i) { const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]] tree.insert(key, key) } module.exports = { TernarySearchTree, tree } /***/ }), /***/ 46425: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(34589) const { kDestroyed, kBodyUsed, kListeners, kBody } = __nccwpck_require__(83112) const { IncomingMessage } = __nccwpck_require__(37067) const stream = __nccwpck_require__(57075) const net = __nccwpck_require__(77030) const { Blob } = __nccwpck_require__(4573) const { stringify } = __nccwpck_require__(41792) const { EventEmitter: EE } = __nccwpck_require__(78474) const timers = __nccwpck_require__(5870) const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(21158) const { headerNameLowerCasedRecord } = __nccwpck_require__(77432) const { tree } = __nccwpck_require__(53105) const [nodeMajor, nodeMinor] = process.versions.node.split('.', 2).map(v => Number(v)) class BodyAsyncIterable { constructor (body) { this[kBody] = body this[kBodyUsed] = false } async * [Symbol.asyncIterator] () { assert(!this[kBodyUsed], 'disturbed') this[kBodyUsed] = true yield * this[kBody] } } function noop () {} /** * @param {*} body * @returns {*} */ function wrapRequestBody (body) { if (isStream(body)) { // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp // so that it can be dispatched again? // TODO (fix): Do we need 100-expect support to provide a way to do this properly? if (bodyLength(body) === 0) { body .on('data', function () { assert(false) }) } if (typeof body.readableDidRead !== 'boolean') { body[kBodyUsed] = false EE.prototype.on.call(body, 'data', function () { this[kBodyUsed] = true }) } return body } else if (body && typeof body.pipeTo === 'function') { // TODO (fix): We can't access ReadableStream internal state // to determine whether or not it has been disturbed. This is just // a workaround. return new BodyAsyncIterable(body) } else if ( body && typeof body !== 'string' && !ArrayBuffer.isView(body) && isIterable(body) ) { // TODO: Should we allow re-using iterable if !this.opts.idempotent // or through some other flag? return new BodyAsyncIterable(body) } else { return body } } /** * @param {*} obj * @returns {obj is import('node:stream').Stream} */ function isStream (obj) { return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' } /** * @param {*} object * @returns {object is Blob} * based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License) */ function isBlobLike (object) { if (object === null) { return false } else if (object instanceof Blob) { return true } else if (typeof object !== 'object') { return false } else { const sTag = object[Symbol.toStringTag] return (sTag === 'Blob' || sTag === 'File') && ( ('stream' in object && typeof object.stream === 'function') || ('arrayBuffer' in object && typeof object.arrayBuffer === 'function') ) } } /** * @param {string} url The URL to add the query params to * @param {import('node:querystring').ParsedUrlQueryInput} queryParams The object to serialize into a URL query string * @returns {string} The URL with the query params added */ function serializePathWithQuery (url, queryParams) { if (url.includes('?') || url.includes('#')) { throw new Error('Query params cannot be passed when url already contains "?" or "#".') } const stringified = stringify(queryParams) if (stringified) { url += '?' + stringified } return url } /** * @param {number|string|undefined} port * @returns {boolean} */ function isValidPort (port) { const value = parseInt(port, 10) return ( value === Number(port) && value >= 0 && value <= 65535 ) } /** * Check if the value is a valid http or https prefixed string. * * @param {string} value * @returns {boolean} */ function isHttpOrHttpsPrefixed (value) { return ( value != null && value[0] === 'h' && value[1] === 't' && value[2] === 't' && value[3] === 'p' && ( value[4] === ':' || ( value[4] === 's' && value[5] === ':' ) ) ) } /** * @param {string|URL|Record} url * @returns {URL} */ function parseURL (url) { if (typeof url === 'string') { /** * @type {URL} */ url = new URL(url) if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') } return url } if (!url || typeof url !== 'object') { throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') } if (!(url instanceof URL)) { if (url.port != null && url.port !== '' && isValidPort(url.port) === false) { throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.') } if (url.path != null && typeof url.path !== 'string') { throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') } if (url.pathname != null && typeof url.pathname !== 'string') { throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.') } if (url.hostname != null && typeof url.hostname !== 'string') { throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.') } if (url.origin != null && typeof url.origin !== 'string') { throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.') } if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') } const port = url.port != null ? url.port : (url.protocol === 'https:' ? 443 : 80) let origin = url.origin != null ? url.origin : `${url.protocol || ''}//${url.hostname || ''}:${port}` let path = url.path != null ? url.path : `${url.pathname || ''}${url.search || ''}` if (origin[origin.length - 1] === '/') { origin = origin.slice(0, origin.length - 1) } if (path && path[0] !== '/') { path = `/${path}` } // new URL(path, origin) is unsafe when `path` contains an absolute URL // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL: // If first parameter is a relative URL, second param is required, and will be used as the base URL. // If first parameter is an absolute URL, a given second param will be ignored. return new URL(`${origin}${path}`) } if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') } return url } /** * @param {string|URL|Record} url * @returns {URL} */ function parseOrigin (url) { url = parseURL(url) if (url.pathname !== '/' || url.search || url.hash) { throw new InvalidArgumentError('invalid url') } return url } /** * @param {string} host * @returns {string} */ function getHostname (host) { if (host[0] === '[') { const idx = host.indexOf(']') assert(idx !== -1) return host.substring(1, idx) } const idx = host.indexOf(':') if (idx === -1) return host return host.substring(0, idx) } /** * IP addresses are not valid server names per RFC6066 * Currently, the only server names supported are DNS hostnames * @param {string|null} host * @returns {string|null} */ function getServerName (host) { if (!host) { return null } assert(typeof host === 'string') const servername = getHostname(host) if (net.isIP(servername)) { return '' } return servername } /** * @function * @template T * @param {T} obj * @returns {T} */ function deepClone (obj) { return JSON.parse(JSON.stringify(obj)) } /** * @param {*} obj * @returns {obj is AsyncIterable} */ function isAsyncIterable (obj) { return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') } /** * @param {*} obj * @returns {obj is Iterable} */ function isIterable (obj) { return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) } /** * @param {Blob|Buffer|import ('stream').Stream} body * @returns {number|null} */ function bodyLength (body) { if (body == null) { return 0 } else if (isStream(body)) { const state = body._readableState return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) ? state.length : null } else if (isBlobLike(body)) { return body.size != null ? body.size : null } else if (isBuffer(body)) { return body.byteLength } return null } /** * @param {import ('stream').Stream} body * @returns {boolean} */ function isDestroyed (body) { return body && !!(body.destroyed || body[kDestroyed] || (stream.isDestroyed?.(body))) } /** * @param {import ('stream').Stream} stream * @param {Error} [err] * @returns {void} */ function destroy (stream, err) { if (stream == null || !isStream(stream) || isDestroyed(stream)) { return } if (typeof stream.destroy === 'function') { if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { // See: https://github.com/nodejs/node/pull/38505/files stream.socket = null } stream.destroy(err) } else if (err) { queueMicrotask(() => { stream.emit('error', err) }) } if (stream.destroyed !== true) { stream[kDestroyed] = true } } const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/ /** * @param {string} val * @returns {number | null} */ function parseKeepAliveTimeout (val) { const m = val.match(KEEPALIVE_TIMEOUT_EXPR) return m ? parseInt(m[1], 10) * 1000 : null } /** * Retrieves a header name and returns its lowercase value. * @param {string | Buffer} value Header name * @returns {string} */ function headerNameToString (value) { return typeof value === 'string' ? headerNameLowerCasedRecord[value] ?? value.toLowerCase() : tree.lookup(value) ?? value.toString('latin1').toLowerCase() } /** * Receive the buffer as a string and return its lowercase value. * @param {Buffer} value Header name * @returns {string} */ function bufferToLowerCasedHeaderName (value) { return tree.lookup(value) ?? value.toString('latin1').toLowerCase() } /** * @param {(Buffer | string)[]} headers * @param {Record} [obj] * @returns {Record} */ function parseHeaders (headers, obj) { if (obj === undefined) obj = {} for (let i = 0; i < headers.length; i += 2) { const key = headerNameToString(headers[i]) let val = obj[key] if (val) { if (typeof val === 'string') { val = [val] obj[key] = val } val.push(headers[i + 1].toString('utf8')) } else { const headersValue = headers[i + 1] if (typeof headersValue === 'string') { obj[key] = headersValue } else { obj[key] = Array.isArray(headersValue) ? headersValue.map(x => x.toString('utf8')) : headersValue.toString('utf8') } } } // See https://github.com/nodejs/node/pull/46528 if ('content-length' in obj && 'content-disposition' in obj) { obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1') } return obj } /** * @param {Buffer[]} headers * @returns {string[]} */ function parseRawHeaders (headers) { const headersLength = headers.length /** * @type {string[]} */ const ret = new Array(headersLength) let hasContentLength = false let contentDispositionIdx = -1 let key let val let kLen = 0 for (let n = 0; n < headersLength; n += 2) { key = headers[n] val = headers[n + 1] typeof key !== 'string' && (key = key.toString()) typeof val !== 'string' && (val = val.toString('utf8')) kLen = key.length if (kLen === 14 && key[7] === '-' && (key === 'content-length' || key.toLowerCase() === 'content-length')) { hasContentLength = true } else if (kLen === 19 && key[7] === '-' && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) { contentDispositionIdx = n + 1 } ret[n] = key ret[n + 1] = val } // See https://github.com/nodejs/node/pull/46528 if (hasContentLength && contentDispositionIdx !== -1) { ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1') } return ret } /** * @param {string[]} headers * @param {Buffer[]} headers */ function encodeRawHeaders (headers) { if (!Array.isArray(headers)) { throw new TypeError('expected headers to be an array') } return headers.map(x => Buffer.from(x)) } /** * @param {*} buffer * @returns {buffer is Buffer} */ function isBuffer (buffer) { // See, https://github.com/mcollina/undici/pull/319 return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) } /** * Asserts that the handler object is a request handler. * * @param {object} handler * @param {string} method * @param {string} [upgrade] * @returns {asserts handler is import('../api/api-request').RequestHandler} */ function assertRequestHandler (handler, method, upgrade) { if (!handler || typeof handler !== 'object') { throw new InvalidArgumentError('handler must be an object') } if (typeof handler.onRequestStart === 'function') { // TODO (fix): More checks... return } if (typeof handler.onConnect !== 'function') { throw new InvalidArgumentError('invalid onConnect method') } if (typeof handler.onError !== 'function') { throw new InvalidArgumentError('invalid onError method') } if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { throw new InvalidArgumentError('invalid onBodySent method') } if (upgrade || method === 'CONNECT') { if (typeof handler.onUpgrade !== 'function') { throw new InvalidArgumentError('invalid onUpgrade method') } } else { if (typeof handler.onHeaders !== 'function') { throw new InvalidArgumentError('invalid onHeaders method') } if (typeof handler.onData !== 'function') { throw new InvalidArgumentError('invalid onData method') } if (typeof handler.onComplete !== 'function') { throw new InvalidArgumentError('invalid onComplete method') } } } /** * A body is disturbed if it has been read from and it cannot be re-used without * losing state or data. * @param {import('node:stream').Readable} body * @returns {boolean} */ function isDisturbed (body) { // TODO (fix): Why is body[kBodyUsed] needed? return !!(body && (stream.isDisturbed(body) || body[kBodyUsed])) } /** * @typedef {object} SocketInfo * @property {string} [localAddress] * @property {number} [localPort] * @property {string} [remoteAddress] * @property {number} [remotePort] * @property {string} [remoteFamily] * @property {number} [timeout] * @property {number} bytesWritten * @property {number} bytesRead */ /** * @param {import('net').Socket} socket * @returns {SocketInfo} */ function getSocketInfo (socket) { return { localAddress: socket.localAddress, localPort: socket.localPort, remoteAddress: socket.remoteAddress, remotePort: socket.remotePort, remoteFamily: socket.remoteFamily, timeout: socket.timeout, bytesWritten: socket.bytesWritten, bytesRead: socket.bytesRead } } /** * @param {Iterable} iterable * @returns {ReadableStream} */ function ReadableStreamFrom (iterable) { // We cannot use ReadableStream.from here because it does not return a byte stream. let iterator return new ReadableStream( { async start () { iterator = iterable[Symbol.asyncIterator]() }, pull (controller) { async function pull () { const { done, value } = await iterator.next() if (done) { queueMicrotask(() => { controller.close() controller.byobRequest?.respond(0) }) } else { const buf = Buffer.isBuffer(value) ? value : Buffer.from(value) if (buf.byteLength) { controller.enqueue(new Uint8Array(buf)) } else { return await pull() } } } return pull() }, async cancel () { await iterator.return() }, type: 'bytes' } ) } /** * The object should be a FormData instance and contains all the required * methods. * @param {*} object * @returns {object is FormData} */ function isFormDataLike (object) { return ( object && typeof object === 'object' && typeof object.append === 'function' && typeof object.delete === 'function' && typeof object.get === 'function' && typeof object.getAll === 'function' && typeof object.has === 'function' && typeof object.set === 'function' && object[Symbol.toStringTag] === 'FormData' ) } function addAbortListener (signal, listener) { if ('addEventListener' in signal) { signal.addEventListener('abort', listener, { once: true }) return () => signal.removeEventListener('abort', listener) } signal.once('abort', listener) return () => signal.removeListener('abort', listener) } /** * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 * @param {number} c * @returns {boolean} */ function isTokenCharCode (c) { switch (c) { case 0x22: case 0x28: case 0x29: case 0x2c: case 0x2f: case 0x3a: case 0x3b: case 0x3c: case 0x3d: case 0x3e: case 0x3f: case 0x40: case 0x5b: case 0x5c: case 0x5d: case 0x7b: case 0x7d: // DQUOTE and "(),/:;<=>?@[\]{}" return false default: // VCHAR %x21-7E return c >= 0x21 && c <= 0x7e } } /** * @param {string} characters * @returns {boolean} */ function isValidHTTPToken (characters) { if (characters.length === 0) { return false } for (let i = 0; i < characters.length; ++i) { if (!isTokenCharCode(characters.charCodeAt(i))) { return false } } return true } // headerCharRegex have been lifted from // https://github.com/nodejs/node/blob/main/lib/_http_common.js /** * Matches if val contains an invalid field-vchar * field-value = *( field-content / obs-fold ) * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] * field-vchar = VCHAR / obs-text */ const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/ /** * @param {string} characters * @returns {boolean} */ function isValidHeaderValue (characters) { return !headerCharRegex.test(characters) } const rangeHeaderRegex = /^bytes (\d+)-(\d+)\/(\d+)?$/ /** * @typedef {object} RangeHeader * @property {number} start * @property {number | null} end * @property {number | null} size */ /** * Parse accordingly to RFC 9110 * @see https://www.rfc-editor.org/rfc/rfc9110#field.content-range * @param {string} [range] * @returns {RangeHeader|null} */ function parseRangeHeader (range) { if (range == null || range === '') return { start: 0, end: null, size: null } const m = range ? range.match(rangeHeaderRegex) : null return m ? { start: parseInt(m[1]), end: m[2] ? parseInt(m[2]) : null, size: m[3] ? parseInt(m[3]) : null } : null } /** * @template {import("events").EventEmitter} T * @param {T} obj * @param {string} name * @param {(...args: any[]) => void} listener * @returns {T} */ function addListener (obj, name, listener) { const listeners = (obj[kListeners] ??= []) listeners.push([name, listener]) obj.on(name, listener) return obj } /** * @template {import("events").EventEmitter} T * @param {T} obj * @returns {T} */ function removeAllListeners (obj) { if (obj[kListeners] != null) { for (const [name, listener] of obj[kListeners]) { obj.removeListener(name, listener) } obj[kListeners] = null } return obj } /** * @param {import ('../dispatcher/client')} client * @param {import ('../core/request')} request * @param {Error} err */ function errorRequest (client, request, err) { try { request.onError(err) assert(request.aborted) } catch (err) { client.emit('error', err) } } /** * @param {WeakRef} socketWeakRef * @param {object} opts * @param {number} opts.timeout * @param {string} opts.hostname * @param {number} opts.port * @returns {() => void} */ const setupConnectTimeout = process.platform === 'win32' ? (socketWeakRef, opts) => { if (!opts.timeout) { return noop } let s1 = null let s2 = null const fastTimer = timers.setFastTimeout(() => { // setImmediate is added to make sure that we prioritize socket error events over timeouts s1 = setImmediate(() => { // Windows needs an extra setImmediate probably due to implementation differences in the socket logic s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts)) }) }, opts.timeout) return () => { timers.clearFastTimeout(fastTimer) clearImmediate(s1) clearImmediate(s2) } } : (socketWeakRef, opts) => { if (!opts.timeout) { return noop } let s1 = null const fastTimer = timers.setFastTimeout(() => { // setImmediate is added to make sure that we prioritize socket error events over timeouts s1 = setImmediate(() => { onConnectTimeout(socketWeakRef.deref(), opts) }) }, opts.timeout) return () => { timers.clearFastTimeout(fastTimer) clearImmediate(s1) } } /** * @param {net.Socket} socket * @param {object} opts * @param {number} opts.timeout * @param {string} opts.hostname * @param {number} opts.port */ function onConnectTimeout (socket, opts) { // The socket could be already garbage collected if (socket == null) { return } let message = 'Connect Timeout Error' if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) { message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(', ')},` } else { message += ` (attempted address: ${opts.hostname}:${opts.port},` } message += ` timeout: ${opts.timeout}ms)` destroy(socket, new ConnectTimeoutError(message)) } const kEnumerableProperty = Object.create(null) kEnumerableProperty.enumerable = true const normalizedMethodRecordsBase = { delete: 'DELETE', DELETE: 'DELETE', get: 'GET', GET: 'GET', head: 'HEAD', HEAD: 'HEAD', options: 'OPTIONS', OPTIONS: 'OPTIONS', post: 'POST', POST: 'POST', put: 'PUT', PUT: 'PUT' } const normalizedMethodRecords = { ...normalizedMethodRecordsBase, patch: 'patch', PATCH: 'PATCH' } // Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. Object.setPrototypeOf(normalizedMethodRecordsBase, null) Object.setPrototypeOf(normalizedMethodRecords, null) module.exports = { kEnumerableProperty, isDisturbed, isBlobLike, parseOrigin, parseURL, getServerName, isStream, isIterable, isAsyncIterable, isDestroyed, headerNameToString, bufferToLowerCasedHeaderName, addListener, removeAllListeners, errorRequest, parseRawHeaders, encodeRawHeaders, parseHeaders, parseKeepAliveTimeout, destroy, bodyLength, deepClone, ReadableStreamFrom, isBuffer, assertRequestHandler, getSocketInfo, isFormDataLike, serializePathWithQuery, addAbortListener, isValidHTTPToken, isValidHeaderValue, isTokenCharCode, parseRangeHeader, normalizedMethodRecordsBase, normalizedMethodRecords, isValidPort, isHttpOrHttpsPrefixed, nodeMajor, nodeMinor, safeHTTPMethods: Object.freeze(['GET', 'HEAD', 'OPTIONS', 'TRACE']), wrapRequestBody, setupConnectTimeout } /***/ }), /***/ 11538: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { InvalidArgumentError } = __nccwpck_require__(21158) const { kClients, kRunning, kClose, kDestroy, kDispatch, kUrl } = __nccwpck_require__(83112) const DispatcherBase = __nccwpck_require__(68750) const Pool = __nccwpck_require__(74561) const Client = __nccwpck_require__(56716) const util = __nccwpck_require__(46425) const kOnConnect = Symbol('onConnect') const kOnDisconnect = Symbol('onDisconnect') const kOnConnectionError = Symbol('onConnectionError') const kOnDrain = Symbol('onDrain') const kFactory = Symbol('factory') const kOptions = Symbol('options') function defaultFactory (origin, opts) { return opts && opts.connections === 1 ? new Client(origin, opts) : new Pool(origin, opts) } class Agent extends DispatcherBase { constructor ({ factory = defaultFactory, connect, ...options } = {}) { if (typeof factory !== 'function') { throw new InvalidArgumentError('factory must be a function.') } if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { throw new InvalidArgumentError('connect must be a function or an object') } super() if (connect && typeof connect !== 'function') { connect = { ...connect } } this[kOptions] = { ...util.deepClone(options), connect } this[kFactory] = factory this[kClients] = new Map() this[kOnDrain] = (origin, targets) => { this.emit('drain', origin, [this, ...targets]) } this[kOnConnect] = (origin, targets) => { const result = this[kClients].get(origin) if (result) { result.count += 1 } this.emit('connect', origin, [this, ...targets]) } this[kOnDisconnect] = (origin, targets, err) => { const result = this[kClients].get(origin) if (result) { result.count -= 1 if (result.count <= 0) { this[kClients].delete(origin) result.dispatcher.destroy() } } this.emit('disconnect', origin, [this, ...targets], err) } this[kOnConnectionError] = (origin, targets, err) => { // TODO: should this decrement result.count here? this.emit('connectionError', origin, [this, ...targets], err) } } get [kRunning] () { let ret = 0 for (const { dispatcher } of this[kClients].values()) { ret += dispatcher[kRunning] } return ret } [kDispatch] (opts, handler) { let key if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { key = String(opts.origin) } else { throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.') } const result = this[kClients].get(key) let dispatcher = result && result.dispatcher if (!dispatcher) { dispatcher = this[kFactory](opts.origin, this[kOptions]) .on('drain', this[kOnDrain]) .on('connect', this[kOnConnect]) .on('disconnect', this[kOnDisconnect]) .on('connectionError', this[kOnConnectionError]) this[kClients].set(key, { count: 0, dispatcher }) } return dispatcher.dispatch(opts, handler) } async [kClose] () { const closePromises = [] for (const { dispatcher } of this[kClients].values()) { closePromises.push(dispatcher.close()) } this[kClients].clear() await Promise.all(closePromises) } async [kDestroy] (err) { const destroyPromises = [] for (const { dispatcher } of this[kClients].values()) { destroyPromises.push(dispatcher.destroy(err)) } this[kClients].clear() await Promise.all(destroyPromises) } get stats () { const allClientStats = {} for (const { dispatcher } of this[kClients].values()) { if (dispatcher.stats) { allClientStats[dispatcher[kUrl].origin] = dispatcher.stats } } return allClientStats } } module.exports = Agent /***/ }), /***/ 18422: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { BalancedPoolMissingUpstreamError, InvalidArgumentError } = __nccwpck_require__(21158) const { PoolBase, kClients, kNeedDrain, kAddClient, kRemoveClient, kGetDispatcher } = __nccwpck_require__(57659) const Pool = __nccwpck_require__(74561) const { kUrl } = __nccwpck_require__(83112) const { parseOrigin } = __nccwpck_require__(46425) const kFactory = Symbol('factory') const kOptions = Symbol('options') const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor') const kCurrentWeight = Symbol('kCurrentWeight') const kIndex = Symbol('kIndex') const kWeight = Symbol('kWeight') const kMaxWeightPerServer = Symbol('kMaxWeightPerServer') const kErrorPenalty = Symbol('kErrorPenalty') /** * Calculate the greatest common divisor of two numbers by * using the Euclidean algorithm. * * @param {number} a * @param {number} b * @returns {number} */ function getGreatestCommonDivisor (a, b) { if (a === 0) return b while (b !== 0) { const t = b b = a % b a = t } return a } function defaultFactory (origin, opts) { return new Pool(origin, opts) } class BalancedPool extends PoolBase { constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { if (typeof factory !== 'function') { throw new InvalidArgumentError('factory must be a function.') } super() this[kOptions] = opts this[kIndex] = -1 this[kCurrentWeight] = 0 this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 this[kErrorPenalty] = this[kOptions].errorPenalty || 15 if (!Array.isArray(upstreams)) { upstreams = [upstreams] } this[kFactory] = factory for (const upstream of upstreams) { this.addUpstream(upstream) } this._updateBalancedPoolStats() } addUpstream (upstream) { const upstreamOrigin = parseOrigin(upstream).origin if (this[kClients].find((pool) => ( pool[kUrl].origin === upstreamOrigin && pool.closed !== true && pool.destroyed !== true ))) { return this } const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions])) this[kAddClient](pool) pool.on('connect', () => { pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) }) pool.on('connectionError', () => { pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) this._updateBalancedPoolStats() }) pool.on('disconnect', (...args) => { const err = args[2] if (err && err.code === 'UND_ERR_SOCKET') { // decrease the weight of the pool. pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) this._updateBalancedPoolStats() } }) for (const client of this[kClients]) { client[kWeight] = this[kMaxWeightPerServer] } this._updateBalancedPoolStats() return this } _updateBalancedPoolStats () { let result = 0 for (let i = 0; i < this[kClients].length; i++) { result = getGreatestCommonDivisor(this[kClients][i][kWeight], result) } this[kGreatestCommonDivisor] = result } removeUpstream (upstream) { const upstreamOrigin = parseOrigin(upstream).origin const pool = this[kClients].find((pool) => ( pool[kUrl].origin === upstreamOrigin && pool.closed !== true && pool.destroyed !== true )) if (pool) { this[kRemoveClient](pool) } return this } get upstreams () { return this[kClients] .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) .map((p) => p[kUrl].origin) } [kGetDispatcher] () { // We validate that pools is greater than 0, // otherwise we would have to wait until an upstream // is added, which might never happen. if (this[kClients].length === 0) { throw new BalancedPoolMissingUpstreamError() } const dispatcher = this[kClients].find(dispatcher => ( !dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true )) if (!dispatcher) { return } const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) if (allClientsBusy) { return } let counter = 0 let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]) while (counter++ < this[kClients].length) { this[kIndex] = (this[kIndex] + 1) % this[kClients].length const pool = this[kClients][this[kIndex]] // find pool index with the largest weight if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { maxWeightIndex = this[kIndex] } // decrease the current weight every `this[kClients].length`. if (this[kIndex] === 0) { // Set the current weight to the next lower weight. this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor] if (this[kCurrentWeight] <= 0) { this[kCurrentWeight] = this[kMaxWeightPerServer] } } if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { return pool } } this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] this[kIndex] = maxWeightIndex return this[kClients][maxWeightIndex] } } module.exports = BalancedPool /***/ }), /***/ 66874: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* global WebAssembly */ const assert = __nccwpck_require__(34589) const util = __nccwpck_require__(46425) const { channels } = __nccwpck_require__(69709) const timers = __nccwpck_require__(5870) const { RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, HeadersTimeoutError, HeadersOverflowError, SocketError, InformationalError, BodyTimeoutError, HTTPParserError, ResponseExceededMaxSizeError } = __nccwpck_require__(21158) const { kUrl, kReset, kClient, kParser, kBlocking, kRunning, kPending, kSize, kWriting, kQueue, kNoRef, kKeepAliveDefaultTimeout, kHostHeader, kPendingIdx, kRunningIdx, kError, kPipelining, kSocket, kKeepAliveTimeoutValue, kMaxHeadersSize, kKeepAliveMaxTimeout, kKeepAliveTimeoutThreshold, kHeadersTimeout, kBodyTimeout, kStrictContentLength, kMaxRequests, kCounter, kMaxResponseSize, kOnError, kResume, kHTTPContext, kClosed } = __nccwpck_require__(83112) const constants = __nccwpck_require__(59619) const EMPTY_BUF = Buffer.alloc(0) const FastBuffer = Buffer[Symbol.species] const removeAllListeners = util.removeAllListeners let extractBody function lazyllhttp () { const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(34493) : undefined let mod try { mod = new WebAssembly.Module(__nccwpck_require__(16559)) } catch (e) { /* istanbul ignore next */ // We could check if the error was caused by the simd option not // being enabled, but the occurring of this other error // * https://github.com/emscripten-core/emscripten/issues/11495 // got me to remove that check to avoid breaking Node 12. mod = new WebAssembly.Module(llhttpWasmData || __nccwpck_require__(34493)) } return new WebAssembly.Instance(mod, { env: { /** * @param {number} p * @param {number} at * @param {number} len * @returns {number} */ wasm_on_url: (p, at, len) => { /* istanbul ignore next */ return 0 }, /** * @param {number} p * @param {number} at * @param {number} len * @returns {number} */ wasm_on_status: (p, at, len) => { assert(currentParser.ptr === p) const start = at - currentBufferPtr + currentBufferRef.byteOffset return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) }, /** * @param {number} p * @returns {number} */ wasm_on_message_begin: (p) => { assert(currentParser.ptr === p) return currentParser.onMessageBegin() }, /** * @param {number} p * @param {number} at * @param {number} len * @returns {number} */ wasm_on_header_field: (p, at, len) => { assert(currentParser.ptr === p) const start = at - currentBufferPtr + currentBufferRef.byteOffset return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) }, /** * @param {number} p * @param {number} at * @param {number} len * @returns {number} */ wasm_on_header_value: (p, at, len) => { assert(currentParser.ptr === p) const start = at - currentBufferPtr + currentBufferRef.byteOffset return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) }, /** * @param {number} p * @param {number} statusCode * @param {0|1} upgrade * @param {0|1} shouldKeepAlive * @returns {number} */ wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => { assert(currentParser.ptr === p) return currentParser.onHeadersComplete(statusCode, upgrade === 1, shouldKeepAlive === 1) }, /** * @param {number} p * @param {number} at * @param {number} len * @returns {number} */ wasm_on_body: (p, at, len) => { assert(currentParser.ptr === p) const start = at - currentBufferPtr + currentBufferRef.byteOffset return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) }, /** * @param {number} p * @returns {number} */ wasm_on_message_complete: (p) => { assert(currentParser.ptr === p) return currentParser.onMessageComplete() } } }) } let llhttpInstance = null /** * @type {Parser|null} */ let currentParser = null let currentBufferRef = null /** * @type {number} */ let currentBufferSize = 0 let currentBufferPtr = null const USE_NATIVE_TIMER = 0 const USE_FAST_TIMER = 1 // Use fast timers for headers and body to take eventual event loop // latency into account. const TIMEOUT_HEADERS = 2 | USE_FAST_TIMER const TIMEOUT_BODY = 4 | USE_FAST_TIMER // Use native timers to ignore event loop latency for keep-alive // handling. const TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER class Parser { /** * @param {import('./client.js')} client * @param {import('net').Socket} socket * @param {*} llhttp */ constructor (client, socket, { exports }) { this.llhttp = exports this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE) this.client = client /** * @type {import('net').Socket} */ this.socket = socket this.timeout = null this.timeoutValue = null this.timeoutType = null this.statusCode = 0 this.statusText = '' this.upgrade = false this.headers = [] this.headersSize = 0 this.headersMaxSize = client[kMaxHeadersSize] this.shouldKeepAlive = false this.paused = false this.resume = this.resume.bind(this) this.bytesRead = 0 this.keepAlive = '' this.contentLength = '' this.connection = '' this.maxResponseSize = client[kMaxResponseSize] } setTimeout (delay, type) { // If the existing timer and the new timer are of different timer type // (fast or native) or have different delay, we need to clear the existing // timer and set a new one. if ( delay !== this.timeoutValue || (type & USE_FAST_TIMER) ^ (this.timeoutType & USE_FAST_TIMER) ) { // If a timeout is already set, clear it with clearTimeout of the fast // timer implementation, as it can clear fast and native timers. if (this.timeout) { timers.clearTimeout(this.timeout) this.timeout = null } if (delay) { if (type & USE_FAST_TIMER) { this.timeout = timers.setFastTimeout(onParserTimeout, delay, new WeakRef(this)) } else { this.timeout = setTimeout(onParserTimeout, delay, new WeakRef(this)) this.timeout?.unref() } } this.timeoutValue = delay } else if (this.timeout) { // istanbul ignore else: only for jest if (this.timeout.refresh) { this.timeout.refresh() } } this.timeoutType = type } resume () { if (this.socket.destroyed || !this.paused) { return } assert(this.ptr != null) assert(currentParser === null) this.llhttp.llhttp_resume(this.ptr) assert(this.timeoutType === TIMEOUT_BODY) if (this.timeout) { // istanbul ignore else: only for jest if (this.timeout.refresh) { this.timeout.refresh() } } this.paused = false this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. this.readMore() } readMore () { while (!this.paused && this.ptr) { const chunk = this.socket.read() if (chunk === null) { break } this.execute(chunk) } } /** * @param {Buffer} chunk */ execute (chunk) { assert(currentParser === null) assert(this.ptr != null) assert(!this.paused) const { socket, llhttp } = this // Allocate a new buffer if the current buffer is too small. if (chunk.length > currentBufferSize) { if (currentBufferPtr) { llhttp.free(currentBufferPtr) } // Allocate a buffer that is a multiple of 4096 bytes. currentBufferSize = Math.ceil(chunk.length / 4096) * 4096 currentBufferPtr = llhttp.malloc(currentBufferSize) } new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(chunk) // Call `execute` on the wasm parser. // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data, // and finally the length of bytes to parse. // The return value is an error code or `constants.ERROR.OK`. try { let ret try { currentBufferRef = chunk currentParser = this ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, chunk.length) /* eslint-disable-next-line no-useless-catch */ } catch (err) { /* istanbul ignore next: difficult to make a test case for */ throw err } finally { currentParser = null currentBufferRef = null } if (ret !== constants.ERROR.OK) { const data = chunk.subarray(llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr) if (ret === constants.ERROR.PAUSED_UPGRADE) { this.onUpgrade(data) } else if (ret === constants.ERROR.PAUSED) { this.paused = true socket.unshift(data) } else { const ptr = llhttp.llhttp_get_error_reason(this.ptr) let message = '' /* istanbul ignore else: difficult to make a test case for */ if (ptr) { const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0) message = 'Response does not match the HTTP/1.1 protocol (' + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ')' } throw new HTTPParserError(message, constants.ERROR[ret], data) } } } catch (err) { util.destroy(socket, err) } } destroy () { assert(currentParser === null) assert(this.ptr != null) this.llhttp.llhttp_free(this.ptr) this.ptr = null this.timeout && timers.clearTimeout(this.timeout) this.timeout = null this.timeoutValue = null this.timeoutType = null this.paused = false } /** * @param {Buffer} buf * @returns {0} */ onStatus (buf) { this.statusText = buf.toString() return 0 } /** * @returns {0|-1} */ onMessageBegin () { const { socket, client } = this /* istanbul ignore next: difficult to make a test case for */ if (socket.destroyed) { return -1 } const request = client[kQueue][client[kRunningIdx]] if (!request) { return -1 } request.onResponseStarted() return 0 } /** * @param {Buffer} buf * @returns {number} */ onHeaderField (buf) { const len = this.headers.length if ((len & 1) === 0) { this.headers.push(buf) } else { this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) } this.trackHeader(buf.length) return 0 } /** * @param {Buffer} buf * @returns {number} */ onHeaderValue (buf) { let len = this.headers.length if ((len & 1) === 1) { this.headers.push(buf) len += 1 } else { this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) } const key = this.headers[len - 2] if (key.length === 10) { const headerName = util.bufferToLowerCasedHeaderName(key) if (headerName === 'keep-alive') { this.keepAlive += buf.toString() } else if (headerName === 'connection') { this.connection += buf.toString() } } else if (key.length === 14 && util.bufferToLowerCasedHeaderName(key) === 'content-length') { this.contentLength += buf.toString() } this.trackHeader(buf.length) return 0 } /** * @param {number} len */ trackHeader (len) { this.headersSize += len if (this.headersSize >= this.headersMaxSize) { util.destroy(this.socket, new HeadersOverflowError()) } } /** * @param {Buffer} head */ onUpgrade (head) { const { upgrade, client, socket, headers, statusCode } = this assert(upgrade) assert(client[kSocket] === socket) assert(!socket.destroyed) assert(!this.paused) assert((headers.length & 1) === 0) const request = client[kQueue][client[kRunningIdx]] assert(request) assert(request.upgrade || request.method === 'CONNECT') this.statusCode = 0 this.statusText = '' this.shouldKeepAlive = false this.headers = [] this.headersSize = 0 socket.unshift(head) socket[kParser].destroy() socket[kParser] = null socket[kClient] = null socket[kError] = null removeAllListeners(socket) client[kSocket] = null client[kHTTPContext] = null // TODO (fix): This is hacky... client[kQueue][client[kRunningIdx]++] = null client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) try { request.onUpgrade(statusCode, headers, socket) } catch (err) { util.destroy(socket, err) } client[kResume]() } /** * @param {number} statusCode * @param {boolean} upgrade * @param {boolean} shouldKeepAlive * @returns {number} */ onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { const { client, socket, headers, statusText } = this /* istanbul ignore next: difficult to make a test case for */ if (socket.destroyed) { return -1 } const request = client[kQueue][client[kRunningIdx]] /* istanbul ignore next: difficult to make a test case for */ if (!request) { return -1 } assert(!this.upgrade) assert(this.statusCode < 200) if (statusCode === 100) { util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) return -1 } /* this can only happen if server is misbehaving */ if (upgrade && !request.upgrade) { util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) return -1 } assert(this.timeoutType === TIMEOUT_HEADERS) this.statusCode = statusCode this.shouldKeepAlive = ( shouldKeepAlive || // Override llhttp value which does not allow keepAlive for HEAD. (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive') ) if (this.statusCode >= 200) { const bodyTimeout = request.bodyTimeout != null ? request.bodyTimeout : client[kBodyTimeout] this.setTimeout(bodyTimeout, TIMEOUT_BODY) } else if (this.timeout) { // istanbul ignore else: only for jest if (this.timeout.refresh) { this.timeout.refresh() } } if (request.method === 'CONNECT') { assert(client[kRunning] === 1) this.upgrade = true return 2 } if (upgrade) { assert(client[kRunning] === 1) this.upgrade = true return 2 } assert((this.headers.length & 1) === 0) this.headers = [] this.headersSize = 0 if (this.shouldKeepAlive && client[kPipelining]) { const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null if (keepAliveTimeout != null) { const timeout = Math.min( keepAliveTimeout - client[kKeepAliveTimeoutThreshold], client[kKeepAliveMaxTimeout] ) if (timeout <= 0) { socket[kReset] = true } else { client[kKeepAliveTimeoutValue] = timeout } } else { client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout] } } else { // Stop more requests from being dispatched. socket[kReset] = true } const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false if (request.aborted) { return -1 } if (request.method === 'HEAD') { return 1 } if (statusCode < 200) { return 1 } if (socket[kBlocking]) { socket[kBlocking] = false client[kResume]() } return pause ? constants.ERROR.PAUSED : 0 } /** * @param {Buffer} buf * @returns {number} */ onBody (buf) { const { client, socket, statusCode, maxResponseSize } = this if (socket.destroyed) { return -1 } const request = client[kQueue][client[kRunningIdx]] assert(request) assert(this.timeoutType === TIMEOUT_BODY) if (this.timeout) { // istanbul ignore else: only for jest if (this.timeout.refresh) { this.timeout.refresh() } } assert(statusCode >= 200) if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { util.destroy(socket, new ResponseExceededMaxSizeError()) return -1 } this.bytesRead += buf.length if (request.onData(buf) === false) { return constants.ERROR.PAUSED } return 0 } /** * @returns {number} */ onMessageComplete () { const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this if (socket.destroyed && (!statusCode || shouldKeepAlive)) { return -1 } if (upgrade) { return 0 } assert(statusCode >= 100) assert((this.headers.length & 1) === 0) const request = client[kQueue][client[kRunningIdx]] assert(request) this.statusCode = 0 this.statusText = '' this.bytesRead = 0 this.contentLength = '' this.keepAlive = '' this.connection = '' this.headers = [] this.headersSize = 0 if (statusCode < 200) { return 0 } /* istanbul ignore next: should be handled by llhttp? */ if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { util.destroy(socket, new ResponseContentLengthMismatchError()) return -1 } request.onComplete(headers) client[kQueue][client[kRunningIdx]++] = null if (socket[kWriting]) { assert(client[kRunning] === 0) // Response completed before request. util.destroy(socket, new InformationalError('reset')) return constants.ERROR.PAUSED } else if (!shouldKeepAlive) { util.destroy(socket, new InformationalError('reset')) return constants.ERROR.PAUSED } else if (socket[kReset] && client[kRunning] === 0) { // Destroy socket once all requests have completed. // The request at the tail of the pipeline is the one // that requested reset and no further requests should // have been queued since then. util.destroy(socket, new InformationalError('reset')) return constants.ERROR.PAUSED } else if (client[kPipelining] == null || client[kPipelining] === 1) { // We must wait a full event loop cycle to reuse this socket to make sure // that non-spec compliant servers are not closing the connection even if they // said they won't. setImmediate(client[kResume]) } else { client[kResume]() } return 0 } } function onParserTimeout (parser) { const { socket, timeoutType, client, paused } = parser.deref() /* istanbul ignore else */ if (timeoutType === TIMEOUT_HEADERS) { if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) { assert(!paused, 'cannot be paused while waiting for headers') util.destroy(socket, new HeadersTimeoutError()) } } else if (timeoutType === TIMEOUT_BODY) { if (!paused) { util.destroy(socket, new BodyTimeoutError()) } } else if (timeoutType === TIMEOUT_KEEP_ALIVE) { assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]) util.destroy(socket, new InformationalError('socket idle timeout')) } } /** * @param {import ('./client.js')} client * @param {import('net').Socket} socket * @returns */ async function connectH1 (client, socket) { client[kSocket] = socket if (!llhttpInstance) { llhttpInstance = lazyllhttp() } if (socket.errored) { throw socket.errored } if (socket.destroyed) { throw new SocketError('destroyed') } socket[kNoRef] = false socket[kWriting] = false socket[kReset] = false socket[kBlocking] = false socket[kParser] = new Parser(client, socket, llhttpInstance) util.addListener(socket, 'error', onHttpSocketError) util.addListener(socket, 'readable', onHttpSocketReadable) util.addListener(socket, 'end', onHttpSocketEnd) util.addListener(socket, 'close', onHttpSocketClose) socket[kClosed] = false socket.on('close', onSocketClose) return { version: 'h1', defaultPipelining: 1, write (request) { return writeH1(client, request) }, resume () { resumeH1(client) }, /** * @param {Error|undefined} err * @param {() => void} callback */ destroy (err, callback) { if (socket[kClosed]) { queueMicrotask(callback) } else { socket.on('close', callback) socket.destroy(err) } }, /** * @returns {boolean} */ get destroyed () { return socket.destroyed }, /** * @param {import('../core/request.js')} request * @returns {boolean} */ busy (request) { if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true } if (request) { if (client[kRunning] > 0 && !request.idempotent) { // Non-idempotent request cannot be retried. // Ensure that no other requests are inflight and // could cause failure. return true } if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) { // Don't dispatch an upgrade until all preceding requests have completed. // A misbehaving server might upgrade the connection before all pipelined // request has completed. return true } if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 && (util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) { // Request with stream or iterator body can error while other requests // are inflight and indirectly error those as well. // Ensure this doesn't happen by waiting for inflight // to complete before dispatching. // Request with stream or iterator body cannot be retried. // Ensure that no other requests are inflight and // could cause failure. return true } } return false } } } function onHttpSocketError (err) { assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') const parser = this[kParser] // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded // to the user. if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) { // We treat all incoming data so for as a valid response. parser.onMessageComplete() return } this[kError] = err this[kClient][kOnError](err) } function onHttpSocketReadable () { this[kParser]?.readMore() } function onHttpSocketEnd () { const parser = this[kParser] if (parser.statusCode && !parser.shouldKeepAlive) { // We treat all incoming data so far as a valid response. parser.onMessageComplete() return } util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) } function onHttpSocketClose () { const parser = this[kParser] if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { // We treat all incoming data so far as a valid response. parser.onMessageComplete() } this[kParser].destroy() this[kParser] = null } const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) const client = this[kClient] client[kSocket] = null client[kHTTPContext] = null // TODO (fix): This is hacky... if (client.destroyed) { assert(client[kPending] === 0) // Fail entire queue. const requests = client[kQueue].splice(client[kRunningIdx]) for (let i = 0; i < requests.length; i++) { const request = requests[i] util.errorRequest(client, request, err) } } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') { // Fail head of pipeline. const request = client[kQueue][client[kRunningIdx]] client[kQueue][client[kRunningIdx]++] = null util.errorRequest(client, request, err) } client[kPendingIdx] = client[kRunningIdx] assert(client[kRunning] === 0) client.emit('disconnect', client[kUrl], [client], err) client[kResume]() } function onSocketClose () { this[kClosed] = true } /** * @param {import('./client.js')} client */ function resumeH1 (client) { const socket = client[kSocket] if (socket && !socket.destroyed) { if (client[kSize] === 0) { if (!socket[kNoRef] && socket.unref) { socket.unref() socket[kNoRef] = true } } else if (socket[kNoRef] && socket.ref) { socket.ref() socket[kNoRef] = false } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE) } } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) { if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) { const request = client[kQueue][client[kRunningIdx]] const headersTimeout = request.headersTimeout != null ? request.headersTimeout : client[kHeadersTimeout] socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS) } } } } // https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 function shouldSendContentLength (method) { return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' } /** * @param {import('./client.js')} client * @param {import('../core/request.js')} request * @returns */ function writeH1 (client, request) { const { method, path, host, upgrade, blocking, reset } = request let { body, headers, contentLength } = request // https://tools.ietf.org/html/rfc7231#section-4.3.1 // https://tools.ietf.org/html/rfc7231#section-4.3.2 // https://tools.ietf.org/html/rfc7231#section-4.3.5 // Sending a payload body on a request that does not // expect it can cause undefined behavior on some // servers and corrupt connection state. Do not // re-use the connection for further requests. const expectsPayload = ( method === 'PUT' || method === 'POST' || method === 'PATCH' || method === 'QUERY' || method === 'PROPFIND' || method === 'PROPPATCH' ) if (util.isFormDataLike(body)) { if (!extractBody) { extractBody = (__nccwpck_require__(27679).extractBody) } const [bodyStream, contentType] = extractBody(body) if (request.contentType == null) { headers.push('content-type', contentType) } body = bodyStream.stream contentLength = bodyStream.length } else if (util.isBlobLike(body) && request.contentType == null && body.type) { headers.push('content-type', body.type) } if (body && typeof body.read === 'function') { // Try to read EOF in order to get length. body.read(0) } const bodyLength = util.bodyLength(body) contentLength = bodyLength ?? contentLength if (contentLength === null) { contentLength = request.contentLength } if (contentLength === 0 && !expectsPayload) { // https://tools.ietf.org/html/rfc7230#section-3.3.2 // A user agent SHOULD NOT send a Content-Length header field when // the request message does not contain a payload body and the method // semantics do not anticipate such a body. contentLength = null } // https://github.com/nodejs/undici/issues/2046 // A user agent may send a Content-Length header with 0 value, this should be allowed. if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) { if (client[kStrictContentLength]) { util.errorRequest(client, request, new RequestContentLengthMismatchError()) return false } process.emitWarning(new RequestContentLengthMismatchError()) } const socket = client[kSocket] /** * @param {Error} [err] * @returns {void} */ const abort = (err) => { if (request.aborted || request.completed) { return } util.errorRequest(client, request, err || new RequestAbortedError()) util.destroy(body) util.destroy(socket, new InformationalError('aborted')) } try { request.onConnect(abort) } catch (err) { util.errorRequest(client, request, err) } if (request.aborted) { return false } if (method === 'HEAD') { // https://github.com/mcollina/undici/issues/258 // Close after a HEAD request to interop with misbehaving servers // that may send a body in the response. socket[kReset] = true } if (upgrade || method === 'CONNECT') { // On CONNECT or upgrade, block pipeline from dispatching further // requests on this connection. socket[kReset] = true } if (reset != null) { socket[kReset] = reset } if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { socket[kReset] = true } if (blocking) { socket[kBlocking] = true } let header = `${method} ${path} HTTP/1.1\r\n` if (typeof host === 'string') { header += `host: ${host}\r\n` } else { header += client[kHostHeader] } if (upgrade) { header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n` } else if (client[kPipelining] && !socket[kReset]) { header += 'connection: keep-alive\r\n' } else { header += 'connection: close\r\n' } if (Array.isArray(headers)) { for (let n = 0; n < headers.length; n += 2) { const key = headers[n + 0] const val = headers[n + 1] if (Array.isArray(val)) { for (let i = 0; i < val.length; i++) { header += `${key}: ${val[i]}\r\n` } } else { header += `${key}: ${val}\r\n` } } } if (channels.sendHeaders.hasSubscribers) { channels.sendHeaders.publish({ request, headers: header, socket }) } /* istanbul ignore else: assertion */ if (!body || bodyLength === 0) { writeBuffer(abort, null, client, request, socket, contentLength, header, expectsPayload) } else if (util.isBuffer(body)) { writeBuffer(abort, body, client, request, socket, contentLength, header, expectsPayload) } else if (util.isBlobLike(body)) { if (typeof body.stream === 'function') { writeIterable(abort, body.stream(), client, request, socket, contentLength, header, expectsPayload) } else { writeBlob(abort, body, client, request, socket, contentLength, header, expectsPayload) } } else if (util.isStream(body)) { writeStream(abort, body, client, request, socket, contentLength, header, expectsPayload) } else if (util.isIterable(body)) { writeIterable(abort, body, client, request, socket, contentLength, header, expectsPayload) } else { assert(false) } return true } /** * @param {AbortCallback} abort * @param {import('stream').Stream} body * @param {import('./client.js')} client * @param {import('../core/request.js')} request * @param {import('net').Socket} socket * @param {number} contentLength * @param {string} header * @param {boolean} expectsPayload */ function writeStream (abort, body, client, request, socket, contentLength, header, expectsPayload) { assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') let finished = false const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header }) /** * @param {Buffer} chunk * @returns {void} */ const onData = function (chunk) { if (finished) { return } try { if (!writer.write(chunk) && this.pause) { this.pause() } } catch (err) { util.destroy(this, err) } } /** * @returns {void} */ const onDrain = function () { if (finished) { return } if (body.resume) { body.resume() } } /** * @returns {void} */ const onClose = function () { // 'close' might be emitted *before* 'error' for // broken streams. Wait a tick to avoid this case. queueMicrotask(() => { // It's only safe to remove 'error' listener after // 'close'. body.removeListener('error', onFinished) }) if (!finished) { const err = new RequestAbortedError() queueMicrotask(() => onFinished(err)) } } /** * @param {Error} [err] * @returns */ const onFinished = function (err) { if (finished) { return } finished = true assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) socket .off('drain', onDrain) .off('error', onFinished) body .removeListener('data', onData) .removeListener('end', onFinished) .removeListener('close', onClose) if (!err) { try { writer.end() } catch (er) { err = er } } writer.destroy(err) if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { util.destroy(body, err) } else { util.destroy(body) } } body .on('data', onData) .on('end', onFinished) .on('error', onFinished) .on('close', onClose) if (body.resume) { body.resume() } socket .on('drain', onDrain) .on('error', onFinished) if (body.errorEmitted ?? body.errored) { setImmediate(onFinished, body.errored) } else if (body.endEmitted ?? body.readableEnded) { setImmediate(onFinished, null) } if (body.closeEmitted ?? body.closed) { setImmediate(onClose) } } /** * @typedef AbortCallback * @type {Function} * @param {Error} [err] * @returns {void} */ /** * @param {AbortCallback} abort * @param {Uint8Array|null} body * @param {import('./client.js')} client * @param {import('../core/request.js')} request * @param {import('net').Socket} socket * @param {number} contentLength * @param {string} header * @param {boolean} expectsPayload * @returns {void} */ function writeBuffer (abort, body, client, request, socket, contentLength, header, expectsPayload) { try { if (!body) { if (contentLength === 0) { socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') } else { assert(contentLength === null, 'no body must not have content length') socket.write(`${header}\r\n`, 'latin1') } } else if (util.isBuffer(body)) { assert(contentLength === body.byteLength, 'buffer body must have content length') socket.cork() socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') socket.write(body) socket.uncork() request.onBodySent(body) if (!expectsPayload && request.reset !== false) { socket[kReset] = true } } request.onRequestSent() client[kResume]() } catch (err) { abort(err) } } /** * @param {AbortCallback} abort * @param {Blob} body * @param {import('./client.js')} client * @param {import('../core/request.js')} request * @param {import('net').Socket} socket * @param {number} contentLength * @param {string} header * @param {boolean} expectsPayload * @returns {Promise} */ async function writeBlob (abort, body, client, request, socket, contentLength, header, expectsPayload) { assert(contentLength === body.size, 'blob body must have content length') try { if (contentLength != null && contentLength !== body.size) { throw new RequestContentLengthMismatchError() } const buffer = Buffer.from(await body.arrayBuffer()) socket.cork() socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') socket.write(buffer) socket.uncork() request.onBodySent(buffer) request.onRequestSent() if (!expectsPayload && request.reset !== false) { socket[kReset] = true } client[kResume]() } catch (err) { abort(err) } } /** * @param {AbortCallback} abort * @param {Iterable} body * @param {import('./client.js')} client * @param {import('../core/request.js')} request * @param {import('net').Socket} socket * @param {number} contentLength * @param {string} header * @param {boolean} expectsPayload * @returns {Promise} */ async function writeIterable (abort, body, client, request, socket, contentLength, header, expectsPayload) { assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') let callback = null function onDrain () { if (callback) { const cb = callback callback = null cb() } } const waitForDrain = () => new Promise((resolve, reject) => { assert(callback === null) if (socket[kError]) { reject(socket[kError]) } else { callback = resolve } }) socket .on('close', onDrain) .on('drain', onDrain) const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header }) try { // It's up to the user to somehow abort the async iterable. for await (const chunk of body) { if (socket[kError]) { throw socket[kError] } if (!writer.write(chunk)) { await waitForDrain() } } writer.end() } catch (err) { writer.destroy(err) } finally { socket .off('close', onDrain) .off('drain', onDrain) } } class AsyncWriter { /** * * @param {object} arg * @param {AbortCallback} arg.abort * @param {import('net').Socket} arg.socket * @param {import('../core/request.js')} arg.request * @param {number} arg.contentLength * @param {import('./client.js')} arg.client * @param {boolean} arg.expectsPayload * @param {string} arg.header */ constructor ({ abort, socket, request, contentLength, client, expectsPayload, header }) { this.socket = socket this.request = request this.contentLength = contentLength this.client = client this.bytesWritten = 0 this.expectsPayload = expectsPayload this.header = header this.abort = abort socket[kWriting] = true } /** * @param {Buffer} chunk * @returns */ write (chunk) { const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this if (socket[kError]) { throw socket[kError] } if (socket.destroyed) { return false } const len = Buffer.byteLength(chunk) if (!len) { return true } // We should defer writing chunks. if (contentLength !== null && bytesWritten + len > contentLength) { if (client[kStrictContentLength]) { throw new RequestContentLengthMismatchError() } process.emitWarning(new RequestContentLengthMismatchError()) } socket.cork() if (bytesWritten === 0) { if (!expectsPayload && request.reset !== false) { socket[kReset] = true } if (contentLength === null) { socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1') } else { socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') } } if (contentLength === null) { socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1') } this.bytesWritten += len const ret = socket.write(chunk) socket.uncork() request.onBodySent(chunk) if (!ret) { if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { // istanbul ignore else: only for jest if (socket[kParser].timeout.refresh) { socket[kParser].timeout.refresh() } } } return ret } /** * @returns {void} */ end () { const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this request.onRequestSent() socket[kWriting] = false if (socket[kError]) { throw socket[kError] } if (socket.destroyed) { return } if (bytesWritten === 0) { if (expectsPayload) { // https://tools.ietf.org/html/rfc7230#section-3.3.2 // A user agent SHOULD send a Content-Length in a request message when // no Transfer-Encoding is sent and the request method defines a meaning // for an enclosed payload body. socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') } else { socket.write(`${header}\r\n`, 'latin1') } } else if (contentLength === null) { socket.write('\r\n0\r\n\r\n', 'latin1') } if (contentLength !== null && bytesWritten !== contentLength) { if (client[kStrictContentLength]) { throw new RequestContentLengthMismatchError() } else { process.emitWarning(new RequestContentLengthMismatchError()) } } if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { // istanbul ignore else: only for jest if (socket[kParser].timeout.refresh) { socket[kParser].timeout.refresh() } } client[kResume]() } /** * @param {Error} [err] * @returns {void} */ destroy (err) { const { socket, client, abort } = this socket[kWriting] = false if (err) { assert(client[kRunning] <= 1, 'pipeline should only contain this request') abort(err) } } } module.exports = connectH1 /***/ }), /***/ 70599: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(34589) const { pipeline } = __nccwpck_require__(57075) const util = __nccwpck_require__(46425) const { RequestContentLengthMismatchError, RequestAbortedError, SocketError, InformationalError } = __nccwpck_require__(21158) const { kUrl, kReset, kClient, kRunning, kPending, kQueue, kPendingIdx, kRunningIdx, kError, kSocket, kStrictContentLength, kOnError, kMaxConcurrentStreams, kHTTP2Session, kResume, kSize, kHTTPContext, kClosed, kBodyTimeout } = __nccwpck_require__(83112) const { channels } = __nccwpck_require__(69709) const kOpenStreams = Symbol('open streams') let extractBody /** @type {import('http2')} */ let http2 try { http2 = __nccwpck_require__(32467) } catch { // @ts-ignore http2 = { constants: {} } } const { constants: { HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_SCHEME, HTTP2_HEADER_CONTENT_LENGTH, HTTP2_HEADER_EXPECT, HTTP2_HEADER_STATUS } } = http2 function parseH2Headers (headers) { const result = [] for (const [name, value] of Object.entries(headers)) { // h2 may concat the header value by array // e.g. Set-Cookie if (Array.isArray(value)) { for (const subvalue of value) { // we need to provide each header value of header name // because the headers handler expect name-value pair result.push(Buffer.from(name), Buffer.from(subvalue)) } } else { result.push(Buffer.from(name), Buffer.from(value)) } } return result } async function connectH2 (client, socket) { client[kSocket] = socket const session = http2.connect(client[kUrl], { createConnection: () => socket, peerMaxConcurrentStreams: client[kMaxConcurrentStreams], settings: { // TODO(metcoder95): add support for PUSH enablePush: false } }) session[kOpenStreams] = 0 session[kClient] = client session[kSocket] = socket session[kHTTP2Session] = null util.addListener(session, 'error', onHttp2SessionError) util.addListener(session, 'frameError', onHttp2FrameError) util.addListener(session, 'end', onHttp2SessionEnd) util.addListener(session, 'goaway', onHttp2SessionGoAway) util.addListener(session, 'close', onHttp2SessionClose) session.unref() client[kHTTP2Session] = session socket[kHTTP2Session] = session util.addListener(socket, 'error', onHttp2SocketError) util.addListener(socket, 'end', onHttp2SocketEnd) util.addListener(socket, 'close', onHttp2SocketClose) socket[kClosed] = false socket.on('close', onSocketClose) return { version: 'h2', defaultPipelining: Infinity, write (request) { return writeH2(client, request) }, resume () { resumeH2(client) }, destroy (err, callback) { if (socket[kClosed]) { queueMicrotask(callback) } else { socket.destroy(err).on('close', callback) } }, get destroyed () { return socket.destroyed }, busy () { return false } } } function resumeH2 (client) { const socket = client[kSocket] if (socket?.destroyed === false) { if (client[kSize] === 0 || client[kMaxConcurrentStreams] === 0) { socket.unref() client[kHTTP2Session].unref() } else { socket.ref() client[kHTTP2Session].ref() } } } function onHttp2SessionError (err) { assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') this[kSocket][kError] = err this[kClient][kOnError](err) } function onHttp2FrameError (type, code, id) { if (id === 0) { const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) this[kSocket][kError] = err this[kClient][kOnError](err) } } function onHttp2SessionEnd () { const err = new SocketError('other side closed', util.getSocketInfo(this[kSocket])) this.destroy(err) util.destroy(this[kSocket], err) } /** * This is the root cause of #3011 * We need to handle GOAWAY frames properly, and trigger the session close * along with the socket right away * * @this {import('http2').ClientHttp2Session} * @param {number} errorCode */ function onHttp2SessionGoAway (errorCode) { // TODO(mcollina): Verify if GOAWAY implements the spec correctly: // https://datatracker.ietf.org/doc/html/rfc7540#section-6.8 // Specifically, we do not verify the "valid" stream id. const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util.getSocketInfo(this[kSocket])) const client = this[kClient] client[kSocket] = null client[kHTTPContext] = null // this is an HTTP2 session this.close() this[kHTTP2Session] = null util.destroy(this[kSocket], err) // Fail head of pipeline. if (client[kRunningIdx] < client[kQueue].length) { const request = client[kQueue][client[kRunningIdx]] client[kQueue][client[kRunningIdx]++] = null util.errorRequest(client, request, err) client[kPendingIdx] = client[kRunningIdx] } assert(client[kRunning] === 0) client.emit('disconnect', client[kUrl], [client], err) client.emit('connectionError', client[kUrl], [client], err) client[kResume]() } function onHttp2SessionClose () { const { [kClient]: client } = this const { [kSocket]: socket } = client const err = this[kSocket][kError] || this[kError] || new SocketError('closed', util.getSocketInfo(socket)) client[kSocket] = null client[kHTTPContext] = null if (client.destroyed) { assert(client[kPending] === 0) // Fail entire queue. const requests = client[kQueue].splice(client[kRunningIdx]) for (let i = 0; i < requests.length; i++) { const request = requests[i] util.errorRequest(client, request, err) } } } function onHttp2SocketClose () { const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) const client = this[kHTTP2Session][kClient] client[kSocket] = null client[kHTTPContext] = null if (this[kHTTP2Session] !== null) { this[kHTTP2Session].destroy(err) } client[kPendingIdx] = client[kRunningIdx] assert(client[kRunning] === 0) client.emit('disconnect', client[kUrl], [client], err) client[kResume]() } function onHttp2SocketError (err) { assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') this[kError] = err this[kClient][kOnError](err) } function onHttp2SocketEnd () { util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) } function onSocketClose () { this[kClosed] = true } // https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 function shouldSendContentLength (method) { return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' } function writeH2 (client, request) { const requestTimeout = request.bodyTimeout ?? client[kBodyTimeout] const session = client[kHTTP2Session] const { method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request let { body } = request if (upgrade) { util.errorRequest(client, request, new Error('Upgrade not supported for H2')) return false } const headers = {} for (let n = 0; n < reqHeaders.length; n += 2) { const key = reqHeaders[n + 0] const val = reqHeaders[n + 1] if (Array.isArray(val)) { for (let i = 0; i < val.length; i++) { if (headers[key]) { headers[key] += `, ${val[i]}` } else { headers[key] = val[i] } } } else if (headers[key]) { headers[key] += `, ${val}` } else { headers[key] = val } } /** @type {import('node:http2').ClientHttp2Stream} */ let stream = null const { hostname, port } = client[kUrl] headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ''}` headers[HTTP2_HEADER_METHOD] = method const abort = (err) => { if (request.aborted || request.completed) { return } err = err || new RequestAbortedError() util.errorRequest(client, request, err) if (stream != null) { // Some chunks might still come after abort, // let's ignore them stream.removeAllListeners('data') // On Abort, we close the stream to send RST_STREAM frame stream.close() // We move the running index to the next request client[kOnError](err) client[kResume]() } // We do not destroy the socket as we can continue using the session // the stream gets destroyed and the session remains to create new streams util.destroy(body, err) } try { // We are already connected, streams are pending. // We can call on connect, and wait for abort request.onConnect(abort) } catch (err) { util.errorRequest(client, request, err) } if (request.aborted) { return false } if (method === 'CONNECT') { session.ref() // We are already connected, streams are pending, first request // will create a new stream. We trigger a request to create the stream and wait until // `ready` event is triggered // We disabled endStream to allow the user to write to the stream stream = session.request(headers, { endStream: false, signal }) if (!stream.pending) { request.onUpgrade(null, null, stream) ++session[kOpenStreams] client[kQueue][client[kRunningIdx]++] = null } else { stream.once('ready', () => { request.onUpgrade(null, null, stream) ++session[kOpenStreams] client[kQueue][client[kRunningIdx]++] = null }) } stream.once('close', () => { session[kOpenStreams] -= 1 if (session[kOpenStreams] === 0) session.unref() }) stream.setTimeout(requestTimeout) return true } // https://tools.ietf.org/html/rfc7540#section-8.3 // :path and :scheme headers must be omitted when sending CONNECT headers[HTTP2_HEADER_PATH] = path headers[HTTP2_HEADER_SCHEME] = 'https' // https://tools.ietf.org/html/rfc7231#section-4.3.1 // https://tools.ietf.org/html/rfc7231#section-4.3.2 // https://tools.ietf.org/html/rfc7231#section-4.3.5 // Sending a payload body on a request that does not // expect it can cause undefined behavior on some // servers and corrupt connection state. Do not // re-use the connection for further requests. const expectsPayload = ( method === 'PUT' || method === 'POST' || method === 'PATCH' ) if (body && typeof body.read === 'function') { // Try to read EOF in order to get length. body.read(0) } let contentLength = util.bodyLength(body) if (util.isFormDataLike(body)) { extractBody ??= (__nccwpck_require__(27679).extractBody) const [bodyStream, contentType] = extractBody(body) headers['content-type'] = contentType body = bodyStream.stream contentLength = bodyStream.length } if (contentLength == null) { contentLength = request.contentLength } if (contentLength === 0 || !expectsPayload) { // https://tools.ietf.org/html/rfc7230#section-3.3.2 // A user agent SHOULD NOT send a Content-Length header field when // the request message does not contain a payload body and the method // semantics do not anticipate such a body. contentLength = null } // https://github.com/nodejs/undici/issues/2046 // A user agent may send a Content-Length header with 0 value, this should be allowed. if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) { if (client[kStrictContentLength]) { util.errorRequest(client, request, new RequestContentLengthMismatchError()) return false } process.emitWarning(new RequestContentLengthMismatchError()) } if (contentLength != null) { assert(body, 'no body must not have content length') headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}` } session.ref() if (channels.sendHeaders.hasSubscribers) { let header = '' for (const key in headers) { header += `${key}: ${headers[key]}\r\n` } channels.sendHeaders.publish({ request, headers: header, socket: session[kSocket] }) } // TODO(metcoder95): add support for sending trailers const shouldEndStream = method === 'GET' || method === 'HEAD' || body === null if (expectContinue) { headers[HTTP2_HEADER_EXPECT] = '100-continue' stream = session.request(headers, { endStream: shouldEndStream, signal }) stream.once('continue', writeBodyH2) } else { stream = session.request(headers, { endStream: shouldEndStream, signal }) writeBodyH2() } // Increment counter as we have new streams open ++session[kOpenStreams] stream.setTimeout(requestTimeout) stream.once('response', headers => { const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers request.onResponseStarted() // Due to the stream nature, it is possible we face a race condition // where the stream has been assigned, but the request has been aborted // the request remains in-flight and headers hasn't been received yet // for those scenarios, best effort is to destroy the stream immediately // as there's no value to keep it open. if (request.aborted) { stream.removeAllListeners('data') return } if (request.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream.resume.bind(stream), '') === false) { stream.pause() } }) stream.on('data', (chunk) => { if (request.onData(chunk) === false) { stream.pause() } }) stream.once('end', (err) => { stream.removeAllListeners('data') // When state is null, it means we haven't consumed body and the stream still do not have // a state. // Present specially when using pipeline or stream if (stream.state?.state == null || stream.state.state < 6) { // Do not complete the request if it was aborted // Not prone to happen for as safety net to avoid race conditions with 'trailers' if (!request.aborted && !request.completed) { request.onComplete({}) } client[kQueue][client[kRunningIdx]++] = null client[kResume]() } else { // Stream is closed or half-closed-remote (6), decrement counter and cleanup // It does not have sense to continue working with the stream as we do not // have yet RST_STREAM support on client-side --session[kOpenStreams] if (session[kOpenStreams] === 0) { session.unref() } abort(err ?? new InformationalError('HTTP/2: stream half-closed (remote)')) client[kQueue][client[kRunningIdx]++] = null client[kPendingIdx] = client[kRunningIdx] client[kResume]() } }) stream.once('close', () => { stream.removeAllListeners('data') session[kOpenStreams] -= 1 if (session[kOpenStreams] === 0) { session.unref() } }) stream.once('error', function (err) { stream.removeAllListeners('data') abort(err) }) stream.once('frameError', (type, code) => { stream.removeAllListeners('data') abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)) }) stream.on('aborted', () => { stream.removeAllListeners('data') }) stream.on('timeout', () => { const err = new InformationalError(`HTTP/2: "stream timeout after ${requestTimeout}"`) stream.removeAllListeners('data') session[kOpenStreams] -= 1 if (session[kOpenStreams] === 0) { session.unref() } abort(err) }) stream.once('trailers', trailers => { if (request.aborted || request.completed) { return } request.onComplete(trailers) }) return true function writeBodyH2 () { /* istanbul ignore else: assertion */ if (!body || contentLength === 0) { writeBuffer( abort, stream, null, client, request, client[kSocket], contentLength, expectsPayload ) } else if (util.isBuffer(body)) { writeBuffer( abort, stream, body, client, request, client[kSocket], contentLength, expectsPayload ) } else if (util.isBlobLike(body)) { if (typeof body.stream === 'function') { writeIterable( abort, stream, body.stream(), client, request, client[kSocket], contentLength, expectsPayload ) } else { writeBlob( abort, stream, body, client, request, client[kSocket], contentLength, expectsPayload ) } } else if (util.isStream(body)) { writeStream( abort, client[kSocket], expectsPayload, stream, body, client, request, contentLength ) } else if (util.isIterable(body)) { writeIterable( abort, stream, body, client, request, client[kSocket], contentLength, expectsPayload ) } else { assert(false) } } } function writeBuffer (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { try { if (body != null && util.isBuffer(body)) { assert(contentLength === body.byteLength, 'buffer body must have content length') h2stream.cork() h2stream.write(body) h2stream.uncork() h2stream.end() request.onBodySent(body) } if (!expectsPayload) { socket[kReset] = true } request.onRequestSent() client[kResume]() } catch (error) { abort(error) } } function writeStream (abort, socket, expectsPayload, h2stream, body, client, request, contentLength) { assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') // For HTTP/2, is enough to pipe the stream const pipe = pipeline( body, h2stream, (err) => { if (err) { util.destroy(pipe, err) abort(err) } else { util.removeAllListeners(pipe) request.onRequestSent() if (!expectsPayload) { socket[kReset] = true } client[kResume]() } } ) util.addListener(pipe, 'data', onPipeData) function onPipeData (chunk) { request.onBodySent(chunk) } } async function writeBlob (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { assert(contentLength === body.size, 'blob body must have content length') try { if (contentLength != null && contentLength !== body.size) { throw new RequestContentLengthMismatchError() } const buffer = Buffer.from(await body.arrayBuffer()) h2stream.cork() h2stream.write(buffer) h2stream.uncork() h2stream.end() request.onBodySent(buffer) request.onRequestSent() if (!expectsPayload) { socket[kReset] = true } client[kResume]() } catch (err) { abort(err) } } async function writeIterable (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') let callback = null function onDrain () { if (callback) { const cb = callback callback = null cb() } } const waitForDrain = () => new Promise((resolve, reject) => { assert(callback === null) if (socket[kError]) { reject(socket[kError]) } else { callback = resolve } }) h2stream .on('close', onDrain) .on('drain', onDrain) try { // It's up to the user to somehow abort the async iterable. for await (const chunk of body) { if (socket[kError]) { throw socket[kError] } const res = h2stream.write(chunk) request.onBodySent(chunk) if (!res) { await waitForDrain() } } h2stream.end() request.onRequestSent() if (!expectsPayload) { socket[kReset] = true } client[kResume]() } catch (err) { abort(err) } finally { h2stream .off('close', onDrain) .off('drain', onDrain) } } module.exports = connectH2 /***/ }), /***/ 56716: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(34589) const net = __nccwpck_require__(77030) const http = __nccwpck_require__(37067) const util = __nccwpck_require__(46425) const { ClientStats } = __nccwpck_require__(81821) const { channels } = __nccwpck_require__(69709) const Request = __nccwpck_require__(53172) const DispatcherBase = __nccwpck_require__(68750) const { InvalidArgumentError, InformationalError, ClientDestroyedError } = __nccwpck_require__(21158) const buildConnector = __nccwpck_require__(50815) const { kUrl, kServerName, kClient, kBusy, kConnect, kResuming, kRunning, kPending, kSize, kQueue, kConnected, kConnecting, kNeedDrain, kKeepAliveDefaultTimeout, kHostHeader, kPendingIdx, kRunningIdx, kError, kPipelining, kKeepAliveTimeoutValue, kMaxHeadersSize, kKeepAliveMaxTimeout, kKeepAliveTimeoutThreshold, kHeadersTimeout, kBodyTimeout, kStrictContentLength, kConnector, kMaxRequests, kCounter, kClose, kDestroy, kDispatch, kLocalAddress, kMaxResponseSize, kOnError, kHTTPContext, kMaxConcurrentStreams, kResume } = __nccwpck_require__(83112) const connectH1 = __nccwpck_require__(66874) const connectH2 = __nccwpck_require__(70599) const kClosedResolve = Symbol('kClosedResolve') const getDefaultNodeMaxHeaderSize = http && http.maxHeaderSize && Number.isInteger(http.maxHeaderSize) && http.maxHeaderSize > 0 ? () => http.maxHeaderSize : () => { throw new InvalidArgumentError('http module not available or http.maxHeaderSize invalid') } const noop = () => {} function getPipelining (client) { return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1 } /** * @type {import('../../types/client.js').default} */ class Client extends DispatcherBase { /** * * @param {string|URL} url * @param {import('../../types/client.js').Client.Options} options */ constructor (url, { maxHeaderSize, headersTimeout, socketTimeout, requestTimeout, connectTimeout, bodyTimeout, idleTimeout, keepAlive, keepAliveTimeout, maxKeepAliveTimeout, keepAliveMaxTimeout, keepAliveTimeoutThreshold, socketPath, pipelining, tls, strictContentLength, maxCachedSessions, connect, maxRequestsPerClient, localAddress, maxResponseSize, autoSelectFamily, autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, allowH2 } = {}) { if (keepAlive !== undefined) { throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') } if (socketTimeout !== undefined) { throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') } if (requestTimeout !== undefined) { throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') } if (idleTimeout !== undefined) { throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') } if (maxKeepAliveTimeout !== undefined) { throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') } if (maxHeaderSize != null) { if (!Number.isInteger(maxHeaderSize) || maxHeaderSize < 1) { throw new InvalidArgumentError('invalid maxHeaderSize') } } else { // If maxHeaderSize is not provided, use the default value from the http module // or if that is not available, throw an error. maxHeaderSize = getDefaultNodeMaxHeaderSize() } if (socketPath != null && typeof socketPath !== 'string') { throw new InvalidArgumentError('invalid socketPath') } if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { throw new InvalidArgumentError('invalid connectTimeout') } if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { throw new InvalidArgumentError('invalid keepAliveTimeout') } if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { throw new InvalidArgumentError('invalid keepAliveMaxTimeout') } if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') } if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') } if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') } if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { throw new InvalidArgumentError('connect must be a function or an object') } if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') } if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { throw new InvalidArgumentError('localAddress must be valid string IP address') } if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { throw new InvalidArgumentError('maxResponseSize must be a positive number') } if ( autoSelectFamilyAttemptTimeout != null && (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) ) { throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') } // h2 if (allowH2 != null && typeof allowH2 !== 'boolean') { throw new InvalidArgumentError('allowH2 must be a valid boolean value') } if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { throw new InvalidArgumentError('maxConcurrentStreams must be a positive integer, greater than 0') } super() if (typeof connect !== 'function') { connect = buildConnector({ ...tls, maxCachedSessions, allowH2, socketPath, timeout: connectTimeout, ...(typeof autoSelectFamily === 'boolean' ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), ...connect }) } this[kUrl] = util.parseOrigin(url) this[kConnector] = connect this[kPipelining] = pipelining != null ? pipelining : 1 this[kMaxHeadersSize] = maxHeaderSize this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 2e3 : keepAliveTimeoutThreshold this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout] this[kServerName] = null this[kLocalAddress] = localAddress != null ? localAddress : null this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n` this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3 this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3 this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength this[kMaxRequests] = maxRequestsPerClient this[kClosedResolve] = null this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1 this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server this[kHTTPContext] = null // kQueue is built up of 3 sections separated by // the kRunningIdx and kPendingIdx indices. // | complete | running | pending | // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length // kRunningIdx points to the first running element. // kPendingIdx points to the first pending element. // This implements a fast queue with an amortized // time of O(1). this[kQueue] = [] this[kRunningIdx] = 0 this[kPendingIdx] = 0 this[kResume] = (sync) => resume(this, sync) this[kOnError] = (err) => onError(this, err) } get pipelining () { return this[kPipelining] } set pipelining (value) { this[kPipelining] = value this[kResume](true) } get stats () { return new ClientStats(this) } get [kPending] () { return this[kQueue].length - this[kPendingIdx] } get [kRunning] () { return this[kPendingIdx] - this[kRunningIdx] } get [kSize] () { return this[kQueue].length - this[kRunningIdx] } get [kConnected] () { return !!this[kHTTPContext] && !this[kConnecting] && !this[kHTTPContext].destroyed } get [kBusy] () { return Boolean( this[kHTTPContext]?.busy(null) || (this[kSize] >= (getPipelining(this) || 1)) || this[kPending] > 0 ) } /* istanbul ignore: only used for test */ [kConnect] (cb) { connect(this) this.once('connect', cb) } [kDispatch] (opts, handler) { const origin = opts.origin || this[kUrl].origin const request = new Request(origin, opts, handler) this[kQueue].push(request) if (this[kResuming]) { // Do nothing. } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) { // Wait a tick in case stream/iterator is ended in the same tick. this[kResuming] = 1 queueMicrotask(() => resume(this)) } else { this[kResume](true) } if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { this[kNeedDrain] = 2 } return this[kNeedDrain] < 2 } async [kClose] () { // TODO: for H2 we need to gracefully flush the remaining enqueued // request and close each stream. return new Promise((resolve) => { if (this[kSize]) { this[kClosedResolve] = resolve } else { resolve(null) } }) } async [kDestroy] (err) { return new Promise((resolve) => { const requests = this[kQueue].splice(this[kPendingIdx]) for (let i = 0; i < requests.length; i++) { const request = requests[i] util.errorRequest(this, request, err) } const callback = () => { if (this[kClosedResolve]) { // TODO (fix): Should we error here with ClientDestroyedError? this[kClosedResolve]() this[kClosedResolve] = null } resolve(null) } if (this[kHTTPContext]) { this[kHTTPContext].destroy(err, callback) this[kHTTPContext] = null } else { queueMicrotask(callback) } this[kResume]() }) } } function onError (client, err) { if ( client[kRunning] === 0 && err.code !== 'UND_ERR_INFO' && err.code !== 'UND_ERR_SOCKET' ) { // Error is not caused by running request and not a recoverable // socket error. assert(client[kPendingIdx] === client[kRunningIdx]) const requests = client[kQueue].splice(client[kRunningIdx]) for (let i = 0; i < requests.length; i++) { const request = requests[i] util.errorRequest(client, request, err) } assert(client[kSize] === 0) } } /** * @param {Client} client * @returns */ async function connect (client) { assert(!client[kConnecting]) assert(!client[kHTTPContext]) let { host, hostname, protocol, port } = client[kUrl] // Resolve ipv6 if (hostname[0] === '[') { const idx = hostname.indexOf(']') assert(idx !== -1) const ip = hostname.substring(1, idx) assert(net.isIPv6(ip)) hostname = ip } client[kConnecting] = true if (channels.beforeConnect.hasSubscribers) { channels.beforeConnect.publish({ connectParams: { host, hostname, protocol, port, version: client[kHTTPContext]?.version, servername: client[kServerName], localAddress: client[kLocalAddress] }, connector: client[kConnector] }) } try { const socket = await new Promise((resolve, reject) => { client[kConnector]({ host, hostname, protocol, port, servername: client[kServerName], localAddress: client[kLocalAddress] }, (err, socket) => { if (err) { reject(err) } else { resolve(socket) } }) }) if (client.destroyed) { util.destroy(socket.on('error', noop), new ClientDestroyedError()) return } assert(socket) try { client[kHTTPContext] = socket.alpnProtocol === 'h2' ? await connectH2(client, socket) : await connectH1(client, socket) } catch (err) { socket.destroy().on('error', noop) throw err } client[kConnecting] = false socket[kCounter] = 0 socket[kMaxRequests] = client[kMaxRequests] socket[kClient] = client socket[kError] = null if (channels.connected.hasSubscribers) { channels.connected.publish({ connectParams: { host, hostname, protocol, port, version: client[kHTTPContext]?.version, servername: client[kServerName], localAddress: client[kLocalAddress] }, connector: client[kConnector], socket }) } client.emit('connect', client[kUrl], [client]) } catch (err) { if (client.destroyed) { return } client[kConnecting] = false if (channels.connectError.hasSubscribers) { channels.connectError.publish({ connectParams: { host, hostname, protocol, port, version: client[kHTTPContext]?.version, servername: client[kServerName], localAddress: client[kLocalAddress] }, connector: client[kConnector], error: err }) } if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { assert(client[kRunning] === 0) while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) { const request = client[kQueue][client[kPendingIdx]++] util.errorRequest(client, request, err) } } else { onError(client, err) } client.emit('connectionError', client[kUrl], [client], err) } client[kResume]() } function emitDrain (client) { client[kNeedDrain] = 0 client.emit('drain', client[kUrl], [client]) } function resume (client, sync) { if (client[kResuming] === 2) { return } client[kResuming] = 2 _resume(client, sync) client[kResuming] = 0 if (client[kRunningIdx] > 256) { client[kQueue].splice(0, client[kRunningIdx]) client[kPendingIdx] -= client[kRunningIdx] client[kRunningIdx] = 0 } } function _resume (client, sync) { while (true) { if (client.destroyed) { assert(client[kPending] === 0) return } if (client[kClosedResolve] && !client[kSize]) { client[kClosedResolve]() client[kClosedResolve] = null return } if (client[kHTTPContext]) { client[kHTTPContext].resume() } if (client[kBusy]) { client[kNeedDrain] = 2 } else if (client[kNeedDrain] === 2) { if (sync) { client[kNeedDrain] = 1 queueMicrotask(() => emitDrain(client)) } else { emitDrain(client) } continue } if (client[kPending] === 0) { return } if (client[kRunning] >= (getPipelining(client) || 1)) { return } const request = client[kQueue][client[kPendingIdx]] if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { if (client[kRunning] > 0) { return } client[kServerName] = request.servername client[kHTTPContext]?.destroy(new InformationalError('servername changed'), () => { client[kHTTPContext] = null resume(client) }) } if (client[kConnecting]) { return } if (!client[kHTTPContext]) { connect(client) return } if (client[kHTTPContext].destroyed) { return } if (client[kHTTPContext].busy(request)) { return } if (!request.aborted && client[kHTTPContext].write(request)) { client[kPendingIdx]++ } else { client[kQueue].splice(client[kPendingIdx], 1) } } } module.exports = Client /***/ }), /***/ 68750: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Dispatcher = __nccwpck_require__(24350) const UnwrapHandler = __nccwpck_require__(14586) const { ClientDestroyedError, ClientClosedError, InvalidArgumentError } = __nccwpck_require__(21158) const { kDestroy, kClose, kClosed, kDestroyed, kDispatch } = __nccwpck_require__(83112) const kOnDestroyed = Symbol('onDestroyed') const kOnClosed = Symbol('onClosed') class DispatcherBase extends Dispatcher { constructor () { super() this[kDestroyed] = false this[kOnDestroyed] = null this[kClosed] = false this[kOnClosed] = [] } get destroyed () { return this[kDestroyed] } get closed () { return this[kClosed] } close (callback) { if (callback === undefined) { return new Promise((resolve, reject) => { this.close((err, data) => { return err ? reject(err) : resolve(data) }) }) } if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } if (this[kDestroyed]) { queueMicrotask(() => callback(new ClientDestroyedError(), null)) return } if (this[kClosed]) { if (this[kOnClosed]) { this[kOnClosed].push(callback) } else { queueMicrotask(() => callback(null, null)) } return } this[kClosed] = true this[kOnClosed].push(callback) const onClosed = () => { const callbacks = this[kOnClosed] this[kOnClosed] = null for (let i = 0; i < callbacks.length; i++) { callbacks[i](null, null) } } // Should not error. this[kClose]() .then(() => this.destroy()) .then(() => { queueMicrotask(onClosed) }) } destroy (err, callback) { if (typeof err === 'function') { callback = err err = null } if (callback === undefined) { return new Promise((resolve, reject) => { this.destroy(err, (err, data) => { return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data) }) }) } if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } if (this[kDestroyed]) { if (this[kOnDestroyed]) { this[kOnDestroyed].push(callback) } else { queueMicrotask(() => callback(null, null)) } return } if (!err) { err = new ClientDestroyedError() } this[kDestroyed] = true this[kOnDestroyed] = this[kOnDestroyed] || [] this[kOnDestroyed].push(callback) const onDestroyed = () => { const callbacks = this[kOnDestroyed] this[kOnDestroyed] = null for (let i = 0; i < callbacks.length; i++) { callbacks[i](null, null) } } // Should not error. this[kDestroy](err).then(() => { queueMicrotask(onDestroyed) }) } dispatch (opts, handler) { if (!handler || typeof handler !== 'object') { throw new InvalidArgumentError('handler must be an object') } handler = UnwrapHandler.unwrap(handler) try { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('opts must be an object.') } if (this[kDestroyed] || this[kOnDestroyed]) { throw new ClientDestroyedError() } if (this[kClosed]) { throw new ClientClosedError() } return this[kDispatch](opts, handler) } catch (err) { if (typeof handler.onError !== 'function') { throw err } handler.onError(err) return false } } } module.exports = DispatcherBase /***/ }), /***/ 24350: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const EventEmitter = __nccwpck_require__(78474) const WrapHandler = __nccwpck_require__(3541) const wrapInterceptor = (dispatch) => (opts, handler) => dispatch(opts, WrapHandler.wrap(handler)) class Dispatcher extends EventEmitter { dispatch () { throw new Error('not implemented') } close () { throw new Error('not implemented') } destroy () { throw new Error('not implemented') } compose (...args) { // So we handle [interceptor1, interceptor2] or interceptor1, interceptor2, ... const interceptors = Array.isArray(args[0]) ? args[0] : args let dispatch = this.dispatch.bind(this) for (const interceptor of interceptors) { if (interceptor == null) { continue } if (typeof interceptor !== 'function') { throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`) } dispatch = interceptor(dispatch) dispatch = wrapInterceptor(dispatch) if (dispatch == null || typeof dispatch !== 'function' || dispatch.length !== 2) { throw new TypeError('invalid interceptor') } } return new Proxy(this, { get: (target, key) => key === 'dispatch' ? dispatch : target[key] }) } } module.exports = Dispatcher /***/ }), /***/ 60592: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const DispatcherBase = __nccwpck_require__(68750) const { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = __nccwpck_require__(83112) const ProxyAgent = __nccwpck_require__(7851) const Agent = __nccwpck_require__(11538) const DEFAULT_PORTS = { 'http:': 80, 'https:': 443 } class EnvHttpProxyAgent extends DispatcherBase { #noProxyValue = null #noProxyEntries = null #opts = null constructor (opts = {}) { super() this.#opts = opts const { httpProxy, httpsProxy, noProxy, ...agentOpts } = opts this[kNoProxyAgent] = new Agent(agentOpts) const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY if (HTTP_PROXY) { this[kHttpProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTP_PROXY }) } else { this[kHttpProxyAgent] = this[kNoProxyAgent] } const HTTPS_PROXY = httpsProxy ?? process.env.https_proxy ?? process.env.HTTPS_PROXY if (HTTPS_PROXY) { this[kHttpsProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTPS_PROXY }) } else { this[kHttpsProxyAgent] = this[kHttpProxyAgent] } this.#parseNoProxy() } [kDispatch] (opts, handler) { const url = new URL(opts.origin) const agent = this.#getProxyAgentForUrl(url) return agent.dispatch(opts, handler) } async [kClose] () { await this[kNoProxyAgent].close() if (!this[kHttpProxyAgent][kClosed]) { await this[kHttpProxyAgent].close() } if (!this[kHttpsProxyAgent][kClosed]) { await this[kHttpsProxyAgent].close() } } async [kDestroy] (err) { await this[kNoProxyAgent].destroy(err) if (!this[kHttpProxyAgent][kDestroyed]) { await this[kHttpProxyAgent].destroy(err) } if (!this[kHttpsProxyAgent][kDestroyed]) { await this[kHttpsProxyAgent].destroy(err) } } #getProxyAgentForUrl (url) { let { protocol, host: hostname, port } = url // Stripping ports in this way instead of using parsedUrl.hostname to make // sure that the brackets around IPv6 addresses are kept. hostname = hostname.replace(/:\d*$/, '').toLowerCase() port = Number.parseInt(port, 10) || DEFAULT_PORTS[protocol] || 0 if (!this.#shouldProxy(hostname, port)) { return this[kNoProxyAgent] } if (protocol === 'https:') { return this[kHttpsProxyAgent] } return this[kHttpProxyAgent] } #shouldProxy (hostname, port) { if (this.#noProxyChanged) { this.#parseNoProxy() } if (this.#noProxyEntries.length === 0) { return true // Always proxy if NO_PROXY is not set or empty. } if (this.#noProxyValue === '*') { return false // Never proxy if wildcard is set. } for (let i = 0; i < this.#noProxyEntries.length; i++) { const entry = this.#noProxyEntries[i] if (entry.port && entry.port !== port) { continue // Skip if ports don't match. } if (!/^[.*]/.test(entry.hostname)) { // No wildcards, so don't proxy only if there is not an exact match. if (hostname === entry.hostname) { return false } } else { // Don't proxy if the hostname ends with the no_proxy host. if (hostname.endsWith(entry.hostname.replace(/^\*/, ''))) { return false } } } return true } #parseNoProxy () { const noProxyValue = this.#opts.noProxy ?? this.#noProxyEnv const noProxySplit = noProxyValue.split(/[,\s]/) const noProxyEntries = [] for (let i = 0; i < noProxySplit.length; i++) { const entry = noProxySplit[i] if (!entry) { continue } const parsed = entry.match(/^(.+):(\d+)$/) noProxyEntries.push({ hostname: (parsed ? parsed[1] : entry).toLowerCase(), port: parsed ? Number.parseInt(parsed[2], 10) : 0 }) } this.#noProxyValue = noProxyValue this.#noProxyEntries = noProxyEntries } get #noProxyChanged () { if (this.#opts.noProxy !== undefined) { return false } return this.#noProxyValue !== this.#noProxyEnv } get #noProxyEnv () { return process.env.no_proxy ?? process.env.NO_PROXY ?? '' } } module.exports = EnvHttpProxyAgent /***/ }), /***/ 46335: /***/ ((module) => { "use strict"; // Extracted from node/lib/internal/fixed_queue.js // Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. const kSize = 2048 const kMask = kSize - 1 // The FixedQueue is implemented as a singly-linked list of fixed-size // circular buffers. It looks something like this: // // head tail // | | // v v // +-----------+ <-----\ +-----------+ <------\ +-----------+ // | [null] | \----- | next | \------- | next | // +-----------+ +-----------+ +-----------+ // | item | <-- bottom | item | <-- bottom | undefined | // | item | | item | | undefined | // | item | | item | | undefined | // | item | | item | | undefined | // | item | | item | bottom --> | item | // | item | | item | | item | // | ... | | ... | | ... | // | item | | item | | item | // | item | | item | | item | // | undefined | <-- top | item | | item | // | undefined | | item | | item | // | undefined | | undefined | <-- top top --> | undefined | // +-----------+ +-----------+ +-----------+ // // Or, if there is only one circular buffer, it looks something // like either of these: // // head tail head tail // | | | | // v v v v // +-----------+ +-----------+ // | [null] | | [null] | // +-----------+ +-----------+ // | undefined | | item | // | undefined | | item | // | item | <-- bottom top --> | undefined | // | item | | undefined | // | undefined | <-- top bottom --> | item | // | undefined | | item | // +-----------+ +-----------+ // // Adding a value means moving `top` forward by one, removing means // moving `bottom` forward by one. After reaching the end, the queue // wraps around. // // When `top === bottom` the current queue is empty and when // `top + 1 === bottom` it's full. This wastes a single space of storage // but allows much quicker checks. /** * @type {FixedCircularBuffer} * @template T */ class FixedCircularBuffer { constructor () { /** * @type {number} */ this.bottom = 0 /** * @type {number} */ this.top = 0 /** * @type {Array} */ this.list = new Array(kSize).fill(undefined) /** * @type {T|null} */ this.next = null } /** * @returns {boolean} */ isEmpty () { return this.top === this.bottom } /** * @returns {boolean} */ isFull () { return ((this.top + 1) & kMask) === this.bottom } /** * @param {T} data * @returns {void} */ push (data) { this.list[this.top] = data this.top = (this.top + 1) & kMask } /** * @returns {T|null} */ shift () { const nextItem = this.list[this.bottom] if (nextItem === undefined) { return null } this.list[this.bottom] = undefined this.bottom = (this.bottom + 1) & kMask return nextItem } } /** * @template T */ module.exports = class FixedQueue { constructor () { /** * @type {FixedCircularBuffer} */ this.head = this.tail = new FixedCircularBuffer() } /** * @returns {boolean} */ isEmpty () { return this.head.isEmpty() } /** * @param {T} data */ push (data) { if (this.head.isFull()) { // Head is full: Creates a new queue, sets the old queue's `.next` to it, // and sets it as the new main queue. this.head = this.head.next = new FixedCircularBuffer() } this.head.push(data) } /** * @returns {T|null} */ shift () { const tail = this.tail const next = tail.shift() if (tail.isEmpty() && tail.next !== null) { // If there is another queue, it forms the new tail. this.tail = tail.next tail.next = null } return next } } /***/ }), /***/ 77046: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { connect } = __nccwpck_require__(77030) const { kClose, kDestroy } = __nccwpck_require__(83112) const { InvalidArgumentError } = __nccwpck_require__(21158) const util = __nccwpck_require__(46425) const Client = __nccwpck_require__(56716) const DispatcherBase = __nccwpck_require__(68750) class H2CClient extends DispatcherBase { #client = null constructor (origin, clientOpts) { super() if (typeof origin === 'string') { origin = new URL(origin) } if (origin.protocol !== 'http:') { throw new InvalidArgumentError( 'h2c-client: Only h2c protocol is supported' ) } const { connect, maxConcurrentStreams, pipelining, ...opts } = clientOpts ?? {} let defaultMaxConcurrentStreams = 100 let defaultPipelining = 100 if ( maxConcurrentStreams != null && Number.isInteger(maxConcurrentStreams) && maxConcurrentStreams > 0 ) { defaultMaxConcurrentStreams = maxConcurrentStreams } if (pipelining != null && Number.isInteger(pipelining) && pipelining > 0) { defaultPipelining = pipelining } if (defaultPipelining > defaultMaxConcurrentStreams) { throw new InvalidArgumentError( 'h2c-client: pipelining cannot be greater than maxConcurrentStreams' ) } this.#client = new Client(origin, { ...opts, connect: this.#buildConnector(connect), maxConcurrentStreams: defaultMaxConcurrentStreams, pipelining: defaultPipelining, allowH2: true }) } #buildConnector (connectOpts) { return (opts, callback) => { const timeout = connectOpts?.connectOpts ?? 10e3 const { hostname, port, pathname } = opts const socket = connect({ ...opts, host: hostname, port, pathname }) // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket if (opts.keepAlive == null || opts.keepAlive) { const keepAliveInitialDelay = opts.keepAliveInitialDelay == null ? 60e3 : opts.keepAliveInitialDelay socket.setKeepAlive(true, keepAliveInitialDelay) } socket.alpnProtocol = 'h2' const clearConnectTimeout = util.setupConnectTimeout( new WeakRef(socket), { timeout, hostname, port } ) socket .setNoDelay(true) .once('connect', function () { queueMicrotask(clearConnectTimeout) if (callback) { const cb = callback callback = null cb(null, this) } }) .on('error', function (err) { queueMicrotask(clearConnectTimeout) if (callback) { const cb = callback callback = null cb(err) } }) return socket } } dispatch (opts, handler) { return this.#client.dispatch(opts, handler) } async [kClose] () { await this.#client.close() } async [kDestroy] () { await this.#client.destroy() } } module.exports = H2CClient /***/ }), /***/ 57659: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { PoolStats } = __nccwpck_require__(81821) const DispatcherBase = __nccwpck_require__(68750) const FixedQueue = __nccwpck_require__(46335) const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(83112) const kClients = Symbol('clients') const kNeedDrain = Symbol('needDrain') const kQueue = Symbol('queue') const kClosedResolve = Symbol('closed resolve') const kOnDrain = Symbol('onDrain') const kOnConnect = Symbol('onConnect') const kOnDisconnect = Symbol('onDisconnect') const kOnConnectionError = Symbol('onConnectionError') const kGetDispatcher = Symbol('get dispatcher') const kAddClient = Symbol('add client') const kRemoveClient = Symbol('remove client') class PoolBase extends DispatcherBase { constructor () { super() this[kQueue] = new FixedQueue() this[kClients] = [] this[kQueued] = 0 const pool = this this[kOnDrain] = function onDrain (origin, targets) { const queue = pool[kQueue] let needDrain = false while (!needDrain) { const item = queue.shift() if (!item) { break } pool[kQueued]-- needDrain = !this.dispatch(item.opts, item.handler) } this[kNeedDrain] = needDrain if (!this[kNeedDrain] && pool[kNeedDrain]) { pool[kNeedDrain] = false pool.emit('drain', origin, [pool, ...targets]) } if (pool[kClosedResolve] && queue.isEmpty()) { Promise .all(pool[kClients].map(c => c.close())) .then(pool[kClosedResolve]) } } this[kOnConnect] = (origin, targets) => { pool.emit('connect', origin, [pool, ...targets]) } this[kOnDisconnect] = (origin, targets, err) => { pool.emit('disconnect', origin, [pool, ...targets], err) } this[kOnConnectionError] = (origin, targets, err) => { pool.emit('connectionError', origin, [pool, ...targets], err) } } get [kBusy] () { return this[kNeedDrain] } get [kConnected] () { return this[kClients].filter(client => client[kConnected]).length } get [kFree] () { return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length } get [kPending] () { let ret = this[kQueued] for (const { [kPending]: pending } of this[kClients]) { ret += pending } return ret } get [kRunning] () { let ret = 0 for (const { [kRunning]: running } of this[kClients]) { ret += running } return ret } get [kSize] () { let ret = this[kQueued] for (const { [kSize]: size } of this[kClients]) { ret += size } return ret } get stats () { return new PoolStats(this) } async [kClose] () { if (this[kQueue].isEmpty()) { await Promise.all(this[kClients].map(c => c.close())) } else { await new Promise((resolve) => { this[kClosedResolve] = resolve }) } } async [kDestroy] (err) { while (true) { const item = this[kQueue].shift() if (!item) { break } item.handler.onError(err) } await Promise.all(this[kClients].map(c => c.destroy(err))) } [kDispatch] (opts, handler) { const dispatcher = this[kGetDispatcher]() if (!dispatcher) { this[kNeedDrain] = true this[kQueue].push({ opts, handler }) this[kQueued]++ } else if (!dispatcher.dispatch(opts, handler)) { dispatcher[kNeedDrain] = true this[kNeedDrain] = !this[kGetDispatcher]() } return !this[kNeedDrain] } [kAddClient] (client) { client .on('drain', this[kOnDrain]) .on('connect', this[kOnConnect]) .on('disconnect', this[kOnDisconnect]) .on('connectionError', this[kOnConnectionError]) this[kClients].push(client) if (this[kNeedDrain]) { queueMicrotask(() => { if (this[kNeedDrain]) { this[kOnDrain](client[kUrl], [this, client]) } }) } return this } [kRemoveClient] (client) { client.close(() => { const idx = this[kClients].indexOf(client) if (idx !== -1) { this[kClients].splice(idx, 1) } }) this[kNeedDrain] = this[kClients].some(dispatcher => ( !dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true )) } } module.exports = { PoolBase, kClients, kNeedDrain, kAddClient, kRemoveClient, kGetDispatcher } /***/ }), /***/ 74561: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { PoolBase, kClients, kNeedDrain, kAddClient, kGetDispatcher, kRemoveClient } = __nccwpck_require__(57659) const Client = __nccwpck_require__(56716) const { InvalidArgumentError } = __nccwpck_require__(21158) const util = __nccwpck_require__(46425) const { kUrl } = __nccwpck_require__(83112) const buildConnector = __nccwpck_require__(50815) const kOptions = Symbol('options') const kConnections = Symbol('connections') const kFactory = Symbol('factory') function defaultFactory (origin, opts) { return new Client(origin, opts) } class Pool extends PoolBase { constructor (origin, { connections, factory = defaultFactory, connect, connectTimeout, tls, maxCachedSessions, socketPath, autoSelectFamily, autoSelectFamilyAttemptTimeout, allowH2, clientTtl, ...options } = {}) { if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError('invalid connections') } if (typeof factory !== 'function') { throw new InvalidArgumentError('factory must be a function.') } if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { throw new InvalidArgumentError('connect must be a function or an object') } super() if (typeof connect !== 'function') { connect = buildConnector({ ...tls, maxCachedSessions, allowH2, socketPath, timeout: connectTimeout, ...(typeof autoSelectFamily === 'boolean' ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), ...connect }) } this[kConnections] = connections || null this[kUrl] = util.parseOrigin(origin) this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl } this[kOptions].interceptors = options.interceptors ? { ...options.interceptors } : undefined this[kFactory] = factory this.on('connect', (origin, targets) => { if (clientTtl != null && clientTtl > 0) { for (const target of targets) { Object.assign(target, { ttl: Date.now() }) } } }) this.on('connectionError', (origin, targets, error) => { // If a connection error occurs, we remove the client from the pool, // and emit a connectionError event. They will not be re-used. // Fixes https://github.com/nodejs/undici/issues/3895 for (const target of targets) { // Do not use kRemoveClient here, as it will close the client, // but the client cannot be closed in this state. const idx = this[kClients].indexOf(target) if (idx !== -1) { this[kClients].splice(idx, 1) } } }) } [kGetDispatcher] () { const clientTtlOption = this[kOptions].clientTtl for (const client of this[kClients]) { // check ttl of client and if it's stale, remove it from the pool if (clientTtlOption != null && clientTtlOption > 0 && client.ttl && ((Date.now() - client.ttl) > clientTtlOption)) { this[kRemoveClient](client) } else if (!client[kNeedDrain]) { return client } } if (!this[kConnections] || this[kClients].length < this[kConnections]) { const dispatcher = this[kFactory](this[kUrl], this[kOptions]) this[kAddClient](dispatcher) return dispatcher } } } module.exports = Pool /***/ }), /***/ 7851: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { kProxy, kClose, kDestroy, kDispatch, kConnector } = __nccwpck_require__(83112) const { URL } = __nccwpck_require__(73136) const Agent = __nccwpck_require__(11538) const Pool = __nccwpck_require__(74561) const DispatcherBase = __nccwpck_require__(68750) const { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = __nccwpck_require__(21158) const buildConnector = __nccwpck_require__(50815) const Client = __nccwpck_require__(56716) const kAgent = Symbol('proxy agent') const kClient = Symbol('proxy client') const kProxyHeaders = Symbol('proxy headers') const kRequestTls = Symbol('request tls settings') const kProxyTls = Symbol('proxy tls settings') const kConnectEndpoint = Symbol('connect endpoint function') const kTunnelProxy = Symbol('tunnel proxy') function defaultProtocolPort (protocol) { return protocol === 'https:' ? 443 : 80 } function defaultFactory (origin, opts) { return new Pool(origin, opts) } const noop = () => {} class ProxyClient extends DispatcherBase { #client = null constructor (origin, opts) { if (typeof origin === 'string') { origin = new URL(origin) } if (origin.protocol !== 'http:' && origin.protocol !== 'https:') { throw new InvalidArgumentError('ProxyClient only supports http and https protocols') } super() this.#client = new Client(origin, opts) } async [kClose] () { await this.#client.close() } async [kDestroy] () { await this.#client.destroy() } async [kDispatch] (opts, handler) { const { method, origin } = opts if (method === 'CONNECT') { this.#client[kConnector]({ origin, port: opts.port || defaultProtocolPort(opts.protocol), path: opts.host, signal: opts.signal, headers: { ...this[kProxyHeaders], host: opts.host }, servername: this[kProxyTls]?.servername || opts.servername }, (err, socket) => { if (err) { handler.callback(err) } else { handler.callback(null, { socket, statusCode: 200 }) } } ) return } if (typeof origin === 'string') { opts.origin = new URL(origin) } return this.#client.dispatch(opts, handler) } } class ProxyAgent extends DispatcherBase { constructor (opts) { if (!opts || (typeof opts === 'object' && !(opts instanceof URL) && !opts.uri)) { throw new InvalidArgumentError('Proxy uri is mandatory') } const { clientFactory = defaultFactory } = opts if (typeof clientFactory !== 'function') { throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.') } const { proxyTunnel = true } = opts super() const url = this.#getUrl(opts) const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url this[kProxy] = { uri: href, protocol } this[kRequestTls] = opts.requestTls this[kProxyTls] = opts.proxyTls this[kProxyHeaders] = opts.headers || {} if (opts.auth && opts.token) { throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token') } else if (opts.auth) { /* @deprecated in favour of opts.token */ this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}` } else if (opts.token) { this[kProxyHeaders]['proxy-authorization'] = opts.token } else if (username && password) { this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}` } const factory = (!proxyTunnel && protocol === 'http:') ? (origin, options) => { if (origin.protocol === 'http:') { return new ProxyClient(origin, options) } return new Client(origin, options) } : undefined const connect = buildConnector({ ...opts.proxyTls }) this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }) this[kClient] = clientFactory(url, { connect, factory }) this[kTunnelProxy] = proxyTunnel this[kAgent] = new Agent({ ...opts, connect: async (opts, callback) => { let requestedPath = opts.host if (!opts.port) { requestedPath += `:${defaultProtocolPort(opts.protocol)}` } try { const { socket, statusCode } = await this[kClient].connect({ origin, port, path: requestedPath, signal: opts.signal, headers: { ...this[kProxyHeaders], host: opts.host, ...(opts.connections == null || opts.connections > 0 ? { 'proxy-connection': 'keep-alive' } : {}) }, servername: this[kProxyTls]?.servername || proxyHostname }) if (statusCode !== 200) { socket.on('error', noop).destroy() callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`)) } if (opts.protocol !== 'https:') { callback(null, socket) return } let servername if (this[kRequestTls]) { servername = this[kRequestTls].servername } else { servername = opts.servername } this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback) } catch (err) { if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { // Throw a custom error to avoid loop in client.js#connect callback(new SecureProxyConnectionError(err)) } else { callback(err) } } } }) } dispatch (opts, handler) { const headers = buildHeaders(opts.headers) throwIfProxyAuthIsSent(headers) if (headers && !('host' in headers) && !('Host' in headers)) { const { host } = new URL(opts.origin) headers.host = host } if (!this.#shouldConnect(new URL(opts.origin))) { opts.path = opts.origin + opts.path } return this[kAgent].dispatch( { ...opts, headers }, handler ) } /** * @param {import('../types/proxy-agent').ProxyAgent.Options | string | URL} opts * @returns {URL} */ #getUrl (opts) { if (typeof opts === 'string') { return new URL(opts) } else if (opts instanceof URL) { return opts } else { return new URL(opts.uri) } } async [kClose] () { await this[kAgent].close() await this[kClient].close() } async [kDestroy] () { await this[kAgent].destroy() await this[kClient].destroy() } #shouldConnect (uri) { if (typeof uri === 'string') { uri = new URL(uri) } if (this[kTunnelProxy]) { return true } if (uri.protocol !== 'http:' || this[kProxy].protocol !== 'http:') { return true } return false } } /** * @param {string[] | Record} headers * @returns {Record} */ function buildHeaders (headers) { // When using undici.fetch, the headers list is stored // as an array. if (Array.isArray(headers)) { /** @type {Record} */ const headersPair = {} for (let i = 0; i < headers.length; i += 2) { headersPair[headers[i]] = headers[i + 1] } return headersPair } return headers } /** * @param {Record} headers * * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers * Nevertheless, it was changed and to avoid a security vulnerability by end users * this check was created. * It should be removed in the next major version for performance reasons */ function throwIfProxyAuthIsSent (headers) { const existProxyAuth = headers && Object.keys(headers) .find((key) => key.toLowerCase() === 'proxy-authorization') if (existProxyAuth) { throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor') } } module.exports = ProxyAgent /***/ }), /***/ 489: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Dispatcher = __nccwpck_require__(24350) const RetryHandler = __nccwpck_require__(90093) class RetryAgent extends Dispatcher { #agent = null #options = null constructor (agent, options = {}) { super(options) this.#agent = agent this.#options = options } dispatch (opts, handler) { const retry = new RetryHandler({ ...opts, retryOptions: this.#options }, { dispatch: this.#agent.dispatch.bind(this.#agent), handler }) return this.#agent.dispatch(opts, retry) } close () { return this.#agent.close() } destroy () { return this.#agent.destroy() } } module.exports = RetryAgent /***/ }), /***/ 14266: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // We include a version number for the Dispatcher API. In case of breaking changes, // this version number must be increased to avoid conflicts. const globalDispatcher = Symbol.for('undici.globalDispatcher.1') const { InvalidArgumentError } = __nccwpck_require__(21158) const Agent = __nccwpck_require__(11538) if (getGlobalDispatcher() === undefined) { setGlobalDispatcher(new Agent()) } function setGlobalDispatcher (agent) { if (!agent || typeof agent.dispatch !== 'function') { throw new InvalidArgumentError('Argument agent must implement Agent') } Object.defineProperty(globalThis, globalDispatcher, { value: agent, writable: true, enumerable: false, configurable: false }) } function getGlobalDispatcher () { return globalThis[globalDispatcher] } module.exports = { setGlobalDispatcher, getGlobalDispatcher } /***/ }), /***/ 31233: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const util = __nccwpck_require__(46425) const { parseCacheControlHeader, parseVaryHeader, isEtagUsable } = __nccwpck_require__(27128) const { parseHttpDate } = __nccwpck_require__(48760) function noop () {} // Status codes that we can use some heuristics on to cache const HEURISTICALLY_CACHEABLE_STATUS_CODES = [ 200, 203, 204, 206, 300, 301, 308, 404, 405, 410, 414, 501 ] const MAX_RESPONSE_AGE = 2147483647000 /** * @typedef {import('../../types/dispatcher.d.ts').default.DispatchHandler} DispatchHandler * * @implements {DispatchHandler} */ class CacheHandler { /** * @type {import('../../types/cache-interceptor.d.ts').default.CacheKey} */ #cacheKey /** * @type {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions['type']} */ #cacheType /** * @type {number | undefined} */ #cacheByDefault /** * @type {import('../../types/cache-interceptor.d.ts').default.CacheStore} */ #store /** * @type {import('../../types/dispatcher.d.ts').default.DispatchHandler} */ #handler /** * @type {import('node:stream').Writable | undefined} */ #writeStream /** * @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions} opts * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey * @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler */ constructor ({ store, type, cacheByDefault }, cacheKey, handler) { this.#store = store this.#cacheType = type this.#cacheByDefault = cacheByDefault this.#cacheKey = cacheKey this.#handler = handler } onRequestStart (controller, context) { this.#writeStream?.destroy() this.#writeStream = undefined this.#handler.onRequestStart?.(controller, context) } onRequestUpgrade (controller, statusCode, headers, socket) { this.#handler.onRequestUpgrade?.(controller, statusCode, headers, socket) } /** * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller * @param {number} statusCode * @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders * @param {string} statusMessage */ onResponseStart ( controller, statusCode, resHeaders, statusMessage ) { const downstreamOnHeaders = () => this.#handler.onResponseStart?.( controller, statusCode, resHeaders, statusMessage ) if ( !util.safeHTTPMethods.includes(this.#cacheKey.method) && statusCode >= 200 && statusCode <= 399 ) { // Successful response to an unsafe method, delete it from cache // https://www.rfc-editor.org/rfc/rfc9111.html#name-invalidating-stored-response try { this.#store.delete(this.#cacheKey)?.catch?.(noop) } catch { // Fail silently } return downstreamOnHeaders() } const cacheControlHeader = resHeaders['cache-control'] const heuristicallyCacheable = resHeaders['last-modified'] && HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode) if ( !cacheControlHeader && !resHeaders['expires'] && !heuristicallyCacheable && !this.#cacheByDefault ) { // Don't have anything to tell us this response is cachable and we're not // caching by default return downstreamOnHeaders() } const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {} if (!canCacheResponse(this.#cacheType, statusCode, resHeaders, cacheControlDirectives)) { return downstreamOnHeaders() } const now = Date.now() const resAge = resHeaders.age ? getAge(resHeaders.age) : undefined if (resAge && resAge >= MAX_RESPONSE_AGE) { // Response considered stale return downstreamOnHeaders() } const resDate = typeof resHeaders.date === 'string' ? parseHttpDate(resHeaders.date) : undefined const staleAt = determineStaleAt(this.#cacheType, now, resAge, resHeaders, resDate, cacheControlDirectives) ?? this.#cacheByDefault if (staleAt === undefined || (resAge && resAge > staleAt)) { return downstreamOnHeaders() } const baseTime = resDate ? resDate.getTime() : now const absoluteStaleAt = staleAt + baseTime if (now >= absoluteStaleAt) { // Response is already stale return downstreamOnHeaders() } let varyDirectives if (this.#cacheKey.headers && resHeaders.vary) { varyDirectives = parseVaryHeader(resHeaders.vary, this.#cacheKey.headers) if (!varyDirectives) { // Parse error return downstreamOnHeaders() } } const deleteAt = determineDeleteAt(baseTime, cacheControlDirectives, absoluteStaleAt) const strippedHeaders = stripNecessaryHeaders(resHeaders, cacheControlDirectives) /** * @type {import('../../types/cache-interceptor.d.ts').default.CacheValue} */ const value = { statusCode, statusMessage, headers: strippedHeaders, vary: varyDirectives, cacheControlDirectives, cachedAt: resAge ? now - resAge : now, staleAt: absoluteStaleAt, deleteAt } if (typeof resHeaders.etag === 'string' && isEtagUsable(resHeaders.etag)) { value.etag = resHeaders.etag } this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value) if (!this.#writeStream) { return downstreamOnHeaders() } const handler = this this.#writeStream .on('drain', () => controller.resume()) .on('error', function () { // TODO (fix): Make error somehow observable? handler.#writeStream = undefined // Delete the value in case the cache store is holding onto state from // the call to createWriteStream handler.#store.delete(handler.#cacheKey) }) .on('close', function () { if (handler.#writeStream === this) { handler.#writeStream = undefined } // TODO (fix): Should we resume even if was paused downstream? controller.resume() }) return downstreamOnHeaders() } onResponseData (controller, chunk) { if (this.#writeStream?.write(chunk) === false) { controller.pause() } this.#handler.onResponseData?.(controller, chunk) } onResponseEnd (controller, trailers) { this.#writeStream?.end() this.#handler.onResponseEnd?.(controller, trailers) } onResponseError (controller, err) { this.#writeStream?.destroy(err) this.#writeStream = undefined this.#handler.onResponseError?.(controller, err) } } /** * @see https://www.rfc-editor.org/rfc/rfc9111.html#name-storing-responses-to-authen * * @param {import('../../types/cache-interceptor.d.ts').default.CacheOptions['type']} cacheType * @param {number} statusCode * @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives */ function canCacheResponse (cacheType, statusCode, resHeaders, cacheControlDirectives) { // Allow caching for status codes 200 and 307 (original behavior) // Also allow caching for other status codes that are heuristically cacheable // when they have explicit cache directives if (statusCode !== 200 && statusCode !== 307 && !HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode)) { return false } if (cacheControlDirectives['no-store']) { return false } if (cacheType === 'shared' && cacheControlDirectives.private === true) { return false } // https://www.rfc-editor.org/rfc/rfc9111.html#section-4.1-5 if (resHeaders.vary?.includes('*')) { return false } // https://www.rfc-editor.org/rfc/rfc9111.html#name-storing-responses-to-authen if (resHeaders.authorization) { if (!cacheControlDirectives.public || typeof resHeaders.authorization !== 'string') { return false } if ( Array.isArray(cacheControlDirectives['no-cache']) && cacheControlDirectives['no-cache'].includes('authorization') ) { return false } if ( Array.isArray(cacheControlDirectives['private']) && cacheControlDirectives['private'].includes('authorization') ) { return false } } return true } /** * @param {string | string[]} ageHeader * @returns {number | undefined} */ function getAge (ageHeader) { const age = parseInt(Array.isArray(ageHeader) ? ageHeader[0] : ageHeader) return isNaN(age) ? undefined : age * 1000 } /** * @param {import('../../types/cache-interceptor.d.ts').default.CacheOptions['type']} cacheType * @param {number} now * @param {number | undefined} age * @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders * @param {Date | undefined} responseDate * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives * * @returns {number | undefined} time that the value is stale at in seconds or undefined if it shouldn't be cached */ function determineStaleAt (cacheType, now, age, resHeaders, responseDate, cacheControlDirectives) { if (cacheType === 'shared') { // Prioritize s-maxage since we're a shared cache // s-maxage > max-age > Expire // https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.2.10-3 const sMaxAge = cacheControlDirectives['s-maxage'] if (sMaxAge !== undefined) { return sMaxAge > 0 ? sMaxAge * 1000 : undefined } } const maxAge = cacheControlDirectives['max-age'] if (maxAge !== undefined) { return maxAge > 0 ? maxAge * 1000 : undefined } if (typeof resHeaders.expires === 'string') { // https://www.rfc-editor.org/rfc/rfc9111.html#section-5.3 const expiresDate = parseHttpDate(resHeaders.expires) if (expiresDate) { if (now >= expiresDate.getTime()) { return undefined } if (responseDate) { if (responseDate >= expiresDate) { return undefined } if (age !== undefined && age > (expiresDate - responseDate)) { return undefined } } return expiresDate.getTime() - now } } if (typeof resHeaders['last-modified'] === 'string') { // https://www.rfc-editor.org/rfc/rfc9111.html#name-calculating-heuristic-fresh const lastModified = new Date(resHeaders['last-modified']) if (isValidDate(lastModified)) { if (lastModified.getTime() >= now) { return undefined } const responseAge = now - lastModified.getTime() return responseAge * 0.1 } } if (cacheControlDirectives.immutable) { // https://www.rfc-editor.org/rfc/rfc8246.html#section-2.2 return 31536000 } return undefined } /** * @param {number} now * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives * @param {number} staleAt */ function determineDeleteAt (now, cacheControlDirectives, staleAt) { let staleWhileRevalidate = -Infinity let staleIfError = -Infinity let immutable = -Infinity if (cacheControlDirectives['stale-while-revalidate']) { staleWhileRevalidate = staleAt + (cacheControlDirectives['stale-while-revalidate'] * 1000) } if (cacheControlDirectives['stale-if-error']) { staleIfError = staleAt + (cacheControlDirectives['stale-if-error'] * 1000) } if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity) { immutable = now + 31536000000 } return Math.max(staleAt, staleWhileRevalidate, staleIfError, immutable) } /** * Strips headers required to be removed in cached responses * @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives * @returns {Record} */ function stripNecessaryHeaders (resHeaders, cacheControlDirectives) { const headersToRemove = [ 'connection', 'proxy-authenticate', 'proxy-authentication-info', 'proxy-authorization', 'proxy-connection', 'te', 'transfer-encoding', 'upgrade', // We'll add age back when serving it 'age' ] if (resHeaders['connection']) { if (Array.isArray(resHeaders['connection'])) { // connection: a // connection: b headersToRemove.push(...resHeaders['connection'].map(header => header.trim())) } else { // connection: a, b headersToRemove.push(...resHeaders['connection'].split(',').map(header => header.trim())) } } if (Array.isArray(cacheControlDirectives['no-cache'])) { headersToRemove.push(...cacheControlDirectives['no-cache']) } if (Array.isArray(cacheControlDirectives['private'])) { headersToRemove.push(...cacheControlDirectives['private']) } let strippedHeaders for (const headerName of headersToRemove) { if (resHeaders[headerName]) { strippedHeaders ??= { ...resHeaders } delete strippedHeaders[headerName] } } return strippedHeaders ?? resHeaders } /** * @param {Date} date * @returns {boolean} */ function isValidDate (date) { return date instanceof Date && Number.isFinite(date.valueOf()) } module.exports = CacheHandler /***/ }), /***/ 54878: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(34589) /** * This takes care of revalidation requests we send to the origin. If we get * a response indicating that what we have is cached (via a HTTP 304), we can * continue using the cached value. Otherwise, we'll receive the new response * here, which we then just pass on to the next handler (most likely a * CacheHandler). Note that this assumes the proper headers were already * included in the request to tell the origin that we want to revalidate the * response (i.e. if-modified-since or if-none-match). * * @see https://www.rfc-editor.org/rfc/rfc9111.html#name-validation * * @implements {import('../../types/dispatcher.d.ts').default.DispatchHandler} */ class CacheRevalidationHandler { #successful = false /** * @type {((boolean, any) => void) | null} */ #callback /** * @type {(import('../../types/dispatcher.d.ts').default.DispatchHandler)} */ #handler #context /** * @type {boolean} */ #allowErrorStatusCodes /** * @param {(boolean) => void} callback Function to call if the cached value is valid * @param {import('../../types/dispatcher.d.ts').default.DispatchHandlers} handler * @param {boolean} allowErrorStatusCodes */ constructor (callback, handler, allowErrorStatusCodes) { if (typeof callback !== 'function') { throw new TypeError('callback must be a function') } this.#callback = callback this.#handler = handler this.#allowErrorStatusCodes = allowErrorStatusCodes } onRequestStart (_, context) { this.#successful = false this.#context = context } onRequestUpgrade (controller, statusCode, headers, socket) { this.#handler.onRequestUpgrade?.(controller, statusCode, headers, socket) } onResponseStart ( controller, statusCode, headers, statusMessage ) { assert(this.#callback != null) // https://www.rfc-editor.org/rfc/rfc9111.html#name-handling-a-validation-respo // https://datatracker.ietf.org/doc/html/rfc5861#section-4 this.#successful = statusCode === 304 || (this.#allowErrorStatusCodes && statusCode >= 500 && statusCode <= 504) this.#callback(this.#successful, this.#context) this.#callback = null if (this.#successful) { return true } this.#handler.onRequestStart?.(controller, this.#context) this.#handler.onResponseStart?.( controller, statusCode, headers, statusMessage ) } onResponseData (controller, chunk) { if (this.#successful) { return } return this.#handler.onResponseData?.(controller, chunk) } onResponseEnd (controller, trailers) { if (this.#successful) { return } this.#handler.onResponseEnd?.(controller, trailers) } onResponseError (controller, err) { if (this.#successful) { return } if (this.#callback) { this.#callback(false) this.#callback = null } if (typeof this.#handler.onResponseError === 'function') { this.#handler.onResponseError(controller, err) } else { throw err } } } module.exports = CacheRevalidationHandler /***/ }), /***/ 11158: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(34589) const WrapHandler = __nccwpck_require__(3541) /** * @deprecated */ module.exports = class DecoratorHandler { #handler #onCompleteCalled = false #onErrorCalled = false #onResponseStartCalled = false constructor (handler) { if (typeof handler !== 'object' || handler === null) { throw new TypeError('handler must be an object') } this.#handler = WrapHandler.wrap(handler) } onRequestStart (...args) { this.#handler.onRequestStart?.(...args) } onRequestUpgrade (...args) { assert(!this.#onCompleteCalled) assert(!this.#onErrorCalled) return this.#handler.onRequestUpgrade?.(...args) } onResponseStart (...args) { assert(!this.#onCompleteCalled) assert(!this.#onErrorCalled) assert(!this.#onResponseStartCalled) this.#onResponseStartCalled = true return this.#handler.onResponseStart?.(...args) } onResponseData (...args) { assert(!this.#onCompleteCalled) assert(!this.#onErrorCalled) return this.#handler.onResponseData?.(...args) } onResponseEnd (...args) { assert(!this.#onCompleteCalled) assert(!this.#onErrorCalled) this.#onCompleteCalled = true return this.#handler.onResponseEnd?.(...args) } onResponseError (...args) { this.#onErrorCalled = true return this.#handler.onResponseError?.(...args) } /** * @deprecated */ onBodySent () {} } /***/ }), /***/ 28733: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const util = __nccwpck_require__(46425) const { kBodyUsed } = __nccwpck_require__(83112) const assert = __nccwpck_require__(34589) const { InvalidArgumentError } = __nccwpck_require__(21158) const EE = __nccwpck_require__(78474) const redirectableStatusCodes = [300, 301, 302, 303, 307, 308] const kBody = Symbol('body') const noop = () => {} class BodyAsyncIterable { constructor (body) { this[kBody] = body this[kBodyUsed] = false } async * [Symbol.asyncIterator] () { assert(!this[kBodyUsed], 'disturbed') this[kBodyUsed] = true yield * this[kBody] } } class RedirectHandler { static buildDispatch (dispatcher, maxRedirections) { if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { throw new InvalidArgumentError('maxRedirections must be a positive number') } const dispatch = dispatcher.dispatch.bind(dispatcher) return (opts, originalHandler) => dispatch(opts, new RedirectHandler(dispatch, maxRedirections, opts, originalHandler)) } constructor (dispatch, maxRedirections, opts, handler) { if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { throw new InvalidArgumentError('maxRedirections must be a positive number') } this.dispatch = dispatch this.location = null const { maxRedirections: _, ...cleanOpts } = opts this.opts = cleanOpts // opts must be a copy, exclude maxRedirections this.maxRedirections = maxRedirections this.handler = handler this.history = [] if (util.isStream(this.opts.body)) { // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp // so that it can be dispatched again? // TODO (fix): Do we need 100-expect support to provide a way to do this properly? if (util.bodyLength(this.opts.body) === 0) { this.opts.body .on('data', function () { assert(false) }) } if (typeof this.opts.body.readableDidRead !== 'boolean') { this.opts.body[kBodyUsed] = false EE.prototype.on.call(this.opts.body, 'data', function () { this[kBodyUsed] = true }) } } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') { // TODO (fix): We can't access ReadableStream internal state // to determine whether or not it has been disturbed. This is just // a workaround. this.opts.body = new BodyAsyncIterable(this.opts.body) } else if ( this.opts.body && typeof this.opts.body !== 'string' && !ArrayBuffer.isView(this.opts.body) && util.isIterable(this.opts.body) && !util.isFormDataLike(this.opts.body) ) { // TODO: Should we allow re-using iterable if !this.opts.idempotent // or through some other flag? this.opts.body = new BodyAsyncIterable(this.opts.body) } } onRequestStart (controller, context) { this.handler.onRequestStart?.(controller, { ...context, history: this.history }) } onRequestUpgrade (controller, statusCode, headers, socket) { this.handler.onRequestUpgrade?.(controller, statusCode, headers, socket) } onResponseStart (controller, statusCode, headers, statusMessage) { if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) { throw new Error('max redirects') } // https://tools.ietf.org/html/rfc7231#section-6.4.2 // https://fetch.spec.whatwg.org/#http-redirect-fetch // In case of HTTP 301 or 302 with POST, change the method to GET if ((statusCode === 301 || statusCode === 302) && this.opts.method === 'POST') { this.opts.method = 'GET' if (util.isStream(this.opts.body)) { util.destroy(this.opts.body.on('error', noop)) } this.opts.body = null } // https://tools.ietf.org/html/rfc7231#section-6.4.4 // In case of HTTP 303, always replace method to be either HEAD or GET if (statusCode === 303 && this.opts.method !== 'HEAD') { this.opts.method = 'GET' if (util.isStream(this.opts.body)) { util.destroy(this.opts.body.on('error', noop)) } this.opts.body = null } this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) || redirectableStatusCodes.indexOf(statusCode) === -1 ? null : headers.location if (this.opts.origin) { this.history.push(new URL(this.opts.path, this.opts.origin)) } if (!this.location) { this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage) return } const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))) const path = search ? `${pathname}${search}` : pathname // Remove headers referring to the original URL. // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers. // https://tools.ietf.org/html/rfc7231#section-6.4 this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin) this.opts.path = path this.opts.origin = origin this.opts.query = null } onResponseData (controller, chunk) { if (this.location) { /* https://tools.ietf.org/html/rfc7231#section-6.4 TLDR: undici always ignores 3xx response bodies. Redirection is used to serve the requested resource from another URL, so it assumes that no body is generated (and thus can be ignored). Even though generating a body is not prohibited. For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually (which means it's optional and not mandated) contain just an hyperlink to the value of the Location response header, so the body can be ignored safely. For status 300, which is "Multiple Choices", the spec mentions both generating a Location response header AND a response body with the other possible location to follow. Since the spec explicitly chooses not to specify a format for such body and leave it to servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it. */ } else { this.handler.onResponseData?.(controller, chunk) } } onResponseEnd (controller, trailers) { if (this.location) { /* https://tools.ietf.org/html/rfc7231#section-6.4 TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections and neither are useful if present. See comment on onData method above for more detailed information. */ this.dispatch(this.opts, this) } else { this.handler.onResponseEnd(controller, trailers) } } onResponseError (controller, error) { this.handler.onResponseError?.(controller, error) } } // https://tools.ietf.org/html/rfc7231#section-6.4.4 function shouldRemoveHeader (header, removeContent, unknownOrigin) { if (header.length === 4) { return util.headerNameToString(header) === 'host' } if (removeContent && util.headerNameToString(header).startsWith('content-')) { return true } if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { const name = util.headerNameToString(header) return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization' } return false } // https://tools.ietf.org/html/rfc7231#section-6.4 function cleanRequestHeaders (headers, removeContent, unknownOrigin) { const ret = [] if (Array.isArray(headers)) { for (let i = 0; i < headers.length; i += 2) { if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) { ret.push(headers[i], headers[i + 1]) } } } else if (headers && typeof headers === 'object') { const entries = typeof headers[Symbol.iterator] === 'function' ? headers : Object.entries(headers) for (const [key, value] of entries) { if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) { ret.push(key, value) } } } else { assert(headers == null, 'headers must be an object or an array') } return ret } module.exports = RedirectHandler /***/ }), /***/ 90093: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(34589) const { kRetryHandlerDefaultRetry } = __nccwpck_require__(83112) const { RequestRetryError } = __nccwpck_require__(21158) const WrapHandler = __nccwpck_require__(3541) const { isDisturbed, parseRangeHeader, wrapRequestBody } = __nccwpck_require__(46425) function calculateRetryAfterHeader (retryAfter) { const retryTime = new Date(retryAfter).getTime() return isNaN(retryTime) ? 0 : retryTime - Date.now() } class RetryHandler { constructor (opts, { dispatch, handler }) { const { retryOptions, ...dispatchOpts } = opts const { // Retry scoped retry: retryFn, maxRetries, maxTimeout, minTimeout, timeoutFactor, // Response scoped methods, errorCodes, retryAfter, statusCodes, throwOnError } = retryOptions ?? {} this.error = null this.dispatch = dispatch this.handler = WrapHandler.wrap(handler) this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) } this.retryOpts = { throwOnError: throwOnError ?? true, retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry], retryAfter: retryAfter ?? true, maxTimeout: maxTimeout ?? 30 * 1000, // 30s, minTimeout: minTimeout ?? 500, // .5s timeoutFactor: timeoutFactor ?? 2, maxRetries: maxRetries ?? 5, // What errors we should retry methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], // Indicates which errors to retry statusCodes: statusCodes ?? [500, 502, 503, 504, 429], // List of errors to retry errorCodes: errorCodes ?? [ 'ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ENETDOWN', 'ENETUNREACH', 'EHOSTDOWN', 'EHOSTUNREACH', 'EPIPE', 'UND_ERR_SOCKET' ] } this.retryCount = 0 this.retryCountCheckpoint = 0 this.headersSent = false this.start = 0 this.end = null this.etag = null } onResponseStartWithRetry (controller, statusCode, headers, statusMessage, err) { if (this.retryOpts.throwOnError) { // Preserve old behavior for status codes that are not eligible for retry if (this.retryOpts.statusCodes.includes(statusCode) === false) { this.headersSent = true this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage) } else { this.error = err } return } if (isDisturbed(this.opts.body)) { this.headersSent = true this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage) return } function shouldRetry (passedErr) { if (passedErr) { this.headersSent = true this.headersSent = true this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage) controller.resume() return } this.error = err controller.resume() } controller.pause() this.retryOpts.retry( err, { state: { counter: this.retryCount }, opts: { retryOptions: this.retryOpts, ...this.opts } }, shouldRetry.bind(this) ) } onRequestStart (controller, context) { if (!this.headersSent) { this.handler.onRequestStart?.(controller, context) } } onRequestUpgrade (controller, statusCode, headers, socket) { this.handler.onRequestUpgrade?.(controller, statusCode, headers, socket) } static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) { const { statusCode, code, headers } = err const { method, retryOptions } = opts const { maxRetries, minTimeout, maxTimeout, timeoutFactor, statusCodes, errorCodes, methods } = retryOptions const { counter } = state // Any code that is not a Undici's originated and allowed to retry if (code && code !== 'UND_ERR_REQ_RETRY' && !errorCodes.includes(code)) { cb(err) return } // If a set of method are provided and the current method is not in the list if (Array.isArray(methods) && !methods.includes(method)) { cb(err) return } // If a set of status code are provided and the current status code is not in the list if ( statusCode != null && Array.isArray(statusCodes) && !statusCodes.includes(statusCode) ) { cb(err) return } // If we reached the max number of retries if (counter > maxRetries) { cb(err) return } let retryAfterHeader = headers?.['retry-after'] if (retryAfterHeader) { retryAfterHeader = Number(retryAfterHeader) retryAfterHeader = Number.isNaN(retryAfterHeader) ? calculateRetryAfterHeader(headers['retry-after']) : retryAfterHeader * 1e3 // Retry-After is in seconds } const retryTimeout = retryAfterHeader > 0 ? Math.min(retryAfterHeader, maxTimeout) : Math.min(minTimeout * timeoutFactor ** (counter - 1), maxTimeout) setTimeout(() => cb(null), retryTimeout) } onResponseStart (controller, statusCode, headers, statusMessage) { this.error = null this.retryCount += 1 if (statusCode >= 300) { const err = new RequestRetryError('Request failed', statusCode, { headers, data: { count: this.retryCount } }) this.onResponseStartWithRetry(controller, statusCode, headers, statusMessage, err) return } // Checkpoint for resume from where we left it if (this.headersSent) { // Only Partial Content 206 supposed to provide Content-Range, // any other status code that partially consumed the payload // should not be retried because it would result in downstream // wrongly concatenate multiple responses. if (statusCode !== 206 && (this.start > 0 || statusCode !== 200)) { throw new RequestRetryError('server does not support the range header and the payload was partially consumed', statusCode, { headers, data: { count: this.retryCount } }) } const contentRange = parseRangeHeader(headers['content-range']) // If no content range if (!contentRange) { // We always throw here as we want to indicate that we entred unexpected path throw new RequestRetryError('Content-Range mismatch', statusCode, { headers, data: { count: this.retryCount } }) } // Let's start with a weak etag check if (this.etag != null && this.etag !== headers.etag) { // We always throw here as we want to indicate that we entred unexpected path throw new RequestRetryError('ETag mismatch', statusCode, { headers, data: { count: this.retryCount } }) } const { start, size, end = size ? size - 1 : null } = contentRange assert(this.start === start, 'content-range mismatch') assert(this.end == null || this.end === end, 'content-range mismatch') return } if (this.end == null) { if (statusCode === 206) { // First time we receive 206 const range = parseRangeHeader(headers['content-range']) if (range == null) { this.headersSent = true this.handler.onResponseStart?.( controller, statusCode, headers, statusMessage ) return } const { start, size, end = size ? size - 1 : null } = range assert( start != null && Number.isFinite(start), 'content-range mismatch' ) assert(end != null && Number.isFinite(end), 'invalid content-length') this.start = start this.end = end } // We make our best to checkpoint the body for further range headers if (this.end == null) { const contentLength = headers['content-length'] this.end = contentLength != null ? Number(contentLength) - 1 : null } assert(Number.isFinite(this.start)) assert( this.end == null || Number.isFinite(this.end), 'invalid content-length' ) this.resume = true this.etag = headers.etag != null ? headers.etag : null // Weak etags are not useful for comparison nor cache // for instance not safe to assume if the response is byte-per-byte // equal if ( this.etag != null && this.etag[0] === 'W' && this.etag[1] === '/' ) { this.etag = null } this.headersSent = true this.handler.onResponseStart?.( controller, statusCode, headers, statusMessage ) } else { throw new RequestRetryError('Request failed', statusCode, { headers, data: { count: this.retryCount } }) } } onResponseData (controller, chunk) { if (this.error) { return } this.start += chunk.length this.handler.onResponseData?.(controller, chunk) } onResponseEnd (controller, trailers) { if (this.error && this.retryOpts.throwOnError) { throw this.error } if (!this.error) { this.retryCount = 0 return this.handler.onResponseEnd?.(controller, trailers) } this.retry(controller) } retry (controller) { if (this.start !== 0) { const headers = { range: `bytes=${this.start}-${this.end ?? ''}` } // Weak etag check - weak etags will make comparison algorithms never match if (this.etag != null) { headers['if-match'] = this.etag } this.opts = { ...this.opts, headers: { ...this.opts.headers, ...headers } } } try { this.retryCountCheckpoint = this.retryCount this.dispatch(this.opts, this) } catch (err) { this.handler.onResponseError?.(controller, err) } } onResponseError (controller, err) { if (controller?.aborted || isDisturbed(this.opts.body)) { this.handler.onResponseError?.(controller, err) return } function shouldRetry (returnedErr) { if (!returnedErr) { this.retry(controller) return } this.handler?.onResponseError?.(controller, returnedErr) } // We reconcile in case of a mix between network errors // and server error response if (this.retryCount - this.retryCountCheckpoint > 0) { // We count the difference between the last checkpoint and the current retry count this.retryCount = this.retryCountCheckpoint + (this.retryCount - this.retryCountCheckpoint) } else { this.retryCount += 1 } this.retryOpts.retry( err, { state: { counter: this.retryCount }, opts: { retryOptions: this.retryOpts, ...this.opts } }, shouldRetry.bind(this) ) } } module.exports = RetryHandler /***/ }), /***/ 14586: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { parseHeaders } = __nccwpck_require__(46425) const { InvalidArgumentError } = __nccwpck_require__(21158) const kResume = Symbol('resume') class UnwrapController { #paused = false #reason = null #aborted = false #abort [kResume] = null constructor (abort) { this.#abort = abort } pause () { this.#paused = true } resume () { if (this.#paused) { this.#paused = false this[kResume]?.() } } abort (reason) { if (!this.#aborted) { this.#aborted = true this.#reason = reason this.#abort(reason) } } get aborted () { return this.#aborted } get reason () { return this.#reason } get paused () { return this.#paused } } module.exports = class UnwrapHandler { #handler #controller constructor (handler) { this.#handler = handler } static unwrap (handler) { // TODO (fix): More checks... return !handler.onRequestStart ? handler : new UnwrapHandler(handler) } onConnect (abort, context) { this.#controller = new UnwrapController(abort) this.#handler.onRequestStart?.(this.#controller, context) } onUpgrade (statusCode, rawHeaders, socket) { this.#handler.onRequestUpgrade?.(this.#controller, statusCode, parseHeaders(rawHeaders), socket) } onHeaders (statusCode, rawHeaders, resume, statusMessage) { this.#controller[kResume] = resume this.#handler.onResponseStart?.(this.#controller, statusCode, parseHeaders(rawHeaders), statusMessage) return !this.#controller.paused } onData (data) { this.#handler.onResponseData?.(this.#controller, data) return !this.#controller.paused } onComplete (rawTrailers) { this.#handler.onResponseEnd?.(this.#controller, parseHeaders(rawTrailers)) } onError (err) { if (!this.#handler.onResponseError) { throw new InvalidArgumentError('invalid onError method') } this.#handler.onResponseError?.(this.#controller, err) } } /***/ }), /***/ 3541: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { InvalidArgumentError } = __nccwpck_require__(21158) module.exports = class WrapHandler { #handler constructor (handler) { this.#handler = handler } static wrap (handler) { // TODO (fix): More checks... return handler.onRequestStart ? handler : new WrapHandler(handler) } // Unwrap Interface onConnect (abort, context) { return this.#handler.onConnect?.(abort, context) } onHeaders (statusCode, rawHeaders, resume, statusMessage) { return this.#handler.onHeaders?.(statusCode, rawHeaders, resume, statusMessage) } onUpgrade (statusCode, rawHeaders, socket) { return this.#handler.onUpgrade?.(statusCode, rawHeaders, socket) } onData (data) { return this.#handler.onData?.(data) } onComplete (trailers) { return this.#handler.onComplete?.(trailers) } onError (err) { if (!this.#handler.onError) { throw err } return this.#handler.onError?.(err) } // Wrap Interface onRequestStart (controller, context) { this.#handler.onConnect?.((reason) => controller.abort(reason), context) } onRequestUpgrade (controller, statusCode, headers, socket) { const rawHeaders = [] for (const [key, val] of Object.entries(headers)) { rawHeaders.push(Buffer.from(key), Array.isArray(val) ? val.map(v => Buffer.from(v)) : Buffer.from(val)) } this.#handler.onUpgrade?.(statusCode, rawHeaders, socket) } onResponseStart (controller, statusCode, headers, statusMessage) { const rawHeaders = [] for (const [key, val] of Object.entries(headers)) { rawHeaders.push(Buffer.from(key), Array.isArray(val) ? val.map(v => Buffer.from(v)) : Buffer.from(val)) } if (this.#handler.onHeaders?.(statusCode, rawHeaders, () => controller.resume(), statusMessage) === false) { controller.pause() } } onResponseData (controller, data) { if (this.#handler.onData?.(data) === false) { controller.pause() } } onResponseEnd (controller, trailers) { const rawTrailers = [] for (const [key, val] of Object.entries(trailers)) { rawTrailers.push(Buffer.from(key), Array.isArray(val) ? val.map(v => Buffer.from(v)) : Buffer.from(val)) } this.#handler.onComplete?.(rawTrailers) } onResponseError (controller, err) { if (!this.#handler.onError) { throw new InvalidArgumentError('invalid onError method') } this.#handler.onError?.(err) } } /***/ }), /***/ 74455: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(34589) const { Readable } = __nccwpck_require__(57075) const util = __nccwpck_require__(46425) const CacheHandler = __nccwpck_require__(31233) const MemoryCacheStore = __nccwpck_require__(92434) const CacheRevalidationHandler = __nccwpck_require__(54878) const { assertCacheStore, assertCacheMethods, makeCacheKey, normaliseHeaders, parseCacheControlHeader } = __nccwpck_require__(27128) const { AbortError } = __nccwpck_require__(21158) /** * @typedef {(options: import('../../types/dispatcher.d.ts').default.DispatchOptions, handler: import('../../types/dispatcher.d.ts').default.DispatchHandler) => void} DispatchFn */ /** * @param {import('../../types/cache-interceptor.d.ts').default.GetResult} result * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives | undefined} cacheControlDirectives * @returns {boolean} */ function needsRevalidation (result, cacheControlDirectives) { if (cacheControlDirectives?.['no-cache']) { // Always revalidate requests with the no-cache request directive return true } if (result.cacheControlDirectives?.['no-cache'] && !Array.isArray(result.cacheControlDirectives['no-cache'])) { // Always revalidate requests with unqualified no-cache response directive return true } const now = Date.now() if (now > result.staleAt) { // Response is stale if (cacheControlDirectives?.['max-stale']) { // There's a threshold where we can serve stale responses, let's see if // we're in it // https://www.rfc-editor.org/rfc/rfc9111.html#name-max-stale const gracePeriod = result.staleAt + (cacheControlDirectives['max-stale'] * 1000) return now > gracePeriod } return true } if (cacheControlDirectives?.['min-fresh']) { // https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.1.3 // At this point, staleAt is always > now const timeLeftTillStale = result.staleAt - now const threshold = cacheControlDirectives['min-fresh'] * 1000 return timeLeftTillStale <= threshold } return false } /** * @param {DispatchFn} dispatch * @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions} globalOpts * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey * @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler * @param {import('../../types/dispatcher.d.ts').default.RequestOptions} opts * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives | undefined} reqCacheControl */ function handleUncachedResponse ( dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl ) { if (reqCacheControl?.['only-if-cached']) { let aborted = false try { if (typeof handler.onConnect === 'function') { handler.onConnect(() => { aborted = true }) if (aborted) { return } } if (typeof handler.onHeaders === 'function') { handler.onHeaders(504, [], () => {}, 'Gateway Timeout') if (aborted) { return } } if (typeof handler.onComplete === 'function') { handler.onComplete([]) } } catch (err) { if (typeof handler.onError === 'function') { handler.onError(err) } } return true } return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler)) } /** * @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler * @param {import('../../types/dispatcher.d.ts').default.RequestOptions} opts * @param {import('../../types/cache-interceptor.d.ts').default.GetResult} result * @param {number} age * @param {any} context * @param {boolean} isStale */ function sendCachedValue (handler, opts, result, age, context, isStale) { // TODO (perf): Readable.from path can be optimized... const stream = util.isStream(result.body) ? result.body : Readable.from(result.body ?? []) assert(!stream.destroyed, 'stream should not be destroyed') assert(!stream.readableDidRead, 'stream should not be readableDidRead') const controller = { resume () { stream.resume() }, pause () { stream.pause() }, get paused () { return stream.isPaused() }, get aborted () { return stream.destroyed }, get reason () { return stream.errored }, abort (reason) { stream.destroy(reason ?? new AbortError()) } } stream .on('error', function (err) { if (!this.readableEnded) { if (typeof handler.onResponseError === 'function') { handler.onResponseError(controller, err) } else { throw err } } }) .on('close', function () { if (!this.errored) { handler.onResponseEnd?.(controller, {}) } }) handler.onRequestStart?.(controller, context) if (stream.destroyed) { return } // Add the age header // https://www.rfc-editor.org/rfc/rfc9111.html#name-age const headers = { ...result.headers, age: String(age) } if (isStale) { // Add warning header // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Warning headers.warning = '110 - "response is stale"' } handler.onResponseStart?.(controller, result.statusCode, headers, result.statusMessage) if (opts.method === 'HEAD') { stream.destroy() } else { stream.on('data', function (chunk) { handler.onResponseData?.(controller, chunk) }) } } /** * @param {DispatchFn} dispatch * @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions} globalOpts * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey * @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler * @param {import('../../types/dispatcher.d.ts').default.RequestOptions} opts * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives | undefined} reqCacheControl * @param {import('../../types/cache-interceptor.d.ts').default.GetResult | undefined} result */ function handleResult ( dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl, result ) { if (!result) { return handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl) } const now = Date.now() if (now > result.deleteAt) { // Response is expired, cache store shouldn't have given this to us return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler)) } const age = Math.round((now - result.cachedAt) / 1000) if (reqCacheControl?.['max-age'] && age >= reqCacheControl['max-age']) { // Response is considered expired for this specific request // https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.1.1 return dispatch(opts, handler) } // Check if the response is stale if (needsRevalidation(result, reqCacheControl)) { if (util.isStream(opts.body) && util.bodyLength(opts.body) !== 0) { // If body is a stream we can't revalidate... // TODO (fix): This could be less strict... return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler)) } let withinStaleIfErrorThreshold = false const staleIfErrorExpiry = result.cacheControlDirectives['stale-if-error'] ?? reqCacheControl?.['stale-if-error'] if (staleIfErrorExpiry) { withinStaleIfErrorThreshold = now < (result.staleAt + (staleIfErrorExpiry * 1000)) } let headers = { ...opts.headers, 'if-modified-since': new Date(result.cachedAt).toUTCString() } if (result.etag) { headers['if-none-match'] = result.etag } if (result.vary) { headers = { ...headers, ...result.vary } } // We need to revalidate the response return dispatch( { ...opts, headers }, new CacheRevalidationHandler( (success, context) => { if (success) { sendCachedValue(handler, opts, result, age, context, true) } else if (util.isStream(result.body)) { result.body.on('error', () => {}).destroy() } }, new CacheHandler(globalOpts, cacheKey, handler), withinStaleIfErrorThreshold ) ) } // Dump request body. if (util.isStream(opts.body)) { opts.body.on('error', () => {}).destroy() } sendCachedValue(handler, opts, result, age, null, false) } /** * @param {import('../../types/cache-interceptor.d.ts').default.CacheOptions} [opts] * @returns {import('../../types/dispatcher.d.ts').default.DispatcherComposeInterceptor} */ module.exports = (opts = {}) => { const { store = new MemoryCacheStore(), methods = ['GET'], cacheByDefault = undefined, type = 'shared' } = opts if (typeof opts !== 'object' || opts === null) { throw new TypeError(`expected type of opts to be an Object, got ${opts === null ? 'null' : typeof opts}`) } assertCacheStore(store, 'opts.store') assertCacheMethods(methods, 'opts.methods') if (typeof cacheByDefault !== 'undefined' && typeof cacheByDefault !== 'number') { throw new TypeError(`expected opts.cacheByDefault to be number or undefined, got ${typeof cacheByDefault}`) } if (typeof type !== 'undefined' && type !== 'shared' && type !== 'private') { throw new TypeError(`expected opts.type to be shared, private, or undefined, got ${typeof type}`) } const globalOpts = { store, methods, cacheByDefault, type } const safeMethodsToNotCache = util.safeHTTPMethods.filter(method => methods.includes(method) === false) return dispatch => { return (opts, handler) => { if (!opts.origin || safeMethodsToNotCache.includes(opts.method)) { // Not a method we want to cache or we don't have the origin, skip return dispatch(opts, handler) } opts = { ...opts, headers: normaliseHeaders(opts) } const reqCacheControl = opts.headers?.['cache-control'] ? parseCacheControlHeader(opts.headers['cache-control']) : undefined if (reqCacheControl?.['no-store']) { return dispatch(opts, handler) } /** * @type {import('../../types/cache-interceptor.d.ts').default.CacheKey} */ const cacheKey = makeCacheKey(opts) const result = store.get(cacheKey) if (result && typeof result.then === 'function') { result.then(result => { handleResult(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl, result ) }) } else { handleResult( dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl, result ) } return true } } } /***/ }), /***/ 8374: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { isIP } = __nccwpck_require__(77030) const { lookup } = __nccwpck_require__(40610) const DecoratorHandler = __nccwpck_require__(11158) const { InvalidArgumentError, InformationalError } = __nccwpck_require__(21158) const maxInt = Math.pow(2, 31) - 1 class DNSInstance { #maxTTL = 0 #maxItems = 0 #records = new Map() dualStack = true affinity = null lookup = null pick = null constructor (opts) { this.#maxTTL = opts.maxTTL this.#maxItems = opts.maxItems this.dualStack = opts.dualStack this.affinity = opts.affinity this.lookup = opts.lookup ?? this.#defaultLookup this.pick = opts.pick ?? this.#defaultPick } get full () { return this.#records.size === this.#maxItems } runLookup (origin, opts, cb) { const ips = this.#records.get(origin.hostname) // If full, we just return the origin if (ips == null && this.full) { cb(null, origin) return } const newOpts = { affinity: this.affinity, dualStack: this.dualStack, lookup: this.lookup, pick: this.pick, ...opts.dns, maxTTL: this.#maxTTL, maxItems: this.#maxItems } // If no IPs we lookup if (ips == null) { this.lookup(origin, newOpts, (err, addresses) => { if (err || addresses == null || addresses.length === 0) { cb(err ?? new InformationalError('No DNS entries found')) return } this.setRecords(origin, addresses) const records = this.#records.get(origin.hostname) const ip = this.pick( origin, records, newOpts.affinity ) let port if (typeof ip.port === 'number') { port = `:${ip.port}` } else if (origin.port !== '') { port = `:${origin.port}` } else { port = '' } cb( null, new URL(`${origin.protocol}//${ ip.family === 6 ? `[${ip.address}]` : ip.address }${port}`) ) }) } else { // If there's IPs we pick const ip = this.pick( origin, ips, newOpts.affinity ) // If no IPs we lookup - deleting old records if (ip == null) { this.#records.delete(origin.hostname) this.runLookup(origin, opts, cb) return } let port if (typeof ip.port === 'number') { port = `:${ip.port}` } else if (origin.port !== '') { port = `:${origin.port}` } else { port = '' } cb( null, new URL(`${origin.protocol}//${ ip.family === 6 ? `[${ip.address}]` : ip.address }${port}`) ) } } #defaultLookup (origin, opts, cb) { lookup( origin.hostname, { all: true, family: this.dualStack === false ? this.affinity : 0, order: 'ipv4first' }, (err, addresses) => { if (err) { return cb(err) } const results = new Map() for (const addr of addresses) { // On linux we found duplicates, we attempt to remove them with // the latest record results.set(`${addr.address}:${addr.family}`, addr) } cb(null, results.values()) } ) } #defaultPick (origin, hostnameRecords, affinity) { let ip = null const { records, offset } = hostnameRecords let family if (this.dualStack) { if (affinity == null) { // Balance between ip families if (offset == null || offset === maxInt) { hostnameRecords.offset = 0 affinity = 4 } else { hostnameRecords.offset++ affinity = (hostnameRecords.offset & 1) === 1 ? 6 : 4 } } if (records[affinity] != null && records[affinity].ips.length > 0) { family = records[affinity] } else { family = records[affinity === 4 ? 6 : 4] } } else { family = records[affinity] } // If no IPs we return null if (family == null || family.ips.length === 0) { return ip } if (family.offset == null || family.offset === maxInt) { family.offset = 0 } else { family.offset++ } const position = family.offset % family.ips.length ip = family.ips[position] ?? null if (ip == null) { return ip } if (Date.now() - ip.timestamp > ip.ttl) { // record TTL is already in ms // We delete expired records // It is possible that they have different TTL, so we manage them individually family.ips.splice(position, 1) return this.pick(origin, hostnameRecords, affinity) } return ip } pickFamily (origin, ipFamily) { const records = this.#records.get(origin.hostname)?.records if (!records) { return null } const family = records[ipFamily] if (!family) { return null } if (family.offset == null || family.offset === maxInt) { family.offset = 0 } else { family.offset++ } const position = family.offset % family.ips.length const ip = family.ips[position] ?? null if (ip == null) { return ip } if (Date.now() - ip.timestamp > ip.ttl) { // record TTL is already in ms // We delete expired records // It is possible that they have different TTL, so we manage them individually family.ips.splice(position, 1) } return ip } setRecords (origin, addresses) { const timestamp = Date.now() const records = { records: { 4: null, 6: null } } for (const record of addresses) { record.timestamp = timestamp if (typeof record.ttl === 'number') { // The record TTL is expected to be in ms record.ttl = Math.min(record.ttl, this.#maxTTL) } else { record.ttl = this.#maxTTL } const familyRecords = records.records[record.family] ?? { ips: [] } familyRecords.ips.push(record) records.records[record.family] = familyRecords } this.#records.set(origin.hostname, records) } deleteRecords (origin) { this.#records.delete(origin.hostname) } getHandler (meta, opts) { return new DNSDispatchHandler(this, meta, opts) } } class DNSDispatchHandler extends DecoratorHandler { #state = null #opts = null #dispatch = null #origin = null #controller = null #newOrigin = null #firstTry = true constructor (state, { origin, handler, dispatch, newOrigin }, opts) { super(handler) this.#origin = origin this.#newOrigin = newOrigin this.#opts = { ...opts } this.#state = state this.#dispatch = dispatch } onResponseError (controller, err) { switch (err.code) { case 'ETIMEDOUT': case 'ECONNREFUSED': { if (this.#state.dualStack) { if (!this.#firstTry) { super.onResponseError(controller, err) return } this.#firstTry = false // Pick an ip address from the other family const otherFamily = this.#newOrigin.hostname[0] === '[' ? 4 : 6 const ip = this.#state.pickFamily(this.#origin, otherFamily) if (ip == null) { super.onResponseError(controller, err) return } let port if (typeof ip.port === 'number') { port = `:${ip.port}` } else if (this.#origin.port !== '') { port = `:${this.#origin.port}` } else { port = '' } const dispatchOpts = { ...this.#opts, origin: `${this.#origin.protocol}//${ ip.family === 6 ? `[${ip.address}]` : ip.address }${port}` } this.#dispatch(dispatchOpts, this) return } // if dual-stack disabled, we error out super.onResponseError(controller, err) break } case 'ENOTFOUND': this.#state.deleteRecords(this.#origin) super.onResponseError(controller, err) break default: super.onResponseError(controller, err) break } } } module.exports = interceptorOpts => { if ( interceptorOpts?.maxTTL != null && (typeof interceptorOpts?.maxTTL !== 'number' || interceptorOpts?.maxTTL < 0) ) { throw new InvalidArgumentError('Invalid maxTTL. Must be a positive number') } if ( interceptorOpts?.maxItems != null && (typeof interceptorOpts?.maxItems !== 'number' || interceptorOpts?.maxItems < 1) ) { throw new InvalidArgumentError( 'Invalid maxItems. Must be a positive number and greater than zero' ) } if ( interceptorOpts?.affinity != null && interceptorOpts?.affinity !== 4 && interceptorOpts?.affinity !== 6 ) { throw new InvalidArgumentError('Invalid affinity. Must be either 4 or 6') } if ( interceptorOpts?.dualStack != null && typeof interceptorOpts?.dualStack !== 'boolean' ) { throw new InvalidArgumentError('Invalid dualStack. Must be a boolean') } if ( interceptorOpts?.lookup != null && typeof interceptorOpts?.lookup !== 'function' ) { throw new InvalidArgumentError('Invalid lookup. Must be a function') } if ( interceptorOpts?.pick != null && typeof interceptorOpts?.pick !== 'function' ) { throw new InvalidArgumentError('Invalid pick. Must be a function') } const dualStack = interceptorOpts?.dualStack ?? true let affinity if (dualStack) { affinity = interceptorOpts?.affinity ?? null } else { affinity = interceptorOpts?.affinity ?? 4 } const opts = { maxTTL: interceptorOpts?.maxTTL ?? 10e3, // Expressed in ms lookup: interceptorOpts?.lookup ?? null, pick: interceptorOpts?.pick ?? null, dualStack, affinity, maxItems: interceptorOpts?.maxItems ?? Infinity } const instance = new DNSInstance(opts) return dispatch => { return function dnsInterceptor (origDispatchOpts, handler) { const origin = origDispatchOpts.origin.constructor === URL ? origDispatchOpts.origin : new URL(origDispatchOpts.origin) if (isIP(origin.hostname) !== 0) { return dispatch(origDispatchOpts, handler) } instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => { if (err) { return handler.onResponseError(null, err) } const dispatchOpts = { ...origDispatchOpts, servername: origin.hostname, // For SNI on TLS origin: newOrigin.origin, headers: { host: origin.host, ...origDispatchOpts.headers } } dispatch( dispatchOpts, instance.getHandler( { origin, dispatch, handler, newOrigin }, origDispatchOpts ) ) }) return true } } } /***/ }), /***/ 92295: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(21158) const DecoratorHandler = __nccwpck_require__(11158) class DumpHandler extends DecoratorHandler { #maxSize = 1024 * 1024 #dumped = false #size = 0 #controller = null aborted = false reason = false constructor ({ maxSize, signal }, handler) { if (maxSize != null && (!Number.isFinite(maxSize) || maxSize < 1)) { throw new InvalidArgumentError('maxSize must be a number greater than 0') } super(handler) this.#maxSize = maxSize ?? this.#maxSize // this.#handler = handler } #abort (reason) { this.aborted = true this.reason = reason } onRequestStart (controller, context) { controller.abort = this.#abort.bind(this) this.#controller = controller return super.onRequestStart(controller, context) } onResponseStart (controller, statusCode, headers, statusMessage) { const contentLength = headers['content-length'] if (contentLength != null && contentLength > this.#maxSize) { throw new RequestAbortedError( `Response size (${contentLength}) larger than maxSize (${ this.#maxSize })` ) } if (this.aborted === true) { return true } return super.onResponseStart(controller, statusCode, headers, statusMessage) } onResponseError (controller, err) { if (this.#dumped) { return } err = this.#controller.reason ?? err super.onResponseError(controller, err) } onResponseData (controller, chunk) { this.#size = this.#size + chunk.length if (this.#size >= this.#maxSize) { this.#dumped = true if (this.aborted === true) { super.onResponseError(controller, this.reason) } else { super.onResponseEnd(controller, {}) } } return true } onResponseEnd (controller, trailers) { if (this.#dumped) { return } if (this.#controller.aborted === true) { super.onResponseError(controller, this.reason) return } super.onResponseEnd(controller, trailers) } } function createDumpInterceptor ( { maxSize: defaultMaxSize } = { maxSize: 1024 * 1024 } ) { return dispatch => { return function Intercept (opts, handler) { const { dumpMaxSize = defaultMaxSize } = opts const dumpHandler = new DumpHandler({ maxSize: dumpMaxSize, signal: opts.signal }, handler) return dispatch(opts, dumpHandler) } } } module.exports = createDumpInterceptor /***/ }), /***/ 92553: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const RedirectHandler = __nccwpck_require__(28733) function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections } = {}) { return (dispatch) => { return function Intercept (opts, handler) { const { maxRedirections = defaultMaxRedirections, ...rest } = opts if (maxRedirections == null || maxRedirections === 0) { return dispatch(opts, handler) } const dispatchOpts = { ...rest } // Stop sub dispatcher from also redirecting. const redirectHandler = new RedirectHandler(dispatch, maxRedirections, dispatchOpts, handler) return dispatch(dispatchOpts, redirectHandler) } } } module.exports = createRedirectInterceptor /***/ }), /***/ 93577: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // const { parseHeaders } = require('../core/util') const DecoratorHandler = __nccwpck_require__(11158) const { ResponseError } = __nccwpck_require__(21158) class ResponseErrorHandler extends DecoratorHandler { #statusCode #contentType #decoder #headers #body constructor (_opts, { handler }) { super(handler) } #checkContentType (contentType) { return (this.#contentType ?? '').indexOf(contentType) === 0 } onRequestStart (controller, context) { this.#statusCode = 0 this.#contentType = null this.#decoder = null this.#headers = null this.#body = '' return super.onRequestStart(controller, context) } onResponseStart (controller, statusCode, headers, statusMessage) { this.#statusCode = statusCode this.#headers = headers this.#contentType = headers['content-type'] if (this.#statusCode < 400) { return super.onResponseStart(controller, statusCode, headers, statusMessage) } if (this.#checkContentType('application/json') || this.#checkContentType('text/plain')) { this.#decoder = new TextDecoder('utf-8') } } onResponseData (controller, chunk) { if (this.#statusCode < 400) { return super.onResponseData(controller, chunk) } this.#body += this.#decoder?.decode(chunk, { stream: true }) ?? '' } onResponseEnd (controller, trailers) { if (this.#statusCode >= 400) { this.#body += this.#decoder?.decode(undefined, { stream: false }) ?? '' if (this.#checkContentType('application/json')) { try { this.#body = JSON.parse(this.#body) } catch { // Do nothing... } } let err const stackTraceLimit = Error.stackTraceLimit Error.stackTraceLimit = 0 try { err = new ResponseError('Response Error', this.#statusCode, { body: this.#body, headers: this.#headers }) } finally { Error.stackTraceLimit = stackTraceLimit } super.onResponseError(controller, err) } else { super.onResponseEnd(controller, trailers) } } onResponseError (controller, err) { super.onResponseError(controller, err) } } module.exports = () => { return (dispatch) => { return function Intercept (opts, handler) { return dispatch(opts, new ResponseErrorHandler(opts, { handler })) } } } /***/ }), /***/ 72895: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const RetryHandler = __nccwpck_require__(90093) module.exports = globalOpts => { return dispatch => { return function retryInterceptor (opts, handler) { return dispatch( opts, new RetryHandler( { ...opts, retryOptions: { ...globalOpts, ...opts.retryOptions } }, { handler, dispatch } ) ) } } } /***/ }), /***/ 59619: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SPECIAL_HEADERS = exports.MINOR = exports.MAJOR = exports.HTAB_SP_VCHAR_OBS_TEXT = exports.QUOTED_STRING = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.HEX = exports.URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.STATUSES_HTTP = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.HEADER_STATE = exports.FINISH = exports.STATUSES = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0; const utils_1 = __nccwpck_require__(57875); // Emums exports.ERROR = { OK: 0, INTERNAL: 1, STRICT: 2, CR_EXPECTED: 25, LF_EXPECTED: 3, UNEXPECTED_CONTENT_LENGTH: 4, UNEXPECTED_SPACE: 30, CLOSED_CONNECTION: 5, INVALID_METHOD: 6, INVALID_URL: 7, INVALID_CONSTANT: 8, INVALID_VERSION: 9, INVALID_HEADER_TOKEN: 10, INVALID_CONTENT_LENGTH: 11, INVALID_CHUNK_SIZE: 12, INVALID_STATUS: 13, INVALID_EOF_STATE: 14, INVALID_TRANSFER_ENCODING: 15, CB_MESSAGE_BEGIN: 16, CB_HEADERS_COMPLETE: 17, CB_MESSAGE_COMPLETE: 18, CB_CHUNK_HEADER: 19, CB_CHUNK_COMPLETE: 20, PAUSED: 21, PAUSED_UPGRADE: 22, PAUSED_H2_UPGRADE: 23, USER: 24, CB_URL_COMPLETE: 26, CB_STATUS_COMPLETE: 27, CB_METHOD_COMPLETE: 32, CB_VERSION_COMPLETE: 33, CB_HEADER_FIELD_COMPLETE: 28, CB_HEADER_VALUE_COMPLETE: 29, CB_CHUNK_EXTENSION_NAME_COMPLETE: 34, CB_CHUNK_EXTENSION_VALUE_COMPLETE: 35, CB_RESET: 31, }; exports.TYPE = { BOTH: 0, // default REQUEST: 1, RESPONSE: 2, }; exports.FLAGS = { CONNECTION_KEEP_ALIVE: 1 << 0, CONNECTION_CLOSE: 1 << 1, CONNECTION_UPGRADE: 1 << 2, CHUNKED: 1 << 3, UPGRADE: 1 << 4, CONTENT_LENGTH: 1 << 5, SKIPBODY: 1 << 6, TRAILING: 1 << 7, // 1 << 8 is unused TRANSFER_ENCODING: 1 << 9, }; exports.LENIENT_FLAGS = { HEADERS: 1 << 0, CHUNKED_LENGTH: 1 << 1, KEEP_ALIVE: 1 << 2, TRANSFER_ENCODING: 1 << 3, VERSION: 1 << 4, DATA_AFTER_CLOSE: 1 << 5, OPTIONAL_LF_AFTER_CR: 1 << 6, OPTIONAL_CRLF_AFTER_CHUNK: 1 << 7, OPTIONAL_CR_BEFORE_LF: 1 << 8, SPACES_AFTER_CHUNK_SIZE: 1 << 9, }; exports.METHODS = { 'DELETE': 0, 'GET': 1, 'HEAD': 2, 'POST': 3, 'PUT': 4, /* pathological */ 'CONNECT': 5, 'OPTIONS': 6, 'TRACE': 7, /* WebDAV */ 'COPY': 8, 'LOCK': 9, 'MKCOL': 10, 'MOVE': 11, 'PROPFIND': 12, 'PROPPATCH': 13, 'SEARCH': 14, 'UNLOCK': 15, 'BIND': 16, 'REBIND': 17, 'UNBIND': 18, 'ACL': 19, /* subversion */ 'REPORT': 20, 'MKACTIVITY': 21, 'CHECKOUT': 22, 'MERGE': 23, /* upnp */ 'M-SEARCH': 24, 'NOTIFY': 25, 'SUBSCRIBE': 26, 'UNSUBSCRIBE': 27, /* RFC-5789 */ 'PATCH': 28, 'PURGE': 29, /* CalDAV */ 'MKCALENDAR': 30, /* RFC-2068, section 19.6.1.2 */ 'LINK': 31, 'UNLINK': 32, /* icecast */ 'SOURCE': 33, /* RFC-7540, section 11.6 */ 'PRI': 34, /* RFC-2326 RTSP */ 'DESCRIBE': 35, 'ANNOUNCE': 36, 'SETUP': 37, 'PLAY': 38, 'PAUSE': 39, 'TEARDOWN': 40, 'GET_PARAMETER': 41, 'SET_PARAMETER': 42, 'REDIRECT': 43, 'RECORD': 44, /* RAOP */ 'FLUSH': 45, /* DRAFT https://www.ietf.org/archive/id/draft-ietf-httpbis-safe-method-w-body-02.html */ 'QUERY': 46, }; exports.STATUSES = { CONTINUE: 100, SWITCHING_PROTOCOLS: 101, PROCESSING: 102, EARLY_HINTS: 103, RESPONSE_IS_STALE: 110, // Unofficial REVALIDATION_FAILED: 111, // Unofficial DISCONNECTED_OPERATION: 112, // Unofficial HEURISTIC_EXPIRATION: 113, // Unofficial MISCELLANEOUS_WARNING: 199, // Unofficial OK: 200, CREATED: 201, ACCEPTED: 202, NON_AUTHORITATIVE_INFORMATION: 203, NO_CONTENT: 204, RESET_CONTENT: 205, PARTIAL_CONTENT: 206, MULTI_STATUS: 207, ALREADY_REPORTED: 208, TRANSFORMATION_APPLIED: 214, // Unofficial IM_USED: 226, MISCELLANEOUS_PERSISTENT_WARNING: 299, // Unofficial MULTIPLE_CHOICES: 300, MOVED_PERMANENTLY: 301, FOUND: 302, SEE_OTHER: 303, NOT_MODIFIED: 304, USE_PROXY: 305, SWITCH_PROXY: 306, // No longer used TEMPORARY_REDIRECT: 307, PERMANENT_REDIRECT: 308, BAD_REQUEST: 400, UNAUTHORIZED: 401, PAYMENT_REQUIRED: 402, FORBIDDEN: 403, NOT_FOUND: 404, METHOD_NOT_ALLOWED: 405, NOT_ACCEPTABLE: 406, PROXY_AUTHENTICATION_REQUIRED: 407, REQUEST_TIMEOUT: 408, CONFLICT: 409, GONE: 410, LENGTH_REQUIRED: 411, PRECONDITION_FAILED: 412, PAYLOAD_TOO_LARGE: 413, URI_TOO_LONG: 414, UNSUPPORTED_MEDIA_TYPE: 415, RANGE_NOT_SATISFIABLE: 416, EXPECTATION_FAILED: 417, IM_A_TEAPOT: 418, PAGE_EXPIRED: 419, // Unofficial ENHANCE_YOUR_CALM: 420, // Unofficial MISDIRECTED_REQUEST: 421, UNPROCESSABLE_ENTITY: 422, LOCKED: 423, FAILED_DEPENDENCY: 424, TOO_EARLY: 425, UPGRADE_REQUIRED: 426, PRECONDITION_REQUIRED: 428, TOO_MANY_REQUESTS: 429, REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL: 430, // Unofficial REQUEST_HEADER_FIELDS_TOO_LARGE: 431, LOGIN_TIMEOUT: 440, // Unofficial NO_RESPONSE: 444, // Unofficial RETRY_WITH: 449, // Unofficial BLOCKED_BY_PARENTAL_CONTROL: 450, // Unofficial UNAVAILABLE_FOR_LEGAL_REASONS: 451, CLIENT_CLOSED_LOAD_BALANCED_REQUEST: 460, // Unofficial INVALID_X_FORWARDED_FOR: 463, // Unofficial REQUEST_HEADER_TOO_LARGE: 494, // Unofficial SSL_CERTIFICATE_ERROR: 495, // Unofficial SSL_CERTIFICATE_REQUIRED: 496, // Unofficial HTTP_REQUEST_SENT_TO_HTTPS_PORT: 497, // Unofficial INVALID_TOKEN: 498, // Unofficial CLIENT_CLOSED_REQUEST: 499, // Unofficial INTERNAL_SERVER_ERROR: 500, NOT_IMPLEMENTED: 501, BAD_GATEWAY: 502, SERVICE_UNAVAILABLE: 503, GATEWAY_TIMEOUT: 504, HTTP_VERSION_NOT_SUPPORTED: 505, VARIANT_ALSO_NEGOTIATES: 506, INSUFFICIENT_STORAGE: 507, LOOP_DETECTED: 508, BANDWIDTH_LIMIT_EXCEEDED: 509, NOT_EXTENDED: 510, NETWORK_AUTHENTICATION_REQUIRED: 511, WEB_SERVER_UNKNOWN_ERROR: 520, // Unofficial WEB_SERVER_IS_DOWN: 521, // Unofficial CONNECTION_TIMEOUT: 522, // Unofficial ORIGIN_IS_UNREACHABLE: 523, // Unofficial TIMEOUT_OCCURED: 524, // Unofficial SSL_HANDSHAKE_FAILED: 525, // Unofficial INVALID_SSL_CERTIFICATE: 526, // Unofficial RAILGUN_ERROR: 527, // Unofficial SITE_IS_OVERLOADED: 529, // Unofficial SITE_IS_FROZEN: 530, // Unofficial IDENTITY_PROVIDER_AUTHENTICATION_ERROR: 561, // Unofficial NETWORK_READ_TIMEOUT: 598, // Unofficial NETWORK_CONNECT_TIMEOUT: 599, // Unofficial }; exports.FINISH = { SAFE: 0, SAFE_WITH_CB: 1, UNSAFE: 2, }; exports.HEADER_STATE = { GENERAL: 0, CONNECTION: 1, CONTENT_LENGTH: 2, TRANSFER_ENCODING: 3, UPGRADE: 4, CONNECTION_KEEP_ALIVE: 5, CONNECTION_CLOSE: 6, CONNECTION_UPGRADE: 7, TRANSFER_ENCODING_CHUNKED: 8, }; // C headers exports.METHODS_HTTP = [ exports.METHODS.DELETE, exports.METHODS.GET, exports.METHODS.HEAD, exports.METHODS.POST, exports.METHODS.PUT, exports.METHODS.CONNECT, exports.METHODS.OPTIONS, exports.METHODS.TRACE, exports.METHODS.COPY, exports.METHODS.LOCK, exports.METHODS.MKCOL, exports.METHODS.MOVE, exports.METHODS.PROPFIND, exports.METHODS.PROPPATCH, exports.METHODS.SEARCH, exports.METHODS.UNLOCK, exports.METHODS.BIND, exports.METHODS.REBIND, exports.METHODS.UNBIND, exports.METHODS.ACL, exports.METHODS.REPORT, exports.METHODS.MKACTIVITY, exports.METHODS.CHECKOUT, exports.METHODS.MERGE, exports.METHODS['M-SEARCH'], exports.METHODS.NOTIFY, exports.METHODS.SUBSCRIBE, exports.METHODS.UNSUBSCRIBE, exports.METHODS.PATCH, exports.METHODS.PURGE, exports.METHODS.MKCALENDAR, exports.METHODS.LINK, exports.METHODS.UNLINK, exports.METHODS.PRI, // TODO(indutny): should we allow it with HTTP? exports.METHODS.SOURCE, exports.METHODS.QUERY, ]; exports.METHODS_ICE = [ exports.METHODS.SOURCE, ]; exports.METHODS_RTSP = [ exports.METHODS.OPTIONS, exports.METHODS.DESCRIBE, exports.METHODS.ANNOUNCE, exports.METHODS.SETUP, exports.METHODS.PLAY, exports.METHODS.PAUSE, exports.METHODS.TEARDOWN, exports.METHODS.GET_PARAMETER, exports.METHODS.SET_PARAMETER, exports.METHODS.REDIRECT, exports.METHODS.RECORD, exports.METHODS.FLUSH, // For AirPlay exports.METHODS.GET, exports.METHODS.POST, ]; exports.METHOD_MAP = (0, utils_1.enumToMap)(exports.METHODS); exports.H_METHOD_MAP = Object.fromEntries(Object.entries(exports.METHODS).filter(([k]) => k.startsWith('H'))); exports.STATUSES_HTTP = [ exports.STATUSES.CONTINUE, exports.STATUSES.SWITCHING_PROTOCOLS, exports.STATUSES.PROCESSING, exports.STATUSES.EARLY_HINTS, exports.STATUSES.RESPONSE_IS_STALE, exports.STATUSES.REVALIDATION_FAILED, exports.STATUSES.DISCONNECTED_OPERATION, exports.STATUSES.HEURISTIC_EXPIRATION, exports.STATUSES.MISCELLANEOUS_WARNING, exports.STATUSES.OK, exports.STATUSES.CREATED, exports.STATUSES.ACCEPTED, exports.STATUSES.NON_AUTHORITATIVE_INFORMATION, exports.STATUSES.NO_CONTENT, exports.STATUSES.RESET_CONTENT, exports.STATUSES.PARTIAL_CONTENT, exports.STATUSES.MULTI_STATUS, exports.STATUSES.ALREADY_REPORTED, exports.STATUSES.TRANSFORMATION_APPLIED, exports.STATUSES.IM_USED, exports.STATUSES.MISCELLANEOUS_PERSISTENT_WARNING, exports.STATUSES.MULTIPLE_CHOICES, exports.STATUSES.MOVED_PERMANENTLY, exports.STATUSES.FOUND, exports.STATUSES.SEE_OTHER, exports.STATUSES.NOT_MODIFIED, exports.STATUSES.USE_PROXY, exports.STATUSES.SWITCH_PROXY, exports.STATUSES.TEMPORARY_REDIRECT, exports.STATUSES.PERMANENT_REDIRECT, exports.STATUSES.BAD_REQUEST, exports.STATUSES.UNAUTHORIZED, exports.STATUSES.PAYMENT_REQUIRED, exports.STATUSES.FORBIDDEN, exports.STATUSES.NOT_FOUND, exports.STATUSES.METHOD_NOT_ALLOWED, exports.STATUSES.NOT_ACCEPTABLE, exports.STATUSES.PROXY_AUTHENTICATION_REQUIRED, exports.STATUSES.REQUEST_TIMEOUT, exports.STATUSES.CONFLICT, exports.STATUSES.GONE, exports.STATUSES.LENGTH_REQUIRED, exports.STATUSES.PRECONDITION_FAILED, exports.STATUSES.PAYLOAD_TOO_LARGE, exports.STATUSES.URI_TOO_LONG, exports.STATUSES.UNSUPPORTED_MEDIA_TYPE, exports.STATUSES.RANGE_NOT_SATISFIABLE, exports.STATUSES.EXPECTATION_FAILED, exports.STATUSES.IM_A_TEAPOT, exports.STATUSES.PAGE_EXPIRED, exports.STATUSES.ENHANCE_YOUR_CALM, exports.STATUSES.MISDIRECTED_REQUEST, exports.STATUSES.UNPROCESSABLE_ENTITY, exports.STATUSES.LOCKED, exports.STATUSES.FAILED_DEPENDENCY, exports.STATUSES.TOO_EARLY, exports.STATUSES.UPGRADE_REQUIRED, exports.STATUSES.PRECONDITION_REQUIRED, exports.STATUSES.TOO_MANY_REQUESTS, exports.STATUSES.REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL, exports.STATUSES.REQUEST_HEADER_FIELDS_TOO_LARGE, exports.STATUSES.LOGIN_TIMEOUT, exports.STATUSES.NO_RESPONSE, exports.STATUSES.RETRY_WITH, exports.STATUSES.BLOCKED_BY_PARENTAL_CONTROL, exports.STATUSES.UNAVAILABLE_FOR_LEGAL_REASONS, exports.STATUSES.CLIENT_CLOSED_LOAD_BALANCED_REQUEST, exports.STATUSES.INVALID_X_FORWARDED_FOR, exports.STATUSES.REQUEST_HEADER_TOO_LARGE, exports.STATUSES.SSL_CERTIFICATE_ERROR, exports.STATUSES.SSL_CERTIFICATE_REQUIRED, exports.STATUSES.HTTP_REQUEST_SENT_TO_HTTPS_PORT, exports.STATUSES.INVALID_TOKEN, exports.STATUSES.CLIENT_CLOSED_REQUEST, exports.STATUSES.INTERNAL_SERVER_ERROR, exports.STATUSES.NOT_IMPLEMENTED, exports.STATUSES.BAD_GATEWAY, exports.STATUSES.SERVICE_UNAVAILABLE, exports.STATUSES.GATEWAY_TIMEOUT, exports.STATUSES.HTTP_VERSION_NOT_SUPPORTED, exports.STATUSES.VARIANT_ALSO_NEGOTIATES, exports.STATUSES.INSUFFICIENT_STORAGE, exports.STATUSES.LOOP_DETECTED, exports.STATUSES.BANDWIDTH_LIMIT_EXCEEDED, exports.STATUSES.NOT_EXTENDED, exports.STATUSES.NETWORK_AUTHENTICATION_REQUIRED, exports.STATUSES.WEB_SERVER_UNKNOWN_ERROR, exports.STATUSES.WEB_SERVER_IS_DOWN, exports.STATUSES.CONNECTION_TIMEOUT, exports.STATUSES.ORIGIN_IS_UNREACHABLE, exports.STATUSES.TIMEOUT_OCCURED, exports.STATUSES.SSL_HANDSHAKE_FAILED, exports.STATUSES.INVALID_SSL_CERTIFICATE, exports.STATUSES.RAILGUN_ERROR, exports.STATUSES.SITE_IS_OVERLOADED, exports.STATUSES.SITE_IS_FROZEN, exports.STATUSES.IDENTITY_PROVIDER_AUTHENTICATION_ERROR, exports.STATUSES.NETWORK_READ_TIMEOUT, exports.STATUSES.NETWORK_CONNECT_TIMEOUT, ]; exports.ALPHA = []; for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) { // Upper case exports.ALPHA.push(String.fromCharCode(i)); // Lower case exports.ALPHA.push(String.fromCharCode(i + 0x20)); } exports.NUM_MAP = { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, }; exports.HEX_MAP = { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF, a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf, }; exports.NUM = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ]; exports.ALPHANUM = exports.ALPHA.concat(exports.NUM); exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')']; exports.USERINFO_CHARS = exports.ALPHANUM .concat(exports.MARK) .concat(['%', ';', ':', '&', '=', '+', '$', ',']); // TODO(indutny): use RFC exports.URL_CHAR = [ '!', '"', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', ].concat(exports.ALPHANUM); exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']); /* Tokens as defined by rfc 2616. Also lowercases them. * token = 1* * separators = "(" | ")" | "<" | ">" | "@" * | "," | ";" | ":" | "\" | <"> * | "/" | "[" | "]" | "?" | "=" * | "{" | "}" | SP | HT */ exports.TOKEN = [ '!', '#', '$', '%', '&', '\'', '*', '+', '-', '.', '^', '_', '`', '|', '~', ].concat(exports.ALPHANUM); /* * Verify that a char is a valid visible (printable) US-ASCII * character or %x80-FF */ exports.HEADER_CHARS = ['\t']; for (let i = 32; i <= 255; i++) { if (i !== 127) { exports.HEADER_CHARS.push(i); } } // ',' = \x44 exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44); exports.QUOTED_STRING = ['\t', ' ']; for (let i = 0x21; i <= 0xff; i++) { if (i !== 0x22 && i !== 0x5c) { // All characters in ASCII except \ and " exports.QUOTED_STRING.push(i); } } exports.HTAB_SP_VCHAR_OBS_TEXT = ['\t', ' ']; // VCHAR: https://tools.ietf.org/html/rfc5234#appendix-B.1 for (let i = 0x21; i <= 0x7E; i++) { exports.HTAB_SP_VCHAR_OBS_TEXT.push(i); } // OBS_TEXT: https://datatracker.ietf.org/doc/html/rfc9110#name-collected-abnf for (let i = 0x80; i <= 0xff; i++) { exports.HTAB_SP_VCHAR_OBS_TEXT.push(i); } exports.MAJOR = exports.NUM_MAP; exports.MINOR = exports.MAJOR; exports.SPECIAL_HEADERS = { 'connection': exports.HEADER_STATE.CONNECTION, 'content-length': exports.HEADER_STATE.CONTENT_LENGTH, 'proxy-connection': exports.HEADER_STATE.CONNECTION, 'transfer-encoding': exports.HEADER_STATE.TRANSFER_ENCODING, 'upgrade': exports.HEADER_STATE.UPGRADE, }; //# sourceMappingURL=constants.js.map /***/ }), /***/ 34493: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* module decorator */ module = __nccwpck_require__.nmd(module); const { Buffer } = __nccwpck_require__(4573) const wasmBase64 = 'AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAn9/AGABfwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAzQzBQYAAAMAAAAAAAADAQMAAwMDAAACAAAAAAICAgICAgICAgIBAQEBAQEBAQEDAAADAAAABAUBcAESEgUDAQACBggBfwFBgNgECwfFBygGbWVtb3J5AgALX2luaXRpYWxpemUACBlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQACRhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUANgxsbGh0dHBfYWxsb2MACwZtYWxsb2MAOAtsbGh0dHBfZnJlZQAMBGZyZWUADA9sbGh0dHBfZ2V0X3R5cGUADRVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADhVsbGh0dHBfZ2V0X2h0dHBfbWlub3IADxFsbGh0dHBfZ2V0X21ldGhvZAAQFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAERJsbGh0dHBfZ2V0X3VwZ3JhZGUAEgxsbGh0dHBfcmVzZXQAEw5sbGh0dHBfZXhlY3V0ZQAUFGxsaHR0cF9zZXR0aW5nc19pbml0ABUNbGxodHRwX2ZpbmlzaAAWDGxsaHR0cF9wYXVzZQAXDWxsaHR0cF9yZXN1bWUAGBtsbGh0dHBfcmVzdW1lX2FmdGVyX3VwZ3JhZGUAGRBsbGh0dHBfZ2V0X2Vycm5vABoXbGxodHRwX2dldF9lcnJvcl9yZWFzb24AGxdsbGh0dHBfc2V0X2Vycm9yX3JlYXNvbgAcFGxsaHR0cF9nZXRfZXJyb3JfcG9zAB0RbGxodHRwX2Vycm5vX25hbWUAHhJsbGh0dHBfbWV0aG9kX25hbWUAHxJsbGh0dHBfc3RhdHVzX25hbWUAIBpsbGh0dHBfc2V0X2xlbmllbnRfaGVhZGVycwAhIWxsaHR0cF9zZXRfbGVuaWVudF9jaHVua2VkX2xlbmd0aAAiHWxsaHR0cF9zZXRfbGVuaWVudF9rZWVwX2FsaXZlACMkbGxodHRwX3NldF9sZW5pZW50X3RyYW5zZmVyX2VuY29kaW5nACQabGxodHRwX3NldF9sZW5pZW50X3ZlcnNpb24AJSNsbGh0dHBfc2V0X2xlbmllbnRfZGF0YV9hZnRlcl9jbG9zZQAmJ2xsaHR0cF9zZXRfbGVuaWVudF9vcHRpb25hbF9sZl9hZnRlcl9jcgAnLGxsaHR0cF9zZXRfbGVuaWVudF9vcHRpb25hbF9jcmxmX2FmdGVyX2NodW5rACgobGxodHRwX3NldF9sZW5pZW50X29wdGlvbmFsX2NyX2JlZm9yZV9sZgApKmxsaHR0cF9zZXRfbGVuaWVudF9zcGFjZXNfYWZ0ZXJfY2h1bmtfc2l6ZQAqGGxsaHR0cF9tZXNzYWdlX25lZWRzX2VvZgA1CRcBAEEBCxEBAgMEBQoGBzEzMi0uLCsvMAq8ywIzFgBB/NMAKAIABEAAC0H80wBBATYCAAsUACAAEDcgACACNgI4IAAgAToAKAsUACAAIAAvATQgAC0AMCAAEDYQAAseAQF/QcAAEDkiARA3IAFBgAg2AjggASAAOgAoIAELjwwBB38CQCAARQ0AIABBCGsiASAAQQRrKAIAIgBBeHEiBGohBQJAIABBAXENACAAQQNxRQ0BIAEgASgCACIAayIBQZDUACgCAEkNASAAIARqIQQCQAJAQZTUACgCACABRwRAIABB/wFNBEAgAEEDdiEDIAEoAggiACABKAIMIgJGBEBBgNQAQYDUACgCAEF+IAN3cTYCAAwFCyACIAA2AgggACACNgIMDAQLIAEoAhghBiABIAEoAgwiAEcEQCAAIAEoAggiAjYCCCACIAA2AgwMAwsgAUEUaiIDKAIAIgJFBEAgASgCECICRQ0CIAFBEGohAwsDQCADIQcgAiIAQRRqIgMoAgAiAg0AIABBEGohAyAAKAIQIgINAAsgB0EANgIADAILIAUoAgQiAEEDcUEDRw0CIAUgAEF+cTYCBEGI1AAgBDYCACAFIAQ2AgAgASAEQQFyNgIEDAMLQQAhAAsgBkUNAAJAIAEoAhwiAkECdEGw1gBqIgMoAgAgAUYEQCADIAA2AgAgAA0BQYTUAEGE1AAoAgBBfiACd3E2AgAMAgsgBkEQQRQgBigCECABRhtqIAA2AgAgAEUNAQsgACAGNgIYIAEoAhAiAgRAIAAgAjYCECACIAA2AhgLIAFBFGooAgAiAkUNACAAQRRqIAI2AgAgAiAANgIYCyABIAVPDQAgBSgCBCIAQQFxRQ0AAkACQAJAAkAgAEECcUUEQEGY1AAoAgAgBUYEQEGY1AAgATYCAEGM1ABBjNQAKAIAIARqIgA2AgAgASAAQQFyNgIEIAFBlNQAKAIARw0GQYjUAEEANgIAQZTUAEEANgIADAYLQZTUACgCACAFRgRAQZTUACABNgIAQYjUAEGI1AAoAgAgBGoiADYCACABIABBAXI2AgQgACABaiAANgIADAYLIABBeHEgBGohBCAAQf8BTQRAIABBA3YhAyAFKAIIIgAgBSgCDCICRgRAQYDUAEGA1AAoAgBBfiADd3E2AgAMBQsgAiAANgIIIAAgAjYCDAwECyAFKAIYIQYgBSAFKAIMIgBHBEBBkNQAKAIAGiAAIAUoAggiAjYCCCACIAA2AgwMAwsgBUEUaiIDKAIAIgJFBEAgBSgCECICRQ0CIAVBEGohAwsDQCADIQcgAiIAQRRqIgMoAgAiAg0AIABBEGohAyAAKAIQIgINAAsgB0EANgIADAILIAUgAEF+cTYCBCABIARqIAQ2AgAgASAEQQFyNgIEDAMLQQAhAAsgBkUNAAJAIAUoAhwiAkECdEGw1gBqIgMoAgAgBUYEQCADIAA2AgAgAA0BQYTUAEGE1AAoAgBBfiACd3E2AgAMAgsgBkEQQRQgBigCECAFRhtqIAA2AgAgAEUNAQsgACAGNgIYIAUoAhAiAgRAIAAgAjYCECACIAA2AhgLIAVBFGooAgAiAkUNACAAQRRqIAI2AgAgAiAANgIYCyABIARqIAQ2AgAgASAEQQFyNgIEIAFBlNQAKAIARw0AQYjUACAENgIADAELIARB/wFNBEAgBEF4cUGo1ABqIQACf0GA1AAoAgAiAkEBIARBA3Z0IgNxRQRAQYDUACACIANyNgIAIAAMAQsgACgCCAsiAiABNgIMIAAgATYCCCABIAA2AgwgASACNgIIDAELQR8hAiAEQf///wdNBEAgBEEmIARBCHZnIgBrdkEBcSAAQQF0a0E+aiECCyABIAI2AhwgAUIANwIQIAJBAnRBsNYAaiEAAkBBhNQAKAIAIgNBASACdCIHcUUEQCAAIAE2AgBBhNQAIAMgB3I2AgAgASAANgIYIAEgATYCCCABIAE2AgwMAQsgBEEZIAJBAXZrQQAgAkEfRxt0IQIgACgCACEAAkADQCAAIgMoAgRBeHEgBEYNASACQR12IQAgAkEBdCECIAMgAEEEcWpBEGoiBygCACIADQALIAcgATYCACABIAM2AhggASABNgIMIAEgATYCCAwBCyADKAIIIgAgATYCDCADIAE2AgggAUEANgIYIAEgAzYCDCABIAA2AggLQaDUAEGg1AAoAgBBAWsiAEF/IAAbNgIACwsHACAALQAoCwcAIAAtACoLBwAgAC0AKwsHACAALQApCwcAIAAvATQLBwAgAC0AMAtAAQR/IAAoAhghASAALwEuIQIgAC0AKCEDIAAoAjghBCAAEDcgACAENgI4IAAgAzoAKCAAIAI7AS4gACABNgIYC8X4AQIHfwN+IAEgAmohBAJAIAAiAygCDCIADQAgAygCBARAIAMgATYCBAsjAEEQayIJJAACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAygCHCICQQFrDuwB7gEB6AECAwQFBgcICQoLDA0ODxAREucBE+YBFBXlARYX5AEYGRobHB0eHyDvAe0BIeMBIiMkJSYnKCkqK+IBLC0uLzAxMuEB4AEzNN8B3gE1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk/pAVBRUlPdAdwBVNsBVdoBVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEBkgGTAZQBlQGWAZcBmAGZAZoBmwGcAZ0BngGfAaABoQGiAaMBpAGlAaYBpwGoAakBqgGrAawBrQGuAa8BsAGxAbIBswG0AbUBtgG3AbgBuQG6AbsBvAG9Ab4BvwHAAcEBwgHDAcQBxQHZAdgBxgHXAccB1gHIAckBygHLAcwBzQHOAc8B0AHRAdIB0wHUAQDqAQtBAAzUAQtBDgzTAQtBDQzSAQtBDwzRAQtBEAzQAQtBEQzPAQtBEgzOAQtBEwzNAQtBFAzMAQtBFQzLAQtBFgzKAQtBFwzJAQtBGAzIAQtBGQzHAQtBGgzGAQtBGwzFAQtBHAzEAQtBHQzDAQtBHgzCAQtBHwzBAQtBCAzAAQtBIAy/AQtBIgy+AQtBIQy9AQtBBwy8AQtBIwy7AQtBJAy6AQtBJQy5AQtBJgy4AQtBJwy3AQtBzgEMtgELQSgMtQELQSkMtAELQSoMswELQSsMsgELQc8BDLEBC0EtDLABC0EuDK8BC0EvDK4BC0EwDK0BC0ExDKwBC0EyDKsBC0EzDKoBC0HQAQypAQtBNAyoAQtBOAynAQtBDAymAQtBNQylAQtBNgykAQtBNwyjAQtBPQyiAQtBOQyhAQtB0QEMoAELQQsMnwELQT4MngELQToMnQELQQoMnAELQTsMmwELQTwMmgELQdIBDJkBC0HAAAyYAQtBPwyXAQtBwQAMlgELQQkMlQELQSwMlAELQcIADJMBC0HDAAySAQtBxAAMkQELQcUADJABC0HGAAyPAQtBxwAMjgELQcgADI0BC0HJAAyMAQtBygAMiwELQcsADIoBC0HMAAyJAQtBzQAMiAELQc4ADIcBC0HPAAyGAQtB0AAMhQELQdEADIQBC0HSAAyDAQtB1AAMggELQdMADIEBC0HVAAyAAQtB1gAMfwtB1wAMfgtB2AAMfQtB2QAMfAtB2gAMewtB2wAMegtB0wEMeQtB3AAMeAtB3QAMdwtBBgx2C0HeAAx1C0EFDHQLQd8ADHMLQQQMcgtB4AAMcQtB4QAMcAtB4gAMbwtB4wAMbgtBAwxtC0HkAAxsC0HlAAxrC0HmAAxqC0HoAAxpC0HnAAxoC0HpAAxnC0HqAAxmC0HrAAxlC0HsAAxkC0ECDGMLQe0ADGILQe4ADGELQe8ADGALQfAADF8LQfEADF4LQfIADF0LQfMADFwLQfQADFsLQfUADFoLQfYADFkLQfcADFgLQfgADFcLQfkADFYLQfoADFULQfsADFQLQfwADFMLQf0ADFILQf4ADFELQf8ADFALQYABDE8LQYEBDE4LQYIBDE0LQYMBDEwLQYQBDEsLQYUBDEoLQYYBDEkLQYcBDEgLQYgBDEcLQYkBDEYLQYoBDEULQYsBDEQLQYwBDEMLQY0BDEILQY4BDEELQY8BDEALQZABDD8LQZEBDD4LQZIBDD0LQZMBDDwLQZQBDDsLQZUBDDoLQZYBDDkLQZcBDDgLQZgBDDcLQZkBDDYLQZoBDDULQZsBDDQLQZwBDDMLQZ0BDDILQZ4BDDELQZ8BDDALQaABDC8LQaEBDC4LQaIBDC0LQaMBDCwLQaQBDCsLQaUBDCoLQaYBDCkLQacBDCgLQagBDCcLQakBDCYLQaoBDCULQasBDCQLQawBDCMLQa0BDCILQa4BDCELQa8BDCALQbABDB8LQbEBDB4LQbIBDB0LQbMBDBwLQbQBDBsLQbUBDBoLQbYBDBkLQbcBDBgLQbgBDBcLQQEMFgtBuQEMFQtBugEMFAtBuwEMEwtBvAEMEgtBvQEMEQtBvgEMEAtBvwEMDwtBwAEMDgtBwQEMDQtBwgEMDAtBwwEMCwtBxAEMCgtBxQEMCQtBxgEMCAtB1AEMBwtBxwEMBgtByAEMBQtByQEMBAtBygEMAwtBywEMAgtBzQEMAQtBzAELIQIDQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAMCfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJ/AkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAMCfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCACDtQBAAECAwQFBgcICQoLDA0ODxARFBUWFxgZGhscHR4fICEjJCUnKCmIA4cDhQOEA/wC9QLuAusC6ALmAuMC4ALfAt0C2wLWAtUC1ALTAtICygLJAsgCxwLGAsUCxALDAr0CvAK6ArkCuAK3ArYCtQK0ArICsQKsAqoCqAKnAqYCpQKkAqMCogKhAqACnwKbApoCmQKYApcCkAKIAoQCgwKCAvkB9gH1AfQB8wHyAfEB8AHvAe0B6wHoAeMB4QHgAd8B3gHdAdwB2wHaAdkB2AHXAdYB1QHUAdIB0QHQAc8BzgHNAcwBywHKAckByAHHAcYBxQHEAcMBwgHBAcABvwG+Ab0BvAG7AboBuQG4AbcBtgG1AbQBswGyAbEBsAGvAa4BrQGsAasBqgGpAagBpwGmAaUBpAGjAaIBoQGgAZ8BngGdAZwBmwGaAZcBlgGRAZABjwGOAY0BjAGLAYoBiQGIAYUBhAGDAX59fHt6d3Z1LFFSU1RVVgsgASAERw1zQewBIQIMqQMLIAEgBEcNkAFB0QEhAgyoAwsgASAERw3pAUGEASECDKcDCyABIARHDfQBQfoAIQIMpgMLIAEgBEcNggJB9QAhAgylAwsgASAERw2JAkHzACECDKQDCyABIARHDYwCQfEAIQIMowMLIAEgBEcNHkEeIQIMogMLIAEgBEcNGUEYIQIMoQMLIAEgBEcNuAJBzQAhAgygAwsgASAERw3DAkHGACECDJ8DCyABIARHDcQCQcMAIQIMngMLIAEgBEcNygJBOCECDJ0DCyADLQAwQQFGDZUDDPICC0EAIQACQAJAAkAgAy0AKkUNACADLQArRQ0AIAMvATIiAkECcUUNAQwCCyADLwEyIgJBAXFFDQELQQEhACADLQAoQQFGDQAgAy8BNCIGQeQAa0HkAEkNACAGQcwBRg0AIAZBsAJGDQAgAkHAAHENAEEAIQAgAkGIBHFBgARGDQAgAkEocUEARyEACyADQQA7ATIgA0EAOgAxAkAgAEUEQCADQQA6ADEgAy0ALkEEcQ0BDJwDCyADQgA3AyALIANBADoAMSADQQE6ADYMSQtBACEAAkAgAygCOCICRQ0AIAIoAiwiAkUNACADIAIRAAAhAAsgAEUNSSAAQRVHDWMgA0EENgIcIAMgATYCFCADQb0aNgIQIANBFTYCDEEAIQIMmgMLIAEgBEYEQEEGIQIMmgMLIAEtAABBCkYNGQwBCyABIARGBEBBByECDJkDCwJAIAEtAABBCmsOBAIBAQABCyABQQFqIQFBECECDP4CCyADLQAuQYABcQ0YQQAhAiADQQA2AhwgAyABNgIUIANBqR82AhAgA0ECNgIMDJcDCyABQQFqIQEgA0Evai0AAEEBcQ0XQQAhAiADQQA2AhwgAyABNgIUIANBhB82AhAgA0EZNgIMDJYDCyADIAMpAyAiDCAEIAFrrSIKfSILQgAgCyAMWBs3AyAgCiAMWg0ZQQghAgyVAwsgASAERwRAIANBCTYCCCADIAE2AgRBEiECDPsCC0EJIQIMlAMLIAMpAyBQDZwCDEQLIAEgBEYEQEELIQIMkwMLIAEtAABBCkcNFyABQQFqIQEMGAsgA0Evai0AAEEBcUUNGgwnC0EAIQACQCADKAI4IgJFDQAgAigCSCICRQ0AIAMgAhEAACEACyAADRoMQwtBACEAAkAgAygCOCICRQ0AIAIoAkgiAkUNACADIAIRAAAhAAsgAA0bDCULQQAhAAJAIAMoAjgiAkUNACACKAJIIgJFDQAgAyACEQAAIQALIAANHAwzCyADQS9qLQAAQQFxRQ0dDCMLQQAhAAJAIAMoAjgiAkUNACACKAJMIgJFDQAgAyACEQAAIQALIAANHQxDC0EAIQACQCADKAI4IgJFDQAgAigCTCICRQ0AIAMgAhEAACEACyAADR4MIQsgASAERgRAQRMhAgyLAwsCQCABLQAAIgBBCmsOBCAkJAAjCyABQQFqIQEMIAtBACEAAkAgAygCOCICRQ0AIAIoAkwiAkUNACADIAIRAAAhAAsgAA0jDEMLIAEgBEYEQEEWIQIMiQMLIAEtAABB8D9qLQAAQQFHDSQM7QILAkADQCABLQAAQeA5ai0AACIAQQFHBEACQCAAQQJrDgIDACgLIAFBAWohAUEfIQIM8AILIAQgAUEBaiIBRw0AC0EYIQIMiAMLIAMoAgQhAEEAIQIgA0EANgIEIAMgACABQQFqIgEQMyIADSIMQgtBACEAAkAgAygCOCICRQ0AIAIoAkwiAkUNACADIAIRAAAhAAsgAA0kDCsLIAEgBEYEQEEcIQIMhgMLIANBCjYCCCADIAE2AgRBACEAAkAgAygCOCICRQ0AIAIoAkgiAkUNACADIAIRAAAhAAsgAA0mQSIhAgzrAgsgASAERwRAA0AgAS0AAEHgO2otAAAiAEEDRwRAIABBAWsOBRkbJ+wCJicLIAQgAUEBaiIBRw0AC0EbIQIMhQMLQRshAgyEAwsDQCABLQAAQeA9ai0AACIAQQNHBEAgAEEBaw4FEBIoFCcoCyAEIAFBAWoiAUcNAAtBHiECDIMDCyABIARHBEAgA0ELNgIIIAMgATYCBEEHIQIM6QILQR8hAgyCAwsgASAERgRAQSAhAgyCAwsCQCABLQAAQQ1rDhQvQEBAQEBAQEBAQEBAQEBAQEBAAEALQQAhAiADQQA2AhwgA0G3CzYCECADQQI2AgwgAyABQQFqNgIUDIEDCyADQS9qIQIDQCABIARGBEBBISECDIIDCwJAAkACQCABLQAAIgBBCWsOGAIAKioBKioqKioqKioqKioqKioqKioqAigLIAFBAWohASADQS9qLQAAQQFxRQ0LDBkLIAFBAWohAQwYCyABQQFqIQEgAi0AAEECcQ0AC0EAIQIgA0EANgIcIAMgATYCFCADQc4UNgIQIANBDDYCDAyAAwsgAUEBaiEBC0EAIQACQCADKAI4IgJFDQAgAigCVCICRQ0AIAMgAhEAACEACyAADQEM0QILIANCADcDIAw8CyAAQRVGBEAgA0EkNgIcIAMgATYCFCADQYYaNgIQIANBFTYCDEEAIQIM/QILQQAhAiADQQA2AhwgAyABNgIUIANB4g02AhAgA0EUNgIMDPwCCyADKAIEIQBBACECIANBADYCBCADIAAgASAMp2oiARAxIgBFDSsgA0EHNgIcIAMgATYCFCADIAA2AgwM+wILIAMtAC5BwABxRQ0BC0EAIQACQCADKAI4IgJFDQAgAigCUCICRQ0AIAMgAhEAACEACyAARQ0rIABBFUYEQCADQQo2AhwgAyABNgIUIANB8Rg2AhAgA0EVNgIMQQAhAgz6AgtBACECIANBADYCHCADIAE2AhQgA0GLDDYCECADQRM2AgwM+QILQQAhAiADQQA2AhwgAyABNgIUIANBsRQ2AhAgA0ECNgIMDPgCC0EAIQIgA0EANgIcIAMgATYCFCADQYwUNgIQIANBGTYCDAz3AgtBACECIANBADYCHCADIAE2AhQgA0HRHDYCECADQRk2AgwM9gILIABBFUYNPUEAIQIgA0EANgIcIAMgATYCFCADQaIPNgIQIANBIjYCDAz1AgsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQMiIARQ0oIANBDTYCHCADIAE2AhQgAyAANgIMDPQCCyAAQRVGDTpBACECIANBADYCHCADIAE2AhQgA0GiDzYCECADQSI2AgwM8wILIAMoAgQhAEEAIQIgA0EANgIEIAMgACABEDIiAEUEQCABQQFqIQEMKAsgA0EONgIcIAMgADYCDCADIAFBAWo2AhQM8gILIABBFUYNN0EAIQIgA0EANgIcIAMgATYCFCADQaIPNgIQIANBIjYCDAzxAgsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQMiIARQRAIAFBAWohAQwnCyADQQ82AhwgAyAANgIMIAMgAUEBajYCFAzwAgtBACECIANBADYCHCADIAE2AhQgA0HoFjYCECADQRk2AgwM7wILIABBFUYNM0EAIQIgA0EANgIcIAMgATYCFCADQc4MNgIQIANBIzYCDAzuAgsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQMyIARQ0lIANBETYCHCADIAE2AhQgAyAANgIMDO0CCyAAQRVGDTBBACECIANBADYCHCADIAE2AhQgA0HODDYCECADQSM2AgwM7AILIAMoAgQhAEEAIQIgA0EANgIEIAMgACABEDMiAEUEQCABQQFqIQEMJQsgA0ESNgIcIAMgADYCDCADIAFBAWo2AhQM6wILIANBL2otAABBAXFFDQELQRUhAgzPAgtBACECIANBADYCHCADIAE2AhQgA0HoFjYCECADQRk2AgwM6AILIABBO0cNACABQQFqIQEMDAtBACECIANBADYCHCADIAE2AhQgA0GYFzYCECADQQI2AgwM5gILIABBFUYNKEEAIQIgA0EANgIcIAMgATYCFCADQc4MNgIQIANBIzYCDAzlAgsgA0EUNgIcIAMgATYCFCADIAA2AgwM5AILIAMoAgQhAEEAIQIgA0EANgIEIAMgACABEDMiAEUEQCABQQFqIQEM3AILIANBFTYCHCADIAA2AgwgAyABQQFqNgIUDOMCCyADKAIEIQBBACECIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDNoCCyADQRc2AhwgAyAANgIMIAMgAUEBajYCFAziAgsgAEEVRg0jQQAhAiADQQA2AhwgAyABNgIUIANBzgw2AhAgA0EjNgIMDOECCyADKAIEIQBBACECIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDB0LIANBGTYCHCADIAA2AgwgAyABQQFqNgIUDOACCyADKAIEIQBBACECIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDNYCCyADQRo2AhwgAyAANgIMIAMgAUEBajYCFAzfAgsgAEEVRg0fQQAhAiADQQA2AhwgAyABNgIUIANBog82AhAgA0EiNgIMDN4CCyADKAIEIQBBACECIANBADYCBCADIAAgARAyIgBFBEAgAUEBaiEBDBsLIANBHDYCHCADIAA2AgwgAyABQQFqNgIUDN0CCyADKAIEIQBBACECIANBADYCBCADIAAgARAyIgBFBEAgAUEBaiEBDNICCyADQR02AhwgAyAANgIMIAMgAUEBajYCFAzcAgsgAEE7Rw0BIAFBAWohAQtBJCECDMACC0EAIQIgA0EANgIcIAMgATYCFCADQc4UNgIQIANBDDYCDAzZAgsgASAERwRAA0AgAS0AAEEgRw3xASAEIAFBAWoiAUcNAAtBLCECDNkCC0EsIQIM2AILIAEgBEYEQEE0IQIM2AILAkACQANAAkAgAS0AAEEKaw4EAgAAAwALIAQgAUEBaiIBRw0AC0E0IQIM2QILIAMoAgQhACADQQA2AgQgAyAAIAEQMCIARQ2MAiADQTI2AhwgAyABNgIUIAMgADYCDEEAIQIM2AILIAMoAgQhACADQQA2AgQgAyAAIAEQMCIARQRAIAFBAWohAQyMAgsgA0EyNgIcIAMgADYCDCADIAFBAWo2AhRBACECDNcCCyABIARHBEACQANAIAEtAABBMGsiAEH/AXFBCk8EQEE5IQIMwAILIAMpAyAiC0KZs+bMmbPmzBlWDQEgAyALQgp+Igo3AyAgCiAArUL/AYMiC0J/hVYNASADIAogC3w3AyAgBCABQQFqIgFHDQALQcAAIQIM2AILIAMoAgQhACADQQA2AgQgAyAAIAFBAWoiARAwIgANFwzJAgtBwAAhAgzWAgsgASAERgRAQckAIQIM1gILAkADQAJAIAEtAABBCWsOGAACjwKPApMCjwKPAo8CjwKPAo8CjwKPAo8CjwKPAo8CjwKPAo8CjwKPAo8CAI8CCyAEIAFBAWoiAUcNAAtByQAhAgzWAgsgAUEBaiEBIANBL2otAABBAXENjwIgA0EANgIcIAMgATYCFCADQekPNgIQIANBCjYCDEEAIQIM1QILIAEgBEcEQANAIAEtAAAiAEEgRwRAAkACQAJAIABByABrDgsAAc0BzQHNAc0BzQHNAc0BzQECzQELIAFBAWohAUHZACECDL8CCyABQQFqIQFB2gAhAgy+AgsgAUEBaiEBQdsAIQIMvQILIAQgAUEBaiIBRw0AC0HuACECDNUCC0HuACECDNQCCyADQQI6ACgMMAtBACECIANBADYCHCADQbcLNgIQIANBAjYCDCADIAFBAWo2AhQM0gILQQAhAgy3AgtBDSECDLYCC0ERIQIMtQILQRMhAgy0AgtBFCECDLMCC0EWIQIMsgILQRchAgyxAgtBGCECDLACC0EZIQIMrwILQRohAgyuAgtBGyECDK0CC0EcIQIMrAILQR0hAgyrAgtBHiECDKoCC0EgIQIMqQILQSEhAgyoAgtBIyECDKcCC0EnIQIMpgILIANBPTYCHCADIAE2AhQgAyAANgIMQQAhAgy/AgsgA0EbNgIcIAMgATYCFCADQY8bNgIQIANBFTYCDEEAIQIMvgILIANBIDYCHCADIAE2AhQgA0GeGTYCECADQRU2AgxBACECDL0CCyADQRM2AhwgAyABNgIUIANBnhk2AhAgA0EVNgIMQQAhAgy8AgsgA0ELNgIcIAMgATYCFCADQZ4ZNgIQIANBFTYCDEEAIQIMuwILIANBEDYCHCADIAE2AhQgA0GeGTYCECADQRU2AgxBACECDLoCCyADQSA2AhwgAyABNgIUIANBjxs2AhAgA0EVNgIMQQAhAgy5AgsgA0ELNgIcIAMgATYCFCADQY8bNgIQIANBFTYCDEEAIQIMuAILIANBDDYCHCADIAE2AhQgA0GPGzYCECADQRU2AgxBACECDLcCC0EAIQIgA0EANgIcIAMgATYCFCADQa8ONgIQIANBEjYCDAy2AgsCQANAAkAgAS0AAEEKaw4EAAICAAILIAQgAUEBaiIBRw0AC0HsASECDLYCCwJAAkAgAy0ANkEBRw0AQQAhAAJAIAMoAjgiAkUNACACKAJYIgJFDQAgAyACEQAAIQALIABFDQAgAEEVRw0BIANB6wE2AhwgAyABNgIUIANB4hg2AhAgA0EVNgIMQQAhAgy3AgtBzAEhAgycAgsgA0EANgIcIAMgATYCFCADQfELNgIQIANBHzYCDEEAIQIMtQILAkACQCADLQAoQQFrDgIEAQALQcsBIQIMmwILQcQBIQIMmgILIANBAjoAMUEAIQACQCADKAI4IgJFDQAgAigCACICRQ0AIAMgAhEAACEACyAARQRAQc0BIQIMmgILIABBFUcEQCADQQA2AhwgAyABNgIUIANBrAw2AhAgA0EQNgIMQQAhAgy0AgsgA0HqATYCHCADIAE2AhQgA0GHGTYCECADQRU2AgxBACECDLMCCyABIARGBEBB6QEhAgyzAgsgAS0AAEHIAEYNASADQQE6ACgLQbYBIQIMlwILQcoBIQIMlgILIAEgBEcEQCADQQw2AgggAyABNgIEQckBIQIMlgILQegBIQIMrwILIAEgBEYEQEHnASECDK8CCyABLQAAQcgARw0EIAFBAWohAUHIASECDJQCCyABIARGBEBB5gEhAgyuAgsCQAJAIAEtAABBxQBrDhAABQUFBQUFBQUFBQUFBQUBBQsgAUEBaiEBQcYBIQIMlAILIAFBAWohAUHHASECDJMCC0HlASECIAEgBEYNrAIgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB99MAai0AAEcNAyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMrQILIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARAtIgBFBEBB1AEhAgyTAgsgA0HkATYCHCADIAE2AhQgAyAANgIMQQAhAgysAgtB4wEhAiABIARGDasCIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQfXTAGotAABHDQIgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADKwCCyADQYEEOwEoIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARAtIgANAwwCCyADQQA2AgALQQAhAiADQQA2AhwgAyABNgIUIANB0B42AhAgA0EINgIMDKkCC0HFASECDI4CCyADQeIBNgIcIAMgATYCFCADIAA2AgxBACECDKcCC0EAIQACQCADKAI4IgJFDQAgAigCOCICRQ0AIAMgAhEAACEACyAARQ1lIABBFUcEQCADQQA2AhwgAyABNgIUIANB1A42AhAgA0EgNgIMQQAhAgynAgsgA0GFATYCHCADIAE2AhQgA0HXGjYCECADQRU2AgxBACECDKYCC0HhASECIAQgASIARg2lAiAEIAFrIAMoAgAiAWohBSAAIAFrQQRqIQYCQANAIAAtAAAgAUHw0wBqLQAARw0BIAFBBEYNAyABQQFqIQEgBCAAQQFqIgBHDQALIAMgBTYCAAymAgsgA0EANgIcIAMgADYCFCADQYQ3NgIQIANBCDYCDCADQQA2AgBBACECDKUCCyABIARHBEAgA0ENNgIIIAMgATYCBEHCASECDIsCC0HgASECDKQCCyADQQA2AgAgBkEBaiEBC0HDASECDIgCCyABIARGBEBB3wEhAgyiAgsgAS0AAEEwayIAQf8BcUEKSQRAIAMgADoAKiABQQFqIQFBwQEhAgyIAgsgAygCBCEAIANBADYCBCADIAAgARAuIgBFDYgCIANB3gE2AhwgAyABNgIUIAMgADYCDEEAIQIMoQILIAEgBEYEQEHdASECDKECCwJAIAEtAABBLkYEQCABQQFqIQEMAQsgAygCBCEAIANBADYCBCADIAAgARAuIgBFDYkCIANB3AE2AhwgAyABNgIUIAMgADYCDEEAIQIMoQILQcABIQIMhgILIAEgBEYEQEHbASECDKACC0EAIQBBASEFQQEhB0EAIQICQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQCABLQAAQTBrDgoKCQABAgMEBQYICwtBAgwGC0EDDAULQQQMBAtBBQwDC0EGDAILQQcMAQtBCAshAkEAIQVBACEHDAILQQkhAkEBIQBBACEFQQAhBwwBC0EAIQVBASECCyADIAI6ACsgAUEBaiEBAkACQCADLQAuQRBxDQACQAJAAkAgAy0AKg4DAQACBAsgB0UNAwwCCyAADQEMAgsgBUUNAQsgAygCBCEAIANBADYCBCADIAAgARAuIgBFDQIgA0HYATYCHCADIAE2AhQgAyAANgIMQQAhAgyiAgsgAygCBCEAIANBADYCBCADIAAgARAuIgBFDYsCIANB2QE2AhwgAyABNgIUIAMgADYCDEEAIQIMoQILIAMoAgQhACADQQA2AgQgAyAAIAEQLiIARQ2JAiADQdoBNgIcIAMgATYCFCADIAA2AgwMoAILQb8BIQIMhQILQQAhAAJAIAMoAjgiAkUNACACKAI8IgJFDQAgAyACEQAAIQALAkAgAARAIABBFUYNASADQQA2AhwgAyABNgIUIANBnA02AhAgA0EhNgIMQQAhAgygAgtBvgEhAgyFAgsgA0HXATYCHCADIAE2AhQgA0HWGTYCECADQRU2AgxBACECDJ4CCyABIARGBEBB1wEhAgyeAgsCQCABLQAAQSBGBEAgA0EAOwE0IAFBAWohAQwBCyADQQA2AhwgAyABNgIUIANB6xA2AhAgA0EJNgIMQQAhAgyeAgtBvQEhAgyDAgsgASAERgRAQdYBIQIMnQILAkAgAS0AAEEwa0H/AXEiAkEKSQRAIAFBAWohAQJAIAMvATQiAEGZM0sNACADIABBCmwiADsBNCAAQf7/A3EgAkH//wNzSw0AIAMgACACajsBNAwCC0EAIQIgA0EANgIcIAMgATYCFCADQYAdNgIQIANBDTYCDAyeAgsgA0EANgIcIAMgATYCFCADQYAdNgIQIANBDTYCDEEAIQIMnQILQbwBIQIMggILIAEgBEYEQEHVASECDJwCCwJAIAEtAABBMGtB/wFxIgJBCkkEQCABQQFqIQECQCADLwE0IgBBmTNLDQAgAyAAQQpsIgA7ATQgAEH+/wNxIAJB//8Dc0sNACADIAAgAmo7ATQMAgtBACECIANBADYCHCADIAE2AhQgA0GAHTYCECADQQ02AgwMnQILIANBADYCHCADIAE2AhQgA0GAHTYCECADQQ02AgxBACECDJwCC0G7ASECDIECCyABIARGBEBB1AEhAgybAgsCQCABLQAAQTBrQf8BcSICQQpJBEAgAUEBaiEBAkAgAy8BNCIAQZkzSw0AIAMgAEEKbCIAOwE0IABB/v8DcSACQf//A3NLDQAgAyAAIAJqOwE0DAILQQAhAiADQQA2AhwgAyABNgIUIANBgB02AhAgA0ENNgIMDJwCCyADQQA2AhwgAyABNgIUIANBgB02AhAgA0ENNgIMQQAhAgybAgtBugEhAgyAAgsgASAERgRAQdMBIQIMmgILAkACQAJAAkAgAS0AAEEKaw4XAgMDAAMDAwMDAwMDAwMDAwMDAwMDAwEDCyABQQFqDAULIAFBAWohAUG5ASECDIECCyABQQFqIQEgA0Evai0AAEEBcQ0IIANBADYCHCADIAE2AhQgA0GFCzYCECADQQ02AgxBACECDJoCCyADQQA2AhwgAyABNgIUIANBhQs2AhAgA0ENNgIMQQAhAgyZAgsgASAERwRAIANBDjYCCCADIAE2AgRBASECDP8BC0HSASECDJgCCwJAAkADQAJAIAEtAABBCmsOBAIAAAMACyAEIAFBAWoiAUcNAAtB0QEhAgyZAgsgAygCBCEAIANBADYCBCADIAAgARAsIgBFBEAgAUEBaiEBDAQLIANB0AE2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMmAILIAMoAgQhACADQQA2AgQgAyAAIAEQLCIADQEgAUEBagshAUG3ASECDPwBCyADQc8BNgIcIAMgADYCDCADIAFBAWo2AhRBACECDJUCC0G4ASECDPoBCyADQS9qLQAAQQFxDQEgA0EANgIcIAMgATYCFCADQc8bNgIQIANBGTYCDEEAIQIMkwILIAEgBEYEQEHPASECDJMCCwJAAkACQCABLQAAQQprDgQBAgIAAgsgAUEBaiEBDAILIAFBAWohAQwBCyADLQAuQcAAcUUNAQtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsgAEUNlgEgAEEVRgRAIANB2QA2AhwgAyABNgIUIANBvRk2AhAgA0EVNgIMQQAhAgySAgsgA0EANgIcIAMgATYCFCADQfgMNgIQIANBGzYCDEEAIQIMkQILIANBADYCHCADIAE2AhQgA0HHJzYCECADQQI2AgxBACECDJACCyABIARHBEAgA0EMNgIIIAMgATYCBEG1ASECDPYBC0HOASECDI8CCyABIARGBEBBzQEhAgyPAgsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAEtAABBwQBrDhUAAQIDWgQFBlpaWgcICQoLDA0ODxBaCyABQQFqIQFB8QAhAgyEAgsgAUEBaiEBQfIAIQIMgwILIAFBAWohAUH3ACECDIICCyABQQFqIQFB+wAhAgyBAgsgAUEBaiEBQfwAIQIMgAILIAFBAWohAUH/ACECDP8BCyABQQFqIQFBgAEhAgz+AQsgAUEBaiEBQYMBIQIM/QELIAFBAWohAUGMASECDPwBCyABQQFqIQFBjQEhAgz7AQsgAUEBaiEBQY4BIQIM+gELIAFBAWohAUGbASECDPkBCyABQQFqIQFBnAEhAgz4AQsgAUEBaiEBQaIBIQIM9wELIAFBAWohAUGqASECDPYBCyABQQFqIQFBrQEhAgz1AQsgAUEBaiEBQbQBIQIM9AELIAEgBEYEQEHMASECDI4CCyABLQAAQc4ARw1IIAFBAWohAUGzASECDPMBCyABIARGBEBBywEhAgyNAgsCQAJAAkAgAS0AAEHCAGsOEgBKSkpKSkpKSkoBSkpKSkpKAkoLIAFBAWohAUGuASECDPQBCyABQQFqIQFBsQEhAgzzAQsgAUEBaiEBQbIBIQIM8gELQcoBIQIgASAERg2LAiADKAIAIgAgBCABa2ohBSABIABrQQdqIQYCQANAIAEtAAAgAEHo0wBqLQAARw1FIABBB0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyMAgsgA0EANgIAIAZBAWohAUEbDEULIAEgBEYEQEHJASECDIsCCwJAAkAgAS0AAEHJAGsOBwBHR0dHRwFHCyABQQFqIQFBrwEhAgzxAQsgAUEBaiEBQbABIQIM8AELQcgBIQIgASAERg2JAiADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHm0wBqLQAARw1DIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyKAgsgA0EANgIAIAZBAWohAUEPDEMLQccBIQIgASAERg2IAiADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHk0wBqLQAARw1CIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyJAgsgA0EANgIAIAZBAWohAUEgDEILQcYBIQIgASAERg2HAiADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHh0wBqLQAARw1BIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyIAgsgA0EANgIAIAZBAWohAUESDEELIAEgBEYEQEHFASECDIcCCwJAAkAgAS0AAEHFAGsODgBDQ0NDQ0NDQ0NDQ0MBQwsgAUEBaiEBQasBIQIM7QELIAFBAWohAUGsASECDOwBC0HEASECIAEgBEYNhQIgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB3tMAai0AAEcNPyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMhgILIANBADYCACAGQQFqIQFBBww/C0HDASECIAEgBEYNhAIgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABB2NMAai0AAEcNPiAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMhQILIANBADYCACAGQQFqIQFBKAw+CyABIARGBEBBwgEhAgyEAgsCQAJAAkAgAS0AAEHFAGsOEQBBQUFBQUFBQUEBQUFBQUECQQsgAUEBaiEBQacBIQIM6wELIAFBAWohAUGoASECDOoBCyABQQFqIQFBqQEhAgzpAQtBwQEhAiABIARGDYICIAMoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAS0AACAAQdHTAGotAABHDTwgAEEGRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADIMCCyADQQA2AgAgBkEBaiEBQRoMPAtBwAEhAiABIARGDYECIAMoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQc3TAGotAABHDTsgAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADIICCyADQQA2AgAgBkEBaiEBQSEMOwsgASAERgRAQb8BIQIMgQILAkACQCABLQAAQcEAaw4UAD09PT09PT09PT09PT09PT09PQE9CyABQQFqIQFBowEhAgznAQsgAUEBaiEBQaYBIQIM5gELIAEgBEYEQEG+ASECDIACCwJAAkAgAS0AAEHVAGsOCwA8PDw8PDw8PDwBPAsgAUEBaiEBQaQBIQIM5gELIAFBAWohAUGlASECDOUBC0G9ASECIAEgBEYN/gEgAygCACIAIAQgAWtqIQUgASAAa0EIaiEGAkADQCABLQAAIABBxNMAai0AAEcNOCAAQQhGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM/wELIANBADYCACAGQQFqIQFBKgw4CyABIARGBEBBvAEhAgz+AQsgAS0AAEHQAEcNOCABQQFqIQFBJQw3C0G7ASECIAEgBEYN/AEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBwdMAai0AAEcNNiAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM/QELIANBADYCACAGQQFqIQFBDgw2CyABIARGBEBBugEhAgz8AQsgAS0AAEHFAEcNNiABQQFqIQFBoQEhAgzhAQsgASAERgRAQbkBIQIM+wELAkACQAJAAkAgAS0AAEHCAGsODwABAjk5OTk5OTk5OTk5AzkLIAFBAWohAUGdASECDOMBCyABQQFqIQFBngEhAgziAQsgAUEBaiEBQZ8BIQIM4QELIAFBAWohAUGgASECDOABC0G4ASECIAEgBEYN+QEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBvtMAai0AAEcNMyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM+gELIANBADYCACAGQQFqIQFBFAwzC0G3ASECIAEgBEYN+AEgAygCACIAIAQgAWtqIQUgASAAa0EEaiEGAkADQCABLQAAIABBudMAai0AAEcNMiAAQQRGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM+QELIANBADYCACAGQQFqIQFBKwwyC0G2ASECIAEgBEYN9wEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBttMAai0AAEcNMSAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM+AELIANBADYCACAGQQFqIQFBLAwxC0G1ASECIAEgBEYN9gEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB4dMAai0AAEcNMCAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM9wELIANBADYCACAGQQFqIQFBEQwwC0G0ASECIAEgBEYN9QEgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABBstMAai0AAEcNLyAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM9gELIANBADYCACAGQQFqIQFBLgwvCyABIARGBEBBswEhAgz1AQsCQAJAAkACQAJAIAEtAABBwQBrDhUANDQ0NDQ0NDQ0NAE0NAI0NAM0NAQ0CyABQQFqIQFBkQEhAgzeAQsgAUEBaiEBQZIBIQIM3QELIAFBAWohAUGTASECDNwBCyABQQFqIQFBmAEhAgzbAQsgAUEBaiEBQZoBIQIM2gELIAEgBEYEQEGyASECDPQBCwJAAkAgAS0AAEHSAGsOAwAwATALIAFBAWohAUGZASECDNoBCyABQQFqIQFBBAwtC0GxASECIAEgBEYN8gEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBsNMAai0AAEcNLCAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM8wELIANBADYCACAGQQFqIQFBHQwsCyABIARGBEBBsAEhAgzyAQsCQAJAIAEtAABByQBrDgcBLi4uLi4ALgsgAUEBaiEBQZcBIQIM2AELIAFBAWohAUEiDCsLIAEgBEYEQEGvASECDPEBCyABLQAAQdAARw0rIAFBAWohAUGWASECDNYBCyABIARGBEBBrgEhAgzwAQsCQAJAIAEtAABBxgBrDgsALCwsLCwsLCwsASwLIAFBAWohAUGUASECDNYBCyABQQFqIQFBlQEhAgzVAQtBrQEhAiABIARGDe4BIAMoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQazTAGotAABHDSggAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADO8BCyADQQA2AgAgBkEBaiEBQQ0MKAtBrAEhAiABIARGDe0BIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQeHTAGotAABHDScgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADO4BCyADQQA2AgAgBkEBaiEBQQwMJwtBqwEhAiABIARGDewBIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQarTAGotAABHDSYgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADO0BCyADQQA2AgAgBkEBaiEBQQMMJgtBqgEhAiABIARGDesBIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQajTAGotAABHDSUgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADOwBCyADQQA2AgAgBkEBaiEBQSYMJQsgASAERgRAQakBIQIM6wELAkACQCABLQAAQdQAaw4CAAEnCyABQQFqIQFBjwEhAgzRAQsgAUEBaiEBQZABIQIM0AELQagBIQIgASAERg3pASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGm0wBqLQAARw0jIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzqAQsgA0EANgIAIAZBAWohAUEnDCMLQacBIQIgASAERg3oASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGk0wBqLQAARw0iIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzpAQsgA0EANgIAIAZBAWohAUEcDCILQaYBIQIgASAERg3nASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGe0wBqLQAARw0hIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzoAQsgA0EANgIAIAZBAWohAUEGDCELQaUBIQIgASAERg3mASADKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEGZ0wBqLQAARw0gIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAznAQsgA0EANgIAIAZBAWohAUEZDCALIAEgBEYEQEGkASECDOYBCwJAAkACQAJAIAEtAABBLWsOIwAkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJAEkJCQkJAIkJCQDJAsgAUEBaiEBQYQBIQIMzgELIAFBAWohAUGFASECDM0BCyABQQFqIQFBigEhAgzMAQsgAUEBaiEBQYsBIQIMywELQaMBIQIgASAERg3kASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGX0wBqLQAARw0eIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzlAQsgA0EANgIAIAZBAWohAUELDB4LIAEgBEYEQEGiASECDOQBCwJAAkAgAS0AAEHBAGsOAwAgASALIAFBAWohAUGGASECDMoBCyABQQFqIQFBiQEhAgzJAQsgASAERgRAQaEBIQIM4wELAkACQCABLQAAQcEAaw4PAB8fHx8fHx8fHx8fHx8BHwsgAUEBaiEBQYcBIQIMyQELIAFBAWohAUGIASECDMgBCyABIARGBEBBoAEhAgziAQsgAS0AAEHMAEcNHCABQQFqIQFBCgwbC0GfASECIAEgBEYN4AEgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBkdMAai0AAEcNGiAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM4QELIANBADYCACAGQQFqIQFBHgwaC0GeASECIAEgBEYN3wEgAygCACIAIAQgAWtqIQUgASAAa0EGaiEGAkADQCABLQAAIABBitMAai0AAEcNGSAAQQZGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM4AELIANBADYCACAGQQFqIQFBFQwZC0GdASECIAEgBEYN3gEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBh9MAai0AAEcNGCAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM3wELIANBADYCACAGQQFqIQFBFwwYC0GcASECIAEgBEYN3QEgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBgdMAai0AAEcNFyAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM3gELIANBADYCACAGQQFqIQFBGAwXCyABIARGBEBBmwEhAgzdAQsCQAJAIAEtAABByQBrDgcAGRkZGRkBGQsgAUEBaiEBQYEBIQIMwwELIAFBAWohAUGCASECDMIBC0GaASECIAEgBEYN2wEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB5tMAai0AAEcNFSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM3AELIANBADYCACAGQQFqIQFBCQwVC0GZASECIAEgBEYN2gEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB5NMAai0AAEcNFCAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM2wELIANBADYCACAGQQFqIQFBHwwUC0GYASECIAEgBEYN2QEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB/tIAai0AAEcNEyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM2gELIANBADYCACAGQQFqIQFBAgwTC0GXASECIAEgBEYN2AEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGA0AgAS0AACAAQfzSAGotAABHDREgAEEBRg0CIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADNgBCyABIARGBEBBlgEhAgzYAQtBASABLQAAQd8ARw0RGiABQQFqIQFB/QAhAgy9AQsgA0EANgIAIAZBAWohAUH+ACECDLwBC0GVASECIAEgBEYN1QEgAygCACIAIAQgAWtqIQUgASAAa0EIaiEGAkADQCABLQAAIABBxNMAai0AAEcNDyAAQQhGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM1gELIANBADYCACAGQQFqIQFBKQwPC0GUASECIAEgBEYN1AEgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABB+NIAai0AAEcNDiAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM1QELIANBADYCACAGQQFqIQFBLQwOCyABIARGBEBBkwEhAgzUAQsgAS0AAEHFAEcNDiABQQFqIQFB+gAhAgy5AQsgASAERgRAQZIBIQIM0wELAkACQCABLQAAQcwAaw4IAA8PDw8PDwEPCyABQQFqIQFB+AAhAgy5AQsgAUEBaiEBQfkAIQIMuAELQZEBIQIgASAERg3RASADKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEHz0gBqLQAARw0LIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzSAQsgA0EANgIAIAZBAWohAUEjDAsLQZABIQIgASAERg3QASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHw0gBqLQAARw0KIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzRAQsgA0EANgIAIAZBAWohAUEADAoLIAEgBEYEQEGPASECDNABCwJAAkAgAS0AAEHIAGsOCAAMDAwMDAwBDAsgAUEBaiEBQfMAIQIMtgELIAFBAWohAUH2ACECDLUBCyABIARGBEBBjgEhAgzPAQsCQAJAIAEtAABBzgBrDgMACwELCyABQQFqIQFB9AAhAgy1AQsgAUEBaiEBQfUAIQIMtAELIAEgBEYEQEGNASECDM4BCyABLQAAQdkARw0IIAFBAWohAUEIDAcLQYwBIQIgASAERg3MASADKAIAIgAgBCABa2ohBSABIABrQQNqIQYCQANAIAEtAAAgAEHs0gBqLQAARw0GIABBA0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzNAQsgA0EANgIAIAZBAWohAUEFDAYLQYsBIQIgASAERg3LASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHm0gBqLQAARw0FIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzMAQsgA0EANgIAIAZBAWohAUEWDAULQYoBIQIgASAERg3KASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHh0wBqLQAARw0EIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzLAQsgA0EANgIAIAZBAWohAUEQDAQLIAEgBEYEQEGJASECDMoBCwJAAkAgAS0AAEHDAGsODAAGBgYGBgYGBgYGAQYLIAFBAWohAUHvACECDLABCyABQQFqIQFB8AAhAgyvAQtBiAEhAiABIARGDcgBIAMoAgAiACAEIAFraiEFIAEgAGtBBWohBgJAA0AgAS0AACAAQeDSAGotAABHDQIgAEEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADMkBCyADQQA2AgAgBkEBaiEBQSQMAgsgA0EANgIADAILIAEgBEYEQEGHASECDMcBCyABLQAAQcwARw0BIAFBAWohAUETCzoAKSADKAIEIQAgA0EANgIEIAMgACABEC0iAA0CDAELQQAhAiADQQA2AhwgAyABNgIUIANB6R42AhAgA0EGNgIMDMQBC0HuACECDKkBCyADQYYBNgIcIAMgATYCFCADIAA2AgxBACECDMIBC0EAIQACQCADKAI4IgJFDQAgAigCOCICRQ0AIAMgAhEAACEACyAARQ0AIABBFUYNASADQQA2AhwgAyABNgIUIANB1A42AhAgA0EgNgIMQQAhAgzBAQtB7QAhAgymAQsgA0GFATYCHCADIAE2AhQgA0HXGjYCECADQRU2AgxBACECDL8BCyABIARGBEBBhQEhAgy/AQsCQCABLQAAQSBGBEAgAUEBaiEBDAELIANBADYCHCADIAE2AhQgA0GGHjYCECADQQY2AgxBACECDL8BC0ECIQIMpAELA0AgAS0AAEEgRw0CIAQgAUEBaiIBRw0AC0GEASECDL0BCyABIARGBEBBgwEhAgy9AQsCQCABLQAAQQlrDgRAAABAAAtB6wAhAgyiAQsgAy0AKUEFRgRAQewAIQIMogELQeoAIQIMoQELIAEgBEYEQEGCASECDLsBCyADQQ82AgggAyABNgIEDAoLIAEgBEYEQEGBASECDLoBCwJAIAEtAABBCWsOBD0AAD0AC0HpACECDJ8BCyABIARHBEAgA0EPNgIIIAMgATYCBEHnACECDJ8BC0GAASECDLgBCwJAIAEgBEcEQANAIAEtAABB4M4Aai0AACIAQQNHBEACQCAAQQFrDgI/AAQLQeYAIQIMoQELIAQgAUEBaiIBRw0AC0H+ACECDLkBC0H+ACECDLgBCyADQQA2AhwgAyABNgIUIANBxh82AhAgA0EHNgIMQQAhAgy3AQsgASAERgRAQf8AIQIMtwELAkACQAJAIAEtAABB4NAAai0AAEEBaw4DPAIAAQtB6AAhAgyeAQsgA0EANgIcIAMgATYCFCADQYYSNgIQIANBBzYCDEEAIQIMtwELQeAAIQIMnAELIAEgBEcEQCABQQFqIQFB5QAhAgycAQtB/QAhAgy1AQsgBCABIgBGBEBB/AAhAgy1AQsgAC0AACIBQS9GBEAgAEEBaiEBQeQAIQIMmwELIAFBCWsiAkEXSw0BIAAhAUEBIAJ0QZuAgARxDTcMAQsgBCABIgBGBEBB+wAhAgy0AQsgAC0AAEEvRw0AIABBAWohAQwDC0EAIQIgA0EANgIcIAMgADYCFCADQcYfNgIQIANBBzYCDAyyAQsCQAJAAkACQAJAA0AgAS0AAEHgzABqLQAAIgBBBUcEQAJAAkAgAEEBaw4IPQUGBwgABAEIC0HhACECDJ8BCyABQQFqIQFB4wAhAgyeAQsgBCABQQFqIgFHDQALQfoAIQIMtgELIAFBAWoMFAsgAygCBCEAIANBADYCBCADIAAgARArIgBFDR4gA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgy0AQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDR4gA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgyzAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDR4gA0HwADYCHCADIAE2AhQgAyAANgIMQQAhAgyyAQsgA0EANgIcIAMgATYCFCADQcsPNgIQIANBBzYCDEEAIQIMsQELIAEgBEYEQEH5ACECDLEBCwJAIAEtAABB4MwAai0AAEEBaw4INAQFBgAIAgMHCyABQQFqIQELQQMhAgyVAQsgAUEBagwNC0EAIQIgA0EANgIcIANBoxI2AhAgA0EHNgIMIAMgAUEBajYCFAytAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDRYgA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgysAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDRYgA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgyrAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDRYgA0HwADYCHCADIAE2AhQgAyAANgIMQQAhAgyqAQsgA0EANgIcIAMgATYCFCADQcsPNgIQIANBBzYCDEEAIQIMqQELQeIAIQIMjgELIAEgBEYEQEH4ACECDKgBCyABQQFqDAILIAEgBEYEQEH3ACECDKcBCyABQQFqDAELIAEgBEYNASABQQFqCyEBQQQhAgyKAQtB9gAhAgyjAQsDQCABLQAAQeDKAGotAAAiAEECRwRAIABBAUcEQEHfACECDIsBCwwnCyAEIAFBAWoiAUcNAAtB9QAhAgyiAQsgASAERgRAQfQAIQIMogELAkAgAS0AAEEJaw43JQMGJQQGBgYGBgYGBgYGBgYGBgYGBgYFBgYCBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGAAYLIAFBAWoLIQFBBSECDIYBCyABQQFqDAYLIAMoAgQhACADQQA2AgQgAyAAIAEQKyIARQ0IIANB2wA2AhwgAyABNgIUIAMgADYCDEEAIQIMngELIAMoAgQhACADQQA2AgQgAyAAIAEQKyIARQ0IIANB3QA2AhwgAyABNgIUIAMgADYCDEEAIQIMnQELIAMoAgQhACADQQA2AgQgAyAAIAEQKyIARQ0IIANB8AA2AhwgAyABNgIUIAMgADYCDEEAIQIMnAELIANBADYCHCADIAE2AhQgA0G8EzYCECADQQc2AgxBACECDJsBCwJAAkACQAJAA0AgAS0AAEHgyABqLQAAIgBBBUcEQAJAIABBAWsOBiQDBAUGAAYLQd4AIQIMhgELIAQgAUEBaiIBRw0AC0HzACECDJ4BCyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNByADQdsANgIcIAMgATYCFCADIAA2AgxBACECDJ0BCyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNByADQd0ANgIcIAMgATYCFCADIAA2AgxBACECDJwBCyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNByADQfAANgIcIAMgATYCFCADIAA2AgxBACECDJsBCyADQQA2AhwgAyABNgIUIANB3Ag2AhAgA0EHNgIMQQAhAgyaAQsgASAERg0BIAFBAWoLIQFBBiECDH4LQfIAIQIMlwELAkACQAJAAkADQCABLQAAQeDGAGotAAAiAEEFRwRAIABBAWsOBB8CAwQFCyAEIAFBAWoiAUcNAAtB8QAhAgyaAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDQMgA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgyZAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDQMgA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgyYAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDQMgA0HwADYCHCADIAE2AhQgAyAANgIMQQAhAgyXAQsgA0EANgIcIAMgATYCFCADQbQKNgIQIANBBzYCDEEAIQIMlgELQc4AIQIMewtB0AAhAgx6C0HdACECDHkLIAEgBEYEQEHwACECDJMBCwJAIAEtAABBCWsOBBYAABYACyABQQFqIQFB3AAhAgx4CyABIARGBEBB7wAhAgySAQsCQCABLQAAQQlrDgQVAAAVAAtBACEAAkAgAygCOCICRQ0AIAIoAjAiAkUNACADIAIRAAAhAAsgAEUEQEHTASECDHgLIABBFUcEQCADQQA2AhwgAyABNgIUIANBwQ02AhAgA0EaNgIMQQAhAgySAQsgA0HuADYCHCADIAE2AhQgA0HwGTYCECADQRU2AgxBACECDJEBC0HtACECIAEgBEYNkAEgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABB18YAai0AAEcNBCAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMkQELIANBADYCACAGQQFqIQEgAy0AKSIAQSNrQQtJDQQCQCAAQQZLDQBBASAAdEHKAHFFDQAMBQtBACECIANBADYCHCADIAE2AhQgA0HlCTYCECADQQg2AgwMkAELQewAIQIgASAERg2PASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHUxgBqLQAARw0DIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyQAQsgA0EANgIAIAZBAWohASADLQApQSFGDQMgA0EANgIcIAMgATYCFCADQYkKNgIQIANBCDYCDEEAIQIMjwELQesAIQIgASAERg2OASADKAIAIgAgBCABa2ohBSABIABrQQNqIQYCQANAIAEtAAAgAEHQxgBqLQAARw0CIABBA0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyPAQsgA0EANgIAIAZBAWohASADLQApIgBBI0kNAiAAQS5GDQIgA0EANgIcIAMgATYCFCADQcEJNgIQIANBCDYCDEEAIQIMjgELIANBADYCAAtBACECIANBADYCHCADIAE2AhQgA0GENzYCECADQQg2AgwMjAELQdgAIQIMcQsgASAERwRAIANBDTYCCCADIAE2AgRB1wAhAgxxC0HqACECDIoBCyABIARGBEBB6QAhAgyKAQsgAS0AAEEwayIAQf8BcUEKSQRAIAMgADoAKiABQQFqIQFB1gAhAgxwCyADKAIEIQAgA0EANgIEIAMgACABEC4iAEUNdCADQegANgIcIAMgATYCFCADIAA2AgxBACECDIkBCyABIARGBEBB5wAhAgyJAQsCQCABLQAAQS5GBEAgAUEBaiEBDAELIAMoAgQhACADQQA2AgQgAyAAIAEQLiIARQ11IANB5gA2AhwgAyABNgIUIAMgADYCDEEAIQIMiQELQdUAIQIMbgsgASAERgRAQeUAIQIMiAELQQAhAEEBIQVBASEHQQAhAgJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAIAEtAABBMGsOCgoJAAECAwQFBggLC0ECDAYLQQMMBQtBBAwEC0EFDAMLQQYMAgtBBwwBC0EICyECQQAhBUEAIQcMAgtBCSECQQEhAEEAIQVBACEHDAELQQAhBUEBIQILIAMgAjoAKyABQQFqIQECQAJAIAMtAC5BEHENAAJAAkACQCADLQAqDgMBAAIECyAHRQ0DDAILIAANAQwCCyAFRQ0BCyADKAIEIQAgA0EANgIEIAMgACABEC4iAEUNAiADQeIANgIcIAMgATYCFCADIAA2AgxBACECDIoBCyADKAIEIQAgA0EANgIEIAMgACABEC4iAEUNdyADQeMANgIcIAMgATYCFCADIAA2AgxBACECDIkBCyADKAIEIQAgA0EANgIEIAMgACABEC4iAEUNdSADQeQANgIcIAMgATYCFCADIAA2AgwMiAELQdMAIQIMbQsgAy0AKUEiRg2AAUHSACECDGwLQQAhAAJAIAMoAjgiAkUNACACKAI8IgJFDQAgAyACEQAAIQALIABFBEBB1AAhAgxsCyAAQRVHBEAgA0EANgIcIAMgATYCFCADQZwNNgIQIANBITYCDEEAIQIMhgELIANB4QA2AhwgAyABNgIUIANB1hk2AhAgA0EVNgIMQQAhAgyFAQsgASAERgRAQeAAIQIMhQELAkACQAJAAkACQCABLQAAQQprDgQBBAQABAsgAUEBaiEBDAELIAFBAWohASADQS9qLQAAQQFxRQ0BC0HRACECDGwLIANBADYCHCADIAE2AhQgA0GIETYCECADQQk2AgxBACECDIUBCyADQQA2AhwgAyABNgIUIANBiBE2AhAgA0EJNgIMQQAhAgyEAQsgASAERgRAQd8AIQIMhAELIAEtAABBCkYEQCABQQFqIQEMCQsgAy0ALkHAAHENCCADQQA2AhwgAyABNgIUIANBiBE2AhAgA0ECNgIMQQAhAgyDAQsgASAERgRAQd0AIQIMgwELIAEtAAAiAkENRgRAIAFBAWohAUHPACECDGkLIAEhACACQQlrDgQFAQEFAQsgBCABIgBGBEBB3AAhAgyCAQsgAC0AAEEKRw0AIABBAWoMAgtBACECIANBADYCHCADIAA2AhQgA0G1LDYCECADQQc2AgwMgAELIAEgBEYEQEHbACECDIABCwJAIAEtAABBCWsOBAMAAAMACyABQQFqCyEBQc0AIQIMZAsgASAERgRAQdoAIQIMfgsgAS0AAEEJaw4EAAEBAAELQQAhAiADQQA2AhwgA0HsETYCECADQQc2AgwgAyABQQFqNgIUDHwLIANBgBI7ASpBACEAAkAgAygCOCICRQ0AIAIoAjAiAkUNACADIAIRAAAhAAsgAEUNACAAQRVHDQEgA0HZADYCHCADIAE2AhQgA0HwGTYCECADQRU2AgxBACECDHsLQcwAIQIMYAsgA0EANgIcIAMgATYCFCADQcENNgIQIANBGjYCDEEAIQIMeQsgASAERgRAQdkAIQIMeQsgAS0AAEEgRw06IAFBAWohASADLQAuQQFxDTogA0EANgIcIAMgATYCFCADQa0bNgIQIANBHjYCDEEAIQIMeAsgASAERgRAQdgAIQIMeAsCQAJAAkACQAJAIAEtAAAiAEEKaw4EAgMDAAELIAFBAWohAUErIQIMYQsgAEE6Rw0BIANBADYCHCADIAE2AhQgA0G5ETYCECADQQo2AgxBACECDHoLIAFBAWohASADQS9qLQAAQQFxRQ1tIAMtADJBgAFxRQRAIANBMmohAiADEDRBACEAAkAgAygCOCIGRQ0AIAYoAiQiBkUNACADIAYRAAAhAAsCQAJAIAAOFkpJSAEBAQEBAQEBAQEBAQEBAQEBAQABCyADQSk2AhwgAyABNgIUIANBshg2AhAgA0EVNgIMQQAhAgx7CyADQQA2AhwgAyABNgIUIANB3Qs2AhAgA0ERNgIMQQAhAgx6C0EAIQACQCADKAI4IgJFDQAgAigCVCICRQ0AIAMgAhEAACEACyAARQ1VIABBFUcNASADQQU2AhwgAyABNgIUIANBhho2AhAgA0EVNgIMQQAhAgx5C0HKACECDF4LQQAhAiADQQA2AhwgAyABNgIUIANB4g02AhAgA0EUNgIMDHcLIAMgAy8BMkGAAXI7ATIMOAsgASAERwRAIANBEDYCCCADIAE2AgRByQAhAgxcC0HXACECDHULIAEgBEYEQEHWACECDHULAkACQAJAAkAgAS0AACIAQSByIAAgAEHBAGtB/wFxQRpJG0H/AXFB4wBrDhMAPT09PT09PT09PT09AT09PQIDPQsgAUEBaiEBQcUAIQIMXQsgAUEBaiEBQcYAIQIMXAsgAUEBaiEBQccAIQIMWwsgAUEBaiEBQcgAIQIMWgtB1QAhAiAEIAEiAEYNcyAEIAFrIAMoAgAiAWohBiAAIAFrQQVqIQcDQCABQcDGAGotAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQhBBCABQQVGDQoaIAFBAWohASAEIABBAWoiAEcNAAsgAyAGNgIADHMLQdQAIQIgBCABIgBGDXIgBCABayADKAIAIgFqIQYgACABa0EPaiEHA0AgAUGwxgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0HQQMgAUEPRg0JGiABQQFqIQEgBCAAQQFqIgBHDQALIAMgBjYCAAxyC0HTACECIAQgASIARg1xIAQgAWsgAygCACIBaiEGIAAgAWtBDmohBwNAIAFBksYAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNBiABQQ5GDQcgAUEBaiEBIAQgAEEBaiIARw0ACyADIAY2AgAMcQtB0gAhAiAEIAEiAEYNcCAEIAFrIAMoAgAiAWohBSAAIAFrQQFqIQYDQCABQZDGAGotAAAgAC0AACIHQSByIAcgB0HBAGtB/wFxQRpJG0H/AXFHDQUgAUEBRg0CIAFBAWohASAEIABBAWoiAEcNAAsgAyAFNgIADHALIAEgBEYEQEHRACECDHALAkACQCABLQAAIgBBIHIgACAAQcEAa0H/AXFBGkkbQf8BcUHuAGsOBwA2NjY2NgE2CyABQQFqIQFBwgAhAgxWCyABQQFqIQFBwwAhAgxVCyADQQA2AgAgBkEBaiEBQcQAIQIMVAtB0AAhAiAEIAEiAEYNbSAEIAFrIAMoAgAiAWohBiAAIAFrQQlqIQcDQCABQYbGAGotAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQJBAiABQQlGDQQaIAFBAWohASAEIABBAWoiAEcNAAsgAyAGNgIADG0LQc8AIQIgBCABIgBGDWwgBCABayADKAIAIgFqIQYgACABa0EFaiEHA0AgAUGAxgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBBUYNAiABQQFqIQEgBCAAQQFqIgBHDQALIAMgBjYCAAxsCyAAIQEgA0EANgIADDALQQELOgAsIANBADYCACAHQQFqIQELQSwhAgxOCwJAA0AgAS0AAEGAxABqLQAAQQFHDQEgBCABQQFqIgFHDQALQc0AIQIMaAtBwQAhAgxNCyABIARGBEBBzAAhAgxnCyABLQAAQTpGBEAgAygCBCEAIANBADYCBCADIAAgARAvIgBFDTAgA0HLADYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgxnCyADQQA2AhwgAyABNgIUIANBuRE2AhAgA0EKNgIMQQAhAgxmCwJAAkAgAy0ALEECaw4CAAEkCyADQTNqLQAAQQJxRQ0jIAMtAC5BAnENIyADQQA2AhwgAyABNgIUIANB1RM2AhAgA0ELNgIMQQAhAgxmCyADLQAyQSBxRQ0iIAMtAC5BAnENIiADQQA2AhwgAyABNgIUIANB7BI2AhAgA0EPNgIMQQAhAgxlC0EAIQACQCADKAI4IgJFDQAgAigCQCICRQ0AIAMgAhEAACEACyAARQRAQcAAIQIMSwsgAEEVRwRAIANBADYCHCADIAE2AhQgA0H4DjYCECADQRw2AgxBACECDGULIANBygA2AhwgAyABNgIUIANB8Bo2AhAgA0EVNgIMQQAhAgxkCyABIARHBEADQCABLQAAQfA/ai0AAEEBRw0XIAQgAUEBaiIBRw0AC0HEACECDGQLQcQAIQIMYwsgASAERwRAA0ACQCABLQAAIgBBIHIgACAAQcEAa0H/AXFBGkkbQf8BcSIAQQlGDQAgAEEgRg0AAkACQAJAAkAgAEHjAGsOEwADAwMDAwMDAQMDAwMDAwMDAwIDCyABQQFqIQFBNSECDE4LIAFBAWohAUE2IQIMTQsgAUEBaiEBQTchAgxMCwwVCyAEIAFBAWoiAUcNAAtBPCECDGMLQTwhAgxiCyABIARGBEBByAAhAgxiCyADQRE2AgggAyABNgIEAkACQAJAAkACQCADLQAsQQFrDgQUAAECCQsgAy0AMkEgcQ0DQdEBIQIMSwsCQCADLwEyIgBBCHFFDQAgAy0AKEEBRw0AIAMtAC5BCHFFDQILIAMgAEH3+wNxQYAEcjsBMgwLCyADIAMvATJBEHI7ATIMBAsgA0EANgIEIAMgASABEDAiAARAIANBwQA2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMYwsgAUEBaiEBDFILIANBADYCHCADIAE2AhQgA0GjEzYCECADQQQ2AgxBACECDGELQccAIQIgASAERg1gIAMoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAEHwwwBqLQAAIAEtAABBIHJHDQEgAEEGRg1GIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADGELIANBADYCAAwFCwJAIAEgBEcEQANAIAEtAABB8MEAai0AACIAQQFHBEAgAEECRw0DIAFBAWohAQwFCyAEIAFBAWoiAUcNAAtBxQAhAgxhC0HFACECDGALCyADQQA6ACwMAQtBCyECDEMLQT4hAgxCCwJAAkADQCABLQAAIgBBIEcEQAJAIABBCmsOBAMFBQMACyAAQSxGDQMMBAsgBCABQQFqIgFHDQALQcYAIQIMXQsgA0EIOgAsDA4LIAMtAChBAUcNAiADLQAuQQhxDQIgAygCBCEAIANBADYCBCADIAAgARAwIgAEQCADQcIANgIcIAMgADYCDCADIAFBAWo2AhRBACECDFwLIAFBAWohAQxKC0E6IQIMQAsCQANAIAEtAAAiAEEgRyAAQQlHcQ0BIAQgAUEBaiIBRw0AC0HDACECDFoLC0E7IQIMPgsCQAJAIAEgBEcEQANAIAEtAAAiAEEgRwRAIABBCmsOBAMEBAMECyAEIAFBAWoiAUcNAAtBPyECDFoLQT8hAgxZCyADIAMvATJBIHI7ATIMCgsgAygCBCEAIANBADYCBCADIAAgARAwIgBFDUggA0E+NgIcIAMgATYCFCADIAA2AgxBACECDFcLAkAgASAERwRAA0AgAS0AAEHwwQBqLQAAIgBBAUcEQCAAQQJGDQMMDAsgBCABQQFqIgFHDQALQTchAgxYC0E3IQIMVwsgAUEBaiEBDAQLQTshAiAEIAEiAEYNVSAEIAFrIAMoAgAiAWohBiAAIAFrQQVqIQcCQANAIAFBwMYAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNASABQQVGBEBBByEBDDsLIAFBAWohASAEIABBAWoiAEcNAAsgAyAGNgIADFYLIANBADYCACAAIQEMBQtBOiECIAQgASIARg1UIAQgAWsgAygCACIBaiEGIAAgAWtBCGohBwJAA0AgAUHkP2otAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQEgAUEIRgRAQQUhAQw6CyABQQFqIQEgBCAAQQFqIgBHDQALIAMgBjYCAAxVCyADQQA2AgAgACEBDAQLQTkhAiAEIAEiAEYNUyAEIAFrIAMoAgAiAWohBiAAIAFrQQNqIQcCQANAIAFB4D9qLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBA0YEQEEGIQEMOQsgAUEBaiEBIAQgAEEBaiIARw0ACyADIAY2AgAMVAsgA0EANgIAIAAhAQwDCwJAA0AgAS0AACIAQSBHBEAgAEEKaw4EBwQEBwILIAQgAUEBaiIBRw0AC0E4IQIMUwsgAEEsRw0BIAFBAWohAEEBIQECQAJAAkACQAJAIAMtACxBBWsOBAMBAgQACyAAIQEMBAtBAiEBDAELQQQhAQsgA0EBOgAsIAMgAy8BMiABcjsBMiAAIQEMAQsgAyADLwEyQQhyOwEyIAAhAQtBPSECDDcLIANBADoALAtBOCECDDULIAEgBEYEQEE2IQIMTwsCQAJAAkACQAJAIAEtAABBCmsOBAACAgECCyADKAIEIQAgA0EANgIEIAMgACABEDAiAEUNAiADQTM2AhwgAyABNgIUIAMgADYCDEEAIQIMUgsgAygCBCEAIANBADYCBCADIAAgARAwIgBFBEAgAUEBaiEBDAYLIANBMjYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgxRCyADLQAuQQFxBEBB0AEhAgw3CyADKAIEIQAgA0EANgIEIAMgACABEDAiAA0BDEMLQTMhAgw1CyADQTU2AhwgAyABNgIUIAMgADYCDEEAIQIMTgtBNCECDDMLIANBL2otAABBAXENACADQQA2AhwgAyABNgIUIANB8RU2AhAgA0EZNgIMQQAhAgxMC0EyIQIMMQsgASAERgRAQTIhAgxLCwJAIAEtAABBCkYEQCABQQFqIQEMAQsgA0EANgIcIAMgATYCFCADQZgWNgIQIANBAzYCDEEAIQIMSwtBMSECDDALIAEgBEYEQEExIQIMSgsgAS0AACIAQQlHIABBIEdxDQEgAy0ALEEIRw0AIANBADoALAtBPCECDC4LQQEhAgJAAkACQAJAIAMtACxBBWsOBAMBAgAKCyADIAMvATJBCHI7ATIMCQtBAiECDAELQQQhAgsgA0EBOgAsIAMgAy8BMiACcjsBMgwGCyABIARGBEBBMCECDEcLIAEtAABBCkYEQCABQQFqIQEMAQsgAy0ALkEBcQ0AIANBADYCHCADIAE2AhQgA0HHJzYCECADQQI2AgxBACECDEYLQS8hAgwrCyABQQFqIQFBMCECDCoLIAEgBEYEQEEvIQIMRAsgAS0AACIAQQlHIABBIEdxRQRAIAFBAWohASADLQAuQQFxDQEgA0EANgIcIAMgATYCFCADQekPNgIQIANBCjYCDEEAIQIMRAtBASECAkACQAJAAkACQAJAIAMtACxBAmsOBwUEBAMBAgAECyADIAMvATJBCHI7ATIMAwtBAiECDAELQQQhAgsgA0EBOgAsIAMgAy8BMiACcjsBMgtBLiECDCoLIANBADYCHCADIAE2AhQgA0GzEjYCECADQQs2AgxBACECDEMLQdIBIQIMKAsgASAERgRAQS4hAgxCCyADQQA2AgQgA0ERNgIIIAMgASABEDAiAA0BC0EtIQIMJgsgA0EtNgIcIAMgATYCFCADIAA2AgxBACECDD8LQQAhAAJAIAMoAjgiAkUNACACKAJEIgJFDQAgAyACEQAAIQALIABFDQAgAEEVRw0BIANB2AA2AhwgAyABNgIUIANBnho2AhAgA0EVNgIMQQAhAgw+C0HLACECDCMLIANBADYCHCADIAE2AhQgA0GFDjYCECADQR02AgxBACECDDwLIAEgBEYEQEHOACECDDwLIAEtAAAiAEEgRg0CIABBOkYNAQsgA0EAOgAsQQkhAgwgCyADKAIEIQAgA0EANgIEIAMgACABEC8iAA0BDAILIAMtAC5BAXEEQEHPASECDB8LIAMoAgQhACADQQA2AgQgAyAAIAEQLyIARQ0CIANBKjYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgw4CyADQcsANgIcIAMgADYCDCADIAFBAWo2AhRBACECDDcLIAFBAWohAUE/IQIMHAsgAUEBaiEBDCkLIAEgBEYEQEErIQIMNQsCQCABLQAAQQpGBEAgAUEBaiEBDAELIAMtAC5BwABxRQ0GCyADLQAyQYABcQRAQQAhAAJAIAMoAjgiAkUNACACKAJUIgJFDQAgAyACEQAAIQALIABFDREgAEEVRgRAIANBBTYCHCADIAE2AhQgA0GGGjYCECADQRU2AgxBACECDDYLIANBADYCHCADIAE2AhQgA0HiDTYCECADQRQ2AgxBACECDDULIANBMmohAiADEDRBACEAAkAgAygCOCIGRQ0AIAYoAiQiBkUNACADIAYRAAAhAAsgAA4WAgEABAQEBAQEBAQEBAQEBAQEBAQEAwQLIANBAToAMAsgAiACLwEAQcAAcjsBAAtBKiECDBcLIANBKTYCHCADIAE2AhQgA0GyGDYCECADQRU2AgxBACECDDALIANBADYCHCADIAE2AhQgA0HdCzYCECADQRE2AgxBACECDC8LIANBADYCHCADIAE2AhQgA0GdCzYCECADQQI2AgxBACECDC4LQQEhByADLwEyIgVBCHFFBEAgAykDIEIAUiEHCwJAIAMtADAEQEEBIQAgAy0AKUEFRg0BIAVBwABxRSAHcUUNAQsCQCADLQAoIgJBAkYEQEEBIQAgAy8BNCIGQeUARg0CQQAhACAFQcAAcQ0CIAZB5ABGDQIgBkHmAGtBAkkNAiAGQcwBRg0CIAZBsAJGDQIMAQtBACEAIAVBwABxDQELQQIhACAFQQhxDQAgBUGABHEEQAJAIAJBAUcNACADLQAuQQpxDQBBBSEADAILQQQhAAwBCyAFQSBxRQRAIAMQNUEAR0ECdCEADAELQQBBAyADKQMgUBshAAsCQCAAQQFrDgUAAQYHAgMLQQAhAgJAIAMoAjgiAEUNACAAKAIsIgBFDQAgAyAAEQAAIQILIAJFDSYgAkEVRgRAIANBAzYCHCADIAE2AhQgA0G9GjYCECADQRU2AgxBACECDC4LQQAhAiADQQA2AhwgAyABNgIUIANBrw42AhAgA0ESNgIMDC0LQc4BIQIMEgtBACECIANBADYCHCADIAE2AhQgA0HkHzYCECADQQ82AgwMKwtBACEAAkAgAygCOCICRQ0AIAIoAiwiAkUNACADIAIRAAAhAAsgAA0BC0EOIQIMDwsgAEEVRgRAIANBAjYCHCADIAE2AhQgA0G9GjYCECADQRU2AgxBACECDCkLQQAhAiADQQA2AhwgAyABNgIUIANBrw42AhAgA0ESNgIMDCgLQSkhAgwNCyADQQE6ADEMJAsgASAERwRAIANBCTYCCCADIAE2AgRBKCECDAwLQSYhAgwlCyADIAMpAyAiDCAEIAFrrSIKfSILQgAgCyAMWBs3AyAgCiAMVARAQSUhAgwlCyADKAIEIQBBACECIANBADYCBCADIAAgASAMp2oiARAxIgBFDQAgA0EFNgIcIAMgATYCFCADIAA2AgwMJAtBDyECDAkLIAEgBEYEQEEjIQIMIwtCACEKAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAEtAABBMGsONxcWAAECAwQFBgcUFBQUFBQUCAkKCwwNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQODxAREhMUC0ICIQoMFgtCAyEKDBULQgQhCgwUC0IFIQoMEwtCBiEKDBILQgchCgwRC0IIIQoMEAtCCSEKDA8LQgohCgwOC0ILIQoMDQtCDCEKDAwLQg0hCgwLC0IOIQoMCgtCDyEKDAkLQgohCgwIC0ILIQoMBwtCDCEKDAYLQg0hCgwFC0IOIQoMBAtCDyEKDAMLQQAhAiADQQA2AhwgAyABNgIUIANBzhQ2AhAgA0EMNgIMDCILIAEgBEYEQEEiIQIMIgtCACEKAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCABLQAAQTBrDjcVFAABAgMEBQYHFhYWFhYWFggJCgsMDRYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWDg8QERITFgtCAiEKDBQLQgMhCgwTC0IEIQoMEgtCBSEKDBELQgYhCgwQC0IHIQoMDwtCCCEKDA4LQgkhCgwNC0IKIQoMDAtCCyEKDAsLQgwhCgwKC0INIQoMCQtCDiEKDAgLQg8hCgwHC0IKIQoMBgtCCyEKDAULQgwhCgwEC0INIQoMAwtCDiEKDAILQg8hCgwBC0IBIQoLIAFBAWohASADKQMgIgtC//////////8PWARAIAMgC0IEhiAKhDcDIAwCC0EAIQIgA0EANgIcIAMgATYCFCADQa0JNgIQIANBDDYCDAwfC0ElIQIMBAtBJiECDAMLIAMgAToALCADQQA2AgAgB0EBaiEBQQwhAgwCCyADQQA2AgAgBkEBaiEBQQohAgwBCyABQQFqIQFBCCECDAALAAtBACECIANBADYCHCADIAE2AhQgA0HVEDYCECADQQk2AgwMGAtBACECIANBADYCHCADIAE2AhQgA0HXCjYCECADQQk2AgwMFwtBACECIANBADYCHCADIAE2AhQgA0G/EDYCECADQQk2AgwMFgtBACECIANBADYCHCADIAE2AhQgA0GkETYCECADQQk2AgwMFQtBACECIANBADYCHCADIAE2AhQgA0HVEDYCECADQQk2AgwMFAtBACECIANBADYCHCADIAE2AhQgA0HXCjYCECADQQk2AgwMEwtBACECIANBADYCHCADIAE2AhQgA0G/EDYCECADQQk2AgwMEgtBACECIANBADYCHCADIAE2AhQgA0GkETYCECADQQk2AgwMEQtBACECIANBADYCHCADIAE2AhQgA0G/FjYCECADQQ82AgwMEAtBACECIANBADYCHCADIAE2AhQgA0G/FjYCECADQQ82AgwMDwtBACECIANBADYCHCADIAE2AhQgA0HIEjYCECADQQs2AgwMDgtBACECIANBADYCHCADIAE2AhQgA0GVCTYCECADQQs2AgwMDQtBACECIANBADYCHCADIAE2AhQgA0HpDzYCECADQQo2AgwMDAtBACECIANBADYCHCADIAE2AhQgA0GDEDYCECADQQo2AgwMCwtBACECIANBADYCHCADIAE2AhQgA0GmHDYCECADQQI2AgwMCgtBACECIANBADYCHCADIAE2AhQgA0HFFTYCECADQQI2AgwMCQtBACECIANBADYCHCADIAE2AhQgA0H/FzYCECADQQI2AgwMCAtBACECIANBADYCHCADIAE2AhQgA0HKFzYCECADQQI2AgwMBwsgA0ECNgIcIAMgATYCFCADQZQdNgIQIANBFjYCDEEAIQIMBgtB3gAhAiABIARGDQUgCUEIaiEHIAMoAgAhBQJAAkAgASAERwRAIAVBxsYAaiEIIAQgBWogAWshBiAFQX9zQQpqIgUgAWohAANAIAEtAAAgCC0AAEcEQEECIQgMAwsgBUUEQEEAIQggACEBDAMLIAVBAWshBSAIQQFqIQggBCABQQFqIgFHDQALIAYhBSAEIQELIAdBATYCACADIAU2AgAMAQsgA0EANgIAIAcgCDYCAAsgByABNgIEIAkoAgwhACAJKAIIDgMBBQIACwALIANBADYCHCADQa0dNgIQIANBFzYCDCADIABBAWo2AhRBACECDAMLIANBADYCHCADIAA2AhQgA0HCHTYCECADQQk2AgxBACECDAILIAEgBEYEQEEoIQIMAgsgA0EJNgIIIAMgATYCBEEnIQIMAQsgASAERgRAQQEhAgwBCwNAAkACQAJAIAEtAABBCmsOBAABAQABCyABQQFqIQEMAQsgAUEBaiEBIAMtAC5BIHENAEEAIQIgA0EANgIcIAMgATYCFCADQYwgNgIQIANBBTYCDAwCC0EBIQIgASAERw0ACwsgCUEQaiQAIAJFBEAgAygCDCEADAELIAMgAjYCHEEAIQAgAygCBCIBRQ0AIAMgASAEIAMoAggRAQAiAUUNACADIAQ2AhQgAyABNgIMIAEhAAsgAAu+AgECfyAAQQA6AAAgAEHcAGoiAUEBa0EAOgAAIABBADoAAiAAQQA6AAEgAUEDa0EAOgAAIAFBAmtBADoAACAAQQA6AAMgAUEEa0EAOgAAQQAgAGtBA3EiASAAaiIAQQA2AgBB3AAgAWtBfHEiAiAAaiIBQQRrQQA2AgACQCACQQlJDQAgAEEANgIIIABBADYCBCABQQhrQQA2AgAgAUEMa0EANgIAIAJBGUkNACAAQQA2AhggAEEANgIUIABBADYCECAAQQA2AgwgAUEQa0EANgIAIAFBFGtBADYCACABQRhrQQA2AgAgAUEca0EANgIAIAIgAEEEcUEYciICayIBQSBJDQAgACACaiEAA0AgAEIANwMYIABCADcDECAAQgA3AwggAEIANwMAIABBIGohACABQSBrIgFBH0sNAAsLC1YBAX8CQCAAKAIMDQACQAJAAkACQCAALQAxDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgAREAACIBDQMLQQAPCwALIABB0Bg2AhBBDiEBCyABCxoAIAAoAgxFBEAgAEHJHjYCECAAQRU2AgwLCxQAIAAoAgxBFUYEQCAAQQA2AgwLCxQAIAAoAgxBFkYEQCAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsXACAAQSRPBEAACyAAQQJ0QZQ3aigCAAsXACAAQS9PBEAACyAAQQJ0QaQ4aigCAAu/CQEBf0HfLCEBAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEHkAGsO9ANjYgABYWFhYWFhAgMEBWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEGBwgJCgsMDQ4PYWFhYWEQYWFhYWFhYWFhYWERYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhEhMUFRYXGBkaG2FhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEcHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTZhNzg5OmFhYWFhYWFhO2FhYTxhYWFhPT4/YWFhYWFhYWFAYWFBYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhQkNERUZHSElKS0xNTk9QUVJTYWFhYWFhYWFUVVZXWFlaW2FcXWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYV5hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFfYGELQdUrDwtBgyUPC0G/MA8LQfI1DwtBtCgPC0GfKA8LQYEsDwtB1ioPC0H0Mw8LQa0zDwtByygPC0HOIw8LQcAjDwtB2SMPC0HRJA8LQZwzDwtBojYPC0H8Mw8LQeArDwtB4SUPC0HtIA8LQcQyDwtBqScPC0G5Ng8LQbggDwtBqyAPC0GjJA8LQbYkDwtBgSMPC0HhMg8LQZ80DwtByCkPC0HAMg8LQe4yDwtB8C8PC0HGNA8LQdAhDwtBmiQPC0HrLw8LQYQ1DwtByzUPC0GWMQ8LQcgrDwtB1C8PC0GTMA8LQd81DwtBtCMPC0G+NQ8LQdIpDwtBsyIPC0HNIA8LQZs2DwtBkCEPC0H/IA8LQa01DwtBsDQPC0HxJA8LQacqDwtB3TAPC0GLIg8LQcgvDwtB6yoPC0H0KQ8LQY8lDwtB3SIPC0HsJg8LQf0wDwtB1iYPC0GUNQ8LQY0jDwtBuikPC0HHIg8LQfIlDwtBtjMPC0GiIQ8LQf8vDwtBwCEPC0GBMw8LQcklDwtBqDEPC0HGMw8LQdM2DwtBxjYPC0HkNA8LQYgmDwtB7ScPC0H4IQ8LQakwDwtBjzQPC0GGNg8LQaovDwtBoSYPC0HsNg8LQZIpDwtBryYPC0GZIg8LQeAhDwsAC0G1JSEBCyABCxcAIAAgAC8BLkH+/wNxIAFBAEdyOwEuCxoAIAAgAC8BLkH9/wNxIAFBAEdBAXRyOwEuCxoAIAAgAC8BLkH7/wNxIAFBAEdBAnRyOwEuCxoAIAAgAC8BLkH3/wNxIAFBAEdBA3RyOwEuCxoAIAAgAC8BLkHv/wNxIAFBAEdBBHRyOwEuCxoAIAAgAC8BLkHf/wNxIAFBAEdBBXRyOwEuCxoAIAAgAC8BLkG//wNxIAFBAEdBBnRyOwEuCxoAIAAgAC8BLkH//gNxIAFBAEdBB3RyOwEuCxoAIAAgAC8BLkH//QNxIAFBAEdBCHRyOwEuCxoAIAAgAC8BLkH/+wNxIAFBAEdBCXRyOwEuCz4BAn8CQCAAKAI4IgNFDQAgAygCBCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBzhE2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCCCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB5Ao2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCDCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB5R02AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCECIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBnRA2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCFCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBoh42AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCGCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB7hQ2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCKCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB9gg2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCHCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB9xs2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCICIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBlRU2AhBBGCEECyAECzgAIAACfyAALwEyQRRxQRRGBEBBASAALQAoQQFGDQEaIAAvATRB5QBGDAELIAAtAClBBUYLOgAwC1kBAn8CQCAALQAoQQFGDQAgAC8BNCIBQeQAa0HkAEkNACABQcwBRg0AIAFBsAJGDQAgAC8BMiIAQcAAcQ0AQQEhAiAAQYgEcUGABEYNACAAQShxRSECCyACC4wBAQJ/AkACQAJAIAAtACpFDQAgAC0AK0UNACAALwEyIgFBAnFFDQEMAgsgAC8BMiIBQQFxRQ0BC0EBIQIgAC0AKEEBRg0AIAAvATQiAEHkAGtB5ABJDQAgAEHMAUYNACAAQbACRg0AIAFBwABxDQBBACECIAFBiARxQYAERg0AIAFBKHFBAEchAgsgAgtXACAAQRhqQgA3AwAgAEIANwMAIABBOGpCADcDACAAQTBqQgA3AwAgAEEoakIANwMAIABBIGpCADcDACAAQRBqQgA3AwAgAEEIakIANwMAIABB7AE2AhwLBgAgABA5C5otAQt/IwBBEGsiCiQAQZjUACgCACIJRQRAQdjXACgCACIFRQRAQeTXAEJ/NwIAQdzXAEKAgISAgIDAADcCAEHY1wAgCkEIakFwcUHYqtWqBXMiBTYCAEHs1wBBADYCAEG81wBBADYCAAtBwNcAQYDYBDYCAEGQ1ABBgNgENgIAQaTUACAFNgIAQaDUAEF/NgIAQcTXAEGAqAM2AgADQCABQbzUAGogAUGw1ABqIgI2AgAgAiABQajUAGoiAzYCACABQbTUAGogAzYCACABQcTUAGogAUG41ABqIgM2AgAgAyACNgIAIAFBzNQAaiABQcDUAGoiAjYCACACIAM2AgAgAUHI1ABqIAI2AgAgAUEgaiIBQYACRw0AC0GM2ARBwacDNgIAQZzUAEHo1wAoAgA2AgBBjNQAQcCnAzYCAEGY1ABBiNgENgIAQcz/B0E4NgIAQYjYBCEJCwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABB7AFNBEBBgNQAKAIAIgZBECAAQRNqQXBxIABBC0kbIgRBA3YiAHYiAUEDcQRAAkAgAUEBcSAAckEBcyICQQN0IgBBqNQAaiIBIABBsNQAaigCACIAKAIIIgNGBEBBgNQAIAZBfiACd3E2AgAMAQsgASADNgIIIAMgATYCDAsgAEEIaiEBIAAgAkEDdCICQQNyNgIEIAAgAmoiACAAKAIEQQFyNgIEDBELQYjUACgCACIIIARPDQEgAQRAAkBBAiAAdCICQQAgAmtyIAEgAHRxaCIAQQN0IgJBqNQAaiIBIAJBsNQAaigCACICKAIIIgNGBEBBgNQAIAZBfiAAd3EiBjYCAAwBCyABIAM2AgggAyABNgIMCyACIARBA3I2AgQgAEEDdCIAIARrIQUgACACaiAFNgIAIAIgBGoiBCAFQQFyNgIEIAgEQCAIQXhxQajUAGohAEGU1AAoAgAhAwJ/QQEgCEEDdnQiASAGcUUEQEGA1AAgASAGcjYCACAADAELIAAoAggLIgEgAzYCDCAAIAM2AgggAyAANgIMIAMgATYCCAsgAkEIaiEBQZTUACAENgIAQYjUACAFNgIADBELQYTUACgCACILRQ0BIAtoQQJ0QbDWAGooAgAiACgCBEF4cSAEayEFIAAhAgNAAkAgAigCECIBRQRAIAJBFGooAgAiAUUNAQsgASgCBEF4cSAEayIDIAVJIQIgAyAFIAIbIQUgASAAIAIbIQAgASECDAELCyAAKAIYIQkgACgCDCIDIABHBEBBkNQAKAIAGiADIAAoAggiATYCCCABIAM2AgwMEAsgAEEUaiICKAIAIgFFBEAgACgCECIBRQ0DIABBEGohAgsDQCACIQcgASIDQRRqIgIoAgAiAQ0AIANBEGohAiADKAIQIgENAAsgB0EANgIADA8LQX8hBCAAQb9/Sw0AIABBE2oiAUFwcSEEQYTUACgCACIIRQ0AQQAgBGshBQJAAkACQAJ/QQAgBEGAAkkNABpBHyAEQf///wdLDQAaIARBJiABQQh2ZyIAa3ZBAXEgAEEBdGtBPmoLIgZBAnRBsNYAaigCACICRQRAQQAhAUEAIQMMAQtBACEBIARBGSAGQQF2a0EAIAZBH0cbdCEAQQAhAwNAAkAgAigCBEF4cSAEayIHIAVPDQAgAiEDIAciBQ0AQQAhBSACIQEMAwsgASACQRRqKAIAIgcgByACIABBHXZBBHFqQRBqKAIAIgJGGyABIAcbIQEgAEEBdCEAIAINAAsLIAEgA3JFBEBBACEDQQIgBnQiAEEAIABrciAIcSIARQ0DIABoQQJ0QbDWAGooAgAhAQsgAUUNAQsDQCABKAIEQXhxIARrIgIgBUkhACACIAUgABshBSABIAMgABshAyABKAIQIgAEfyAABSABQRRqKAIACyIBDQALCyADRQ0AIAVBiNQAKAIAIARrTw0AIAMoAhghByADIAMoAgwiAEcEQEGQ1AAoAgAaIAAgAygCCCIBNgIIIAEgADYCDAwOCyADQRRqIgIoAgAiAUUEQCADKAIQIgFFDQMgA0EQaiECCwNAIAIhBiABIgBBFGoiAigCACIBDQAgAEEQaiECIAAoAhAiAQ0ACyAGQQA2AgAMDQtBiNQAKAIAIgMgBE8EQEGU1AAoAgAhAQJAIAMgBGsiAkEQTwRAIAEgBGoiACACQQFyNgIEIAEgA2ogAjYCACABIARBA3I2AgQMAQsgASADQQNyNgIEIAEgA2oiACAAKAIEQQFyNgIEQQAhAEEAIQILQYjUACACNgIAQZTUACAANgIAIAFBCGohAQwPC0GM1AAoAgAiAyAESwRAIAQgCWoiACADIARrIgFBAXI2AgRBmNQAIAA2AgBBjNQAIAE2AgAgCSAEQQNyNgIEIAlBCGohAQwPC0EAIQEgBAJ/QdjXACgCAARAQeDXACgCAAwBC0Hk1wBCfzcCAEHc1wBCgICEgICAwAA3AgBB2NcAIApBDGpBcHFB2KrVqgVzNgIAQezXAEEANgIAQbzXAEEANgIAQYCABAsiACAEQccAaiIFaiIGQQAgAGsiB3EiAk8EQEHw1wBBMDYCAAwPCwJAQbjXACgCACIBRQ0AQbDXACgCACIIIAJqIQAgACABTSAAIAhLcQ0AQQAhAUHw1wBBMDYCAAwPC0G81wAtAABBBHENBAJAAkAgCQRAQcDXACEBA0AgASgCACIAIAlNBEAgACABKAIEaiAJSw0DCyABKAIIIgENAAsLQQAQOiIAQX9GDQUgAiEGQdzXACgCACIBQQFrIgMgAHEEQCACIABrIAAgA2pBACABa3FqIQYLIAQgBk8NBSAGQf7///8HSw0FQbjXACgCACIDBEBBsNcAKAIAIgcgBmohASABIAdNDQYgASADSw0GCyAGEDoiASAARw0BDAcLIAYgA2sgB3EiBkH+////B0sNBCAGEDohACAAIAEoAgAgASgCBGpGDQMgACEBCwJAIAYgBEHIAGpPDQAgAUF/Rg0AQeDXACgCACIAIAUgBmtqQQAgAGtxIgBB/v///wdLBEAgASEADAcLIAAQOkF/RwRAIAAgBmohBiABIQAMBwtBACAGaxA6GgwECyABIgBBf0cNBQwDC0EAIQMMDAtBACEADAoLIABBf0cNAgtBvNcAQbzXACgCAEEEcjYCAAsgAkH+////B0sNASACEDohAEEAEDohASAAQX9GDQEgAUF/Rg0BIAAgAU8NASABIABrIgYgBEE4ak0NAQtBsNcAQbDXACgCACAGaiIBNgIAQbTXACgCACABSQRAQbTXACABNgIACwJAAkACQEGY1AAoAgAiAgRAQcDXACEBA0AgACABKAIAIgMgASgCBCIFakYNAiABKAIIIgENAAsMAgtBkNQAKAIAIgFBAEcgACABT3FFBEBBkNQAIAA2AgALQQAhAUHE1wAgBjYCAEHA1wAgADYCAEGg1ABBfzYCAEGk1ABB2NcAKAIANgIAQczXAEEANgIAA0AgAUG81ABqIAFBsNQAaiICNgIAIAIgAUGo1ABqIgM2AgAgAUG01ABqIAM2AgAgAUHE1ABqIAFBuNQAaiIDNgIAIAMgAjYCACABQczUAGogAUHA1ABqIgI2AgAgAiADNgIAIAFByNQAaiACNgIAIAFBIGoiAUGAAkcNAAtBeCAAa0EPcSIBIABqIgIgBkE4ayIDIAFrIgFBAXI2AgRBnNQAQejXACgCADYCAEGM1AAgATYCAEGY1AAgAjYCACAAIANqQTg2AgQMAgsgACACTQ0AIAIgA0kNACABKAIMQQhxDQBBeCACa0EPcSIAIAJqIgNBjNQAKAIAIAZqIgcgAGsiAEEBcjYCBCABIAUgBmo2AgRBnNQAQejXACgCADYCAEGM1AAgADYCAEGY1AAgAzYCACACIAdqQTg2AgQMAQsgAEGQ1AAoAgBJBEBBkNQAIAA2AgALIAAgBmohA0HA1wAhAQJAAkACQANAIAMgASgCAEcEQCABKAIIIgENAQwCCwsgAS0ADEEIcUUNAQtBwNcAIQEDQCABKAIAIgMgAk0EQCADIAEoAgRqIgUgAksNAwsgASgCCCEBDAALAAsgASAANgIAIAEgASgCBCAGajYCBCAAQXggAGtBD3FqIgkgBEEDcjYCBCADQXggA2tBD3FqIgYgBCAJaiIEayEBIAIgBkYEQEGY1AAgBDYCAEGM1ABBjNQAKAIAIAFqIgA2AgAgBCAAQQFyNgIEDAgLQZTUACgCACAGRgRAQZTUACAENgIAQYjUAEGI1AAoAgAgAWoiADYCACAEIABBAXI2AgQgACAEaiAANgIADAgLIAYoAgQiBUEDcUEBRw0GIAVBeHEhCCAFQf8BTQRAIAVBA3YhAyAGKAIIIgAgBigCDCICRgRAQYDUAEGA1AAoAgBBfiADd3E2AgAMBwsgAiAANgIIIAAgAjYCDAwGCyAGKAIYIQcgBiAGKAIMIgBHBEAgACAGKAIIIgI2AgggAiAANgIMDAULIAZBFGoiAigCACIFRQRAIAYoAhAiBUUNBCAGQRBqIQILA0AgAiEDIAUiAEEUaiICKAIAIgUNACAAQRBqIQIgACgCECIFDQALIANBADYCAAwEC0F4IABrQQ9xIgEgAGoiByAGQThrIgMgAWsiAUEBcjYCBCAAIANqQTg2AgQgAiAFQTcgBWtBD3FqQT9rIgMgAyACQRBqSRsiA0EjNgIEQZzUAEHo1wAoAgA2AgBBjNQAIAE2AgBBmNQAIAc2AgAgA0EQakHI1wApAgA3AgAgA0HA1wApAgA3AghByNcAIANBCGo2AgBBxNcAIAY2AgBBwNcAIAA2AgBBzNcAQQA2AgAgA0EkaiEBA0AgAUEHNgIAIAUgAUEEaiIBSw0ACyACIANGDQAgAyADKAIEQX5xNgIEIAMgAyACayIFNgIAIAIgBUEBcjYCBCAFQf8BTQRAIAVBeHFBqNQAaiEAAn9BgNQAKAIAIgFBASAFQQN2dCIDcUUEQEGA1AAgASADcjYCACAADAELIAAoAggLIgEgAjYCDCAAIAI2AgggAiAANgIMIAIgATYCCAwBC0EfIQEgBUH///8HTQRAIAVBJiAFQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAQsgAiABNgIcIAJCADcCECABQQJ0QbDWAGohAEGE1AAoAgAiA0EBIAF0IgZxRQRAIAAgAjYCAEGE1AAgAyAGcjYCACACIAA2AhggAiACNgIIIAIgAjYCDAwBCyAFQRkgAUEBdmtBACABQR9HG3QhASAAKAIAIQMCQANAIAMiACgCBEF4cSAFRg0BIAFBHXYhAyABQQF0IQEgACADQQRxakEQaiIGKAIAIgMNAAsgBiACNgIAIAIgADYCGCACIAI2AgwgAiACNgIIDAELIAAoAggiASACNgIMIAAgAjYCCCACQQA2AhggAiAANgIMIAIgATYCCAtBjNQAKAIAIgEgBE0NAEGY1AAoAgAiACAEaiICIAEgBGsiAUEBcjYCBEGM1AAgATYCAEGY1AAgAjYCACAAIARBA3I2AgQgAEEIaiEBDAgLQQAhAUHw1wBBMDYCAAwHC0EAIQALIAdFDQACQCAGKAIcIgJBAnRBsNYAaiIDKAIAIAZGBEAgAyAANgIAIAANAUGE1ABBhNQAKAIAQX4gAndxNgIADAILIAdBEEEUIAcoAhAgBkYbaiAANgIAIABFDQELIAAgBzYCGCAGKAIQIgIEQCAAIAI2AhAgAiAANgIYCyAGQRRqKAIAIgJFDQAgAEEUaiACNgIAIAIgADYCGAsgASAIaiEBIAYgCGoiBigCBCEFCyAGIAVBfnE2AgQgASAEaiABNgIAIAQgAUEBcjYCBCABQf8BTQRAIAFBeHFBqNQAaiEAAn9BgNQAKAIAIgJBASABQQN2dCIBcUUEQEGA1AAgASACcjYCACAADAELIAAoAggLIgEgBDYCDCAAIAQ2AgggBCAANgIMIAQgATYCCAwBC0EfIQUgAUH///8HTQRAIAFBJiABQQh2ZyIAa3ZBAXEgAEEBdGtBPmohBQsgBCAFNgIcIARCADcCECAFQQJ0QbDWAGohAEGE1AAoAgAiAkEBIAV0IgNxRQRAIAAgBDYCAEGE1AAgAiADcjYCACAEIAA2AhggBCAENgIIIAQgBDYCDAwBCyABQRkgBUEBdmtBACAFQR9HG3QhBSAAKAIAIQACQANAIAAiAigCBEF4cSABRg0BIAVBHXYhACAFQQF0IQUgAiAAQQRxakEQaiIDKAIAIgANAAsgAyAENgIAIAQgAjYCGCAEIAQ2AgwgBCAENgIIDAELIAIoAggiACAENgIMIAIgBDYCCCAEQQA2AhggBCACNgIMIAQgADYCCAsgCUEIaiEBDAILAkAgB0UNAAJAIAMoAhwiAUECdEGw1gBqIgIoAgAgA0YEQCACIAA2AgAgAA0BQYTUACAIQX4gAXdxIgg2AgAMAgsgB0EQQRQgBygCECADRhtqIAA2AgAgAEUNAQsgACAHNgIYIAMoAhAiAQRAIAAgATYCECABIAA2AhgLIANBFGooAgAiAUUNACAAQRRqIAE2AgAgASAANgIYCwJAIAVBD00EQCADIAQgBWoiAEEDcjYCBCAAIANqIgAgACgCBEEBcjYCBAwBCyADIARqIgIgBUEBcjYCBCADIARBA3I2AgQgAiAFaiAFNgIAIAVB/wFNBEAgBUF4cUGo1ABqIQACf0GA1AAoAgAiAUEBIAVBA3Z0IgVxRQRAQYDUACABIAVyNgIAIAAMAQsgACgCCAsiASACNgIMIAAgAjYCCCACIAA2AgwgAiABNgIIDAELQR8hASAFQf///wdNBEAgBUEmIAVBCHZnIgBrdkEBcSAAQQF0a0E+aiEBCyACIAE2AhwgAkIANwIQIAFBAnRBsNYAaiEAQQEgAXQiBCAIcUUEQCAAIAI2AgBBhNQAIAQgCHI2AgAgAiAANgIYIAIgAjYCCCACIAI2AgwMAQsgBUEZIAFBAXZrQQAgAUEfRxt0IQEgACgCACEEAkADQCAEIgAoAgRBeHEgBUYNASABQR12IQQgAUEBdCEBIAAgBEEEcWpBEGoiBigCACIEDQALIAYgAjYCACACIAA2AhggAiACNgIMIAIgAjYCCAwBCyAAKAIIIgEgAjYCDCAAIAI2AgggAkEANgIYIAIgADYCDCACIAE2AggLIANBCGohAQwBCwJAIAlFDQACQCAAKAIcIgFBAnRBsNYAaiICKAIAIABGBEAgAiADNgIAIAMNAUGE1AAgC0F+IAF3cTYCAAwCCyAJQRBBFCAJKAIQIABGG2ogAzYCACADRQ0BCyADIAk2AhggACgCECIBBEAgAyABNgIQIAEgAzYCGAsgAEEUaigCACIBRQ0AIANBFGogATYCACABIAM2AhgLAkAgBUEPTQRAIAAgBCAFaiIBQQNyNgIEIAAgAWoiASABKAIEQQFyNgIEDAELIAAgBGoiByAFQQFyNgIEIAAgBEEDcjYCBCAFIAdqIAU2AgAgCARAIAhBeHFBqNQAaiEBQZTUACgCACEDAn9BASAIQQN2dCICIAZxRQRAQYDUACACIAZyNgIAIAEMAQsgASgCCAsiAiADNgIMIAEgAzYCCCADIAE2AgwgAyACNgIIC0GU1AAgBzYCAEGI1AAgBTYCAAsgAEEIaiEBCyAKQRBqJAAgAQtDACAARQRAPwBBEHQPCwJAIABB//8DcQ0AIABBAEgNACAAQRB2QAAiAEF/RgRAQfDXAEEwNgIAQX8PCyAAQRB0DwsACwvbQCIAQYAICwkBAAAAAgAAAAMAQZQICwUEAAAABQBBpAgLCQYAAAAHAAAACABB3AgLgjFJbnZhbGlkIGNoYXIgaW4gdXJsIHF1ZXJ5AFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fYm9keQBDb250ZW50LUxlbmd0aCBvdmVyZmxvdwBDaHVuayBzaXplIG92ZXJmbG93AEludmFsaWQgbWV0aG9kIGZvciBIVFRQL3gueCByZXF1ZXN0AEludmFsaWQgbWV0aG9kIGZvciBSVFNQL3gueCByZXF1ZXN0AEV4cGVjdGVkIFNPVVJDRSBtZXRob2QgZm9yIElDRS94LnggcmVxdWVzdABJbnZhbGlkIGNoYXIgaW4gdXJsIGZyYWdtZW50IHN0YXJ0AEV4cGVjdGVkIGRvdABTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3N0YXR1cwBJbnZhbGlkIHJlc3BvbnNlIHN0YXR1cwBFeHBlY3RlZCBMRiBhZnRlciBoZWFkZXJzAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMAVXNlciBjYWxsYmFjayBlcnJvcgBgb25fcmVzZXRgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19oZWFkZXJgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2JlZ2luYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlYCBjYWxsYmFjayBlcnJvcgBgb25fc3RhdHVzX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdmVyc2lvbl9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3VybF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWVzc2FnZV9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX21ldGhvZF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lYCBjYWxsYmFjayBlcnJvcgBVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNlcnZlcgBJbnZhbGlkIGhlYWRlciB2YWx1ZSBjaGFyAEludmFsaWQgaGVhZGVyIGZpZWxkIGNoYXIAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl92ZXJzaW9uAEludmFsaWQgbWlub3IgdmVyc2lvbgBJbnZhbGlkIG1ham9yIHZlcnNpb24ARXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgdmVyc2lvbgBFeHBlY3RlZCBDUkxGIGFmdGVyIHZlcnNpb24ASW52YWxpZCBIVFRQIHZlcnNpb24ASW52YWxpZCBoZWFkZXIgdG9rZW4AU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl91cmwASW52YWxpZCBjaGFyYWN0ZXJzIGluIHVybABVbmV4cGVjdGVkIHN0YXJ0IGNoYXIgaW4gdXJsAERvdWJsZSBAIGluIHVybABFbXB0eSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXJhY3RlciBpbiBDb250ZW50LUxlbmd0aABUcmFuc2Zlci1FbmNvZGluZyBjYW4ndCBiZSBwcmVzZW50IHdpdGggQ29udGVudC1MZW5ndGgARHVwbGljYXRlIENvbnRlbnQtTGVuZ3RoAEludmFsaWQgY2hhciBpbiB1cmwgcGF0aABDb250ZW50LUxlbmd0aCBjYW4ndCBiZSBwcmVzZW50IHdpdGggVHJhbnNmZXItRW5jb2RpbmcATWlzc2luZyBleHBlY3RlZCBDUiBhZnRlciBjaHVuayBzaXplAEV4cGVjdGVkIExGIGFmdGVyIGNodW5rIHNpemUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgc2l6ZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2hlYWRlcl92YWx1ZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIHZhbHVlAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgaGVhZGVyIHZhbHVlAE1pc3NpbmcgZXhwZWN0ZWQgTEYgYWZ0ZXIgaGVhZGVyIHZhbHVlAEludmFsaWQgYFRyYW5zZmVyLUVuY29kaW5nYCBoZWFkZXIgdmFsdWUATWlzc2luZyBleHBlY3RlZCBDUiBhZnRlciBjaHVuayBleHRlbnNpb24gdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBxdW90ZSB2YWx1ZQBJbnZhbGlkIHF1b3RlZC1wYWlyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGVkIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGVkIHZhbHVlAFBhdXNlZCBieSBvbl9oZWFkZXJzX2NvbXBsZXRlAEludmFsaWQgRU9GIHN0YXRlAG9uX3Jlc2V0IHBhdXNlAG9uX2NodW5rX2hlYWRlciBwYXVzZQBvbl9tZXNzYWdlX2JlZ2luIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZSBwYXVzZQBvbl9zdGF0dXNfY29tcGxldGUgcGF1c2UAb25fdmVyc2lvbl9jb21wbGV0ZSBwYXVzZQBvbl91cmxfY29tcGxldGUgcGF1c2UAb25fY2h1bmtfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlIHBhdXNlAG9uX21lc3NhZ2VfY29tcGxldGUgcGF1c2UAb25fbWV0aG9kX2NvbXBsZXRlIHBhdXNlAG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19leHRlbnNpb25fbmFtZSBwYXVzZQBVbmV4cGVjdGVkIHNwYWNlIGFmdGVyIHN0YXJ0IGxpbmUATWlzc2luZyBleHBlY3RlZCBDUiBhZnRlciByZXNwb25zZSBsaW5lAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fY2h1bmtfZXh0ZW5zaW9uX25hbWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBuYW1lAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgY2h1bmsgZXh0ZW5zaW9uIG5hbWUASW52YWxpZCBzdGF0dXMgY29kZQBQYXVzZSBvbiBDT05ORUNUL1VwZ3JhZGUAUGF1c2Ugb24gUFJJL1VwZ3JhZGUARXhwZWN0ZWQgSFRUUC8yIENvbm5lY3Rpb24gUHJlZmFjZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX21ldGhvZABFeHBlY3RlZCBzcGFjZSBhZnRlciBtZXRob2QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfZmllbGQAUGF1c2VkAEludmFsaWQgd29yZCBlbmNvdW50ZXJlZABJbnZhbGlkIG1ldGhvZCBlbmNvdW50ZXJlZABNaXNzaW5nIGV4cGVjdGVkIENSIGFmdGVyIGNodW5rIGRhdGEARXhwZWN0ZWQgTEYgYWZ0ZXIgY2h1bmsgZGF0YQBVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNjaGVtYQBSZXF1ZXN0IGhhcyBpbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AARGF0YSBhZnRlciBgQ29ubmVjdGlvbjogY2xvc2VgAFNXSVRDSF9QUk9YWQBVU0VfUFJPWFkATUtBQ1RJVklUWQBVTlBST0NFU1NBQkxFX0VOVElUWQBRVUVSWQBDT1BZAE1PVkVEX1BFUk1BTkVOVExZAFRPT19FQVJMWQBOT1RJRlkARkFJTEVEX0RFUEVOREVOQ1kAQkFEX0dBVEVXQVkAUExBWQBQVVQAQ0hFQ0tPVVQAR0FURVdBWV9USU1FT1VUAFJFUVVFU1RfVElNRU9VVABORVRXT1JLX0NPTk5FQ1RfVElNRU9VVABDT05ORUNUSU9OX1RJTUVPVVQATE9HSU5fVElNRU9VVABORVRXT1JLX1JFQURfVElNRU9VVABQT1NUAE1JU0RJUkVDVEVEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9SRVFVRVNUAENMSUVOVF9DTE9TRURfTE9BRF9CQUxBTkNFRF9SRVFVRVNUAEJBRF9SRVFVRVNUAEhUVFBfUkVRVUVTVF9TRU5UX1RPX0hUVFBTX1BPUlQAUkVQT1JUAElNX0FfVEVBUE9UAFJFU0VUX0NPTlRFTlQATk9fQ09OVEVOVABQQVJUSUFMX0NPTlRFTlQASFBFX0lOVkFMSURfQ09OU1RBTlQASFBFX0NCX1JFU0VUAEdFVABIUEVfU1RSSUNUAENPTkZMSUNUAFRFTVBPUkFSWV9SRURJUkVDVABQRVJNQU5FTlRfUkVESVJFQ1QAQ09OTkVDVABNVUxUSV9TVEFUVVMASFBFX0lOVkFMSURfU1RBVFVTAFRPT19NQU5ZX1JFUVVFU1RTAEVBUkxZX0hJTlRTAFVOQVZBSUxBQkxFX0ZPUl9MRUdBTF9SRUFTT05TAE9QVElPTlMAU1dJVENISU5HX1BST1RPQ09MUwBWQVJJQU5UX0FMU09fTkVHT1RJQVRFUwBNVUxUSVBMRV9DSE9JQ0VTAElOVEVSTkFMX1NFUlZFUl9FUlJPUgBXRUJfU0VSVkVSX1VOS05PV05fRVJST1IAUkFJTEdVTl9FUlJPUgBJREVOVElUWV9QUk9WSURFUl9BVVRIRU5USUNBVElPTl9FUlJPUgBTU0xfQ0VSVElGSUNBVEVfRVJST1IASU5WQUxJRF9YX0ZPUldBUkRFRF9GT1IAU0VUX1BBUkFNRVRFUgBHRVRfUEFSQU1FVEVSAEhQRV9VU0VSAFNFRV9PVEhFUgBIUEVfQ0JfQ0hVTktfSEVBREVSAEV4cGVjdGVkIExGIGFmdGVyIENSAE1LQ0FMRU5EQVIAU0VUVVAAV0VCX1NFUlZFUl9JU19ET1dOAFRFQVJET1dOAEhQRV9DTE9TRURfQ09OTkVDVElPTgBIRVVSSVNUSUNfRVhQSVJBVElPTgBESVNDT05ORUNURURfT1BFUkFUSU9OAE5PTl9BVVRIT1JJVEFUSVZFX0lORk9STUFUSU9OAEhQRV9JTlZBTElEX1ZFUlNJT04ASFBFX0NCX01FU1NBR0VfQkVHSU4AU0lURV9JU19GUk9aRU4ASFBFX0lOVkFMSURfSEVBREVSX1RPS0VOAElOVkFMSURfVE9LRU4ARk9SQklEREVOAEVOSEFOQ0VfWU9VUl9DQUxNAEhQRV9JTlZBTElEX1VSTABCTE9DS0VEX0JZX1BBUkVOVEFMX0NPTlRST0wATUtDT0wAQUNMAEhQRV9JTlRFUk5BTABSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFX1VOT0ZGSUNJQUwASFBFX09LAFVOTElOSwBVTkxPQ0sAUFJJAFJFVFJZX1dJVEgASFBFX0lOVkFMSURfQ09OVEVOVF9MRU5HVEgASFBFX1VORVhQRUNURURfQ09OVEVOVF9MRU5HVEgARkxVU0gAUFJPUFBBVENIAE0tU0VBUkNIAFVSSV9UT09fTE9ORwBQUk9DRVNTSU5HAE1JU0NFTExBTkVPVVNfUEVSU0lTVEVOVF9XQVJOSU5HAE1JU0NFTExBTkVPVVNfV0FSTklORwBIUEVfSU5WQUxJRF9UUkFOU0ZFUl9FTkNPRElORwBFeHBlY3RlZCBDUkxGAEhQRV9JTlZBTElEX0NIVU5LX1NJWkUATU9WRQBDT05USU5VRQBIUEVfQ0JfU1RBVFVTX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJTX0NPTVBMRVRFAEhQRV9DQl9WRVJTSU9OX0NPTVBMRVRFAEhQRV9DQl9VUkxfQ09NUExFVEUASFBFX0NCX0NIVU5LX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfVkFMVUVfQ09NUExFVEUASFBFX0NCX0NIVU5LX0VYVEVOU0lPTl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX05BTUVfQ09NUExFVEUASFBFX0NCX01FU1NBR0VfQ09NUExFVEUASFBFX0NCX01FVEhPRF9DT01QTEVURQBIUEVfQ0JfSEVBREVSX0ZJRUxEX0NPTVBMRVRFAERFTEVURQBIUEVfSU5WQUxJRF9FT0ZfU1RBVEUASU5WQUxJRF9TU0xfQ0VSVElGSUNBVEUAUEFVU0UATk9fUkVTUE9OU0UAVU5TVVBQT1JURURfTUVESUFfVFlQRQBHT05FAE5PVF9BQ0NFUFRBQkxFAFNFUlZJQ0VfVU5BVkFJTEFCTEUAUkFOR0VfTk9UX1NBVElTRklBQkxFAE9SSUdJTl9JU19VTlJFQUNIQUJMRQBSRVNQT05TRV9JU19TVEFMRQBQVVJHRQBNRVJHRQBSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFAFJFUVVFU1RfSEVBREVSX1RPT19MQVJHRQBQQVlMT0FEX1RPT19MQVJHRQBJTlNVRkZJQ0lFTlRfU1RPUkFHRQBIUEVfUEFVU0VEX1VQR1JBREUASFBFX1BBVVNFRF9IMl9VUEdSQURFAFNPVVJDRQBBTk5PVU5DRQBUUkFDRQBIUEVfVU5FWFBFQ1RFRF9TUEFDRQBERVNDUklCRQBVTlNVQlNDUklCRQBSRUNPUkQASFBFX0lOVkFMSURfTUVUSE9EAE5PVF9GT1VORABQUk9QRklORABVTkJJTkQAUkVCSU5EAFVOQVVUSE9SSVpFRABNRVRIT0RfTk9UX0FMTE9XRUQASFRUUF9WRVJTSU9OX05PVF9TVVBQT1JURUQAQUxSRUFEWV9SRVBPUlRFRABBQ0NFUFRFRABOT1RfSU1QTEVNRU5URUQATE9PUF9ERVRFQ1RFRABIUEVfQ1JfRVhQRUNURUQASFBFX0xGX0VYUEVDVEVEAENSRUFURUQASU1fVVNFRABIUEVfUEFVU0VEAFRJTUVPVVRfT0NDVVJFRABQQVlNRU5UX1JFUVVJUkVEAFBSRUNPTkRJVElPTl9SRVFVSVJFRABQUk9YWV9BVVRIRU5USUNBVElPTl9SRVFVSVJFRABORVRXT1JLX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAExFTkdUSF9SRVFVSVJFRABTU0xfQ0VSVElGSUNBVEVfUkVRVUlSRUQAVVBHUkFERV9SRVFVSVJFRABQQUdFX0VYUElSRUQAUFJFQ09ORElUSU9OX0ZBSUxFRABFWFBFQ1RBVElPTl9GQUlMRUQAUkVWQUxJREFUSU9OX0ZBSUxFRABTU0xfSEFORFNIQUtFX0ZBSUxFRABMT0NLRUQAVFJBTlNGT1JNQVRJT05fQVBQTElFRABOT1RfTU9ESUZJRUQATk9UX0VYVEVOREVEAEJBTkRXSURUSF9MSU1JVF9FWENFRURFRABTSVRFX0lTX09WRVJMT0FERUQASEVBRABFeHBlY3RlZCBIVFRQLwAAUhUAABoVAAAPEgAA5BkAAJEVAAAJFAAALRkAAOQUAADpEQAAaRQAAKEUAAB2FQAAQxYAAF4SAACUFwAAFxYAAH0UAAB/FgAAQRcAALMTAADDFgAABBoAAL0YAADQGAAAoBMAANQZAACvFgAAaBYAAHAXAADZFgAA/BgAAP4RAABZFwAAlxYAABwXAAD2FgAAjRcAAAsSAAB/GwAALhEAALMQAABJEgAArRIAAPYYAABoEAAAYhUAABAVAABaFgAAShkAALUVAADBFQAAYBUAAFwZAABaGQAAUxkAABYVAACtEQAAQhAAALcQAABXGAAAvxUAAIkQAAAcGQAAGhkAALkVAABRGAAA3BMAAFsVAABZFQAA5hgAAGcVAAARGQAA7RgAAOcTAACuEAAAwhcAAAAUAACSEwAAhBMAAEASAAAmGQAArxUAAGIQAEHpOQsBAQBBgDoL4AEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBB6jsLBAEAAAIAQYE8C14DBAMDAwMDAAADAwADAwADAwMDAwMDAwMDAAUAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAwADAEHqPQsEAQAAAgBBgT4LXgMAAwMDAwMAAAMDAAMDAAMDAwMDAwMDAwMABAAFAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwADAAMAQeA/Cw1sb3NlZWVwLWFsaXZlAEH5PwsBAQBBkMAAC+ABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAQfnBAAsBAQBBkMIAC+cBAQEBAQEBAQEBAQEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQFjaHVua2VkAEGhxAALXgEAAQEBAQEAAAEBAAEBAAEBAQEBAQEBAQEAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAEAQYDGAAshZWN0aW9uZW50LWxlbmd0aG9ucm94eS1jb25uZWN0aW9uAEGwxgALK3JhbnNmZXItZW5jb2RpbmdwZ3JhZGUNCg0KU00NCg0KVFRQL0NFL1RTUC8AQenGAAsFAQIAAQMAQYDHAAtfBAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUAQenIAAsFAQIAAQMAQYDJAAtfBAUFBgUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUAQenKAAsEAQAAAQBBgcsAC14CAgACAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAEHpzAALBQECAAEDAEGAzQALXwQFAAAFBQUFBQUFBQUFBQYFBQUFBQUFBQUFBQUABQAHCAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQAFAAUABQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUAAAAFAEHpzgALBQEBAAEBAEGAzwALAQEAQZrPAAtBAgAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAQenQAAsFAQEAAQEAQYDRAAsBAQBBitEACwYCAAAAAAIAQaHRAAs6AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBB4NIAC5oBTk9VTkNFRUNLT1VUTkVDVEVURUNSSUJFTFVTSEVURUFEU0VBUkNIUkdFQ1RJVklUWUxFTkRBUlZFT1RJRllQVElPTlNDSFNFQVlTVEFUQ0hHRVVFUllPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw==' let wasmBuffer Object.defineProperty(module, 'exports', { get: () => { return wasmBuffer ? wasmBuffer : (wasmBuffer = Buffer.from(wasmBase64, 'base64')) } }) /***/ }), /***/ 16559: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* module decorator */ module = __nccwpck_require__.nmd(module); const { Buffer } = __nccwpck_require__(4573) const wasmBase64 = 'AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAn9/AGABfwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAzQzBQYAAAMAAAAAAAADAQMAAwMDAAACAAAAAAICAgICAgICAgIBAQEBAQEBAQEDAAADAAAABAUBcAESEgUDAQACBggBfwFBgNgECwfFBygGbWVtb3J5AgALX2luaXRpYWxpemUACBlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQACRhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUANgxsbGh0dHBfYWxsb2MACwZtYWxsb2MAOAtsbGh0dHBfZnJlZQAMBGZyZWUADA9sbGh0dHBfZ2V0X3R5cGUADRVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADhVsbGh0dHBfZ2V0X2h0dHBfbWlub3IADxFsbGh0dHBfZ2V0X21ldGhvZAAQFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAERJsbGh0dHBfZ2V0X3VwZ3JhZGUAEgxsbGh0dHBfcmVzZXQAEw5sbGh0dHBfZXhlY3V0ZQAUFGxsaHR0cF9zZXR0aW5nc19pbml0ABUNbGxodHRwX2ZpbmlzaAAWDGxsaHR0cF9wYXVzZQAXDWxsaHR0cF9yZXN1bWUAGBtsbGh0dHBfcmVzdW1lX2FmdGVyX3VwZ3JhZGUAGRBsbGh0dHBfZ2V0X2Vycm5vABoXbGxodHRwX2dldF9lcnJvcl9yZWFzb24AGxdsbGh0dHBfc2V0X2Vycm9yX3JlYXNvbgAcFGxsaHR0cF9nZXRfZXJyb3JfcG9zAB0RbGxodHRwX2Vycm5vX25hbWUAHhJsbGh0dHBfbWV0aG9kX25hbWUAHxJsbGh0dHBfc3RhdHVzX25hbWUAIBpsbGh0dHBfc2V0X2xlbmllbnRfaGVhZGVycwAhIWxsaHR0cF9zZXRfbGVuaWVudF9jaHVua2VkX2xlbmd0aAAiHWxsaHR0cF9zZXRfbGVuaWVudF9rZWVwX2FsaXZlACMkbGxodHRwX3NldF9sZW5pZW50X3RyYW5zZmVyX2VuY29kaW5nACQabGxodHRwX3NldF9sZW5pZW50X3ZlcnNpb24AJSNsbGh0dHBfc2V0X2xlbmllbnRfZGF0YV9hZnRlcl9jbG9zZQAmJ2xsaHR0cF9zZXRfbGVuaWVudF9vcHRpb25hbF9sZl9hZnRlcl9jcgAnLGxsaHR0cF9zZXRfbGVuaWVudF9vcHRpb25hbF9jcmxmX2FmdGVyX2NodW5rACgobGxodHRwX3NldF9sZW5pZW50X29wdGlvbmFsX2NyX2JlZm9yZV9sZgApKmxsaHR0cF9zZXRfbGVuaWVudF9zcGFjZXNfYWZ0ZXJfY2h1bmtfc2l6ZQAqGGxsaHR0cF9tZXNzYWdlX25lZWRzX2VvZgA1CRcBAEEBCxEBAgMEBQoGBzEzMi0uLCsvMArYywIzFgBB/NMAKAIABEAAC0H80wBBATYCAAsUACAAEDcgACACNgI4IAAgAToAKAsUACAAIAAvATQgAC0AMCAAEDYQAAseAQF/QcAAEDkiARA3IAFBgAg2AjggASAAOgAoIAELjwwBB38CQCAARQ0AIABBCGsiASAAQQRrKAIAIgBBeHEiBGohBQJAIABBAXENACAAQQNxRQ0BIAEgASgCACIAayIBQZDUACgCAEkNASAAIARqIQQCQAJAQZTUACgCACABRwRAIABB/wFNBEAgAEEDdiEDIAEoAggiACABKAIMIgJGBEBBgNQAQYDUACgCAEF+IAN3cTYCAAwFCyACIAA2AgggACACNgIMDAQLIAEoAhghBiABIAEoAgwiAEcEQCAAIAEoAggiAjYCCCACIAA2AgwMAwsgAUEUaiIDKAIAIgJFBEAgASgCECICRQ0CIAFBEGohAwsDQCADIQcgAiIAQRRqIgMoAgAiAg0AIABBEGohAyAAKAIQIgINAAsgB0EANgIADAILIAUoAgQiAEEDcUEDRw0CIAUgAEF+cTYCBEGI1AAgBDYCACAFIAQ2AgAgASAEQQFyNgIEDAMLQQAhAAsgBkUNAAJAIAEoAhwiAkECdEGw1gBqIgMoAgAgAUYEQCADIAA2AgAgAA0BQYTUAEGE1AAoAgBBfiACd3E2AgAMAgsgBkEQQRQgBigCECABRhtqIAA2AgAgAEUNAQsgACAGNgIYIAEoAhAiAgRAIAAgAjYCECACIAA2AhgLIAFBFGooAgAiAkUNACAAQRRqIAI2AgAgAiAANgIYCyABIAVPDQAgBSgCBCIAQQFxRQ0AAkACQAJAAkAgAEECcUUEQEGY1AAoAgAgBUYEQEGY1AAgATYCAEGM1ABBjNQAKAIAIARqIgA2AgAgASAAQQFyNgIEIAFBlNQAKAIARw0GQYjUAEEANgIAQZTUAEEANgIADAYLQZTUACgCACAFRgRAQZTUACABNgIAQYjUAEGI1AAoAgAgBGoiADYCACABIABBAXI2AgQgACABaiAANgIADAYLIABBeHEgBGohBCAAQf8BTQRAIABBA3YhAyAFKAIIIgAgBSgCDCICRgRAQYDUAEGA1AAoAgBBfiADd3E2AgAMBQsgAiAANgIIIAAgAjYCDAwECyAFKAIYIQYgBSAFKAIMIgBHBEBBkNQAKAIAGiAAIAUoAggiAjYCCCACIAA2AgwMAwsgBUEUaiIDKAIAIgJFBEAgBSgCECICRQ0CIAVBEGohAwsDQCADIQcgAiIAQRRqIgMoAgAiAg0AIABBEGohAyAAKAIQIgINAAsgB0EANgIADAILIAUgAEF+cTYCBCABIARqIAQ2AgAgASAEQQFyNgIEDAMLQQAhAAsgBkUNAAJAIAUoAhwiAkECdEGw1gBqIgMoAgAgBUYEQCADIAA2AgAgAA0BQYTUAEGE1AAoAgBBfiACd3E2AgAMAgsgBkEQQRQgBigCECAFRhtqIAA2AgAgAEUNAQsgACAGNgIYIAUoAhAiAgRAIAAgAjYCECACIAA2AhgLIAVBFGooAgAiAkUNACAAQRRqIAI2AgAgAiAANgIYCyABIARqIAQ2AgAgASAEQQFyNgIEIAFBlNQAKAIARw0AQYjUACAENgIADAELIARB/wFNBEAgBEF4cUGo1ABqIQACf0GA1AAoAgAiAkEBIARBA3Z0IgNxRQRAQYDUACACIANyNgIAIAAMAQsgACgCCAsiAiABNgIMIAAgATYCCCABIAA2AgwgASACNgIIDAELQR8hAiAEQf///wdNBEAgBEEmIARBCHZnIgBrdkEBcSAAQQF0a0E+aiECCyABIAI2AhwgAUIANwIQIAJBAnRBsNYAaiEAAkBBhNQAKAIAIgNBASACdCIHcUUEQCAAIAE2AgBBhNQAIAMgB3I2AgAgASAANgIYIAEgATYCCCABIAE2AgwMAQsgBEEZIAJBAXZrQQAgAkEfRxt0IQIgACgCACEAAkADQCAAIgMoAgRBeHEgBEYNASACQR12IQAgAkEBdCECIAMgAEEEcWpBEGoiBygCACIADQALIAcgATYCACABIAM2AhggASABNgIMIAEgATYCCAwBCyADKAIIIgAgATYCDCADIAE2AgggAUEANgIYIAEgAzYCDCABIAA2AggLQaDUAEGg1AAoAgBBAWsiAEF/IAAbNgIACwsHACAALQAoCwcAIAAtACoLBwAgAC0AKwsHACAALQApCwcAIAAvATQLBwAgAC0AMAtAAQR/IAAoAhghASAALwEuIQIgAC0AKCEDIAAoAjghBCAAEDcgACAENgI4IAAgAzoAKCAAIAI7AS4gACABNgIYC8X4AQIHfwN+IAEgAmohBAJAIAAiAygCDCIADQAgAygCBARAIAMgATYCBAsjAEEQayIJJAACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAygCHCICQQFrDuwB7gEB6AECAwQFBgcICQoLDA0ODxAREucBE+YBFBXlARYX5AEYGRobHB0eHyDvAe0BIeMBIiMkJSYnKCkqK+IBLC0uLzAxMuEB4AEzNN8B3gE1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk/pAVBRUlPdAdwBVNsBVdoBVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEBkgGTAZQBlQGWAZcBmAGZAZoBmwGcAZ0BngGfAaABoQGiAaMBpAGlAaYBpwGoAakBqgGrAawBrQGuAa8BsAGxAbIBswG0AbUBtgG3AbgBuQG6AbsBvAG9Ab4BvwHAAcEBwgHDAcQBxQHZAdgBxgHXAccB1gHIAckBygHLAcwBzQHOAc8B0AHRAdIB0wHUAQDqAQtBAAzUAQtBDgzTAQtBDQzSAQtBDwzRAQtBEAzQAQtBEQzPAQtBEgzOAQtBEwzNAQtBFAzMAQtBFQzLAQtBFgzKAQtBFwzJAQtBGAzIAQtBGQzHAQtBGgzGAQtBGwzFAQtBHAzEAQtBHQzDAQtBHgzCAQtBHwzBAQtBCAzAAQtBIAy/AQtBIgy+AQtBIQy9AQtBBwy8AQtBIwy7AQtBJAy6AQtBJQy5AQtBJgy4AQtBJwy3AQtBzgEMtgELQSgMtQELQSkMtAELQSoMswELQSsMsgELQc8BDLEBC0EtDLABC0EuDK8BC0EvDK4BC0EwDK0BC0ExDKwBC0EyDKsBC0EzDKoBC0HQAQypAQtBNAyoAQtBOAynAQtBDAymAQtBNQylAQtBNgykAQtBNwyjAQtBPQyiAQtBOQyhAQtB0QEMoAELQQsMnwELQT4MngELQToMnQELQQoMnAELQTsMmwELQTwMmgELQdIBDJkBC0HAAAyYAQtBPwyXAQtBwQAMlgELQQkMlQELQSwMlAELQcIADJMBC0HDAAySAQtBxAAMkQELQcUADJABC0HGAAyPAQtBxwAMjgELQcgADI0BC0HJAAyMAQtBygAMiwELQcsADIoBC0HMAAyJAQtBzQAMiAELQc4ADIcBC0HPAAyGAQtB0AAMhQELQdEADIQBC0HSAAyDAQtB1AAMggELQdMADIEBC0HVAAyAAQtB1gAMfwtB1wAMfgtB2AAMfQtB2QAMfAtB2gAMewtB2wAMegtB0wEMeQtB3AAMeAtB3QAMdwtBBgx2C0HeAAx1C0EFDHQLQd8ADHMLQQQMcgtB4AAMcQtB4QAMcAtB4gAMbwtB4wAMbgtBAwxtC0HkAAxsC0HlAAxrC0HmAAxqC0HoAAxpC0HnAAxoC0HpAAxnC0HqAAxmC0HrAAxlC0HsAAxkC0ECDGMLQe0ADGILQe4ADGELQe8ADGALQfAADF8LQfEADF4LQfIADF0LQfMADFwLQfQADFsLQfUADFoLQfYADFkLQfcADFgLQfgADFcLQfkADFYLQfoADFULQfsADFQLQfwADFMLQf0ADFILQf4ADFELQf8ADFALQYABDE8LQYEBDE4LQYIBDE0LQYMBDEwLQYQBDEsLQYUBDEoLQYYBDEkLQYcBDEgLQYgBDEcLQYkBDEYLQYoBDEULQYsBDEQLQYwBDEMLQY0BDEILQY4BDEELQY8BDEALQZABDD8LQZEBDD4LQZIBDD0LQZMBDDwLQZQBDDsLQZUBDDoLQZYBDDkLQZcBDDgLQZgBDDcLQZkBDDYLQZoBDDULQZsBDDQLQZwBDDMLQZ0BDDILQZ4BDDELQZ8BDDALQaABDC8LQaEBDC4LQaIBDC0LQaMBDCwLQaQBDCsLQaUBDCoLQaYBDCkLQacBDCgLQagBDCcLQakBDCYLQaoBDCULQasBDCQLQawBDCMLQa0BDCILQa4BDCELQa8BDCALQbABDB8LQbEBDB4LQbIBDB0LQbMBDBwLQbQBDBsLQbUBDBoLQbYBDBkLQbcBDBgLQbgBDBcLQQEMFgtBuQEMFQtBugEMFAtBuwEMEwtBvAEMEgtBvQEMEQtBvgEMEAtBvwEMDwtBwAEMDgtBwQEMDQtBwgEMDAtBwwEMCwtBxAEMCgtBxQEMCQtBxgEMCAtB1AEMBwtBxwEMBgtByAEMBQtByQEMBAtBygEMAwtBywEMAgtBzQEMAQtBzAELIQIDQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAMCfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJ/AkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAMCfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCACDtQBAAECAwQFBgcICQoLDA0ODxARFBUWFxgZGhscHR4fICEjJCUnKCmIA4cDhQOEA/wC9QLuAusC6ALmAuMC4ALfAt0C2wLWAtUC1ALTAtICygLJAsgCxwLGAsUCxALDAr0CvAK6ArkCuAK3ArYCtQK0ArICsQKsAqoCqAKnAqYCpQKkAqMCogKhAqACnwKbApoCmQKYApcCkAKIAoQCgwKCAvkB9gH1AfQB8wHyAfEB8AHvAe0B6wHoAeMB4QHgAd8B3gHdAdwB2wHaAdkB2AHXAdYB1QHUAdIB0QHQAc8BzgHNAcwBywHKAckByAHHAcYBxQHEAcMBwgHBAcABvwG+Ab0BvAG7AboBuQG4AbcBtgG1AbQBswGyAbEBsAGvAa4BrQGsAasBqgGpAagBpwGmAaUBpAGjAaIBoQGgAZ8BngGdAZwBmwGaAZcBlgGRAZABjwGOAY0BjAGLAYoBiQGIAYUBhAGDAX59fHt6d3Z1LFFSU1RVVgsgASAERw1zQewBIQIMqQMLIAEgBEcNkAFB0QEhAgyoAwsgASAERw3pAUGEASECDKcDCyABIARHDfQBQfoAIQIMpgMLIAEgBEcNggJB9QAhAgylAwsgASAERw2JAkHzACECDKQDCyABIARHDYwCQfEAIQIMowMLIAEgBEcNHkEeIQIMogMLIAEgBEcNGUEYIQIMoQMLIAEgBEcNuAJBzQAhAgygAwsgASAERw3DAkHGACECDJ8DCyABIARHDcQCQcMAIQIMngMLIAEgBEcNygJBOCECDJ0DCyADLQAwQQFGDZUDDPICC0EAIQACQAJAAkAgAy0AKkUNACADLQArRQ0AIAMvATIiAkECcUUNAQwCCyADLwEyIgJBAXFFDQELQQEhACADLQAoQQFGDQAgAy8BNCIGQeQAa0HkAEkNACAGQcwBRg0AIAZBsAJGDQAgAkHAAHENAEEAIQAgAkGIBHFBgARGDQAgAkEocUEARyEACyADQQA7ATIgA0EAOgAxAkAgAEUEQCADQQA6ADEgAy0ALkEEcQ0BDJwDCyADQgA3AyALIANBADoAMSADQQE6ADYMSQtBACEAAkAgAygCOCICRQ0AIAIoAiwiAkUNACADIAIRAAAhAAsgAEUNSSAAQRVHDWMgA0EENgIcIAMgATYCFCADQb0aNgIQIANBFTYCDEEAIQIMmgMLIAEgBEYEQEEGIQIMmgMLIAEtAABBCkYNGQwBCyABIARGBEBBByECDJkDCwJAIAEtAABBCmsOBAIBAQABCyABQQFqIQFBECECDP4CCyADLQAuQYABcQ0YQQAhAiADQQA2AhwgAyABNgIUIANBqR82AhAgA0ECNgIMDJcDCyABQQFqIQEgA0Evai0AAEEBcQ0XQQAhAiADQQA2AhwgAyABNgIUIANBhB82AhAgA0EZNgIMDJYDCyADIAMpAyAiDCAEIAFrrSIKfSILQgAgCyAMWBs3AyAgCiAMWg0ZQQghAgyVAwsgASAERwRAIANBCTYCCCADIAE2AgRBEiECDPsCC0EJIQIMlAMLIAMpAyBQDZwCDEQLIAEgBEYEQEELIQIMkwMLIAEtAABBCkcNFyABQQFqIQEMGAsgA0Evai0AAEEBcUUNGgwnC0EAIQACQCADKAI4IgJFDQAgAigCSCICRQ0AIAMgAhEAACEACyAADRoMQwtBACEAAkAgAygCOCICRQ0AIAIoAkgiAkUNACADIAIRAAAhAAsgAA0bDCULQQAhAAJAIAMoAjgiAkUNACACKAJIIgJFDQAgAyACEQAAIQALIAANHAwzCyADQS9qLQAAQQFxRQ0dDCMLQQAhAAJAIAMoAjgiAkUNACACKAJMIgJFDQAgAyACEQAAIQALIAANHQxDC0EAIQACQCADKAI4IgJFDQAgAigCTCICRQ0AIAMgAhEAACEACyAADR4MIQsgASAERgRAQRMhAgyLAwsCQCABLQAAIgBBCmsOBCAkJAAjCyABQQFqIQEMIAtBACEAAkAgAygCOCICRQ0AIAIoAkwiAkUNACADIAIRAAAhAAsgAA0jDEMLIAEgBEYEQEEWIQIMiQMLIAEtAABB8D9qLQAAQQFHDSQM7QILAkADQCABLQAAQeA5ai0AACIAQQFHBEACQCAAQQJrDgIDACgLIAFBAWohAUEfIQIM8AILIAQgAUEBaiIBRw0AC0EYIQIMiAMLIAMoAgQhAEEAIQIgA0EANgIEIAMgACABQQFqIgEQMyIADSIMQgtBACEAAkAgAygCOCICRQ0AIAIoAkwiAkUNACADIAIRAAAhAAsgAA0kDCsLIAEgBEYEQEEcIQIMhgMLIANBCjYCCCADIAE2AgRBACEAAkAgAygCOCICRQ0AIAIoAkgiAkUNACADIAIRAAAhAAsgAA0mQSIhAgzrAgsgASAERwRAA0AgAS0AAEHgO2otAAAiAEEDRwRAIABBAWsOBRkbJ+wCJicLIAQgAUEBaiIBRw0AC0EbIQIMhQMLQRshAgyEAwsDQCABLQAAQeA9ai0AACIAQQNHBEAgAEEBaw4FEBIoFCcoCyAEIAFBAWoiAUcNAAtBHiECDIMDCyABIARHBEAgA0ELNgIIIAMgATYCBEEHIQIM6QILQR8hAgyCAwsgASAERgRAQSAhAgyCAwsCQCABLQAAQQ1rDhQvQEBAQEBAQEBAQEBAQEBAQEBAAEALQQAhAiADQQA2AhwgA0G3CzYCECADQQI2AgwgAyABQQFqNgIUDIEDCyADQS9qIQIDQCABIARGBEBBISECDIIDCwJAAkACQCABLQAAIgBBCWsOGAIAKioBKioqKioqKioqKioqKioqKioqAigLIAFBAWohASADQS9qLQAAQQFxRQ0LDBkLIAFBAWohAQwYCyABQQFqIQEgAi0AAEECcQ0AC0EAIQIgA0EANgIcIAMgATYCFCADQc4UNgIQIANBDDYCDAyAAwsgAUEBaiEBC0EAIQACQCADKAI4IgJFDQAgAigCVCICRQ0AIAMgAhEAACEACyAADQEM0QILIANCADcDIAw8CyAAQRVGBEAgA0EkNgIcIAMgATYCFCADQYYaNgIQIANBFTYCDEEAIQIM/QILQQAhAiADQQA2AhwgAyABNgIUIANB4g02AhAgA0EUNgIMDPwCCyADKAIEIQBBACECIANBADYCBCADIAAgASAMp2oiARAxIgBFDSsgA0EHNgIcIAMgATYCFCADIAA2AgwM+wILIAMtAC5BwABxRQ0BC0EAIQACQCADKAI4IgJFDQAgAigCUCICRQ0AIAMgAhEAACEACyAARQ0rIABBFUYEQCADQQo2AhwgAyABNgIUIANB8Rg2AhAgA0EVNgIMQQAhAgz6AgtBACECIANBADYCHCADIAE2AhQgA0GLDDYCECADQRM2AgwM+QILQQAhAiADQQA2AhwgAyABNgIUIANBsRQ2AhAgA0ECNgIMDPgCC0EAIQIgA0EANgIcIAMgATYCFCADQYwUNgIQIANBGTYCDAz3AgtBACECIANBADYCHCADIAE2AhQgA0HRHDYCECADQRk2AgwM9gILIABBFUYNPUEAIQIgA0EANgIcIAMgATYCFCADQaIPNgIQIANBIjYCDAz1AgsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQMiIARQ0oIANBDTYCHCADIAE2AhQgAyAANgIMDPQCCyAAQRVGDTpBACECIANBADYCHCADIAE2AhQgA0GiDzYCECADQSI2AgwM8wILIAMoAgQhAEEAIQIgA0EANgIEIAMgACABEDIiAEUEQCABQQFqIQEMKAsgA0EONgIcIAMgADYCDCADIAFBAWo2AhQM8gILIABBFUYNN0EAIQIgA0EANgIcIAMgATYCFCADQaIPNgIQIANBIjYCDAzxAgsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQMiIARQRAIAFBAWohAQwnCyADQQ82AhwgAyAANgIMIAMgAUEBajYCFAzwAgtBACECIANBADYCHCADIAE2AhQgA0HoFjYCECADQRk2AgwM7wILIABBFUYNM0EAIQIgA0EANgIcIAMgATYCFCADQc4MNgIQIANBIzYCDAzuAgsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQMyIARQ0lIANBETYCHCADIAE2AhQgAyAANgIMDO0CCyAAQRVGDTBBACECIANBADYCHCADIAE2AhQgA0HODDYCECADQSM2AgwM7AILIAMoAgQhAEEAIQIgA0EANgIEIAMgACABEDMiAEUEQCABQQFqIQEMJQsgA0ESNgIcIAMgADYCDCADIAFBAWo2AhQM6wILIANBL2otAABBAXFFDQELQRUhAgzPAgtBACECIANBADYCHCADIAE2AhQgA0HoFjYCECADQRk2AgwM6AILIABBO0cNACABQQFqIQEMDAtBACECIANBADYCHCADIAE2AhQgA0GYFzYCECADQQI2AgwM5gILIABBFUYNKEEAIQIgA0EANgIcIAMgATYCFCADQc4MNgIQIANBIzYCDAzlAgsgA0EUNgIcIAMgATYCFCADIAA2AgwM5AILIAMoAgQhAEEAIQIgA0EANgIEIAMgACABEDMiAEUEQCABQQFqIQEM3AILIANBFTYCHCADIAA2AgwgAyABQQFqNgIUDOMCCyADKAIEIQBBACECIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDNoCCyADQRc2AhwgAyAANgIMIAMgAUEBajYCFAziAgsgAEEVRg0jQQAhAiADQQA2AhwgAyABNgIUIANBzgw2AhAgA0EjNgIMDOECCyADKAIEIQBBACECIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDB0LIANBGTYCHCADIAA2AgwgAyABQQFqNgIUDOACCyADKAIEIQBBACECIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDNYCCyADQRo2AhwgAyAANgIMIAMgAUEBajYCFAzfAgsgAEEVRg0fQQAhAiADQQA2AhwgAyABNgIUIANBog82AhAgA0EiNgIMDN4CCyADKAIEIQBBACECIANBADYCBCADIAAgARAyIgBFBEAgAUEBaiEBDBsLIANBHDYCHCADIAA2AgwgAyABQQFqNgIUDN0CCyADKAIEIQBBACECIANBADYCBCADIAAgARAyIgBFBEAgAUEBaiEBDNICCyADQR02AhwgAyAANgIMIAMgAUEBajYCFAzcAgsgAEE7Rw0BIAFBAWohAQtBJCECDMACC0EAIQIgA0EANgIcIAMgATYCFCADQc4UNgIQIANBDDYCDAzZAgsgASAERwRAA0AgAS0AAEEgRw3xASAEIAFBAWoiAUcNAAtBLCECDNkCC0EsIQIM2AILIAEgBEYEQEE0IQIM2AILAkACQANAAkAgAS0AAEEKaw4EAgAAAwALIAQgAUEBaiIBRw0AC0E0IQIM2QILIAMoAgQhACADQQA2AgQgAyAAIAEQMCIARQ2MAiADQTI2AhwgAyABNgIUIAMgADYCDEEAIQIM2AILIAMoAgQhACADQQA2AgQgAyAAIAEQMCIARQRAIAFBAWohAQyMAgsgA0EyNgIcIAMgADYCDCADIAFBAWo2AhRBACECDNcCCyABIARHBEACQANAIAEtAABBMGsiAEH/AXFBCk8EQEE5IQIMwAILIAMpAyAiC0KZs+bMmbPmzBlWDQEgAyALQgp+Igo3AyAgCiAArUL/AYMiC0J/hVYNASADIAogC3w3AyAgBCABQQFqIgFHDQALQcAAIQIM2AILIAMoAgQhACADQQA2AgQgAyAAIAFBAWoiARAwIgANFwzJAgtBwAAhAgzWAgsgASAERgRAQckAIQIM1gILAkADQAJAIAEtAABBCWsOGAACjwKPApMCjwKPAo8CjwKPAo8CjwKPAo8CjwKPAo8CjwKPAo8CjwKPAo8CAI8CCyAEIAFBAWoiAUcNAAtByQAhAgzWAgsgAUEBaiEBIANBL2otAABBAXENjwIgA0EANgIcIAMgATYCFCADQekPNgIQIANBCjYCDEEAIQIM1QILIAEgBEcEQANAIAEtAAAiAEEgRwRAAkACQAJAIABByABrDgsAAc0BzQHNAc0BzQHNAc0BzQECzQELIAFBAWohAUHZACECDL8CCyABQQFqIQFB2gAhAgy+AgsgAUEBaiEBQdsAIQIMvQILIAQgAUEBaiIBRw0AC0HuACECDNUCC0HuACECDNQCCyADQQI6ACgMMAtBACECIANBADYCHCADQbcLNgIQIANBAjYCDCADIAFBAWo2AhQM0gILQQAhAgy3AgtBDSECDLYCC0ERIQIMtQILQRMhAgy0AgtBFCECDLMCC0EWIQIMsgILQRchAgyxAgtBGCECDLACC0EZIQIMrwILQRohAgyuAgtBGyECDK0CC0EcIQIMrAILQR0hAgyrAgtBHiECDKoCC0EgIQIMqQILQSEhAgyoAgtBIyECDKcCC0EnIQIMpgILIANBPTYCHCADIAE2AhQgAyAANgIMQQAhAgy/AgsgA0EbNgIcIAMgATYCFCADQY8bNgIQIANBFTYCDEEAIQIMvgILIANBIDYCHCADIAE2AhQgA0GeGTYCECADQRU2AgxBACECDL0CCyADQRM2AhwgAyABNgIUIANBnhk2AhAgA0EVNgIMQQAhAgy8AgsgA0ELNgIcIAMgATYCFCADQZ4ZNgIQIANBFTYCDEEAIQIMuwILIANBEDYCHCADIAE2AhQgA0GeGTYCECADQRU2AgxBACECDLoCCyADQSA2AhwgAyABNgIUIANBjxs2AhAgA0EVNgIMQQAhAgy5AgsgA0ELNgIcIAMgATYCFCADQY8bNgIQIANBFTYCDEEAIQIMuAILIANBDDYCHCADIAE2AhQgA0GPGzYCECADQRU2AgxBACECDLcCC0EAIQIgA0EANgIcIAMgATYCFCADQa8ONgIQIANBEjYCDAy2AgsCQANAAkAgAS0AAEEKaw4EAAICAAILIAQgAUEBaiIBRw0AC0HsASECDLYCCwJAAkAgAy0ANkEBRw0AQQAhAAJAIAMoAjgiAkUNACACKAJYIgJFDQAgAyACEQAAIQALIABFDQAgAEEVRw0BIANB6wE2AhwgAyABNgIUIANB4hg2AhAgA0EVNgIMQQAhAgy3AgtBzAEhAgycAgsgA0EANgIcIAMgATYCFCADQfELNgIQIANBHzYCDEEAIQIMtQILAkACQCADLQAoQQFrDgIEAQALQcsBIQIMmwILQcQBIQIMmgILIANBAjoAMUEAIQACQCADKAI4IgJFDQAgAigCACICRQ0AIAMgAhEAACEACyAARQRAQc0BIQIMmgILIABBFUcEQCADQQA2AhwgAyABNgIUIANBrAw2AhAgA0EQNgIMQQAhAgy0AgsgA0HqATYCHCADIAE2AhQgA0GHGTYCECADQRU2AgxBACECDLMCCyABIARGBEBB6QEhAgyzAgsgAS0AAEHIAEYNASADQQE6ACgLQbYBIQIMlwILQcoBIQIMlgILIAEgBEcEQCADQQw2AgggAyABNgIEQckBIQIMlgILQegBIQIMrwILIAEgBEYEQEHnASECDK8CCyABLQAAQcgARw0EIAFBAWohAUHIASECDJQCCyABIARGBEBB5gEhAgyuAgsCQAJAIAEtAABBxQBrDhAABQUFBQUFBQUFBQUFBQUBBQsgAUEBaiEBQcYBIQIMlAILIAFBAWohAUHHASECDJMCC0HlASECIAEgBEYNrAIgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB99MAai0AAEcNAyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMrQILIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARAtIgBFBEBB1AEhAgyTAgsgA0HkATYCHCADIAE2AhQgAyAANgIMQQAhAgysAgtB4wEhAiABIARGDasCIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQfXTAGotAABHDQIgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADKwCCyADQYEEOwEoIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARAtIgANAwwCCyADQQA2AgALQQAhAiADQQA2AhwgAyABNgIUIANB0B42AhAgA0EINgIMDKkCC0HFASECDI4CCyADQeIBNgIcIAMgATYCFCADIAA2AgxBACECDKcCC0EAIQACQCADKAI4IgJFDQAgAigCOCICRQ0AIAMgAhEAACEACyAARQ1lIABBFUcEQCADQQA2AhwgAyABNgIUIANB1A42AhAgA0EgNgIMQQAhAgynAgsgA0GFATYCHCADIAE2AhQgA0HXGjYCECADQRU2AgxBACECDKYCC0HhASECIAQgASIARg2lAiAEIAFrIAMoAgAiAWohBSAAIAFrQQRqIQYCQANAIAAtAAAgAUHw0wBqLQAARw0BIAFBBEYNAyABQQFqIQEgBCAAQQFqIgBHDQALIAMgBTYCAAymAgsgA0EANgIcIAMgADYCFCADQYQ3NgIQIANBCDYCDCADQQA2AgBBACECDKUCCyABIARHBEAgA0ENNgIIIAMgATYCBEHCASECDIsCC0HgASECDKQCCyADQQA2AgAgBkEBaiEBC0HDASECDIgCCyABIARGBEBB3wEhAgyiAgsgAS0AAEEwayIAQf8BcUEKSQRAIAMgADoAKiABQQFqIQFBwQEhAgyIAgsgAygCBCEAIANBADYCBCADIAAgARAuIgBFDYgCIANB3gE2AhwgAyABNgIUIAMgADYCDEEAIQIMoQILIAEgBEYEQEHdASECDKECCwJAIAEtAABBLkYEQCABQQFqIQEMAQsgAygCBCEAIANBADYCBCADIAAgARAuIgBFDYkCIANB3AE2AhwgAyABNgIUIAMgADYCDEEAIQIMoQILQcABIQIMhgILIAEgBEYEQEHbASECDKACC0EAIQBBASEFQQEhB0EAIQICQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQCABLQAAQTBrDgoKCQABAgMEBQYICwtBAgwGC0EDDAULQQQMBAtBBQwDC0EGDAILQQcMAQtBCAshAkEAIQVBACEHDAILQQkhAkEBIQBBACEFQQAhBwwBC0EAIQVBASECCyADIAI6ACsgAUEBaiEBAkACQCADLQAuQRBxDQACQAJAAkAgAy0AKg4DAQACBAsgB0UNAwwCCyAADQEMAgsgBUUNAQsgAygCBCEAIANBADYCBCADIAAgARAuIgBFDQIgA0HYATYCHCADIAE2AhQgAyAANgIMQQAhAgyiAgsgAygCBCEAIANBADYCBCADIAAgARAuIgBFDYsCIANB2QE2AhwgAyABNgIUIAMgADYCDEEAIQIMoQILIAMoAgQhACADQQA2AgQgAyAAIAEQLiIARQ2JAiADQdoBNgIcIAMgATYCFCADIAA2AgwMoAILQb8BIQIMhQILQQAhAAJAIAMoAjgiAkUNACACKAI8IgJFDQAgAyACEQAAIQALAkAgAARAIABBFUYNASADQQA2AhwgAyABNgIUIANBnA02AhAgA0EhNgIMQQAhAgygAgtBvgEhAgyFAgsgA0HXATYCHCADIAE2AhQgA0HWGTYCECADQRU2AgxBACECDJ4CCyABIARGBEBB1wEhAgyeAgsCQCABLQAAQSBGBEAgA0EAOwE0IAFBAWohAQwBCyADQQA2AhwgAyABNgIUIANB6xA2AhAgA0EJNgIMQQAhAgyeAgtBvQEhAgyDAgsgASAERgRAQdYBIQIMnQILAkAgAS0AAEEwa0H/AXEiAkEKSQRAIAFBAWohAQJAIAMvATQiAEGZM0sNACADIABBCmwiADsBNCAAQf7/A3EgAkH//wNzSw0AIAMgACACajsBNAwCC0EAIQIgA0EANgIcIAMgATYCFCADQYAdNgIQIANBDTYCDAyeAgsgA0EANgIcIAMgATYCFCADQYAdNgIQIANBDTYCDEEAIQIMnQILQbwBIQIMggILIAEgBEYEQEHVASECDJwCCwJAIAEtAABBMGtB/wFxIgJBCkkEQCABQQFqIQECQCADLwE0IgBBmTNLDQAgAyAAQQpsIgA7ATQgAEH+/wNxIAJB//8Dc0sNACADIAAgAmo7ATQMAgtBACECIANBADYCHCADIAE2AhQgA0GAHTYCECADQQ02AgwMnQILIANBADYCHCADIAE2AhQgA0GAHTYCECADQQ02AgxBACECDJwCC0G7ASECDIECCyABIARGBEBB1AEhAgybAgsCQCABLQAAQTBrQf8BcSICQQpJBEAgAUEBaiEBAkAgAy8BNCIAQZkzSw0AIAMgAEEKbCIAOwE0IABB/v8DcSACQf//A3NLDQAgAyAAIAJqOwE0DAILQQAhAiADQQA2AhwgAyABNgIUIANBgB02AhAgA0ENNgIMDJwCCyADQQA2AhwgAyABNgIUIANBgB02AhAgA0ENNgIMQQAhAgybAgtBugEhAgyAAgsgASAERgRAQdMBIQIMmgILAkACQAJAAkAgAS0AAEEKaw4XAgMDAAMDAwMDAwMDAwMDAwMDAwMDAwEDCyABQQFqDAULIAFBAWohAUG5ASECDIECCyABQQFqIQEgA0Evai0AAEEBcQ0IIANBADYCHCADIAE2AhQgA0GFCzYCECADQQ02AgxBACECDJoCCyADQQA2AhwgAyABNgIUIANBhQs2AhAgA0ENNgIMQQAhAgyZAgsgASAERwRAIANBDjYCCCADIAE2AgRBASECDP8BC0HSASECDJgCCwJAAkADQAJAIAEtAABBCmsOBAIAAAMACyAEIAFBAWoiAUcNAAtB0QEhAgyZAgsgAygCBCEAIANBADYCBCADIAAgARAsIgBFBEAgAUEBaiEBDAQLIANB0AE2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMmAILIAMoAgQhACADQQA2AgQgAyAAIAEQLCIADQEgAUEBagshAUG3ASECDPwBCyADQc8BNgIcIAMgADYCDCADIAFBAWo2AhRBACECDJUCC0G4ASECDPoBCyADQS9qLQAAQQFxDQEgA0EANgIcIAMgATYCFCADQc8bNgIQIANBGTYCDEEAIQIMkwILIAEgBEYEQEHPASECDJMCCwJAAkACQCABLQAAQQprDgQBAgIAAgsgAUEBaiEBDAILIAFBAWohAQwBCyADLQAuQcAAcUUNAQtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsgAEUNlgEgAEEVRgRAIANB2QA2AhwgAyABNgIUIANBvRk2AhAgA0EVNgIMQQAhAgySAgsgA0EANgIcIAMgATYCFCADQfgMNgIQIANBGzYCDEEAIQIMkQILIANBADYCHCADIAE2AhQgA0HHJzYCECADQQI2AgxBACECDJACCyABIARHBEAgA0EMNgIIIAMgATYCBEG1ASECDPYBC0HOASECDI8CCyABIARGBEBBzQEhAgyPAgsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAEtAABBwQBrDhUAAQIDWgQFBlpaWgcICQoLDA0ODxBaCyABQQFqIQFB8QAhAgyEAgsgAUEBaiEBQfIAIQIMgwILIAFBAWohAUH3ACECDIICCyABQQFqIQFB+wAhAgyBAgsgAUEBaiEBQfwAIQIMgAILIAFBAWohAUH/ACECDP8BCyABQQFqIQFBgAEhAgz+AQsgAUEBaiEBQYMBIQIM/QELIAFBAWohAUGMASECDPwBCyABQQFqIQFBjQEhAgz7AQsgAUEBaiEBQY4BIQIM+gELIAFBAWohAUGbASECDPkBCyABQQFqIQFBnAEhAgz4AQsgAUEBaiEBQaIBIQIM9wELIAFBAWohAUGqASECDPYBCyABQQFqIQFBrQEhAgz1AQsgAUEBaiEBQbQBIQIM9AELIAEgBEYEQEHMASECDI4CCyABLQAAQc4ARw1IIAFBAWohAUGzASECDPMBCyABIARGBEBBywEhAgyNAgsCQAJAAkAgAS0AAEHCAGsOEgBKSkpKSkpKSkoBSkpKSkpKAkoLIAFBAWohAUGuASECDPQBCyABQQFqIQFBsQEhAgzzAQsgAUEBaiEBQbIBIQIM8gELQcoBIQIgASAERg2LAiADKAIAIgAgBCABa2ohBSABIABrQQdqIQYCQANAIAEtAAAgAEHo0wBqLQAARw1FIABBB0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyMAgsgA0EANgIAIAZBAWohAUEbDEULIAEgBEYEQEHJASECDIsCCwJAAkAgAS0AAEHJAGsOBwBHR0dHRwFHCyABQQFqIQFBrwEhAgzxAQsgAUEBaiEBQbABIQIM8AELQcgBIQIgASAERg2JAiADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHm0wBqLQAARw1DIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyKAgsgA0EANgIAIAZBAWohAUEPDEMLQccBIQIgASAERg2IAiADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHk0wBqLQAARw1CIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyJAgsgA0EANgIAIAZBAWohAUEgDEILQcYBIQIgASAERg2HAiADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHh0wBqLQAARw1BIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyIAgsgA0EANgIAIAZBAWohAUESDEELIAEgBEYEQEHFASECDIcCCwJAAkAgAS0AAEHFAGsODgBDQ0NDQ0NDQ0NDQ0MBQwsgAUEBaiEBQasBIQIM7QELIAFBAWohAUGsASECDOwBC0HEASECIAEgBEYNhQIgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB3tMAai0AAEcNPyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMhgILIANBADYCACAGQQFqIQFBBww/C0HDASECIAEgBEYNhAIgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABB2NMAai0AAEcNPiAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMhQILIANBADYCACAGQQFqIQFBKAw+CyABIARGBEBBwgEhAgyEAgsCQAJAAkAgAS0AAEHFAGsOEQBBQUFBQUFBQUEBQUFBQUECQQsgAUEBaiEBQacBIQIM6wELIAFBAWohAUGoASECDOoBCyABQQFqIQFBqQEhAgzpAQtBwQEhAiABIARGDYICIAMoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAS0AACAAQdHTAGotAABHDTwgAEEGRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADIMCCyADQQA2AgAgBkEBaiEBQRoMPAtBwAEhAiABIARGDYECIAMoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQc3TAGotAABHDTsgAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADIICCyADQQA2AgAgBkEBaiEBQSEMOwsgASAERgRAQb8BIQIMgQILAkACQCABLQAAQcEAaw4UAD09PT09PT09PT09PT09PT09PQE9CyABQQFqIQFBowEhAgznAQsgAUEBaiEBQaYBIQIM5gELIAEgBEYEQEG+ASECDIACCwJAAkAgAS0AAEHVAGsOCwA8PDw8PDw8PDwBPAsgAUEBaiEBQaQBIQIM5gELIAFBAWohAUGlASECDOUBC0G9ASECIAEgBEYN/gEgAygCACIAIAQgAWtqIQUgASAAa0EIaiEGAkADQCABLQAAIABBxNMAai0AAEcNOCAAQQhGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM/wELIANBADYCACAGQQFqIQFBKgw4CyABIARGBEBBvAEhAgz+AQsgAS0AAEHQAEcNOCABQQFqIQFBJQw3C0G7ASECIAEgBEYN/AEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBwdMAai0AAEcNNiAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM/QELIANBADYCACAGQQFqIQFBDgw2CyABIARGBEBBugEhAgz8AQsgAS0AAEHFAEcNNiABQQFqIQFBoQEhAgzhAQsgASAERgRAQbkBIQIM+wELAkACQAJAAkAgAS0AAEHCAGsODwABAjk5OTk5OTk5OTk5AzkLIAFBAWohAUGdASECDOMBCyABQQFqIQFBngEhAgziAQsgAUEBaiEBQZ8BIQIM4QELIAFBAWohAUGgASECDOABC0G4ASECIAEgBEYN+QEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBvtMAai0AAEcNMyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM+gELIANBADYCACAGQQFqIQFBFAwzC0G3ASECIAEgBEYN+AEgAygCACIAIAQgAWtqIQUgASAAa0EEaiEGAkADQCABLQAAIABBudMAai0AAEcNMiAAQQRGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM+QELIANBADYCACAGQQFqIQFBKwwyC0G2ASECIAEgBEYN9wEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBttMAai0AAEcNMSAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM+AELIANBADYCACAGQQFqIQFBLAwxC0G1ASECIAEgBEYN9gEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB4dMAai0AAEcNMCAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM9wELIANBADYCACAGQQFqIQFBEQwwC0G0ASECIAEgBEYN9QEgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABBstMAai0AAEcNLyAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM9gELIANBADYCACAGQQFqIQFBLgwvCyABIARGBEBBswEhAgz1AQsCQAJAAkACQAJAIAEtAABBwQBrDhUANDQ0NDQ0NDQ0NAE0NAI0NAM0NAQ0CyABQQFqIQFBkQEhAgzeAQsgAUEBaiEBQZIBIQIM3QELIAFBAWohAUGTASECDNwBCyABQQFqIQFBmAEhAgzbAQsgAUEBaiEBQZoBIQIM2gELIAEgBEYEQEGyASECDPQBCwJAAkAgAS0AAEHSAGsOAwAwATALIAFBAWohAUGZASECDNoBCyABQQFqIQFBBAwtC0GxASECIAEgBEYN8gEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBsNMAai0AAEcNLCAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM8wELIANBADYCACAGQQFqIQFBHQwsCyABIARGBEBBsAEhAgzyAQsCQAJAIAEtAABByQBrDgcBLi4uLi4ALgsgAUEBaiEBQZcBIQIM2AELIAFBAWohAUEiDCsLIAEgBEYEQEGvASECDPEBCyABLQAAQdAARw0rIAFBAWohAUGWASECDNYBCyABIARGBEBBrgEhAgzwAQsCQAJAIAEtAABBxgBrDgsALCwsLCwsLCwsASwLIAFBAWohAUGUASECDNYBCyABQQFqIQFBlQEhAgzVAQtBrQEhAiABIARGDe4BIAMoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQazTAGotAABHDSggAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADO8BCyADQQA2AgAgBkEBaiEBQQ0MKAtBrAEhAiABIARGDe0BIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQeHTAGotAABHDScgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADO4BCyADQQA2AgAgBkEBaiEBQQwMJwtBqwEhAiABIARGDewBIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQarTAGotAABHDSYgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADO0BCyADQQA2AgAgBkEBaiEBQQMMJgtBqgEhAiABIARGDesBIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQajTAGotAABHDSUgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADOwBCyADQQA2AgAgBkEBaiEBQSYMJQsgASAERgRAQakBIQIM6wELAkACQCABLQAAQdQAaw4CAAEnCyABQQFqIQFBjwEhAgzRAQsgAUEBaiEBQZABIQIM0AELQagBIQIgASAERg3pASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGm0wBqLQAARw0jIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzqAQsgA0EANgIAIAZBAWohAUEnDCMLQacBIQIgASAERg3oASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGk0wBqLQAARw0iIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzpAQsgA0EANgIAIAZBAWohAUEcDCILQaYBIQIgASAERg3nASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGe0wBqLQAARw0hIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzoAQsgA0EANgIAIAZBAWohAUEGDCELQaUBIQIgASAERg3mASADKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEGZ0wBqLQAARw0gIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAznAQsgA0EANgIAIAZBAWohAUEZDCALIAEgBEYEQEGkASECDOYBCwJAAkACQAJAIAEtAABBLWsOIwAkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJAEkJCQkJAIkJCQDJAsgAUEBaiEBQYQBIQIMzgELIAFBAWohAUGFASECDM0BCyABQQFqIQFBigEhAgzMAQsgAUEBaiEBQYsBIQIMywELQaMBIQIgASAERg3kASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGX0wBqLQAARw0eIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzlAQsgA0EANgIAIAZBAWohAUELDB4LIAEgBEYEQEGiASECDOQBCwJAAkAgAS0AAEHBAGsOAwAgASALIAFBAWohAUGGASECDMoBCyABQQFqIQFBiQEhAgzJAQsgASAERgRAQaEBIQIM4wELAkACQCABLQAAQcEAaw4PAB8fHx8fHx8fHx8fHx8BHwsgAUEBaiEBQYcBIQIMyQELIAFBAWohAUGIASECDMgBCyABIARGBEBBoAEhAgziAQsgAS0AAEHMAEcNHCABQQFqIQFBCgwbC0GfASECIAEgBEYN4AEgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBkdMAai0AAEcNGiAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM4QELIANBADYCACAGQQFqIQFBHgwaC0GeASECIAEgBEYN3wEgAygCACIAIAQgAWtqIQUgASAAa0EGaiEGAkADQCABLQAAIABBitMAai0AAEcNGSAAQQZGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM4AELIANBADYCACAGQQFqIQFBFQwZC0GdASECIAEgBEYN3gEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBh9MAai0AAEcNGCAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM3wELIANBADYCACAGQQFqIQFBFwwYC0GcASECIAEgBEYN3QEgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBgdMAai0AAEcNFyAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM3gELIANBADYCACAGQQFqIQFBGAwXCyABIARGBEBBmwEhAgzdAQsCQAJAIAEtAABByQBrDgcAGRkZGRkBGQsgAUEBaiEBQYEBIQIMwwELIAFBAWohAUGCASECDMIBC0GaASECIAEgBEYN2wEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB5tMAai0AAEcNFSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM3AELIANBADYCACAGQQFqIQFBCQwVC0GZASECIAEgBEYN2gEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB5NMAai0AAEcNFCAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM2wELIANBADYCACAGQQFqIQFBHwwUC0GYASECIAEgBEYN2QEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB/tIAai0AAEcNEyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM2gELIANBADYCACAGQQFqIQFBAgwTC0GXASECIAEgBEYN2AEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGA0AgAS0AACAAQfzSAGotAABHDREgAEEBRg0CIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADNgBCyABIARGBEBBlgEhAgzYAQtBASABLQAAQd8ARw0RGiABQQFqIQFB/QAhAgy9AQsgA0EANgIAIAZBAWohAUH+ACECDLwBC0GVASECIAEgBEYN1QEgAygCACIAIAQgAWtqIQUgASAAa0EIaiEGAkADQCABLQAAIABBxNMAai0AAEcNDyAAQQhGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM1gELIANBADYCACAGQQFqIQFBKQwPC0GUASECIAEgBEYN1AEgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABB+NIAai0AAEcNDiAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM1QELIANBADYCACAGQQFqIQFBLQwOCyABIARGBEBBkwEhAgzUAQsgAS0AAEHFAEcNDiABQQFqIQFB+gAhAgy5AQsgASAERgRAQZIBIQIM0wELAkACQCABLQAAQcwAaw4IAA8PDw8PDwEPCyABQQFqIQFB+AAhAgy5AQsgAUEBaiEBQfkAIQIMuAELQZEBIQIgASAERg3RASADKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEHz0gBqLQAARw0LIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzSAQsgA0EANgIAIAZBAWohAUEjDAsLQZABIQIgASAERg3QASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHw0gBqLQAARw0KIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzRAQsgA0EANgIAIAZBAWohAUEADAoLIAEgBEYEQEGPASECDNABCwJAAkAgAS0AAEHIAGsOCAAMDAwMDAwBDAsgAUEBaiEBQfMAIQIMtgELIAFBAWohAUH2ACECDLUBCyABIARGBEBBjgEhAgzPAQsCQAJAIAEtAABBzgBrDgMACwELCyABQQFqIQFB9AAhAgy1AQsgAUEBaiEBQfUAIQIMtAELIAEgBEYEQEGNASECDM4BCyABLQAAQdkARw0IIAFBAWohAUEIDAcLQYwBIQIgASAERg3MASADKAIAIgAgBCABa2ohBSABIABrQQNqIQYCQANAIAEtAAAgAEHs0gBqLQAARw0GIABBA0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzNAQsgA0EANgIAIAZBAWohAUEFDAYLQYsBIQIgASAERg3LASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHm0gBqLQAARw0FIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzMAQsgA0EANgIAIAZBAWohAUEWDAULQYoBIQIgASAERg3KASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHh0wBqLQAARw0EIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzLAQsgA0EANgIAIAZBAWohAUEQDAQLIAEgBEYEQEGJASECDMoBCwJAAkAgAS0AAEHDAGsODAAGBgYGBgYGBgYGAQYLIAFBAWohAUHvACECDLABCyABQQFqIQFB8AAhAgyvAQtBiAEhAiABIARGDcgBIAMoAgAiACAEIAFraiEFIAEgAGtBBWohBgJAA0AgAS0AACAAQeDSAGotAABHDQIgAEEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADMkBCyADQQA2AgAgBkEBaiEBQSQMAgsgA0EANgIADAILIAEgBEYEQEGHASECDMcBCyABLQAAQcwARw0BIAFBAWohAUETCzoAKSADKAIEIQAgA0EANgIEIAMgACABEC0iAA0CDAELQQAhAiADQQA2AhwgAyABNgIUIANB6R42AhAgA0EGNgIMDMQBC0HuACECDKkBCyADQYYBNgIcIAMgATYCFCADIAA2AgxBACECDMIBC0EAIQACQCADKAI4IgJFDQAgAigCOCICRQ0AIAMgAhEAACEACyAARQ0AIABBFUYNASADQQA2AhwgAyABNgIUIANB1A42AhAgA0EgNgIMQQAhAgzBAQtB7QAhAgymAQsgA0GFATYCHCADIAE2AhQgA0HXGjYCECADQRU2AgxBACECDL8BCyABIARGBEBBhQEhAgy/AQsCQCABLQAAQSBGBEAgAUEBaiEBDAELIANBADYCHCADIAE2AhQgA0GGHjYCECADQQY2AgxBACECDL8BC0ECIQIMpAELA0AgAS0AAEEgRw0CIAQgAUEBaiIBRw0AC0GEASECDL0BCyABIARGBEBBgwEhAgy9AQsCQCABLQAAQQlrDgRAAABAAAtB6wAhAgyiAQsgAy0AKUEFRgRAQewAIQIMogELQeoAIQIMoQELIAEgBEYEQEGCASECDLsBCyADQQ82AgggAyABNgIEDAoLIAEgBEYEQEGBASECDLoBCwJAIAEtAABBCWsOBD0AAD0AC0HpACECDJ8BCyABIARHBEAgA0EPNgIIIAMgATYCBEHnACECDJ8BC0GAASECDLgBCwJAIAEgBEcEQANAIAEtAABB4M4Aai0AACIAQQNHBEACQCAAQQFrDgI/AAQLQeYAIQIMoQELIAQgAUEBaiIBRw0AC0H+ACECDLkBC0H+ACECDLgBCyADQQA2AhwgAyABNgIUIANBxh82AhAgA0EHNgIMQQAhAgy3AQsgASAERgRAQf8AIQIMtwELAkACQAJAIAEtAABB4NAAai0AAEEBaw4DPAIAAQtB6AAhAgyeAQsgA0EANgIcIAMgATYCFCADQYYSNgIQIANBBzYCDEEAIQIMtwELQeAAIQIMnAELIAEgBEcEQCABQQFqIQFB5QAhAgycAQtB/QAhAgy1AQsgBCABIgBGBEBB/AAhAgy1AQsgAC0AACIBQS9GBEAgAEEBaiEBQeQAIQIMmwELIAFBCWsiAkEXSw0BIAAhAUEBIAJ0QZuAgARxDTcMAQsgBCABIgBGBEBB+wAhAgy0AQsgAC0AAEEvRw0AIABBAWohAQwDC0EAIQIgA0EANgIcIAMgADYCFCADQcYfNgIQIANBBzYCDAyyAQsCQAJAAkACQAJAA0AgAS0AAEHgzABqLQAAIgBBBUcEQAJAAkAgAEEBaw4IPQUGBwgABAEIC0HhACECDJ8BCyABQQFqIQFB4wAhAgyeAQsgBCABQQFqIgFHDQALQfoAIQIMtgELIAFBAWoMFAsgAygCBCEAIANBADYCBCADIAAgARArIgBFDR4gA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgy0AQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDR4gA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgyzAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDR4gA0HwADYCHCADIAE2AhQgAyAANgIMQQAhAgyyAQsgA0EANgIcIAMgATYCFCADQcsPNgIQIANBBzYCDEEAIQIMsQELIAEgBEYEQEH5ACECDLEBCwJAIAEtAABB4MwAai0AAEEBaw4INAQFBgAIAgMHCyABQQFqIQELQQMhAgyVAQsgAUEBagwNC0EAIQIgA0EANgIcIANBoxI2AhAgA0EHNgIMIAMgAUEBajYCFAytAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDRYgA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgysAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDRYgA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgyrAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDRYgA0HwADYCHCADIAE2AhQgAyAANgIMQQAhAgyqAQsgA0EANgIcIAMgATYCFCADQcsPNgIQIANBBzYCDEEAIQIMqQELQeIAIQIMjgELIAEgBEYEQEH4ACECDKgBCyABQQFqDAILIAEgBEYEQEH3ACECDKcBCyABQQFqDAELIAEgBEYNASABQQFqCyEBQQQhAgyKAQtB9gAhAgyjAQsDQCABLQAAQeDKAGotAAAiAEECRwRAIABBAUcEQEHfACECDIsBCwwnCyAEIAFBAWoiAUcNAAtB9QAhAgyiAQsgASAERgRAQfQAIQIMogELAkAgAS0AAEEJaw43JQMGJQQGBgYGBgYGBgYGBgYGBgYGBgYFBgYCBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGAAYLIAFBAWoLIQFBBSECDIYBCyABQQFqDAYLIAMoAgQhACADQQA2AgQgAyAAIAEQKyIARQ0IIANB2wA2AhwgAyABNgIUIAMgADYCDEEAIQIMngELIAMoAgQhACADQQA2AgQgAyAAIAEQKyIARQ0IIANB3QA2AhwgAyABNgIUIAMgADYCDEEAIQIMnQELIAMoAgQhACADQQA2AgQgAyAAIAEQKyIARQ0IIANB8AA2AhwgAyABNgIUIAMgADYCDEEAIQIMnAELIANBADYCHCADIAE2AhQgA0G8EzYCECADQQc2AgxBACECDJsBCwJAAkACQAJAA0AgAS0AAEHgyABqLQAAIgBBBUcEQAJAIABBAWsOBiQDBAUGAAYLQd4AIQIMhgELIAQgAUEBaiIBRw0AC0HzACECDJ4BCyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNByADQdsANgIcIAMgATYCFCADIAA2AgxBACECDJ0BCyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNByADQd0ANgIcIAMgATYCFCADIAA2AgxBACECDJwBCyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNByADQfAANgIcIAMgATYCFCADIAA2AgxBACECDJsBCyADQQA2AhwgAyABNgIUIANB3Ag2AhAgA0EHNgIMQQAhAgyaAQsgASAERg0BIAFBAWoLIQFBBiECDH4LQfIAIQIMlwELAkACQAJAAkADQCABLQAAQeDGAGotAAAiAEEFRwRAIABBAWsOBB8CAwQFCyAEIAFBAWoiAUcNAAtB8QAhAgyaAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDQMgA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgyZAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDQMgA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgyYAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDQMgA0HwADYCHCADIAE2AhQgAyAANgIMQQAhAgyXAQsgA0EANgIcIAMgATYCFCADQbQKNgIQIANBBzYCDEEAIQIMlgELQc4AIQIMewtB0AAhAgx6C0HdACECDHkLIAEgBEYEQEHwACECDJMBCwJAIAEtAABBCWsOBBYAABYACyABQQFqIQFB3AAhAgx4CyABIARGBEBB7wAhAgySAQsCQCABLQAAQQlrDgQVAAAVAAtBACEAAkAgAygCOCICRQ0AIAIoAjAiAkUNACADIAIRAAAhAAsgAEUEQEHTASECDHgLIABBFUcEQCADQQA2AhwgAyABNgIUIANBwQ02AhAgA0EaNgIMQQAhAgySAQsgA0HuADYCHCADIAE2AhQgA0HwGTYCECADQRU2AgxBACECDJEBC0HtACECIAEgBEYNkAEgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABB18YAai0AAEcNBCAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMkQELIANBADYCACAGQQFqIQEgAy0AKSIAQSNrQQtJDQQCQCAAQQZLDQBBASAAdEHKAHFFDQAMBQtBACECIANBADYCHCADIAE2AhQgA0HlCTYCECADQQg2AgwMkAELQewAIQIgASAERg2PASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHUxgBqLQAARw0DIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyQAQsgA0EANgIAIAZBAWohASADLQApQSFGDQMgA0EANgIcIAMgATYCFCADQYkKNgIQIANBCDYCDEEAIQIMjwELQesAIQIgASAERg2OASADKAIAIgAgBCABa2ohBSABIABrQQNqIQYCQANAIAEtAAAgAEHQxgBqLQAARw0CIABBA0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyPAQsgA0EANgIAIAZBAWohASADLQApIgBBI0kNAiAAQS5GDQIgA0EANgIcIAMgATYCFCADQcEJNgIQIANBCDYCDEEAIQIMjgELIANBADYCAAtBACECIANBADYCHCADIAE2AhQgA0GENzYCECADQQg2AgwMjAELQdgAIQIMcQsgASAERwRAIANBDTYCCCADIAE2AgRB1wAhAgxxC0HqACECDIoBCyABIARGBEBB6QAhAgyKAQsgAS0AAEEwayIAQf8BcUEKSQRAIAMgADoAKiABQQFqIQFB1gAhAgxwCyADKAIEIQAgA0EANgIEIAMgACABEC4iAEUNdCADQegANgIcIAMgATYCFCADIAA2AgxBACECDIkBCyABIARGBEBB5wAhAgyJAQsCQCABLQAAQS5GBEAgAUEBaiEBDAELIAMoAgQhACADQQA2AgQgAyAAIAEQLiIARQ11IANB5gA2AhwgAyABNgIUIAMgADYCDEEAIQIMiQELQdUAIQIMbgsgASAERgRAQeUAIQIMiAELQQAhAEEBIQVBASEHQQAhAgJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAIAEtAABBMGsOCgoJAAECAwQFBggLC0ECDAYLQQMMBQtBBAwEC0EFDAMLQQYMAgtBBwwBC0EICyECQQAhBUEAIQcMAgtBCSECQQEhAEEAIQVBACEHDAELQQAhBUEBIQILIAMgAjoAKyABQQFqIQECQAJAIAMtAC5BEHENAAJAAkACQCADLQAqDgMBAAIECyAHRQ0DDAILIAANAQwCCyAFRQ0BCyADKAIEIQAgA0EANgIEIAMgACABEC4iAEUNAiADQeIANgIcIAMgATYCFCADIAA2AgxBACECDIoBCyADKAIEIQAgA0EANgIEIAMgACABEC4iAEUNdyADQeMANgIcIAMgATYCFCADIAA2AgxBACECDIkBCyADKAIEIQAgA0EANgIEIAMgACABEC4iAEUNdSADQeQANgIcIAMgATYCFCADIAA2AgwMiAELQdMAIQIMbQsgAy0AKUEiRg2AAUHSACECDGwLQQAhAAJAIAMoAjgiAkUNACACKAI8IgJFDQAgAyACEQAAIQALIABFBEBB1AAhAgxsCyAAQRVHBEAgA0EANgIcIAMgATYCFCADQZwNNgIQIANBITYCDEEAIQIMhgELIANB4QA2AhwgAyABNgIUIANB1hk2AhAgA0EVNgIMQQAhAgyFAQsgASAERgRAQeAAIQIMhQELAkACQAJAAkACQCABLQAAQQprDgQBBAQABAsgAUEBaiEBDAELIAFBAWohASADQS9qLQAAQQFxRQ0BC0HRACECDGwLIANBADYCHCADIAE2AhQgA0GIETYCECADQQk2AgxBACECDIUBCyADQQA2AhwgAyABNgIUIANBiBE2AhAgA0EJNgIMQQAhAgyEAQsgASAERgRAQd8AIQIMhAELIAEtAABBCkYEQCABQQFqIQEMCQsgAy0ALkHAAHENCCADQQA2AhwgAyABNgIUIANBiBE2AhAgA0ECNgIMQQAhAgyDAQsgASAERgRAQd0AIQIMgwELIAEtAAAiAkENRgRAIAFBAWohAUHPACECDGkLIAEhACACQQlrDgQFAQEFAQsgBCABIgBGBEBB3AAhAgyCAQsgAC0AAEEKRw0AIABBAWoMAgtBACECIANBADYCHCADIAA2AhQgA0G1LDYCECADQQc2AgwMgAELIAEgBEYEQEHbACECDIABCwJAIAEtAABBCWsOBAMAAAMACyABQQFqCyEBQc0AIQIMZAsgASAERgRAQdoAIQIMfgsgAS0AAEEJaw4EAAEBAAELQQAhAiADQQA2AhwgA0HsETYCECADQQc2AgwgAyABQQFqNgIUDHwLIANBgBI7ASpBACEAAkAgAygCOCICRQ0AIAIoAjAiAkUNACADIAIRAAAhAAsgAEUNACAAQRVHDQEgA0HZADYCHCADIAE2AhQgA0HwGTYCECADQRU2AgxBACECDHsLQcwAIQIMYAsgA0EANgIcIAMgATYCFCADQcENNgIQIANBGjYCDEEAIQIMeQsgASAERgRAQdkAIQIMeQsgAS0AAEEgRw06IAFBAWohASADLQAuQQFxDTogA0EANgIcIAMgATYCFCADQa0bNgIQIANBHjYCDEEAIQIMeAsgASAERgRAQdgAIQIMeAsCQAJAAkACQAJAIAEtAAAiAEEKaw4EAgMDAAELIAFBAWohAUErIQIMYQsgAEE6Rw0BIANBADYCHCADIAE2AhQgA0G5ETYCECADQQo2AgxBACECDHoLIAFBAWohASADQS9qLQAAQQFxRQ1tIAMtADJBgAFxRQRAIANBMmohAiADEDRBACEAAkAgAygCOCIGRQ0AIAYoAiQiBkUNACADIAYRAAAhAAsCQAJAIAAOFkpJSAEBAQEBAQEBAQEBAQEBAQEBAQABCyADQSk2AhwgAyABNgIUIANBshg2AhAgA0EVNgIMQQAhAgx7CyADQQA2AhwgAyABNgIUIANB3Qs2AhAgA0ERNgIMQQAhAgx6C0EAIQACQCADKAI4IgJFDQAgAigCVCICRQ0AIAMgAhEAACEACyAARQ1VIABBFUcNASADQQU2AhwgAyABNgIUIANBhho2AhAgA0EVNgIMQQAhAgx5C0HKACECDF4LQQAhAiADQQA2AhwgAyABNgIUIANB4g02AhAgA0EUNgIMDHcLIAMgAy8BMkGAAXI7ATIMOAsgASAERwRAIANBEDYCCCADIAE2AgRByQAhAgxcC0HXACECDHULIAEgBEYEQEHWACECDHULAkACQAJAAkAgAS0AACIAQSByIAAgAEHBAGtB/wFxQRpJG0H/AXFB4wBrDhMAPT09PT09PT09PT09AT09PQIDPQsgAUEBaiEBQcUAIQIMXQsgAUEBaiEBQcYAIQIMXAsgAUEBaiEBQccAIQIMWwsgAUEBaiEBQcgAIQIMWgtB1QAhAiAEIAEiAEYNcyAEIAFrIAMoAgAiAWohBiAAIAFrQQVqIQcDQCABQcDGAGotAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQhBBCABQQVGDQoaIAFBAWohASAEIABBAWoiAEcNAAsgAyAGNgIADHMLQdQAIQIgBCABIgBGDXIgBCABayADKAIAIgFqIQYgACABa0EPaiEHA0AgAUGwxgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0HQQMgAUEPRg0JGiABQQFqIQEgBCAAQQFqIgBHDQALIAMgBjYCAAxyC0HTACECIAQgASIARg1xIAQgAWsgAygCACIBaiEGIAAgAWtBDmohBwNAIAFBksYAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNBiABQQ5GDQcgAUEBaiEBIAQgAEEBaiIARw0ACyADIAY2AgAMcQtB0gAhAiAEIAEiAEYNcCAEIAFrIAMoAgAiAWohBSAAIAFrQQFqIQYDQCABQZDGAGotAAAgAC0AACIHQSByIAcgB0HBAGtB/wFxQRpJG0H/AXFHDQUgAUEBRg0CIAFBAWohASAEIABBAWoiAEcNAAsgAyAFNgIADHALIAEgBEYEQEHRACECDHALAkACQCABLQAAIgBBIHIgACAAQcEAa0H/AXFBGkkbQf8BcUHuAGsOBwA2NjY2NgE2CyABQQFqIQFBwgAhAgxWCyABQQFqIQFBwwAhAgxVCyADQQA2AgAgBkEBaiEBQcQAIQIMVAtB0AAhAiAEIAEiAEYNbSAEIAFrIAMoAgAiAWohBiAAIAFrQQlqIQcDQCABQYbGAGotAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQJBAiABQQlGDQQaIAFBAWohASAEIABBAWoiAEcNAAsgAyAGNgIADG0LQc8AIQIgBCABIgBGDWwgBCABayADKAIAIgFqIQYgACABa0EFaiEHA0AgAUGAxgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBBUYNAiABQQFqIQEgBCAAQQFqIgBHDQALIAMgBjYCAAxsCyAAIQEgA0EANgIADDALQQELOgAsIANBADYCACAHQQFqIQELQSwhAgxOCwJAA0AgAS0AAEGAxABqLQAAQQFHDQEgBCABQQFqIgFHDQALQc0AIQIMaAtBwQAhAgxNCyABIARGBEBBzAAhAgxnCyABLQAAQTpGBEAgAygCBCEAIANBADYCBCADIAAgARAvIgBFDTAgA0HLADYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgxnCyADQQA2AhwgAyABNgIUIANBuRE2AhAgA0EKNgIMQQAhAgxmCwJAAkAgAy0ALEECaw4CAAEkCyADQTNqLQAAQQJxRQ0jIAMtAC5BAnENIyADQQA2AhwgAyABNgIUIANB1RM2AhAgA0ELNgIMQQAhAgxmCyADLQAyQSBxRQ0iIAMtAC5BAnENIiADQQA2AhwgAyABNgIUIANB7BI2AhAgA0EPNgIMQQAhAgxlC0EAIQACQCADKAI4IgJFDQAgAigCQCICRQ0AIAMgAhEAACEACyAARQRAQcAAIQIMSwsgAEEVRwRAIANBADYCHCADIAE2AhQgA0H4DjYCECADQRw2AgxBACECDGULIANBygA2AhwgAyABNgIUIANB8Bo2AhAgA0EVNgIMQQAhAgxkCyABIARHBEADQCABLQAAQfA/ai0AAEEBRw0XIAQgAUEBaiIBRw0AC0HEACECDGQLQcQAIQIMYwsgASAERwRAA0ACQCABLQAAIgBBIHIgACAAQcEAa0H/AXFBGkkbQf8BcSIAQQlGDQAgAEEgRg0AAkACQAJAAkAgAEHjAGsOEwADAwMDAwMDAQMDAwMDAwMDAwIDCyABQQFqIQFBNSECDE4LIAFBAWohAUE2IQIMTQsgAUEBaiEBQTchAgxMCwwVCyAEIAFBAWoiAUcNAAtBPCECDGMLQTwhAgxiCyABIARGBEBByAAhAgxiCyADQRE2AgggAyABNgIEAkACQAJAAkACQCADLQAsQQFrDgQUAAECCQsgAy0AMkEgcQ0DQdEBIQIMSwsCQCADLwEyIgBBCHFFDQAgAy0AKEEBRw0AIAMtAC5BCHFFDQILIAMgAEH3+wNxQYAEcjsBMgwLCyADIAMvATJBEHI7ATIMBAsgA0EANgIEIAMgASABEDAiAARAIANBwQA2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMYwsgAUEBaiEBDFILIANBADYCHCADIAE2AhQgA0GjEzYCECADQQQ2AgxBACECDGELQccAIQIgASAERg1gIAMoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAEHwwwBqLQAAIAEtAABBIHJHDQEgAEEGRg1GIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADGELIANBADYCAAwFCwJAIAEgBEcEQANAIAEtAABB8MEAai0AACIAQQFHBEAgAEECRw0DIAFBAWohAQwFCyAEIAFBAWoiAUcNAAtBxQAhAgxhC0HFACECDGALCyADQQA6ACwMAQtBCyECDEMLQT4hAgxCCwJAAkADQCABLQAAIgBBIEcEQAJAIABBCmsOBAMFBQMACyAAQSxGDQMMBAsgBCABQQFqIgFHDQALQcYAIQIMXQsgA0EIOgAsDA4LIAMtAChBAUcNAiADLQAuQQhxDQIgAygCBCEAIANBADYCBCADIAAgARAwIgAEQCADQcIANgIcIAMgADYCDCADIAFBAWo2AhRBACECDFwLIAFBAWohAQxKC0E6IQIMQAsCQANAIAEtAAAiAEEgRyAAQQlHcQ0BIAQgAUEBaiIBRw0AC0HDACECDFoLC0E7IQIMPgsCQAJAIAEgBEcEQANAIAEtAAAiAEEgRwRAIABBCmsOBAMEBAMECyAEIAFBAWoiAUcNAAtBPyECDFoLQT8hAgxZCyADIAMvATJBIHI7ATIMCgsgAygCBCEAIANBADYCBCADIAAgARAwIgBFDUggA0E+NgIcIAMgATYCFCADIAA2AgxBACECDFcLAkAgASAERwRAA0AgAS0AAEHwwQBqLQAAIgBBAUcEQCAAQQJGDQMMDAsgBCABQQFqIgFHDQALQTchAgxYC0E3IQIMVwsgAUEBaiEBDAQLQTshAiAEIAEiAEYNVSAEIAFrIAMoAgAiAWohBiAAIAFrQQVqIQcCQANAIAFBwMYAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNASABQQVGBEBBByEBDDsLIAFBAWohASAEIABBAWoiAEcNAAsgAyAGNgIADFYLIANBADYCACAAIQEMBQtBOiECIAQgASIARg1UIAQgAWsgAygCACIBaiEGIAAgAWtBCGohBwJAA0AgAUHkP2otAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQEgAUEIRgRAQQUhAQw6CyABQQFqIQEgBCAAQQFqIgBHDQALIAMgBjYCAAxVCyADQQA2AgAgACEBDAQLQTkhAiAEIAEiAEYNUyAEIAFrIAMoAgAiAWohBiAAIAFrQQNqIQcCQANAIAFB4D9qLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBA0YEQEEGIQEMOQsgAUEBaiEBIAQgAEEBaiIARw0ACyADIAY2AgAMVAsgA0EANgIAIAAhAQwDCwJAA0AgAS0AACIAQSBHBEAgAEEKaw4EBwQEBwILIAQgAUEBaiIBRw0AC0E4IQIMUwsgAEEsRw0BIAFBAWohAEEBIQECQAJAAkACQAJAIAMtACxBBWsOBAMBAgQACyAAIQEMBAtBAiEBDAELQQQhAQsgA0EBOgAsIAMgAy8BMiABcjsBMiAAIQEMAQsgAyADLwEyQQhyOwEyIAAhAQtBPSECDDcLIANBADoALAtBOCECDDULIAEgBEYEQEE2IQIMTwsCQAJAAkACQAJAIAEtAABBCmsOBAACAgECCyADKAIEIQAgA0EANgIEIAMgACABEDAiAEUNAiADQTM2AhwgAyABNgIUIAMgADYCDEEAIQIMUgsgAygCBCEAIANBADYCBCADIAAgARAwIgBFBEAgAUEBaiEBDAYLIANBMjYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgxRCyADLQAuQQFxBEBB0AEhAgw3CyADKAIEIQAgA0EANgIEIAMgACABEDAiAA0BDEMLQTMhAgw1CyADQTU2AhwgAyABNgIUIAMgADYCDEEAIQIMTgtBNCECDDMLIANBL2otAABBAXENACADQQA2AhwgAyABNgIUIANB8RU2AhAgA0EZNgIMQQAhAgxMC0EyIQIMMQsgASAERgRAQTIhAgxLCwJAIAEtAABBCkYEQCABQQFqIQEMAQsgA0EANgIcIAMgATYCFCADQZgWNgIQIANBAzYCDEEAIQIMSwtBMSECDDALIAEgBEYEQEExIQIMSgsgAS0AACIAQQlHIABBIEdxDQEgAy0ALEEIRw0AIANBADoALAtBPCECDC4LQQEhAgJAAkACQAJAIAMtACxBBWsOBAMBAgAKCyADIAMvATJBCHI7ATIMCQtBAiECDAELQQQhAgsgA0EBOgAsIAMgAy8BMiACcjsBMgwGCyABIARGBEBBMCECDEcLIAEtAABBCkYEQCABQQFqIQEMAQsgAy0ALkEBcQ0AIANBADYCHCADIAE2AhQgA0HHJzYCECADQQI2AgxBACECDEYLQS8hAgwrCyABQQFqIQFBMCECDCoLIAEgBEYEQEEvIQIMRAsgAS0AACIAQQlHIABBIEdxRQRAIAFBAWohASADLQAuQQFxDQEgA0EANgIcIAMgATYCFCADQekPNgIQIANBCjYCDEEAIQIMRAtBASECAkACQAJAAkACQAJAIAMtACxBAmsOBwUEBAMBAgAECyADIAMvATJBCHI7ATIMAwtBAiECDAELQQQhAgsgA0EBOgAsIAMgAy8BMiACcjsBMgtBLiECDCoLIANBADYCHCADIAE2AhQgA0GzEjYCECADQQs2AgxBACECDEMLQdIBIQIMKAsgASAERgRAQS4hAgxCCyADQQA2AgQgA0ERNgIIIAMgASABEDAiAA0BC0EtIQIMJgsgA0EtNgIcIAMgATYCFCADIAA2AgxBACECDD8LQQAhAAJAIAMoAjgiAkUNACACKAJEIgJFDQAgAyACEQAAIQALIABFDQAgAEEVRw0BIANB2AA2AhwgAyABNgIUIANBnho2AhAgA0EVNgIMQQAhAgw+C0HLACECDCMLIANBADYCHCADIAE2AhQgA0GFDjYCECADQR02AgxBACECDDwLIAEgBEYEQEHOACECDDwLIAEtAAAiAEEgRg0CIABBOkYNAQsgA0EAOgAsQQkhAgwgCyADKAIEIQAgA0EANgIEIAMgACABEC8iAA0BDAILIAMtAC5BAXEEQEHPASECDB8LIAMoAgQhACADQQA2AgQgAyAAIAEQLyIARQ0CIANBKjYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgw4CyADQcsANgIcIAMgADYCDCADIAFBAWo2AhRBACECDDcLIAFBAWohAUE/IQIMHAsgAUEBaiEBDCkLIAEgBEYEQEErIQIMNQsCQCABLQAAQQpGBEAgAUEBaiEBDAELIAMtAC5BwABxRQ0GCyADLQAyQYABcQRAQQAhAAJAIAMoAjgiAkUNACACKAJUIgJFDQAgAyACEQAAIQALIABFDREgAEEVRgRAIANBBTYCHCADIAE2AhQgA0GGGjYCECADQRU2AgxBACECDDYLIANBADYCHCADIAE2AhQgA0HiDTYCECADQRQ2AgxBACECDDULIANBMmohAiADEDRBACEAAkAgAygCOCIGRQ0AIAYoAiQiBkUNACADIAYRAAAhAAsgAA4WAgEABAQEBAQEBAQEBAQEBAQEBAQEAwQLIANBAToAMAsgAiACLwEAQcAAcjsBAAtBKiECDBcLIANBKTYCHCADIAE2AhQgA0GyGDYCECADQRU2AgxBACECDDALIANBADYCHCADIAE2AhQgA0HdCzYCECADQRE2AgxBACECDC8LIANBADYCHCADIAE2AhQgA0GdCzYCECADQQI2AgxBACECDC4LQQEhByADLwEyIgVBCHFFBEAgAykDIEIAUiEHCwJAIAMtADAEQEEBIQAgAy0AKUEFRg0BIAVBwABxRSAHcUUNAQsCQCADLQAoIgJBAkYEQEEBIQAgAy8BNCIGQeUARg0CQQAhACAFQcAAcQ0CIAZB5ABGDQIgBkHmAGtBAkkNAiAGQcwBRg0CIAZBsAJGDQIMAQtBACEAIAVBwABxDQELQQIhACAFQQhxDQAgBUGABHEEQAJAIAJBAUcNACADLQAuQQpxDQBBBSEADAILQQQhAAwBCyAFQSBxRQRAIAMQNUEAR0ECdCEADAELQQBBAyADKQMgUBshAAsCQCAAQQFrDgUAAQYHAgMLQQAhAgJAIAMoAjgiAEUNACAAKAIsIgBFDQAgAyAAEQAAIQILIAJFDSYgAkEVRgRAIANBAzYCHCADIAE2AhQgA0G9GjYCECADQRU2AgxBACECDC4LQQAhAiADQQA2AhwgAyABNgIUIANBrw42AhAgA0ESNgIMDC0LQc4BIQIMEgtBACECIANBADYCHCADIAE2AhQgA0HkHzYCECADQQ82AgwMKwtBACEAAkAgAygCOCICRQ0AIAIoAiwiAkUNACADIAIRAAAhAAsgAA0BC0EOIQIMDwsgAEEVRgRAIANBAjYCHCADIAE2AhQgA0G9GjYCECADQRU2AgxBACECDCkLQQAhAiADQQA2AhwgAyABNgIUIANBrw42AhAgA0ESNgIMDCgLQSkhAgwNCyADQQE6ADEMJAsgASAERwRAIANBCTYCCCADIAE2AgRBKCECDAwLQSYhAgwlCyADIAMpAyAiDCAEIAFrrSIKfSILQgAgCyAMWBs3AyAgCiAMVARAQSUhAgwlCyADKAIEIQBBACECIANBADYCBCADIAAgASAMp2oiARAxIgBFDQAgA0EFNgIcIAMgATYCFCADIAA2AgwMJAtBDyECDAkLIAEgBEYEQEEjIQIMIwtCACEKAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAEtAABBMGsONxcWAAECAwQFBgcUFBQUFBQUCAkKCwwNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQODxAREhMUC0ICIQoMFgtCAyEKDBULQgQhCgwUC0IFIQoMEwtCBiEKDBILQgchCgwRC0IIIQoMEAtCCSEKDA8LQgohCgwOC0ILIQoMDQtCDCEKDAwLQg0hCgwLC0IOIQoMCgtCDyEKDAkLQgohCgwIC0ILIQoMBwtCDCEKDAYLQg0hCgwFC0IOIQoMBAtCDyEKDAMLQQAhAiADQQA2AhwgAyABNgIUIANBzhQ2AhAgA0EMNgIMDCILIAEgBEYEQEEiIQIMIgtCACEKAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCABLQAAQTBrDjcVFAABAgMEBQYHFhYWFhYWFggJCgsMDRYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWDg8QERITFgtCAiEKDBQLQgMhCgwTC0IEIQoMEgtCBSEKDBELQgYhCgwQC0IHIQoMDwtCCCEKDA4LQgkhCgwNC0IKIQoMDAtCCyEKDAsLQgwhCgwKC0INIQoMCQtCDiEKDAgLQg8hCgwHC0IKIQoMBgtCCyEKDAULQgwhCgwEC0INIQoMAwtCDiEKDAILQg8hCgwBC0IBIQoLIAFBAWohASADKQMgIgtC//////////8PWARAIAMgC0IEhiAKhDcDIAwCC0EAIQIgA0EANgIcIAMgATYCFCADQa0JNgIQIANBDDYCDAwfC0ElIQIMBAtBJiECDAMLIAMgAToALCADQQA2AgAgB0EBaiEBQQwhAgwCCyADQQA2AgAgBkEBaiEBQQohAgwBCyABQQFqIQFBCCECDAALAAtBACECIANBADYCHCADIAE2AhQgA0HVEDYCECADQQk2AgwMGAtBACECIANBADYCHCADIAE2AhQgA0HXCjYCECADQQk2AgwMFwtBACECIANBADYCHCADIAE2AhQgA0G/EDYCECADQQk2AgwMFgtBACECIANBADYCHCADIAE2AhQgA0GkETYCECADQQk2AgwMFQtBACECIANBADYCHCADIAE2AhQgA0HVEDYCECADQQk2AgwMFAtBACECIANBADYCHCADIAE2AhQgA0HXCjYCECADQQk2AgwMEwtBACECIANBADYCHCADIAE2AhQgA0G/EDYCECADQQk2AgwMEgtBACECIANBADYCHCADIAE2AhQgA0GkETYCECADQQk2AgwMEQtBACECIANBADYCHCADIAE2AhQgA0G/FjYCECADQQ82AgwMEAtBACECIANBADYCHCADIAE2AhQgA0G/FjYCECADQQ82AgwMDwtBACECIANBADYCHCADIAE2AhQgA0HIEjYCECADQQs2AgwMDgtBACECIANBADYCHCADIAE2AhQgA0GVCTYCECADQQs2AgwMDQtBACECIANBADYCHCADIAE2AhQgA0HpDzYCECADQQo2AgwMDAtBACECIANBADYCHCADIAE2AhQgA0GDEDYCECADQQo2AgwMCwtBACECIANBADYCHCADIAE2AhQgA0GmHDYCECADQQI2AgwMCgtBACECIANBADYCHCADIAE2AhQgA0HFFTYCECADQQI2AgwMCQtBACECIANBADYCHCADIAE2AhQgA0H/FzYCECADQQI2AgwMCAtBACECIANBADYCHCADIAE2AhQgA0HKFzYCECADQQI2AgwMBwsgA0ECNgIcIAMgATYCFCADQZQdNgIQIANBFjYCDEEAIQIMBgtB3gAhAiABIARGDQUgCUEIaiEHIAMoAgAhBQJAAkAgASAERwRAIAVBxsYAaiEIIAQgBWogAWshBiAFQX9zQQpqIgUgAWohAANAIAEtAAAgCC0AAEcEQEECIQgMAwsgBUUEQEEAIQggACEBDAMLIAVBAWshBSAIQQFqIQggBCABQQFqIgFHDQALIAYhBSAEIQELIAdBATYCACADIAU2AgAMAQsgA0EANgIAIAcgCDYCAAsgByABNgIEIAkoAgwhACAJKAIIDgMBBQIACwALIANBADYCHCADQa0dNgIQIANBFzYCDCADIABBAWo2AhRBACECDAMLIANBADYCHCADIAA2AhQgA0HCHTYCECADQQk2AgxBACECDAILIAEgBEYEQEEoIQIMAgsgA0EJNgIIIAMgATYCBEEnIQIMAQsgASAERgRAQQEhAgwBCwNAAkACQAJAIAEtAABBCmsOBAABAQABCyABQQFqIQEMAQsgAUEBaiEBIAMtAC5BIHENAEEAIQIgA0EANgIcIAMgATYCFCADQYwgNgIQIANBBTYCDAwCC0EBIQIgASAERw0ACwsgCUEQaiQAIAJFBEAgAygCDCEADAELIAMgAjYCHEEAIQAgAygCBCIBRQ0AIAMgASAEIAMoAggRAQAiAUUNACADIAQ2AhQgAyABNgIMIAEhAAsgAAu+AgECfyAAQQA6AAAgAEHcAGoiAUEBa0EAOgAAIABBADoAAiAAQQA6AAEgAUEDa0EAOgAAIAFBAmtBADoAACAAQQA6AAMgAUEEa0EAOgAAQQAgAGtBA3EiASAAaiIAQQA2AgBB3AAgAWtBfHEiAiAAaiIBQQRrQQA2AgACQCACQQlJDQAgAEEANgIIIABBADYCBCABQQhrQQA2AgAgAUEMa0EANgIAIAJBGUkNACAAQQA2AhggAEEANgIUIABBADYCECAAQQA2AgwgAUEQa0EANgIAIAFBFGtBADYCACABQRhrQQA2AgAgAUEca0EANgIAIAIgAEEEcUEYciICayIBQSBJDQAgACACaiEAA0AgAEIANwMYIABCADcDECAAQgA3AwggAEIANwMAIABBIGohACABQSBrIgFBH0sNAAsLC1YBAX8CQCAAKAIMDQACQAJAAkACQCAALQAxDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgAREAACIBDQMLQQAPCwALIABB0Bg2AhBBDiEBCyABCxoAIAAoAgxFBEAgAEHJHjYCECAAQRU2AgwLCxQAIAAoAgxBFUYEQCAAQQA2AgwLCxQAIAAoAgxBFkYEQCAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsXACAAQSRPBEAACyAAQQJ0QZQ3aigCAAsXACAAQS9PBEAACyAAQQJ0QaQ4aigCAAu/CQEBf0HfLCEBAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEHkAGsO9ANjYgABYWFhYWFhAgMEBWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEGBwgJCgsMDQ4PYWFhYWEQYWFhYWFhYWFhYWERYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhEhMUFRYXGBkaG2FhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEcHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTZhNzg5OmFhYWFhYWFhO2FhYTxhYWFhPT4/YWFhYWFhYWFAYWFBYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhQkNERUZHSElKS0xNTk9QUVJTYWFhYWFhYWFUVVZXWFlaW2FcXWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYV5hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFfYGELQdUrDwtBgyUPC0G/MA8LQfI1DwtBtCgPC0GfKA8LQYEsDwtB1ioPC0H0Mw8LQa0zDwtByygPC0HOIw8LQcAjDwtB2SMPC0HRJA8LQZwzDwtBojYPC0H8Mw8LQeArDwtB4SUPC0HtIA8LQcQyDwtBqScPC0G5Ng8LQbggDwtBqyAPC0GjJA8LQbYkDwtBgSMPC0HhMg8LQZ80DwtByCkPC0HAMg8LQe4yDwtB8C8PC0HGNA8LQdAhDwtBmiQPC0HrLw8LQYQ1DwtByzUPC0GWMQ8LQcgrDwtB1C8PC0GTMA8LQd81DwtBtCMPC0G+NQ8LQdIpDwtBsyIPC0HNIA8LQZs2DwtBkCEPC0H/IA8LQa01DwtBsDQPC0HxJA8LQacqDwtB3TAPC0GLIg8LQcgvDwtB6yoPC0H0KQ8LQY8lDwtB3SIPC0HsJg8LQf0wDwtB1iYPC0GUNQ8LQY0jDwtBuikPC0HHIg8LQfIlDwtBtjMPC0GiIQ8LQf8vDwtBwCEPC0GBMw8LQcklDwtBqDEPC0HGMw8LQdM2DwtBxjYPC0HkNA8LQYgmDwtB7ScPC0H4IQ8LQakwDwtBjzQPC0GGNg8LQaovDwtBoSYPC0HsNg8LQZIpDwtBryYPC0GZIg8LQeAhDwsAC0G1JSEBCyABCxcAIAAgAC8BLkH+/wNxIAFBAEdyOwEuCxoAIAAgAC8BLkH9/wNxIAFBAEdBAXRyOwEuCxoAIAAgAC8BLkH7/wNxIAFBAEdBAnRyOwEuCxoAIAAgAC8BLkH3/wNxIAFBAEdBA3RyOwEuCxoAIAAgAC8BLkHv/wNxIAFBAEdBBHRyOwEuCxoAIAAgAC8BLkHf/wNxIAFBAEdBBXRyOwEuCxoAIAAgAC8BLkG//wNxIAFBAEdBBnRyOwEuCxoAIAAgAC8BLkH//gNxIAFBAEdBB3RyOwEuCxoAIAAgAC8BLkH//QNxIAFBAEdBCHRyOwEuCxoAIAAgAC8BLkH/+wNxIAFBAEdBCXRyOwEuCz4BAn8CQCAAKAI4IgNFDQAgAygCBCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBzhE2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCCCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB5Ao2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCDCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB5R02AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCECIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBnRA2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCFCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBoh42AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCGCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB7hQ2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCKCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB9gg2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCHCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB9xs2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCICIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBlRU2AhBBGCEECyAECzgAIAACfyAALwEyQRRxQRRGBEBBASAALQAoQQFGDQEaIAAvATRB5QBGDAELIAAtAClBBUYLOgAwC1kBAn8CQCAALQAoQQFGDQAgAC8BNCIBQeQAa0HkAEkNACABQcwBRg0AIAFBsAJGDQAgAC8BMiIAQcAAcQ0AQQEhAiAAQYgEcUGABEYNACAAQShxRSECCyACC4wBAQJ/AkACQAJAIAAtACpFDQAgAC0AK0UNACAALwEyIgFBAnFFDQEMAgsgAC8BMiIBQQFxRQ0BC0EBIQIgAC0AKEEBRg0AIAAvATQiAEHkAGtB5ABJDQAgAEHMAUYNACAAQbACRg0AIAFBwABxDQBBACECIAFBiARxQYAERg0AIAFBKHFBAEchAgsgAgtzACAAQRBq/QwAAAAAAAAAAAAAAAAAAAAA/QsDACAA/QwAAAAAAAAAAAAAAAAAAAAA/QsDACAAQTBq/QwAAAAAAAAAAAAAAAAAAAAA/QsDACAAQSBq/QwAAAAAAAAAAAAAAAAAAAAA/QsDACAAQewBNgIcCwYAIAAQOQuaLQELfyMAQRBrIgokAEGY1AAoAgAiCUUEQEHY1wAoAgAiBUUEQEHk1wBCfzcCAEHc1wBCgICEgICAwAA3AgBB2NcAIApBCGpBcHFB2KrVqgVzIgU2AgBB7NcAQQA2AgBBvNcAQQA2AgALQcDXAEGA2AQ2AgBBkNQAQYDYBDYCAEGk1AAgBTYCAEGg1ABBfzYCAEHE1wBBgKgDNgIAA0AgAUG81ABqIAFBsNQAaiICNgIAIAIgAUGo1ABqIgM2AgAgAUG01ABqIAM2AgAgAUHE1ABqIAFBuNQAaiIDNgIAIAMgAjYCACABQczUAGogAUHA1ABqIgI2AgAgAiADNgIAIAFByNQAaiACNgIAIAFBIGoiAUGAAkcNAAtBjNgEQcGnAzYCAEGc1ABB6NcAKAIANgIAQYzUAEHApwM2AgBBmNQAQYjYBDYCAEHM/wdBODYCAEGI2AQhCQsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAAQewBTQRAQYDUACgCACIGQRAgAEETakFwcSAAQQtJGyIEQQN2IgB2IgFBA3EEQAJAIAFBAXEgAHJBAXMiAkEDdCIAQajUAGoiASAAQbDUAGooAgAiACgCCCIDRgRAQYDUACAGQX4gAndxNgIADAELIAEgAzYCCCADIAE2AgwLIABBCGohASAAIAJBA3QiAkEDcjYCBCAAIAJqIgAgACgCBEEBcjYCBAwRC0GI1AAoAgAiCCAETw0BIAEEQAJAQQIgAHQiAkEAIAJrciABIAB0cWgiAEEDdCICQajUAGoiASACQbDUAGooAgAiAigCCCIDRgRAQYDUACAGQX4gAHdxIgY2AgAMAQsgASADNgIIIAMgATYCDAsgAiAEQQNyNgIEIABBA3QiACAEayEFIAAgAmogBTYCACACIARqIgQgBUEBcjYCBCAIBEAgCEF4cUGo1ABqIQBBlNQAKAIAIQMCf0EBIAhBA3Z0IgEgBnFFBEBBgNQAIAEgBnI2AgAgAAwBCyAAKAIICyIBIAM2AgwgACADNgIIIAMgADYCDCADIAE2AggLIAJBCGohAUGU1AAgBDYCAEGI1AAgBTYCAAwRC0GE1AAoAgAiC0UNASALaEECdEGw1gBqKAIAIgAoAgRBeHEgBGshBSAAIQIDQAJAIAIoAhAiAUUEQCACQRRqKAIAIgFFDQELIAEoAgRBeHEgBGsiAyAFSSECIAMgBSACGyEFIAEgACACGyEAIAEhAgwBCwsgACgCGCEJIAAoAgwiAyAARwRAQZDUACgCABogAyAAKAIIIgE2AgggASADNgIMDBALIABBFGoiAigCACIBRQRAIAAoAhAiAUUNAyAAQRBqIQILA0AgAiEHIAEiA0EUaiICKAIAIgENACADQRBqIQIgAygCECIBDQALIAdBADYCAAwPC0F/IQQgAEG/f0sNACAAQRNqIgFBcHEhBEGE1AAoAgAiCEUNAEEAIARrIQUCQAJAAkACf0EAIARBgAJJDQAaQR8gBEH///8HSw0AGiAEQSYgAUEIdmciAGt2QQFxIABBAXRrQT5qCyIGQQJ0QbDWAGooAgAiAkUEQEEAIQFBACEDDAELQQAhASAEQRkgBkEBdmtBACAGQR9HG3QhAEEAIQMDQAJAIAIoAgRBeHEgBGsiByAFTw0AIAIhAyAHIgUNAEEAIQUgAiEBDAMLIAEgAkEUaigCACIHIAcgAiAAQR12QQRxakEQaigCACICRhsgASAHGyEBIABBAXQhACACDQALCyABIANyRQRAQQAhA0ECIAZ0IgBBACAAa3IgCHEiAEUNAyAAaEECdEGw1gBqKAIAIQELIAFFDQELA0AgASgCBEF4cSAEayICIAVJIQAgAiAFIAAbIQUgASADIAAbIQMgASgCECIABH8gAAUgAUEUaigCAAsiAQ0ACwsgA0UNACAFQYjUACgCACAEa08NACADKAIYIQcgAyADKAIMIgBHBEBBkNQAKAIAGiAAIAMoAggiATYCCCABIAA2AgwMDgsgA0EUaiICKAIAIgFFBEAgAygCECIBRQ0DIANBEGohAgsDQCACIQYgASIAQRRqIgIoAgAiAQ0AIABBEGohAiAAKAIQIgENAAsgBkEANgIADA0LQYjUACgCACIDIARPBEBBlNQAKAIAIQECQCADIARrIgJBEE8EQCABIARqIgAgAkEBcjYCBCABIANqIAI2AgAgASAEQQNyNgIEDAELIAEgA0EDcjYCBCABIANqIgAgACgCBEEBcjYCBEEAIQBBACECC0GI1AAgAjYCAEGU1AAgADYCACABQQhqIQEMDwtBjNQAKAIAIgMgBEsEQCAEIAlqIgAgAyAEayIBQQFyNgIEQZjUACAANgIAQYzUACABNgIAIAkgBEEDcjYCBCAJQQhqIQEMDwtBACEBIAQCf0HY1wAoAgAEQEHg1wAoAgAMAQtB5NcAQn83AgBB3NcAQoCAhICAgMAANwIAQdjXACAKQQxqQXBxQdiq1aoFczYCAEHs1wBBADYCAEG81wBBADYCAEGAgAQLIgAgBEHHAGoiBWoiBkEAIABrIgdxIgJPBEBB8NcAQTA2AgAMDwsCQEG41wAoAgAiAUUNAEGw1wAoAgAiCCACaiEAIAAgAU0gACAIS3ENAEEAIQFB8NcAQTA2AgAMDwtBvNcALQAAQQRxDQQCQAJAIAkEQEHA1wAhAQNAIAEoAgAiACAJTQRAIAAgASgCBGogCUsNAwsgASgCCCIBDQALC0EAEDoiAEF/Rg0FIAIhBkHc1wAoAgAiAUEBayIDIABxBEAgAiAAayAAIANqQQAgAWtxaiEGCyAEIAZPDQUgBkH+////B0sNBUG41wAoAgAiAwRAQbDXACgCACIHIAZqIQEgASAHTQ0GIAEgA0sNBgsgBhA6IgEgAEcNAQwHCyAGIANrIAdxIgZB/v///wdLDQQgBhA6IQAgACABKAIAIAEoAgRqRg0DIAAhAQsCQCAGIARByABqTw0AIAFBf0YNAEHg1wAoAgAiACAFIAZrakEAIABrcSIAQf7///8HSwRAIAEhAAwHCyAAEDpBf0cEQCAAIAZqIQYgASEADAcLQQAgBmsQOhoMBAsgASIAQX9HDQUMAwtBACEDDAwLQQAhAAwKCyAAQX9HDQILQbzXAEG81wAoAgBBBHI2AgALIAJB/v///wdLDQEgAhA6IQBBABA6IQEgAEF/Rg0BIAFBf0YNASAAIAFPDQEgASAAayIGIARBOGpNDQELQbDXAEGw1wAoAgAgBmoiATYCAEG01wAoAgAgAUkEQEG01wAgATYCAAsCQAJAAkBBmNQAKAIAIgIEQEHA1wAhAQNAIAAgASgCACIDIAEoAgQiBWpGDQIgASgCCCIBDQALDAILQZDUACgCACIBQQBHIAAgAU9xRQRAQZDUACAANgIAC0EAIQFBxNcAIAY2AgBBwNcAIAA2AgBBoNQAQX82AgBBpNQAQdjXACgCADYCAEHM1wBBADYCAANAIAFBvNQAaiABQbDUAGoiAjYCACACIAFBqNQAaiIDNgIAIAFBtNQAaiADNgIAIAFBxNQAaiABQbjUAGoiAzYCACADIAI2AgAgAUHM1ABqIAFBwNQAaiICNgIAIAIgAzYCACABQcjUAGogAjYCACABQSBqIgFBgAJHDQALQXggAGtBD3EiASAAaiICIAZBOGsiAyABayIBQQFyNgIEQZzUAEHo1wAoAgA2AgBBjNQAIAE2AgBBmNQAIAI2AgAgACADakE4NgIEDAILIAAgAk0NACACIANJDQAgASgCDEEIcQ0AQXggAmtBD3EiACACaiIDQYzUACgCACAGaiIHIABrIgBBAXI2AgQgASAFIAZqNgIEQZzUAEHo1wAoAgA2AgBBjNQAIAA2AgBBmNQAIAM2AgAgAiAHakE4NgIEDAELIABBkNQAKAIASQRAQZDUACAANgIACyAAIAZqIQNBwNcAIQECQAJAAkADQCADIAEoAgBHBEAgASgCCCIBDQEMAgsLIAEtAAxBCHFFDQELQcDXACEBA0AgASgCACIDIAJNBEAgAyABKAIEaiIFIAJLDQMLIAEoAgghAQwACwALIAEgADYCACABIAEoAgQgBmo2AgQgAEF4IABrQQ9xaiIJIARBA3I2AgQgA0F4IANrQQ9xaiIGIAQgCWoiBGshASACIAZGBEBBmNQAIAQ2AgBBjNQAQYzUACgCACABaiIANgIAIAQgAEEBcjYCBAwIC0GU1AAoAgAgBkYEQEGU1AAgBDYCAEGI1ABBiNQAKAIAIAFqIgA2AgAgBCAAQQFyNgIEIAAgBGogADYCAAwICyAGKAIEIgVBA3FBAUcNBiAFQXhxIQggBUH/AU0EQCAFQQN2IQMgBigCCCIAIAYoAgwiAkYEQEGA1ABBgNQAKAIAQX4gA3dxNgIADAcLIAIgADYCCCAAIAI2AgwMBgsgBigCGCEHIAYgBigCDCIARwRAIAAgBigCCCICNgIIIAIgADYCDAwFCyAGQRRqIgIoAgAiBUUEQCAGKAIQIgVFDQQgBkEQaiECCwNAIAIhAyAFIgBBFGoiAigCACIFDQAgAEEQaiECIAAoAhAiBQ0ACyADQQA2AgAMBAtBeCAAa0EPcSIBIABqIgcgBkE4ayIDIAFrIgFBAXI2AgQgACADakE4NgIEIAIgBUE3IAVrQQ9xakE/ayIDIAMgAkEQakkbIgNBIzYCBEGc1ABB6NcAKAIANgIAQYzUACABNgIAQZjUACAHNgIAIANBEGpByNcAKQIANwIAIANBwNcAKQIANwIIQcjXACADQQhqNgIAQcTXACAGNgIAQcDXACAANgIAQczXAEEANgIAIANBJGohAQNAIAFBBzYCACAFIAFBBGoiAUsNAAsgAiADRg0AIAMgAygCBEF+cTYCBCADIAMgAmsiBTYCACACIAVBAXI2AgQgBUH/AU0EQCAFQXhxQajUAGohAAJ/QYDUACgCACIBQQEgBUEDdnQiA3FFBEBBgNQAIAEgA3I2AgAgAAwBCyAAKAIICyIBIAI2AgwgACACNgIIIAIgADYCDCACIAE2AggMAQtBHyEBIAVB////B00EQCAFQSYgBUEIdmciAGt2QQFxIABBAXRrQT5qIQELIAIgATYCHCACQgA3AhAgAUECdEGw1gBqIQBBhNQAKAIAIgNBASABdCIGcUUEQCAAIAI2AgBBhNQAIAMgBnI2AgAgAiAANgIYIAIgAjYCCCACIAI2AgwMAQsgBUEZIAFBAXZrQQAgAUEfRxt0IQEgACgCACEDAkADQCADIgAoAgRBeHEgBUYNASABQR12IQMgAUEBdCEBIAAgA0EEcWpBEGoiBigCACIDDQALIAYgAjYCACACIAA2AhggAiACNgIMIAIgAjYCCAwBCyAAKAIIIgEgAjYCDCAAIAI2AgggAkEANgIYIAIgADYCDCACIAE2AggLQYzUACgCACIBIARNDQBBmNQAKAIAIgAgBGoiAiABIARrIgFBAXI2AgRBjNQAIAE2AgBBmNQAIAI2AgAgACAEQQNyNgIEIABBCGohAQwIC0EAIQFB8NcAQTA2AgAMBwtBACEACyAHRQ0AAkAgBigCHCICQQJ0QbDWAGoiAygCACAGRgRAIAMgADYCACAADQFBhNQAQYTUACgCAEF+IAJ3cTYCAAwCCyAHQRBBFCAHKAIQIAZGG2ogADYCACAARQ0BCyAAIAc2AhggBigCECICBEAgACACNgIQIAIgADYCGAsgBkEUaigCACICRQ0AIABBFGogAjYCACACIAA2AhgLIAEgCGohASAGIAhqIgYoAgQhBQsgBiAFQX5xNgIEIAEgBGogATYCACAEIAFBAXI2AgQgAUH/AU0EQCABQXhxQajUAGohAAJ/QYDUACgCACICQQEgAUEDdnQiAXFFBEBBgNQAIAEgAnI2AgAgAAwBCyAAKAIICyIBIAQ2AgwgACAENgIIIAQgADYCDCAEIAE2AggMAQtBHyEFIAFB////B00EQCABQSYgAUEIdmciAGt2QQFxIABBAXRrQT5qIQULIAQgBTYCHCAEQgA3AhAgBUECdEGw1gBqIQBBhNQAKAIAIgJBASAFdCIDcUUEQCAAIAQ2AgBBhNQAIAIgA3I2AgAgBCAANgIYIAQgBDYCCCAEIAQ2AgwMAQsgAUEZIAVBAXZrQQAgBUEfRxt0IQUgACgCACEAAkADQCAAIgIoAgRBeHEgAUYNASAFQR12IQAgBUEBdCEFIAIgAEEEcWpBEGoiAygCACIADQALIAMgBDYCACAEIAI2AhggBCAENgIMIAQgBDYCCAwBCyACKAIIIgAgBDYCDCACIAQ2AgggBEEANgIYIAQgAjYCDCAEIAA2AggLIAlBCGohAQwCCwJAIAdFDQACQCADKAIcIgFBAnRBsNYAaiICKAIAIANGBEAgAiAANgIAIAANAUGE1AAgCEF+IAF3cSIINgIADAILIAdBEEEUIAcoAhAgA0YbaiAANgIAIABFDQELIAAgBzYCGCADKAIQIgEEQCAAIAE2AhAgASAANgIYCyADQRRqKAIAIgFFDQAgAEEUaiABNgIAIAEgADYCGAsCQCAFQQ9NBEAgAyAEIAVqIgBBA3I2AgQgACADaiIAIAAoAgRBAXI2AgQMAQsgAyAEaiICIAVBAXI2AgQgAyAEQQNyNgIEIAIgBWogBTYCACAFQf8BTQRAIAVBeHFBqNQAaiEAAn9BgNQAKAIAIgFBASAFQQN2dCIFcUUEQEGA1AAgASAFcjYCACAADAELIAAoAggLIgEgAjYCDCAAIAI2AgggAiAANgIMIAIgATYCCAwBC0EfIQEgBUH///8HTQRAIAVBJiAFQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAQsgAiABNgIcIAJCADcCECABQQJ0QbDWAGohAEEBIAF0IgQgCHFFBEAgACACNgIAQYTUACAEIAhyNgIAIAIgADYCGCACIAI2AgggAiACNgIMDAELIAVBGSABQQF2a0EAIAFBH0cbdCEBIAAoAgAhBAJAA0AgBCIAKAIEQXhxIAVGDQEgAUEddiEEIAFBAXQhASAAIARBBHFqQRBqIgYoAgAiBA0ACyAGIAI2AgAgAiAANgIYIAIgAjYCDCACIAI2AggMAQsgACgCCCIBIAI2AgwgACACNgIIIAJBADYCGCACIAA2AgwgAiABNgIICyADQQhqIQEMAQsCQCAJRQ0AAkAgACgCHCIBQQJ0QbDWAGoiAigCACAARgRAIAIgAzYCACADDQFBhNQAIAtBfiABd3E2AgAMAgsgCUEQQRQgCSgCECAARhtqIAM2AgAgA0UNAQsgAyAJNgIYIAAoAhAiAQRAIAMgATYCECABIAM2AhgLIABBFGooAgAiAUUNACADQRRqIAE2AgAgASADNgIYCwJAIAVBD00EQCAAIAQgBWoiAUEDcjYCBCAAIAFqIgEgASgCBEEBcjYCBAwBCyAAIARqIgcgBUEBcjYCBCAAIARBA3I2AgQgBSAHaiAFNgIAIAgEQCAIQXhxQajUAGohAUGU1AAoAgAhAwJ/QQEgCEEDdnQiAiAGcUUEQEGA1AAgAiAGcjYCACABDAELIAEoAggLIgIgAzYCDCABIAM2AgggAyABNgIMIAMgAjYCCAtBlNQAIAc2AgBBiNQAIAU2AgALIABBCGohAQsgCkEQaiQAIAELQwAgAEUEQD8AQRB0DwsCQCAAQf//A3ENACAAQQBIDQAgAEEQdkAAIgBBf0YEQEHw1wBBMDYCAEF/DwsgAEEQdA8LAAsL20AiAEGACAsJAQAAAAIAAAADAEGUCAsFBAAAAAUAQaQICwkGAAAABwAAAAgAQdwIC4IxSW52YWxpZCBjaGFyIGluIHVybCBxdWVyeQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2JvZHkAQ29udGVudC1MZW5ndGggb3ZlcmZsb3cAQ2h1bmsgc2l6ZSBvdmVyZmxvdwBJbnZhbGlkIG1ldGhvZCBmb3IgSFRUUC94LnggcmVxdWVzdABJbnZhbGlkIG1ldGhvZCBmb3IgUlRTUC94LnggcmVxdWVzdABFeHBlY3RlZCBTT1VSQ0UgbWV0aG9kIGZvciBJQ0UveC54IHJlcXVlc3QASW52YWxpZCBjaGFyIGluIHVybCBmcmFnbWVudCBzdGFydABFeHBlY3RlZCBkb3QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9zdGF0dXMASW52YWxpZCByZXNwb25zZSBzdGF0dXMARXhwZWN0ZWQgTEYgYWZ0ZXIgaGVhZGVycwBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zAFVzZXIgY2FsbGJhY2sgZXJyb3IAYG9uX3Jlc2V0YCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfaGVhZGVyYCBjYWxsYmFjayBlcnJvcgBgb25fbWVzc2FnZV9iZWdpbmAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3N0YXR1c19jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3ZlcnNpb25fY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl91cmxfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2hlYWRlcl92YWx1ZV9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX21lc3NhZ2VfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXRob2RfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9oZWFkZXJfZmllbGRfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19leHRlbnNpb25fbmFtZWAgY2FsbGJhY2sgZXJyb3IAVW5leHBlY3RlZCBjaGFyIGluIHVybCBzZXJ2ZXIASW52YWxpZCBoZWFkZXIgdmFsdWUgY2hhcgBJbnZhbGlkIGhlYWRlciBmaWVsZCBjaGFyAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fdmVyc2lvbgBJbnZhbGlkIG1pbm9yIHZlcnNpb24ASW52YWxpZCBtYWpvciB2ZXJzaW9uAEV4cGVjdGVkIHNwYWNlIGFmdGVyIHZlcnNpb24ARXhwZWN0ZWQgQ1JMRiBhZnRlciB2ZXJzaW9uAEludmFsaWQgSFRUUCB2ZXJzaW9uAEludmFsaWQgaGVhZGVyIHRva2VuAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fdXJsAEludmFsaWQgY2hhcmFjdGVycyBpbiB1cmwAVW5leHBlY3RlZCBzdGFydCBjaGFyIGluIHVybABEb3VibGUgQCBpbiB1cmwARW1wdHkgQ29udGVudC1MZW5ndGgASW52YWxpZCBjaGFyYWN0ZXIgaW4gQ29udGVudC1MZW5ndGgAVHJhbnNmZXItRW5jb2RpbmcgY2FuJ3QgYmUgcHJlc2VudCB3aXRoIENvbnRlbnQtTGVuZ3RoAER1cGxpY2F0ZSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXIgaW4gdXJsIHBhdGgAQ29udGVudC1MZW5ndGggY2FuJ3QgYmUgcHJlc2VudCB3aXRoIFRyYW5zZmVyLUVuY29kaW5nAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgY2h1bmsgc2l6ZQBFeHBlY3RlZCBMRiBhZnRlciBjaHVuayBzaXplAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIHNpemUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfdmFsdWUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyB2YWx1ZQBNaXNzaW5nIGV4cGVjdGVkIENSIGFmdGVyIGhlYWRlciB2YWx1ZQBNaXNzaW5nIGV4cGVjdGVkIExGIGFmdGVyIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AgaGVhZGVyIHZhbHVlAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgY2h1bmsgZXh0ZW5zaW9uIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGUgdmFsdWUASW52YWxpZCBxdW90ZWQtcGFpciBpbiBjaHVuayBleHRlbnNpb25zIHF1b3RlZCB2YWx1ZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIHF1b3RlZCB2YWx1ZQBQYXVzZWQgYnkgb25faGVhZGVyc19jb21wbGV0ZQBJbnZhbGlkIEVPRiBzdGF0ZQBvbl9yZXNldCBwYXVzZQBvbl9jaHVua19oZWFkZXIgcGF1c2UAb25fbWVzc2FnZV9iZWdpbiBwYXVzZQBvbl9jaHVua19leHRlbnNpb25fdmFsdWUgcGF1c2UAb25fc3RhdHVzX2NvbXBsZXRlIHBhdXNlAG9uX3ZlcnNpb25fY29tcGxldGUgcGF1c2UAb25fdXJsX2NvbXBsZXRlIHBhdXNlAG9uX2NodW5rX2NvbXBsZXRlIHBhdXNlAG9uX2hlYWRlcl92YWx1ZV9jb21wbGV0ZSBwYXVzZQBvbl9tZXNzYWdlX2NvbXBsZXRlIHBhdXNlAG9uX21ldGhvZF9jb21wbGV0ZSBwYXVzZQBvbl9oZWFkZXJfZmllbGRfY29tcGxldGUgcGF1c2UAb25fY2h1bmtfZXh0ZW5zaW9uX25hbWUgcGF1c2UAVW5leHBlY3RlZCBzcGFjZSBhZnRlciBzdGFydCBsaW5lAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgcmVzcG9uc2UgbGluZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgbmFtZQBNaXNzaW5nIGV4cGVjdGVkIENSIGFmdGVyIGNodW5rIGV4dGVuc2lvbiBuYW1lAEludmFsaWQgc3RhdHVzIGNvZGUAUGF1c2Ugb24gQ09OTkVDVC9VcGdyYWRlAFBhdXNlIG9uIFBSSS9VcGdyYWRlAEV4cGVjdGVkIEhUVFAvMiBDb25uZWN0aW9uIFByZWZhY2UAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9tZXRob2QARXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgbWV0aG9kAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25faGVhZGVyX2ZpZWxkAFBhdXNlZABJbnZhbGlkIHdvcmQgZW5jb3VudGVyZWQASW52YWxpZCBtZXRob2QgZW5jb3VudGVyZWQATWlzc2luZyBleHBlY3RlZCBDUiBhZnRlciBjaHVuayBkYXRhAEV4cGVjdGVkIExGIGFmdGVyIGNodW5rIGRhdGEAVW5leHBlY3RlZCBjaGFyIGluIHVybCBzY2hlbWEAUmVxdWVzdCBoYXMgaW52YWxpZCBgVHJhbnNmZXItRW5jb2RpbmdgAERhdGEgYWZ0ZXIgYENvbm5lY3Rpb246IGNsb3NlYABTV0lUQ0hfUFJPWFkAVVNFX1BST1hZAE1LQUNUSVZJVFkAVU5QUk9DRVNTQUJMRV9FTlRJVFkAUVVFUlkAQ09QWQBNT1ZFRF9QRVJNQU5FTlRMWQBUT09fRUFSTFkATk9USUZZAEZBSUxFRF9ERVBFTkRFTkNZAEJBRF9HQVRFV0FZAFBMQVkAUFVUAENIRUNLT1VUAEdBVEVXQVlfVElNRU9VVABSRVFVRVNUX1RJTUVPVVQATkVUV09SS19DT05ORUNUX1RJTUVPVVQAQ09OTkVDVElPTl9USU1FT1VUAExPR0lOX1RJTUVPVVQATkVUV09SS19SRUFEX1RJTUVPVVQAUE9TVABNSVNESVJFQ1RFRF9SRVFVRVNUAENMSUVOVF9DTE9TRURfUkVRVUVTVABDTElFTlRfQ0xPU0VEX0xPQURfQkFMQU5DRURfUkVRVUVTVABCQURfUkVRVUVTVABIVFRQX1JFUVVFU1RfU0VOVF9UT19IVFRQU19QT1JUAFJFUE9SVABJTV9BX1RFQVBPVABSRVNFVF9DT05URU5UAE5PX0NPTlRFTlQAUEFSVElBTF9DT05URU5UAEhQRV9JTlZBTElEX0NPTlNUQU5UAEhQRV9DQl9SRVNFVABHRVQASFBFX1NUUklDVABDT05GTElDVABURU1QT1JBUllfUkVESVJFQ1QAUEVSTUFORU5UX1JFRElSRUNUAENPTk5FQ1QATVVMVElfU1RBVFVTAEhQRV9JTlZBTElEX1NUQVRVUwBUT09fTUFOWV9SRVFVRVNUUwBFQVJMWV9ISU5UUwBVTkFWQUlMQUJMRV9GT1JfTEVHQUxfUkVBU09OUwBPUFRJT05TAFNXSVRDSElOR19QUk9UT0NPTFMAVkFSSUFOVF9BTFNPX05FR09USUFURVMATVVMVElQTEVfQ0hPSUNFUwBJTlRFUk5BTF9TRVJWRVJfRVJST1IAV0VCX1NFUlZFUl9VTktOT1dOX0VSUk9SAFJBSUxHVU5fRVJST1IASURFTlRJVFlfUFJPVklERVJfQVVUSEVOVElDQVRJT05fRVJST1IAU1NMX0NFUlRJRklDQVRFX0VSUk9SAElOVkFMSURfWF9GT1JXQVJERURfRk9SAFNFVF9QQVJBTUVURVIAR0VUX1BBUkFNRVRFUgBIUEVfVVNFUgBTRUVfT1RIRVIASFBFX0NCX0NIVU5LX0hFQURFUgBFeHBlY3RlZCBMRiBhZnRlciBDUgBNS0NBTEVOREFSAFNFVFVQAFdFQl9TRVJWRVJfSVNfRE9XTgBURUFSRE9XTgBIUEVfQ0xPU0VEX0NPTk5FQ1RJT04ASEVVUklTVElDX0VYUElSQVRJT04ARElTQ09OTkVDVEVEX09QRVJBVElPTgBOT05fQVVUSE9SSVRBVElWRV9JTkZPUk1BVElPTgBIUEVfSU5WQUxJRF9WRVJTSU9OAEhQRV9DQl9NRVNTQUdFX0JFR0lOAFNJVEVfSVNfRlJPWkVOAEhQRV9JTlZBTElEX0hFQURFUl9UT0tFTgBJTlZBTElEX1RPS0VOAEZPUkJJRERFTgBFTkhBTkNFX1lPVVJfQ0FMTQBIUEVfSU5WQUxJRF9VUkwAQkxPQ0tFRF9CWV9QQVJFTlRBTF9DT05UUk9MAE1LQ09MAEFDTABIUEVfSU5URVJOQUwAUkVRVUVTVF9IRUFERVJfRklFTERTX1RPT19MQVJHRV9VTk9GRklDSUFMAEhQRV9PSwBVTkxJTksAVU5MT0NLAFBSSQBSRVRSWV9XSVRIAEhQRV9JTlZBTElEX0NPTlRFTlRfTEVOR1RIAEhQRV9VTkVYUEVDVEVEX0NPTlRFTlRfTEVOR1RIAEZMVVNIAFBST1BQQVRDSABNLVNFQVJDSABVUklfVE9PX0xPTkcAUFJPQ0VTU0lORwBNSVNDRUxMQU5FT1VTX1BFUlNJU1RFTlRfV0FSTklORwBNSVNDRUxMQU5FT1VTX1dBUk5JTkcASFBFX0lOVkFMSURfVFJBTlNGRVJfRU5DT0RJTkcARXhwZWN0ZWQgQ1JMRgBIUEVfSU5WQUxJRF9DSFVOS19TSVpFAE1PVkUAQ09OVElOVUUASFBFX0NCX1NUQVRVU19DT01QTEVURQBIUEVfQ0JfSEVBREVSU19DT01QTEVURQBIUEVfQ0JfVkVSU0lPTl9DT01QTEVURQBIUEVfQ0JfVVJMX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19DT01QTEVURQBIUEVfQ0JfSEVBREVSX1ZBTFVFX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19FWFRFTlNJT05fVkFMVUVfQ09NUExFVEUASFBFX0NCX0NIVU5LX0VYVEVOU0lPTl9OQU1FX0NPTVBMRVRFAEhQRV9DQl9NRVNTQUdFX0NPTVBMRVRFAEhQRV9DQl9NRVRIT0RfQ09NUExFVEUASFBFX0NCX0hFQURFUl9GSUVMRF9DT01QTEVURQBERUxFVEUASFBFX0lOVkFMSURfRU9GX1NUQVRFAElOVkFMSURfU1NMX0NFUlRJRklDQVRFAFBBVVNFAE5PX1JFU1BPTlNFAFVOU1VQUE9SVEVEX01FRElBX1RZUEUAR09ORQBOT1RfQUNDRVBUQUJMRQBTRVJWSUNFX1VOQVZBSUxBQkxFAFJBTkdFX05PVF9TQVRJU0ZJQUJMRQBPUklHSU5fSVNfVU5SRUFDSEFCTEUAUkVTUE9OU0VfSVNfU1RBTEUAUFVSR0UATUVSR0UAUkVRVUVTVF9IRUFERVJfRklFTERTX1RPT19MQVJHRQBSRVFVRVNUX0hFQURFUl9UT09fTEFSR0UAUEFZTE9BRF9UT09fTEFSR0UASU5TVUZGSUNJRU5UX1NUT1JBR0UASFBFX1BBVVNFRF9VUEdSQURFAEhQRV9QQVVTRURfSDJfVVBHUkFERQBTT1VSQ0UAQU5OT1VOQ0UAVFJBQ0UASFBFX1VORVhQRUNURURfU1BBQ0UAREVTQ1JJQkUAVU5TVUJTQ1JJQkUAUkVDT1JEAEhQRV9JTlZBTElEX01FVEhPRABOT1RfRk9VTkQAUFJPUEZJTkQAVU5CSU5EAFJFQklORABVTkFVVEhPUklaRUQATUVUSE9EX05PVF9BTExPV0VEAEhUVFBfVkVSU0lPTl9OT1RfU1VQUE9SVEVEAEFMUkVBRFlfUkVQT1JURUQAQUNDRVBURUQATk9UX0lNUExFTUVOVEVEAExPT1BfREVURUNURUQASFBFX0NSX0VYUEVDVEVEAEhQRV9MRl9FWFBFQ1RFRABDUkVBVEVEAElNX1VTRUQASFBFX1BBVVNFRABUSU1FT1VUX09DQ1VSRUQAUEFZTUVOVF9SRVFVSVJFRABQUkVDT05ESVRJT05fUkVRVUlSRUQAUFJPWFlfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQATkVUV09SS19BVVRIRU5USUNBVElPTl9SRVFVSVJFRABMRU5HVEhfUkVRVUlSRUQAU1NMX0NFUlRJRklDQVRFX1JFUVVJUkVEAFVQR1JBREVfUkVRVUlSRUQAUEFHRV9FWFBJUkVEAFBSRUNPTkRJVElPTl9GQUlMRUQARVhQRUNUQVRJT05fRkFJTEVEAFJFVkFMSURBVElPTl9GQUlMRUQAU1NMX0hBTkRTSEFLRV9GQUlMRUQATE9DS0VEAFRSQU5TRk9STUFUSU9OX0FQUExJRUQATk9UX01PRElGSUVEAE5PVF9FWFRFTkRFRABCQU5EV0lEVEhfTElNSVRfRVhDRUVERUQAU0lURV9JU19PVkVSTE9BREVEAEhFQUQARXhwZWN0ZWQgSFRUUC8AAFIVAAAaFQAADxIAAOQZAACRFQAACRQAAC0ZAADkFAAA6REAAGkUAAChFAAAdhUAAEMWAABeEgAAlBcAABcWAAB9FAAAfxYAAEEXAACzEwAAwxYAAAQaAAC9GAAA0BgAAKATAADUGQAArxYAAGgWAABwFwAA2RYAAPwYAAD+EQAAWRcAAJcWAAAcFwAA9hYAAI0XAAALEgAAfxsAAC4RAACzEAAASRIAAK0SAAD2GAAAaBAAAGIVAAAQFQAAWhYAAEoZAAC1FQAAwRUAAGAVAABcGQAAWhkAAFMZAAAWFQAArREAAEIQAAC3EAAAVxgAAL8VAACJEAAAHBkAABoZAAC5FQAAURgAANwTAABbFQAAWRUAAOYYAABnFQAAERkAAO0YAADnEwAArhAAAMIXAAAAFAAAkhMAAIQTAABAEgAAJhkAAK8VAABiEABB6TkLAQEAQYA6C+ABAQECAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAwEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAQeo7CwQBAAACAEGBPAteAwQDAwMDAwAAAwMAAwMAAwMDAwMDAwMDAwAFAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAMAAwBB6j0LBAEAAAIAQYE+C14DAAMDAwMDAAADAwADAwADAwMDAwMDAwMDAAQABQAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAwADAEHgPwsNbG9zZWVlcC1hbGl2ZQBB+T8LAQEAQZDAAAvgAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAEH5wQALAQEAQZDCAAvnAQEBAQEBAQEBAQEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBY2h1bmtlZABBocQAC14BAAEBAQEBAAABAQABAQABAQEBAQEBAQEBAAAAAAAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQABAEGAxgALIWVjdGlvbmVudC1sZW5ndGhvbnJveHktY29ubmVjdGlvbgBBsMYACytyYW5zZmVyLWVuY29kaW5ncGdyYWRlDQoNClNNDQoNClRUUC9DRS9UU1AvAEHpxgALBQECAAEDAEGAxwALXwQFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFAEHpyAALBQECAAEDAEGAyQALXwQFBQYFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFAEHpygALBAEAAAEAQYHLAAteAgIAAgICAgICAgICAgICAgICAgICAgICAgICAgICAAICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgBB6cwACwUBAgABAwBBgM0AC18EBQAABQUFBQUFBQUFBQUGBQUFBQUFBQUFBQUFAAUABwgFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUABQAFAAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFAAAABQBB6c4ACwUBAQABAQBBgM8ACwEBAEGazwALQQIAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAEHp0AALBQEBAAEBAEGA0QALAQEAQYrRAAsGAgAAAAACAEGh0QALOgMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAQeDSAAuaAU5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VVRVJZT1JESVJFQ1RPUlRSQ0hQQVJBTUVURVJVUkNFQlNDUklCRUFSRE9XTkFDRUlORE5LQ0tVQlNDUklCRUhUVFAvQURUUC8=' let wasmBuffer Object.defineProperty(module, 'exports', { get: () => { return wasmBuffer ? wasmBuffer : (wasmBuffer = Buffer.from(wasmBase64, 'base64')) } }) /***/ }), /***/ 57875: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.enumToMap = void 0; function enumToMap(obj, filter = [], exceptions = []) { var _a, _b; const emptyFilter = ((_a = filter === null || filter === void 0 ? void 0 : filter.length) !== null && _a !== void 0 ? _a : 0) === 0; const emptyExceptions = ((_b = exceptions === null || exceptions === void 0 ? void 0 : exceptions.length) !== null && _b !== void 0 ? _b : 0) === 0; return Object.fromEntries(Object.entries(obj).filter(([, value]) => { return (typeof value === 'number' && (emptyFilter || filter.includes(value)) && (emptyExceptions || !exceptions.includes(value))); })); } exports.enumToMap = enumToMap; //# sourceMappingURL=utils.js.map /***/ }), /***/ 82980: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { kClients } = __nccwpck_require__(83112) const Agent = __nccwpck_require__(11538) const { kAgent, kMockAgentSet, kMockAgentGet, kDispatches, kIsMockActive, kNetConnect, kGetNetConnect, kOptions, kFactory, kMockAgentRegisterCallHistory, kMockAgentIsCallHistoryEnabled, kMockAgentAddCallHistoryLog, kMockAgentMockCallHistoryInstance, kMockAgentAcceptsNonStandardSearchParameters, kMockCallHistoryAddLog } = __nccwpck_require__(14416) const MockClient = __nccwpck_require__(20274) const MockPool = __nccwpck_require__(82319) const { matchValue, normalizeSearchParams, buildAndValidateMockOptions } = __nccwpck_require__(89668) const { InvalidArgumentError, UndiciError } = __nccwpck_require__(21158) const Dispatcher = __nccwpck_require__(24350) const PendingInterceptorsFormatter = __nccwpck_require__(5555) const { MockCallHistory } = __nccwpck_require__(96376) class MockAgent extends Dispatcher { constructor (opts) { super(opts) const mockOptions = buildAndValidateMockOptions(opts) this[kNetConnect] = true this[kIsMockActive] = true this[kMockAgentIsCallHistoryEnabled] = mockOptions?.enableCallHistory ?? false this[kMockAgentAcceptsNonStandardSearchParameters] = mockOptions?.acceptNonStandardSearchParameters ?? false // Instantiate Agent and encapsulate if (opts?.agent && typeof opts.agent.dispatch !== 'function') { throw new InvalidArgumentError('Argument opts.agent must implement Agent') } const agent = opts?.agent ? opts.agent : new Agent(opts) this[kAgent] = agent this[kClients] = agent[kClients] this[kOptions] = mockOptions if (this[kMockAgentIsCallHistoryEnabled]) { this[kMockAgentRegisterCallHistory]() } } get (origin) { let dispatcher = this[kMockAgentGet](origin) if (!dispatcher) { dispatcher = this[kFactory](origin) this[kMockAgentSet](origin, dispatcher) } return dispatcher } dispatch (opts, handler) { // Call MockAgent.get to perform additional setup before dispatching as normal this.get(opts.origin) this[kMockAgentAddCallHistoryLog](opts) const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters] const dispatchOpts = { ...opts } if (acceptNonStandardSearchParameters && dispatchOpts.path) { const [path, searchParams] = dispatchOpts.path.split('?') const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters) dispatchOpts.path = `${path}?${normalizedSearchParams}` } return this[kAgent].dispatch(dispatchOpts, handler) } async close () { this.clearCallHistory() await this[kAgent].close() this[kClients].clear() } deactivate () { this[kIsMockActive] = false } activate () { this[kIsMockActive] = true } enableNetConnect (matcher) { if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) { if (Array.isArray(this[kNetConnect])) { this[kNetConnect].push(matcher) } else { this[kNetConnect] = [matcher] } } else if (typeof matcher === 'undefined') { this[kNetConnect] = true } else { throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.') } } disableNetConnect () { this[kNetConnect] = false } enableCallHistory () { this[kMockAgentIsCallHistoryEnabled] = true return this } disableCallHistory () { this[kMockAgentIsCallHistoryEnabled] = false return this } getCallHistory () { return this[kMockAgentMockCallHistoryInstance] } clearCallHistory () { if (this[kMockAgentMockCallHistoryInstance] !== undefined) { this[kMockAgentMockCallHistoryInstance].clear() } } // This is required to bypass issues caused by using global symbols - see: // https://github.com/nodejs/undici/issues/1447 get isMockActive () { return this[kIsMockActive] } [kMockAgentRegisterCallHistory] () { if (this[kMockAgentMockCallHistoryInstance] === undefined) { this[kMockAgentMockCallHistoryInstance] = new MockCallHistory() } } [kMockAgentAddCallHistoryLog] (opts) { if (this[kMockAgentIsCallHistoryEnabled]) { // additional setup when enableCallHistory class method is used after mockAgent instantiation this[kMockAgentRegisterCallHistory]() // add call history log on every call (intercepted or not) this[kMockAgentMockCallHistoryInstance][kMockCallHistoryAddLog](opts) } } [kMockAgentSet] (origin, dispatcher) { this[kClients].set(origin, { count: 0, dispatcher }) } [kFactory] (origin) { const mockOptions = Object.assign({ agent: this }, this[kOptions]) return this[kOptions] && this[kOptions].connections === 1 ? new MockClient(origin, mockOptions) : new MockPool(origin, mockOptions) } [kMockAgentGet] (origin) { // First check if we can immediately find it const result = this[kClients].get(origin) if (result?.dispatcher) { return result.dispatcher } // If the origin is not a string create a dummy parent pool and return to user if (typeof origin !== 'string') { const dispatcher = this[kFactory]('http://localhost:9999') this[kMockAgentSet](origin, dispatcher) return dispatcher } // If we match, create a pool and assign the same dispatches for (const [keyMatcher, result] of Array.from(this[kClients])) { if (result && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) { const dispatcher = this[kFactory](origin) this[kMockAgentSet](origin, dispatcher) dispatcher[kDispatches] = result.dispatcher[kDispatches] return dispatcher } } } [kGetNetConnect] () { return this[kNetConnect] } pendingInterceptors () { const mockAgentClients = this[kClients] return Array.from(mockAgentClients.entries()) .flatMap(([origin, result]) => result.dispatcher[kDispatches].map(dispatch => ({ ...dispatch, origin }))) .filter(({ pending }) => pending) } assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) { const pending = this.pendingInterceptors() if (pending.length === 0) { return } throw new UndiciError( pending.length === 1 ? `1 interceptor is pending:\n\n${pendingInterceptorsFormatter.format(pending)}`.trim() : `${pending.length} interceptors are pending:\n\n${pendingInterceptorsFormatter.format(pending)}`.trim() ) } } module.exports = MockAgent /***/ }), /***/ 96376: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { kMockCallHistoryAddLog } = __nccwpck_require__(14416) const { InvalidArgumentError } = __nccwpck_require__(21158) function handleFilterCallsWithOptions (criteria, options, handler, store) { switch (options.operator) { case 'OR': store.push(...handler(criteria)) return store case 'AND': return handler.call({ logs: store }, criteria) default: // guard -- should never happens because buildAndValidateFilterCallsOptions is called before throw new InvalidArgumentError('options.operator must to be a case insensitive string equal to \'OR\' or \'AND\'') } } function buildAndValidateFilterCallsOptions (options = {}) { const finalOptions = {} if ('operator' in options) { if (typeof options.operator !== 'string' || (options.operator.toUpperCase() !== 'OR' && options.operator.toUpperCase() !== 'AND')) { throw new InvalidArgumentError('options.operator must to be a case insensitive string equal to \'OR\' or \'AND\'') } return { ...finalOptions, operator: options.operator.toUpperCase() } } return finalOptions } function makeFilterCalls (parameterName) { return (parameterValue) => { if (typeof parameterValue === 'string' || parameterValue == null) { return this.logs.filter((log) => { return log[parameterName] === parameterValue }) } if (parameterValue instanceof RegExp) { return this.logs.filter((log) => { return parameterValue.test(log[parameterName]) }) } throw new InvalidArgumentError(`${parameterName} parameter should be one of string, regexp, undefined or null`) } } function computeUrlWithMaybeSearchParameters (requestInit) { // path can contains query url parameters // or query can contains query url parameters try { const url = new URL(requestInit.path, requestInit.origin) // requestInit.path contains query url parameters // requestInit.query is then undefined if (url.search.length !== 0) { return url } // requestInit.query can be populated here url.search = new URLSearchParams(requestInit.query).toString() return url } catch (error) { throw new InvalidArgumentError('An error occurred when computing MockCallHistoryLog.url', { cause: error }) } } class MockCallHistoryLog { constructor (requestInit = {}) { this.body = requestInit.body this.headers = requestInit.headers this.method = requestInit.method const url = computeUrlWithMaybeSearchParameters(requestInit) this.fullUrl = url.toString() this.origin = url.origin this.path = url.pathname this.searchParams = Object.fromEntries(url.searchParams) this.protocol = url.protocol this.host = url.host this.port = url.port this.hash = url.hash } toMap () { return new Map([ ['protocol', this.protocol], ['host', this.host], ['port', this.port], ['origin', this.origin], ['path', this.path], ['hash', this.hash], ['searchParams', this.searchParams], ['fullUrl', this.fullUrl], ['method', this.method], ['body', this.body], ['headers', this.headers]] ) } toString () { const options = { betweenKeyValueSeparator: '->', betweenPairSeparator: '|' } let result = '' this.toMap().forEach((value, key) => { if (typeof value === 'string' || value === undefined || value === null) { result = `${result}${key}${options.betweenKeyValueSeparator}${value}${options.betweenPairSeparator}` } if ((typeof value === 'object' && value !== null) || Array.isArray(value)) { result = `${result}${key}${options.betweenKeyValueSeparator}${JSON.stringify(value)}${options.betweenPairSeparator}` } // maybe miss something for non Record / Array headers and searchParams here }) // delete last betweenPairSeparator return result.slice(0, -1) } } class MockCallHistory { logs = [] calls () { return this.logs } firstCall () { return this.logs.at(0) } lastCall () { return this.logs.at(-1) } nthCall (number) { if (typeof number !== 'number') { throw new InvalidArgumentError('nthCall must be called with a number') } if (!Number.isInteger(number)) { throw new InvalidArgumentError('nthCall must be called with an integer') } if (Math.sign(number) !== 1) { throw new InvalidArgumentError('nthCall must be called with a positive value. use firstCall or lastCall instead') } // non zero based index. this is more human readable return this.logs.at(number - 1) } filterCalls (criteria, options) { // perf if (this.logs.length === 0) { return this.logs } if (typeof criteria === 'function') { return this.logs.filter(criteria) } if (criteria instanceof RegExp) { return this.logs.filter((log) => { return criteria.test(log.toString()) }) } if (typeof criteria === 'object' && criteria !== null) { // no criteria - returning all logs if (Object.keys(criteria).length === 0) { return this.logs } const finalOptions = { operator: 'OR', ...buildAndValidateFilterCallsOptions(options) } let maybeDuplicatedLogsFiltered = [] if ('protocol' in criteria) { maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.protocol, finalOptions, this.filterCallsByProtocol, maybeDuplicatedLogsFiltered) } if ('host' in criteria) { maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.host, finalOptions, this.filterCallsByHost, maybeDuplicatedLogsFiltered) } if ('port' in criteria) { maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.port, finalOptions, this.filterCallsByPort, maybeDuplicatedLogsFiltered) } if ('origin' in criteria) { maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.origin, finalOptions, this.filterCallsByOrigin, maybeDuplicatedLogsFiltered) } if ('path' in criteria) { maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.path, finalOptions, this.filterCallsByPath, maybeDuplicatedLogsFiltered) } if ('hash' in criteria) { maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.hash, finalOptions, this.filterCallsByHash, maybeDuplicatedLogsFiltered) } if ('fullUrl' in criteria) { maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.fullUrl, finalOptions, this.filterCallsByFullUrl, maybeDuplicatedLogsFiltered) } if ('method' in criteria) { maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.method, finalOptions, this.filterCallsByMethod, maybeDuplicatedLogsFiltered) } const uniqLogsFiltered = [...new Set(maybeDuplicatedLogsFiltered)] return uniqLogsFiltered } throw new InvalidArgumentError('criteria parameter should be one of function, regexp, or object') } filterCallsByProtocol = makeFilterCalls.call(this, 'protocol') filterCallsByHost = makeFilterCalls.call(this, 'host') filterCallsByPort = makeFilterCalls.call(this, 'port') filterCallsByOrigin = makeFilterCalls.call(this, 'origin') filterCallsByPath = makeFilterCalls.call(this, 'path') filterCallsByHash = makeFilterCalls.call(this, 'hash') filterCallsByFullUrl = makeFilterCalls.call(this, 'fullUrl') filterCallsByMethod = makeFilterCalls.call(this, 'method') clear () { this.logs = [] } [kMockCallHistoryAddLog] (requestInit) { const log = new MockCallHistoryLog(requestInit) this.logs.push(log) return log } * [Symbol.iterator] () { for (const log of this.calls()) { yield log } } } module.exports.MockCallHistory = MockCallHistory module.exports.MockCallHistoryLog = MockCallHistoryLog /***/ }), /***/ 20274: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { promisify } = __nccwpck_require__(57975) const Client = __nccwpck_require__(56716) const { buildMockDispatch } = __nccwpck_require__(89668) const { kDispatches, kMockAgent, kClose, kOriginalClose, kOrigin, kOriginalDispatch, kConnected, kIgnoreTrailingSlash } = __nccwpck_require__(14416) const { MockInterceptor } = __nccwpck_require__(30926) const Symbols = __nccwpck_require__(83112) const { InvalidArgumentError } = __nccwpck_require__(21158) /** * MockClient provides an API that extends the Client to influence the mockDispatches. */ class MockClient extends Client { constructor (origin, opts) { if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { throw new InvalidArgumentError('Argument opts.agent must implement Agent') } super(origin, opts) this[kMockAgent] = opts.agent this[kOrigin] = origin this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false this[kDispatches] = [] this[kConnected] = 1 this[kOriginalDispatch] = this.dispatch this[kOriginalClose] = this.close.bind(this) this.dispatch = buildMockDispatch.call(this) this.close = this[kClose] } get [Symbols.kConnected] () { return this[kConnected] } /** * Sets up the base interceptor for mocking replies from undici. */ intercept (opts) { return new MockInterceptor( opts && { ignoreTrailingSlash: this[kIgnoreTrailingSlash], ...opts }, this[kDispatches] ) } cleanMocks () { this[kDispatches] = [] } async [kClose] () { await promisify(this[kOriginalClose])() this[kConnected] = 0 this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) } } module.exports = MockClient /***/ }), /***/ 63534: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { UndiciError } = __nccwpck_require__(21158) /** * The request does not match any registered mock dispatches. */ class MockNotMatchedError extends UndiciError { constructor (message) { super(message) this.name = 'MockNotMatchedError' this.message = message || 'The request does not match any registered mock dispatches' this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED' } } module.exports = { MockNotMatchedError } /***/ }), /***/ 30926: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(89668) const { kDispatches, kDispatchKey, kDefaultHeaders, kDefaultTrailers, kContentLength, kMockDispatch, kIgnoreTrailingSlash } = __nccwpck_require__(14416) const { InvalidArgumentError } = __nccwpck_require__(21158) const { serializePathWithQuery } = __nccwpck_require__(46425) /** * Defines the scope API for an interceptor reply */ class MockScope { constructor (mockDispatch) { this[kMockDispatch] = mockDispatch } /** * Delay a reply by a set amount in ms. */ delay (waitInMs) { if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) { throw new InvalidArgumentError('waitInMs must be a valid integer > 0') } this[kMockDispatch].delay = waitInMs return this } /** * For a defined reply, never mark as consumed. */ persist () { this[kMockDispatch].persist = true return this } /** * Allow one to define a reply for a set amount of matching requests. */ times (repeatTimes) { if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) { throw new InvalidArgumentError('repeatTimes must be a valid integer > 0') } this[kMockDispatch].times = repeatTimes return this } } /** * Defines an interceptor for a Mock */ class MockInterceptor { constructor (opts, mockDispatches) { if (typeof opts !== 'object') { throw new InvalidArgumentError('opts must be an object') } if (typeof opts.path === 'undefined') { throw new InvalidArgumentError('opts.path must be defined') } if (typeof opts.method === 'undefined') { opts.method = 'GET' } // See https://github.com/nodejs/undici/issues/1245 // As per RFC 3986, clients are not supposed to send URI // fragments to servers when they retrieve a document, if (typeof opts.path === 'string') { if (opts.query) { opts.path = serializePathWithQuery(opts.path, opts.query) } else { // Matches https://github.com/nodejs/undici/blob/main/lib/web/fetch/index.js#L1811 const parsedURL = new URL(opts.path, 'data://') opts.path = parsedURL.pathname + parsedURL.search } } if (typeof opts.method === 'string') { opts.method = opts.method.toUpperCase() } this[kDispatchKey] = buildKey(opts) this[kDispatches] = mockDispatches this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false this[kDefaultHeaders] = {} this[kDefaultTrailers] = {} this[kContentLength] = false } createMockScopeDispatchData ({ statusCode, data, responseOptions }) { const responseData = getResponseData(data) const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {} const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers } const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers } return { statusCode, data, headers, trailers } } validateReplyParameters (replyParameters) { if (typeof replyParameters.statusCode === 'undefined') { throw new InvalidArgumentError('statusCode must be defined') } if (typeof replyParameters.responseOptions !== 'object' || replyParameters.responseOptions === null) { throw new InvalidArgumentError('responseOptions must be an object') } } /** * Mock an undici request with a defined reply. */ reply (replyOptionsCallbackOrStatusCode) { // Values of reply aren't available right now as they // can only be available when the reply callback is invoked. if (typeof replyOptionsCallbackOrStatusCode === 'function') { // We'll first wrap the provided callback in another function, // this function will properly resolve the data from the callback // when invoked. const wrappedDefaultsCallback = (opts) => { // Our reply options callback contains the parameter for statusCode, data and options. const resolvedData = replyOptionsCallbackOrStatusCode(opts) // Check if it is in the right format if (typeof resolvedData !== 'object' || resolvedData === null) { throw new InvalidArgumentError('reply options callback must return an object') } const replyParameters = { data: '', responseOptions: {}, ...resolvedData } this.validateReplyParameters(replyParameters) // Since the values can be obtained immediately we return them // from this higher order function that will be resolved later. return { ...this.createMockScopeDispatchData(replyParameters) } } // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data. const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] }) return new MockScope(newMockDispatch) } // We can have either one or three parameters, if we get here, // we should have 1-3 parameters. So we spread the arguments of // this function to obtain the parameters, since replyData will always // just be the statusCode. const replyParameters = { statusCode: replyOptionsCallbackOrStatusCode, data: arguments[1] === undefined ? '' : arguments[1], responseOptions: arguments[2] === undefined ? {} : arguments[2] } this.validateReplyParameters(replyParameters) // Send in-already provided data like usual const dispatchData = this.createMockScopeDispatchData(replyParameters) const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] }) return new MockScope(newMockDispatch) } /** * Mock an undici request with a defined error. */ replyWithError (error) { if (typeof error === 'undefined') { throw new InvalidArgumentError('error must be defined') } const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] }) return new MockScope(newMockDispatch) } /** * Set default reply headers on the interceptor for subsequent replies */ defaultReplyHeaders (headers) { if (typeof headers === 'undefined') { throw new InvalidArgumentError('headers must be defined') } this[kDefaultHeaders] = headers return this } /** * Set default reply trailers on the interceptor for subsequent replies */ defaultReplyTrailers (trailers) { if (typeof trailers === 'undefined') { throw new InvalidArgumentError('trailers must be defined') } this[kDefaultTrailers] = trailers return this } /** * Set reply content length header for replies on the interceptor */ replyContentLength () { this[kContentLength] = true return this } } module.exports.MockInterceptor = MockInterceptor module.exports.MockScope = MockScope /***/ }), /***/ 82319: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { promisify } = __nccwpck_require__(57975) const Pool = __nccwpck_require__(74561) const { buildMockDispatch } = __nccwpck_require__(89668) const { kDispatches, kMockAgent, kClose, kOriginalClose, kOrigin, kOriginalDispatch, kConnected, kIgnoreTrailingSlash } = __nccwpck_require__(14416) const { MockInterceptor } = __nccwpck_require__(30926) const Symbols = __nccwpck_require__(83112) const { InvalidArgumentError } = __nccwpck_require__(21158) /** * MockPool provides an API that extends the Pool to influence the mockDispatches. */ class MockPool extends Pool { constructor (origin, opts) { if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { throw new InvalidArgumentError('Argument opts.agent must implement Agent') } super(origin, opts) this[kMockAgent] = opts.agent this[kOrigin] = origin this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false this[kDispatches] = [] this[kConnected] = 1 this[kOriginalDispatch] = this.dispatch this[kOriginalClose] = this.close.bind(this) this.dispatch = buildMockDispatch.call(this) this.close = this[kClose] } get [Symbols.kConnected] () { return this[kConnected] } /** * Sets up the base interceptor for mocking replies from undici. */ intercept (opts) { return new MockInterceptor( opts && { ignoreTrailingSlash: this[kIgnoreTrailingSlash], ...opts }, this[kDispatches] ) } cleanMocks () { this[kDispatches] = [] } async [kClose] () { await promisify(this[kOriginalClose])() this[kConnected] = 0 this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) } } module.exports = MockPool /***/ }), /***/ 14416: /***/ ((module) => { "use strict"; module.exports = { kAgent: Symbol('agent'), kOptions: Symbol('options'), kFactory: Symbol('factory'), kDispatches: Symbol('dispatches'), kDispatchKey: Symbol('dispatch key'), kDefaultHeaders: Symbol('default headers'), kDefaultTrailers: Symbol('default trailers'), kContentLength: Symbol('content length'), kMockAgent: Symbol('mock agent'), kMockAgentSet: Symbol('mock agent set'), kMockAgentGet: Symbol('mock agent get'), kMockDispatch: Symbol('mock dispatch'), kClose: Symbol('close'), kOriginalClose: Symbol('original agent close'), kOriginalDispatch: Symbol('original dispatch'), kOrigin: Symbol('origin'), kIsMockActive: Symbol('is mock active'), kNetConnect: Symbol('net connect'), kGetNetConnect: Symbol('get net connect'), kConnected: Symbol('connected'), kIgnoreTrailingSlash: Symbol('ignore trailing slash'), kMockAgentMockCallHistoryInstance: Symbol('mock agent mock call history name'), kMockAgentRegisterCallHistory: Symbol('mock agent register mock call history'), kMockAgentAddCallHistoryLog: Symbol('mock agent add call history log'), kMockAgentIsCallHistoryEnabled: Symbol('mock agent is call history enabled'), kMockAgentAcceptsNonStandardSearchParameters: Symbol('mock agent accepts non standard search parameters'), kMockCallHistoryAddLog: Symbol('mock call history add log') } /***/ }), /***/ 89668: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { MockNotMatchedError } = __nccwpck_require__(63534) const { kDispatches, kMockAgent, kOriginalDispatch, kOrigin, kGetNetConnect } = __nccwpck_require__(14416) const { serializePathWithQuery } = __nccwpck_require__(46425) const { STATUS_CODES } = __nccwpck_require__(37067) const { types: { isPromise } } = __nccwpck_require__(57975) const { InvalidArgumentError } = __nccwpck_require__(21158) function matchValue (match, value) { if (typeof match === 'string') { return match === value } if (match instanceof RegExp) { return match.test(value) } if (typeof match === 'function') { return match(value) === true } return false } function lowerCaseEntries (headers) { return Object.fromEntries( Object.entries(headers).map(([headerName, headerValue]) => { return [headerName.toLocaleLowerCase(), headerValue] }) ) } /** * @param {import('../../index').Headers|string[]|Record} headers * @param {string} key */ function getHeaderByName (headers, key) { if (Array.isArray(headers)) { for (let i = 0; i < headers.length; i += 2) { if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) { return headers[i + 1] } } return undefined } else if (typeof headers.get === 'function') { return headers.get(key) } else { return lowerCaseEntries(headers)[key.toLocaleLowerCase()] } } /** @param {string[]} headers */ function buildHeadersFromArray (headers) { // fetch HeadersList const clone = headers.slice() const entries = [] for (let index = 0; index < clone.length; index += 2) { entries.push([clone[index], clone[index + 1]]) } return Object.fromEntries(entries) } function matchHeaders (mockDispatch, headers) { if (typeof mockDispatch.headers === 'function') { if (Array.isArray(headers)) { // fetch HeadersList headers = buildHeadersFromArray(headers) } return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {}) } if (typeof mockDispatch.headers === 'undefined') { return true } if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') { return false } for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) { const headerValue = getHeaderByName(headers, matchHeaderName) if (!matchValue(matchHeaderValue, headerValue)) { return false } } return true } function normalizeSearchParams (query) { if (typeof query !== 'string') { return query } const originalQp = new URLSearchParams(query) const normalizedQp = new URLSearchParams() for (let [key, value] of originalQp.entries()) { key = key.replace('[]', '') const valueRepresentsString = /^(['"]).*\1$/.test(value) if (valueRepresentsString) { normalizedQp.append(key, value) continue } if (value.includes(',')) { const values = value.split(',') for (const v of values) { normalizedQp.append(key, v) } continue } normalizedQp.append(key, value) } return normalizedQp } function safeUrl (path) { if (typeof path !== 'string') { return path } const pathSegments = path.split('?', 3) if (pathSegments.length !== 2) { return path } const qp = new URLSearchParams(pathSegments.pop()) qp.sort() return [...pathSegments, qp.toString()].join('?') } function matchKey (mockDispatch, { path, method, body, headers }) { const pathMatch = matchValue(mockDispatch.path, path) const methodMatch = matchValue(mockDispatch.method, method) const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true const headersMatch = matchHeaders(mockDispatch, headers) return pathMatch && methodMatch && bodyMatch && headersMatch } function getResponseData (data) { if (Buffer.isBuffer(data)) { return data } else if (data instanceof Uint8Array) { return data } else if (data instanceof ArrayBuffer) { return data } else if (typeof data === 'object') { return JSON.stringify(data) } else if (data) { return data.toString() } else { return '' } } function getMockDispatch (mockDispatches, key) { const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath) // Match path let matchedMockDispatches = mockDispatches .filter(({ consumed }) => !consumed) .filter(({ path, ignoreTrailingSlash }) => { return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path), resolvedPath) }) if (matchedMockDispatches.length === 0) { throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`) } // Match method matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method)) if (matchedMockDispatches.length === 0) { throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}' on path '${resolvedPath}'`) } // Match body matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true) if (matchedMockDispatches.length === 0) { throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}' on path '${resolvedPath}'`) } // Match headers matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers)) if (matchedMockDispatches.length === 0) { const headers = typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers throw new MockNotMatchedError(`Mock dispatch not matched for headers '${headers}' on path '${resolvedPath}'`) } return matchedMockDispatches[0] } function addMockDispatch (mockDispatches, key, data, opts) { const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false, ...opts } const replyData = typeof data === 'function' ? { callback: data } : { ...data } const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } } mockDispatches.push(newMockDispatch) return newMockDispatch } function deleteMockDispatch (mockDispatches, key) { const index = mockDispatches.findIndex(dispatch => { if (!dispatch.consumed) { return false } return matchKey(dispatch, key) }) if (index !== -1) { mockDispatches.splice(index, 1) } } /** * @param {string} path Path to remove trailing slash from */ function removeTrailingSlash (path) { while (path.endsWith('/')) { path = path.slice(0, -1) } if (path.length === 0) { path = '/' } return path } function buildKey (opts) { const { path, method, body, headers, query } = opts return { path, method, body, headers, query } } function generateKeyValues (data) { const keys = Object.keys(data) const result = [] for (let i = 0; i < keys.length; ++i) { const key = keys[i] const value = data[key] const name = Buffer.from(`${key}`) if (Array.isArray(value)) { for (let j = 0; j < value.length; ++j) { result.push(name, Buffer.from(`${value[j]}`)) } } else { result.push(name, Buffer.from(`${value}`)) } } return result } /** * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status * @param {number} statusCode */ function getStatusText (statusCode) { return STATUS_CODES[statusCode] || 'unknown' } async function getResponse (body) { const buffers = [] for await (const data of body) { buffers.push(data) } return Buffer.concat(buffers).toString('utf8') } /** * Mock dispatch function used to simulate undici dispatches */ function mockDispatch (opts, handler) { // Get mock dispatch from built key const key = buildKey(opts) const mockDispatch = getMockDispatch(this[kDispatches], key) mockDispatch.timesInvoked++ // Here's where we resolve a callback if a callback is present for the dispatch data. if (mockDispatch.data.callback) { mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) } } // Parse mockDispatch data const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch const { timesInvoked, times } = mockDispatch // If it's used up and not persistent, mark as consumed mockDispatch.consumed = !persist && timesInvoked >= times mockDispatch.pending = timesInvoked < times // If specified, trigger dispatch error if (error !== null) { deleteMockDispatch(this[kDispatches], key) handler.onError(error) return true } // Handle the request with a delay if necessary if (typeof delay === 'number' && delay > 0) { setTimeout(() => { handleReply(this[kDispatches]) }, delay) } else { handleReply(this[kDispatches]) } function handleReply (mockDispatches, _data = data) { // fetch's HeadersList is a 1D string array const optsHeaders = Array.isArray(opts.headers) ? buildHeadersFromArray(opts.headers) : opts.headers const body = typeof _data === 'function' ? _data({ ...opts, headers: optsHeaders }) : _data // util.types.isPromise is likely needed for jest. if (isPromise(body)) { // If handleReply is asynchronous, throwing an error // in the callback will reject the promise, rather than // synchronously throw the error, which breaks some tests. // Rather, we wait for the callback to resolve if it is a // promise, and then re-run handleReply with the new body. body.then((newData) => handleReply(mockDispatches, newData)) return } const responseData = getResponseData(body) const responseHeaders = generateKeyValues(headers) const responseTrailers = generateKeyValues(trailers) handler.onConnect?.(err => handler.onError(err), null) handler.onHeaders?.(statusCode, responseHeaders, resume, getStatusText(statusCode)) handler.onData?.(Buffer.from(responseData)) handler.onComplete?.(responseTrailers) deleteMockDispatch(mockDispatches, key) } function resume () {} return true } function buildMockDispatch () { const agent = this[kMockAgent] const origin = this[kOrigin] const originalDispatch = this[kOriginalDispatch] return function dispatch (opts, handler) { if (agent.isMockActive) { try { mockDispatch.call(this, opts, handler) } catch (error) { if (error instanceof MockNotMatchedError) { const netConnect = agent[kGetNetConnect]() if (netConnect === false) { throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`) } if (checkNetConnect(netConnect, origin)) { originalDispatch.call(this, opts, handler) } else { throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`) } } else { throw error } } } else { originalDispatch.call(this, opts, handler) } } } function checkNetConnect (netConnect, origin) { const url = new URL(origin) if (netConnect === true) { return true } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) { return true } return false } function buildAndValidateMockOptions (opts) { if (opts) { const { agent, ...mockOptions } = opts if ('enableCallHistory' in mockOptions && typeof mockOptions.enableCallHistory !== 'boolean') { throw new InvalidArgumentError('options.enableCallHistory must to be a boolean') } if ('acceptNonStandardSearchParameters' in mockOptions && typeof mockOptions.acceptNonStandardSearchParameters !== 'boolean') { throw new InvalidArgumentError('options.acceptNonStandardSearchParameters must to be a boolean') } return mockOptions } } module.exports = { getResponseData, getMockDispatch, addMockDispatch, deleteMockDispatch, buildKey, generateKeyValues, matchValue, getResponse, getStatusText, mockDispatch, buildMockDispatch, checkNetConnect, buildAndValidateMockOptions, getHeaderByName, buildHeadersFromArray, normalizeSearchParams } /***/ }), /***/ 5555: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Transform } = __nccwpck_require__(57075) const { Console } = __nccwpck_require__(37540) const PERSISTENT = process.versions.icu ? '✅' : 'Y ' const NOT_PERSISTENT = process.versions.icu ? '❌' : 'N ' /** * Gets the output of `console.table(…)` as a string. */ module.exports = class PendingInterceptorsFormatter { constructor ({ disableColors } = {}) { this.transform = new Transform({ transform (chunk, _enc, cb) { cb(null, chunk) } }) this.logger = new Console({ stdout: this.transform, inspectOptions: { colors: !disableColors && !process.env.CI } }) } format (pendingInterceptors) { const withPrettyHeaders = pendingInterceptors.map( ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ Method: method, Origin: origin, Path: path, 'Status code': statusCode, Persistent: persist ? PERSISTENT : NOT_PERSISTENT, Invocations: timesInvoked, Remaining: persist ? Infinity : times - timesInvoked })) this.logger.table(withPrettyHeaders) return this.transform.read().toString() } } /***/ }), /***/ 27128: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { safeHTTPMethods } = __nccwpck_require__(46425) const { serializePathWithQuery } = __nccwpck_require__(46425) /** * @param {import('../../types/dispatcher.d.ts').default.DispatchOptions} opts */ function makeCacheKey (opts) { if (!opts.origin) { throw new Error('opts.origin is undefined') } let fullPath try { fullPath = serializePathWithQuery(opts.path || '/', opts.query) } catch (error) { // If fails (path already has query params), use as-is fullPath = opts.path || '/' } return { origin: opts.origin.toString(), method: opts.method, path: fullPath, headers: opts.headers } } /** * @param {Record} * @returns {Record} */ function normaliseHeaders (opts) { let headers if (opts.headers == null) { headers = {} } else if (typeof opts.headers[Symbol.iterator] === 'function') { headers = {} for (const x of opts.headers) { if (!Array.isArray(x)) { throw new Error('opts.headers is not a valid header map') } const [key, val] = x if (typeof key !== 'string' || typeof val !== 'string') { throw new Error('opts.headers is not a valid header map') } headers[key.toLowerCase()] = val } } else if (typeof opts.headers === 'object') { headers = {} for (const key of Object.keys(opts.headers)) { headers[key.toLowerCase()] = opts.headers[key] } } else { throw new Error('opts.headers is not an object') } return headers } /** * @param {any} key */ function assertCacheKey (key) { if (typeof key !== 'object') { throw new TypeError(`expected key to be object, got ${typeof key}`) } for (const property of ['origin', 'method', 'path']) { if (typeof key[property] !== 'string') { throw new TypeError(`expected key.${property} to be string, got ${typeof key[property]}`) } } if (key.headers !== undefined && typeof key.headers !== 'object') { throw new TypeError(`expected headers to be object, got ${typeof key}`) } } /** * @param {any} value */ function assertCacheValue (value) { if (typeof value !== 'object') { throw new TypeError(`expected value to be object, got ${typeof value}`) } for (const property of ['statusCode', 'cachedAt', 'staleAt', 'deleteAt']) { if (typeof value[property] !== 'number') { throw new TypeError(`expected value.${property} to be number, got ${typeof value[property]}`) } } if (typeof value.statusMessage !== 'string') { throw new TypeError(`expected value.statusMessage to be string, got ${typeof value.statusMessage}`) } if (value.headers != null && typeof value.headers !== 'object') { throw new TypeError(`expected value.rawHeaders to be object, got ${typeof value.headers}`) } if (value.vary !== undefined && typeof value.vary !== 'object') { throw new TypeError(`expected value.vary to be object, got ${typeof value.vary}`) } if (value.etag !== undefined && typeof value.etag !== 'string') { throw new TypeError(`expected value.etag to be string, got ${typeof value.etag}`) } } /** * @see https://www.rfc-editor.org/rfc/rfc9111.html#name-cache-control * @see https://www.iana.org/assignments/http-cache-directives/http-cache-directives.xhtml * @param {string | string[]} header * @returns {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} */ function parseCacheControlHeader (header) { /** * @type {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} */ const output = {} let directives if (Array.isArray(header)) { directives = [] for (const directive of header) { directives.push(...directive.split(',')) } } else { directives = header.split(',') } for (let i = 0; i < directives.length; i++) { const directive = directives[i].toLowerCase() const keyValueDelimiter = directive.indexOf('=') let key let value if (keyValueDelimiter !== -1) { key = directive.substring(0, keyValueDelimiter).trimStart() value = directive.substring(keyValueDelimiter + 1) } else { key = directive.trim() } switch (key) { case 'min-fresh': case 'max-stale': case 'max-age': case 's-maxage': case 'stale-while-revalidate': case 'stale-if-error': { if (value === undefined || value[0] === ' ') { continue } if ( value.length >= 2 && value[0] === '"' && value[value.length - 1] === '"' ) { value = value.substring(1, value.length - 1) } const parsedValue = parseInt(value, 10) // eslint-disable-next-line no-self-compare if (parsedValue !== parsedValue) { continue } if (key === 'max-age' && key in output && output[key] >= parsedValue) { continue } output[key] = parsedValue break } case 'private': case 'no-cache': { if (value) { // The private and no-cache directives can be unqualified (aka just // `private` or `no-cache`) or qualified (w/ a value). When they're // qualified, it's a list of headers like `no-cache=header1`, // `no-cache="header1"`, or `no-cache="header1, header2"` // If we're given multiple headers, the comma messes us up since // we split the full header by commas. So, let's loop through the // remaining parts in front of us until we find one that ends in a // quote. We can then just splice all of the parts in between the // starting quote and the ending quote out of the directives array // and continue parsing like normal. // https://www.rfc-editor.org/rfc/rfc9111.html#name-no-cache-2 if (value[0] === '"') { // Something like `no-cache="some-header"` OR `no-cache="some-header, another-header"`. // Add the first header on and cut off the leading quote const headers = [value.substring(1)] let foundEndingQuote = value[value.length - 1] === '"' if (!foundEndingQuote) { // Something like `no-cache="some-header, another-header"` // This can still be something invalid, e.g. `no-cache="some-header, ...` for (let j = i + 1; j < directives.length; j++) { const nextPart = directives[j] const nextPartLength = nextPart.length headers.push(nextPart.trim()) if (nextPartLength !== 0 && nextPart[nextPartLength - 1] === '"') { foundEndingQuote = true break } } } if (foundEndingQuote) { let lastHeader = headers[headers.length - 1] if (lastHeader[lastHeader.length - 1] === '"') { lastHeader = lastHeader.substring(0, lastHeader.length - 1) headers[headers.length - 1] = lastHeader } if (key in output) { output[key] = output[key].concat(headers) } else { output[key] = headers } } } else { // Something like `no-cache=some-header` if (key in output) { output[key] = output[key].concat(value) } else { output[key] = [value] } } break } } // eslint-disable-next-line no-fallthrough case 'public': case 'no-store': case 'must-revalidate': case 'proxy-revalidate': case 'immutable': case 'no-transform': case 'must-understand': case 'only-if-cached': if (value) { // These are qualified (something like `public=...`) when they aren't // allowed to be, skip continue } output[key] = true break default: // Ignore unknown directives as per https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.3-1 continue } } return output } /** * @param {string | string[]} varyHeader Vary header from the server * @param {Record} headers Request headers * @returns {Record} */ function parseVaryHeader (varyHeader, headers) { if (typeof varyHeader === 'string' && varyHeader.includes('*')) { return headers } const output = /** @type {Record} */ ({}) const varyingHeaders = typeof varyHeader === 'string' ? varyHeader.split(',') : varyHeader for (const header of varyingHeaders) { const trimmedHeader = header.trim().toLowerCase() output[trimmedHeader] = headers[trimmedHeader] ?? null } return output } /** * Note: this deviates from the spec a little. Empty etags ("", W/"") are valid, * however, including them in cached resposnes serves little to no purpose. * * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-etag * * @param {string} etag * @returns {boolean} */ function isEtagUsable (etag) { if (etag.length <= 2) { // Shortest an etag can be is two chars (just ""). This is where we deviate // from the spec requiring a min of 3 chars however return false } if (etag[0] === '"' && etag[etag.length - 1] === '"') { // ETag: ""asd123"" or ETag: "W/"asd123"", kinda undefined behavior in the // spec. Some servers will accept these while others don't. // ETag: "asd123" return !(etag[1] === '"' || etag.startsWith('"W/')) } if (etag.startsWith('W/"') && etag[etag.length - 1] === '"') { // ETag: W/"", also where we deviate from the spec & require a min of 3 // chars // ETag: for W/"", W/"asd123" return etag.length !== 4 } // Anything else return false } /** * @param {unknown} store * @returns {asserts store is import('../../types/cache-interceptor.d.ts').default.CacheStore} */ function assertCacheStore (store, name = 'CacheStore') { if (typeof store !== 'object' || store === null) { throw new TypeError(`expected type of ${name} to be a CacheStore, got ${store === null ? 'null' : typeof store}`) } for (const fn of ['get', 'createWriteStream', 'delete']) { if (typeof store[fn] !== 'function') { throw new TypeError(`${name} needs to have a \`${fn}()\` function`) } } } /** * @param {unknown} methods * @returns {asserts methods is import('../../types/cache-interceptor.d.ts').default.CacheMethods[]} */ function assertCacheMethods (methods, name = 'CacheMethods') { if (!Array.isArray(methods)) { throw new TypeError(`expected type of ${name} needs to be an array, got ${methods === null ? 'null' : typeof methods}`) } if (methods.length === 0) { throw new TypeError(`${name} needs to have at least one method`) } for (const method of methods) { if (!safeHTTPMethods.includes(method)) { throw new TypeError(`element of ${name}-array needs to be one of following values: ${safeHTTPMethods.join(', ')}, got ${method}`) } } } module.exports = { makeCacheKey, normaliseHeaders, assertCacheKey, assertCacheValue, parseCacheControlHeader, parseVaryHeader, isEtagUsable, assertCacheMethods, assertCacheStore } /***/ }), /***/ 48760: /***/ ((module) => { "use strict"; const IMF_DAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] const IMF_SPACES = [4, 7, 11, 16, 25] const IMF_MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] const IMF_COLONS = [19, 22] const ASCTIME_SPACES = [3, 7, 10, 19] const RFC850_DAYS = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] /** * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-date-time-formats * * @param {string} date * @param {Date} [now] * @returns {Date | undefined} */ function parseHttpDate (date, now) { // Sun, 06 Nov 1994 08:49:37 GMT ; IMF-fixdate // Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format // Sunday, 06-Nov-94 08:49:37 GMT ; obsolete RFC 850 format date = date.toLowerCase() switch (date[3]) { case ',': return parseImfDate(date) case ' ': return parseAscTimeDate(date) default: return parseRfc850Date(date, now) } } /** * @see https://httpwg.org/specs/rfc9110.html#preferred.date.format * * @param {string} date * @returns {Date | undefined} */ function parseImfDate (date) { if (date.length !== 29) { return undefined } if (!date.endsWith('gmt')) { // Unsupported timezone return undefined } for (const spaceInx of IMF_SPACES) { if (date[spaceInx] !== ' ') { return undefined } } for (const colonIdx of IMF_COLONS) { if (date[colonIdx] !== ':') { return undefined } } const dayName = date.substring(0, 3) if (!IMF_DAYS.includes(dayName)) { return undefined } const dayString = date.substring(5, 7) const day = Number.parseInt(dayString) if (isNaN(day) || (day < 10 && dayString[0] !== '0')) { // Not a number, 0, or it's less than 10 and didn't start with a 0 return undefined } const month = date.substring(8, 11) const monthIdx = IMF_MONTHS.indexOf(month) if (monthIdx === -1) { return undefined } const year = Number.parseInt(date.substring(12, 16)) if (isNaN(year)) { return undefined } const hourString = date.substring(17, 19) const hour = Number.parseInt(hourString) if (isNaN(hour) || (hour < 10 && hourString[0] !== '0')) { return undefined } const minuteString = date.substring(20, 22) const minute = Number.parseInt(minuteString) if (isNaN(minute) || (minute < 10 && minuteString[0] !== '0')) { return undefined } const secondString = date.substring(23, 25) const second = Number.parseInt(secondString) if (isNaN(second) || (second < 10 && secondString[0] !== '0')) { return undefined } return new Date(Date.UTC(year, monthIdx, day, hour, minute, second)) } /** * @see https://httpwg.org/specs/rfc9110.html#obsolete.date.formats * * @param {string} date * @returns {Date | undefined} */ function parseAscTimeDate (date) { // This is assumed to be in UTC if (date.length !== 24) { return undefined } for (const spaceIdx of ASCTIME_SPACES) { if (date[spaceIdx] !== ' ') { return undefined } } const dayName = date.substring(0, 3) if (!IMF_DAYS.includes(dayName)) { return undefined } const month = date.substring(4, 7) const monthIdx = IMF_MONTHS.indexOf(month) if (monthIdx === -1) { return undefined } const dayString = date.substring(8, 10) const day = Number.parseInt(dayString) if (isNaN(day) || (day < 10 && dayString[0] !== ' ')) { return undefined } const hourString = date.substring(11, 13) const hour = Number.parseInt(hourString) if (isNaN(hour) || (hour < 10 && hourString[0] !== '0')) { return undefined } const minuteString = date.substring(14, 16) const minute = Number.parseInt(minuteString) if (isNaN(minute) || (minute < 10 && minuteString[0] !== '0')) { return undefined } const secondString = date.substring(17, 19) const second = Number.parseInt(secondString) if (isNaN(second) || (second < 10 && secondString[0] !== '0')) { return undefined } const year = Number.parseInt(date.substring(20, 24)) if (isNaN(year)) { return undefined } return new Date(Date.UTC(year, monthIdx, day, hour, minute, second)) } /** * @see https://httpwg.org/specs/rfc9110.html#obsolete.date.formats * * @param {string} date * @param {Date} [now] * @returns {Date | undefined} */ function parseRfc850Date (date, now = new Date()) { if (!date.endsWith('gmt')) { // Unsupported timezone return undefined } const commaIndex = date.indexOf(',') if (commaIndex === -1) { return undefined } if ((date.length - commaIndex - 1) !== 23) { return undefined } const dayName = date.substring(0, commaIndex) if (!RFC850_DAYS.includes(dayName)) { return undefined } if ( date[commaIndex + 1] !== ' ' || date[commaIndex + 4] !== '-' || date[commaIndex + 8] !== '-' || date[commaIndex + 11] !== ' ' || date[commaIndex + 14] !== ':' || date[commaIndex + 17] !== ':' || date[commaIndex + 20] !== ' ' ) { return undefined } const dayString = date.substring(commaIndex + 2, commaIndex + 4) const day = Number.parseInt(dayString) if (isNaN(day) || (day < 10 && dayString[0] !== '0')) { // Not a number, or it's less than 10 and didn't start with a 0 return undefined } const month = date.substring(commaIndex + 5, commaIndex + 8) const monthIdx = IMF_MONTHS.indexOf(month) if (monthIdx === -1) { return undefined } // As of this point year is just the decade (i.e. 94) let year = Number.parseInt(date.substring(commaIndex + 9, commaIndex + 11)) if (isNaN(year)) { return undefined } const currentYear = now.getUTCFullYear() const currentDecade = currentYear % 100 const currentCentury = Math.floor(currentYear / 100) if (year > currentDecade && year - currentDecade >= 50) { // Over 50 years in future, go to previous century year += (currentCentury - 1) * 100 } else { year += currentCentury * 100 } const hourString = date.substring(commaIndex + 12, commaIndex + 14) const hour = Number.parseInt(hourString) if (isNaN(hour) || (hour < 10 && hourString[0] !== '0')) { return undefined } const minuteString = date.substring(commaIndex + 15, commaIndex + 17) const minute = Number.parseInt(minuteString) if (isNaN(minute) || (minute < 10 && minuteString[0] !== '0')) { return undefined } const secondString = date.substring(commaIndex + 18, commaIndex + 20) const second = Number.parseInt(secondString) if (isNaN(second) || (second < 10 && secondString[0] !== '0')) { return undefined } return new Date(Date.UTC(year, monthIdx, day, hour, minute, second)) } module.exports = { parseHttpDate } /***/ }), /***/ 78499: /***/ ((module) => { "use strict"; /** * @template {*} T * @typedef {Object} DeferredPromise * @property {Promise} promise * @property {(value?: T) => void} resolve * @property {(reason?: any) => void} reject */ /** * @template {*} T * @returns {DeferredPromise} An object containing a promise and its resolve/reject methods. */ function createDeferredPromise () { let res let rej const promise = new Promise((resolve, reject) => { res = resolve rej = reject }) return { promise, resolve: res, reject: rej } } module.exports = { createDeferredPromise } /***/ }), /***/ 81821: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { kConnected, kPending, kRunning, kSize, kFree, kQueued } = __nccwpck_require__(83112) class ClientStats { constructor (client) { this.connected = client[kConnected] this.pending = client[kPending] this.running = client[kRunning] this.size = client[kSize] } } class PoolStats { constructor (pool) { this.connected = pool[kConnected] this.free = pool[kFree] this.pending = pool[kPending] this.queued = pool[kQueued] this.running = pool[kRunning] this.size = pool[kSize] } } module.exports = { ClientStats, PoolStats } /***/ }), /***/ 5870: /***/ ((module) => { "use strict"; /** * This module offers an optimized timer implementation designed for scenarios * where high precision is not critical. * * The timer achieves faster performance by using a low-resolution approach, * with an accuracy target of within 500ms. This makes it particularly useful * for timers with delays of 1 second or more, where exact timing is less * crucial. * * It's important to note that Node.js timers are inherently imprecise, as * delays can occur due to the event loop being blocked by other operations. * Consequently, timers may trigger later than their scheduled time. */ /** * The fastNow variable contains the internal fast timer clock value. * * @type {number} */ let fastNow = 0 /** * RESOLUTION_MS represents the target resolution time in milliseconds. * * @type {number} * @default 1000 */ const RESOLUTION_MS = 1e3 /** * TICK_MS defines the desired interval in milliseconds between each tick. * The target value is set to half the resolution time, minus 1 ms, to account * for potential event loop overhead. * * @type {number} * @default 499 */ const TICK_MS = (RESOLUTION_MS >> 1) - 1 /** * fastNowTimeout is a Node.js timer used to manage and process * the FastTimers stored in the `fastTimers` array. * * @type {NodeJS.Timeout} */ let fastNowTimeout /** * The kFastTimer symbol is used to identify FastTimer instances. * * @type {Symbol} */ const kFastTimer = Symbol('kFastTimer') /** * The fastTimers array contains all active FastTimers. * * @type {FastTimer[]} */ const fastTimers = [] /** * These constants represent the various states of a FastTimer. */ /** * The `NOT_IN_LIST` constant indicates that the FastTimer is not included * in the `fastTimers` array. Timers with this status will not be processed * during the next tick by the `onTick` function. * * A FastTimer can be re-added to the `fastTimers` array by invoking the * `refresh` method on the FastTimer instance. * * @type {-2} */ const NOT_IN_LIST = -2 /** * The `TO_BE_CLEARED` constant indicates that the FastTimer is scheduled * for removal from the `fastTimers` array. A FastTimer in this state will * be removed in the next tick by the `onTick` function and will no longer * be processed. * * This status is also set when the `clear` method is called on the FastTimer instance. * * @type {-1} */ const TO_BE_CLEARED = -1 /** * The `PENDING` constant signifies that the FastTimer is awaiting processing * in the next tick by the `onTick` function. Timers with this status will have * their `_idleStart` value set and their status updated to `ACTIVE` in the next tick. * * @type {0} */ const PENDING = 0 /** * The `ACTIVE` constant indicates that the FastTimer is active and waiting * for its timer to expire. During the next tick, the `onTick` function will * check if the timer has expired, and if so, it will execute the associated callback. * * @type {1} */ const ACTIVE = 1 /** * The onTick function processes the fastTimers array. * * @returns {void} */ function onTick () { /** * Increment the fastNow value by the TICK_MS value, despite the actual time * that has passed since the last tick. This approach ensures independence * from the system clock and delays caused by a blocked event loop. * * @type {number} */ fastNow += TICK_MS /** * The `idx` variable is used to iterate over the `fastTimers` array. * Expired timers are removed by replacing them with the last element in the array. * Consequently, `idx` is only incremented when the current element is not removed. * * @type {number} */ let idx = 0 /** * The len variable will contain the length of the fastTimers array * and will be decremented when a FastTimer should be removed from the * fastTimers array. * * @type {number} */ let len = fastTimers.length while (idx < len) { /** * @type {FastTimer} */ const timer = fastTimers[idx] // If the timer is in the ACTIVE state and the timer has expired, it will // be processed in the next tick. if (timer._state === PENDING) { // Set the _idleStart value to the fastNow value minus the TICK_MS value // to account for the time the timer was in the PENDING state. timer._idleStart = fastNow - TICK_MS timer._state = ACTIVE } else if ( timer._state === ACTIVE && fastNow >= timer._idleStart + timer._idleTimeout ) { timer._state = TO_BE_CLEARED timer._idleStart = -1 timer._onTimeout(timer._timerArg) } if (timer._state === TO_BE_CLEARED) { timer._state = NOT_IN_LIST // Move the last element to the current index and decrement len if it is // not the only element in the array. if (--len !== 0) { fastTimers[idx] = fastTimers[len] } } else { ++idx } } // Set the length of the fastTimers array to the new length and thus // removing the excess FastTimers elements from the array. fastTimers.length = len // If there are still active FastTimers in the array, refresh the Timer. // If there are no active FastTimers, the timer will be refreshed again // when a new FastTimer is instantiated. if (fastTimers.length !== 0) { refreshTimeout() } } function refreshTimeout () { // If the fastNowTimeout is already set and the Timer has the refresh()- // method available, call it to refresh the timer. // Some timer objects returned by setTimeout may not have a .refresh() // method (e.g. mocked timers in tests). if (fastNowTimeout?.refresh) { fastNowTimeout.refresh() // fastNowTimeout is not instantiated yet or refresh is not availabe, // create a new Timer. } else { clearTimeout(fastNowTimeout) fastNowTimeout = setTimeout(onTick, TICK_MS) // If the Timer has an unref method, call it to allow the process to exit, // if there are no other active handles. When using fake timers or mocked // environments (like Jest), .unref() may not be defined, fastNowTimeout?.unref() } } /** * The `FastTimer` class is a data structure designed to store and manage * timer information. */ class FastTimer { [kFastTimer] = true /** * The state of the timer, which can be one of the following: * - NOT_IN_LIST (-2) * - TO_BE_CLEARED (-1) * - PENDING (0) * - ACTIVE (1) * * @type {-2|-1|0|1} * @private */ _state = NOT_IN_LIST /** * The number of milliseconds to wait before calling the callback. * * @type {number} * @private */ _idleTimeout = -1 /** * The time in milliseconds when the timer was started. This value is used to * calculate when the timer should expire. * * @type {number} * @default -1 * @private */ _idleStart = -1 /** * The function to be executed when the timer expires. * @type {Function} * @private */ _onTimeout /** * The argument to be passed to the callback when the timer expires. * * @type {*} * @private */ _timerArg /** * @constructor * @param {Function} callback A function to be executed after the timer * expires. * @param {number} delay The time, in milliseconds that the timer should wait * before the specified function or code is executed. * @param {*} arg */ constructor (callback, delay, arg) { this._onTimeout = callback this._idleTimeout = delay this._timerArg = arg this.refresh() } /** * Sets the timer's start time to the current time, and reschedules the timer * to call its callback at the previously specified duration adjusted to the * current time. * Using this on a timer that has already called its callback will reactivate * the timer. * * @returns {void} */ refresh () { // In the special case that the timer is not in the list of active timers, // add it back to the array to be processed in the next tick by the onTick // function. if (this._state === NOT_IN_LIST) { fastTimers.push(this) } // If the timer is the only active timer, refresh the fastNowTimeout for // better resolution. if (!fastNowTimeout || fastTimers.length === 1) { refreshTimeout() } // Setting the state to PENDING will cause the timer to be reset in the // next tick by the onTick function. this._state = PENDING } /** * The `clear` method cancels the timer, preventing it from executing. * * @returns {void} * @private */ clear () { // Set the state to TO_BE_CLEARED to mark the timer for removal in the next // tick by the onTick function. this._state = TO_BE_CLEARED // Reset the _idleStart value to -1 to indicate that the timer is no longer // active. this._idleStart = -1 } } /** * This module exports a setTimeout and clearTimeout function that can be * used as a drop-in replacement for the native functions. */ module.exports = { /** * The setTimeout() method sets a timer which executes a function once the * timer expires. * @param {Function} callback A function to be executed after the timer * expires. * @param {number} delay The time, in milliseconds that the timer should * wait before the specified function or code is executed. * @param {*} [arg] An optional argument to be passed to the callback function * when the timer expires. * @returns {NodeJS.Timeout|FastTimer} */ setTimeout (callback, delay, arg) { // If the delay is less than or equal to the RESOLUTION_MS value return a // native Node.js Timer instance. return delay <= RESOLUTION_MS ? setTimeout(callback, delay, arg) : new FastTimer(callback, delay, arg) }, /** * The clearTimeout method cancels an instantiated Timer previously created * by calling setTimeout. * * @param {NodeJS.Timeout|FastTimer} timeout */ clearTimeout (timeout) { // If the timeout is a FastTimer, call its own clear method. if (timeout[kFastTimer]) { /** * @type {FastTimer} */ timeout.clear() // Otherwise it is an instance of a native NodeJS.Timeout, so call the // Node.js native clearTimeout function. } else { clearTimeout(timeout) } }, /** * The setFastTimeout() method sets a fastTimer which executes a function once * the timer expires. * @param {Function} callback A function to be executed after the timer * expires. * @param {number} delay The time, in milliseconds that the timer should * wait before the specified function or code is executed. * @param {*} [arg] An optional argument to be passed to the callback function * when the timer expires. * @returns {FastTimer} */ setFastTimeout (callback, delay, arg) { return new FastTimer(callback, delay, arg) }, /** * The clearTimeout method cancels an instantiated FastTimer previously * created by calling setFastTimeout. * * @param {FastTimer} timeout */ clearFastTimeout (timeout) { timeout.clear() }, /** * The now method returns the value of the internal fast timer clock. * * @returns {number} */ now () { return fastNow }, /** * Trigger the onTick function to process the fastTimers array. * Exported for testing purposes only. * Marking as deprecated to discourage any use outside of testing. * @deprecated * @param {number} [delay=0] The delay in milliseconds to add to the now value. */ tick (delay = 0) { fastNow += delay - RESOLUTION_MS + 1 onTick() onTick() }, /** * Reset FastTimers. * Exported for testing purposes only. * Marking as deprecated to discourage any use outside of testing. * @deprecated */ reset () { fastNow = 0 fastTimers.length = 0 clearTimeout(fastNowTimeout) fastNowTimeout = null }, /** * Exporting for testing purposes only. * Marking as deprecated to discourage any use outside of testing. * @deprecated */ kFastTimer } /***/ }), /***/ 41667: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(34589) const { kConstruct } = __nccwpck_require__(83112) const { urlEquals, getFieldValues } = __nccwpck_require__(60293) const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(46425) const { webidl } = __nccwpck_require__(16480) const { cloneResponse, fromInnerResponse, getResponseState } = __nccwpck_require__(46632) const { Request, fromInnerRequest, getRequestState } = __nccwpck_require__(7622) const { fetching } = __nccwpck_require__(25071) const { urlIsHttpHttpsScheme, readAllBytes } = __nccwpck_require__(58799) const { createDeferredPromise } = __nccwpck_require__(78499) /** * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation * @typedef {Object} CacheBatchOperation * @property {'delete' | 'put'} type * @property {any} request * @property {any} response * @property {import('../../types/cache').CacheQueryOptions} options */ /** * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list * @typedef {[any, any][]} requestResponseList */ class Cache { /** * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list * @type {requestResponseList} */ #relevantRequestResponseList constructor () { if (arguments[0] !== kConstruct) { webidl.illegalConstructor() } webidl.util.markAsUncloneable(this) this.#relevantRequestResponseList = arguments[1] } async match (request, options = {}) { webidl.brandCheck(this, Cache) const prefix = 'Cache.match' webidl.argumentLengthCheck(arguments, 1, prefix) request = webidl.converters.RequestInfo(request) options = webidl.converters.CacheQueryOptions(options, prefix, 'options') const p = this.#internalMatchAll(request, options, 1) if (p.length === 0) { return } return p[0] } async matchAll (request = undefined, options = {}) { webidl.brandCheck(this, Cache) const prefix = 'Cache.matchAll' if (request !== undefined) request = webidl.converters.RequestInfo(request) options = webidl.converters.CacheQueryOptions(options, prefix, 'options') return this.#internalMatchAll(request, options) } async add (request) { webidl.brandCheck(this, Cache) const prefix = 'Cache.add' webidl.argumentLengthCheck(arguments, 1, prefix) request = webidl.converters.RequestInfo(request) // 1. const requests = [request] // 2. const responseArrayPromise = this.addAll(requests) // 3. return await responseArrayPromise } async addAll (requests) { webidl.brandCheck(this, Cache) const prefix = 'Cache.addAll' webidl.argumentLengthCheck(arguments, 1, prefix) // 1. const responsePromises = [] // 2. const requestList = [] // 3. for (let request of requests) { if (request === undefined) { throw webidl.errors.conversionFailed({ prefix, argument: 'Argument 1', types: ['undefined is not allowed'] }) } request = webidl.converters.RequestInfo(request) if (typeof request === 'string') { continue } // 3.1 const r = getRequestState(request) // 3.2 if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') { throw webidl.errors.exception({ header: prefix, message: 'Expected http/s scheme when method is not GET.' }) } } // 4. /** @type {ReturnType[]} */ const fetchControllers = [] // 5. for (const request of requests) { // 5.1 const r = getRequestState(new Request(request)) // 5.2 if (!urlIsHttpHttpsScheme(r.url)) { throw webidl.errors.exception({ header: prefix, message: 'Expected http/s scheme.' }) } // 5.4 r.initiator = 'fetch' r.destination = 'subresource' // 5.5 requestList.push(r) // 5.6 const responsePromise = createDeferredPromise() // 5.7 fetchControllers.push(fetching({ request: r, processResponse (response) { // 1. if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) { responsePromise.reject(webidl.errors.exception({ header: 'Cache.addAll', message: 'Received an invalid status code or the request failed.' })) } else if (response.headersList.contains('vary')) { // 2. // 2.1 const fieldValues = getFieldValues(response.headersList.get('vary')) // 2.2 for (const fieldValue of fieldValues) { // 2.2.1 if (fieldValue === '*') { responsePromise.reject(webidl.errors.exception({ header: 'Cache.addAll', message: 'invalid vary field value' })) for (const controller of fetchControllers) { controller.abort() } return } } } }, processResponseEndOfBody (response) { // 1. if (response.aborted) { responsePromise.reject(new DOMException('aborted', 'AbortError')) return } // 2. responsePromise.resolve(response) } })) // 5.8 responsePromises.push(responsePromise.promise) } // 6. const p = Promise.all(responsePromises) // 7. const responses = await p // 7.1 const operations = [] // 7.2 let index = 0 // 7.3 for (const response of responses) { // 7.3.1 /** @type {CacheBatchOperation} */ const operation = { type: 'put', // 7.3.2 request: requestList[index], // 7.3.3 response // 7.3.4 } operations.push(operation) // 7.3.5 index++ // 7.3.6 } // 7.5 const cacheJobPromise = createDeferredPromise() // 7.6.1 let errorData = null // 7.6.2 try { this.#batchCacheOperations(operations) } catch (e) { errorData = e } // 7.6.3 queueMicrotask(() => { // 7.6.3.1 if (errorData === null) { cacheJobPromise.resolve(undefined) } else { // 7.6.3.2 cacheJobPromise.reject(errorData) } }) // 7.7 return cacheJobPromise.promise } async put (request, response) { webidl.brandCheck(this, Cache) const prefix = 'Cache.put' webidl.argumentLengthCheck(arguments, 2, prefix) request = webidl.converters.RequestInfo(request) response = webidl.converters.Response(response, prefix, 'response') // 1. let innerRequest = null // 2. if (webidl.is.Request(request)) { innerRequest = getRequestState(request) } else { // 3. innerRequest = getRequestState(new Request(request)) } // 4. if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') { throw webidl.errors.exception({ header: prefix, message: 'Expected an http/s scheme when method is not GET' }) } // 5. const innerResponse = getResponseState(response) // 6. if (innerResponse.status === 206) { throw webidl.errors.exception({ header: prefix, message: 'Got 206 status' }) } // 7. if (innerResponse.headersList.contains('vary')) { // 7.1. const fieldValues = getFieldValues(innerResponse.headersList.get('vary')) // 7.2. for (const fieldValue of fieldValues) { // 7.2.1 if (fieldValue === '*') { throw webidl.errors.exception({ header: prefix, message: 'Got * vary field value' }) } } } // 8. if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) { throw webidl.errors.exception({ header: prefix, message: 'Response body is locked or disturbed' }) } // 9. const clonedResponse = cloneResponse(innerResponse) // 10. const bodyReadPromise = createDeferredPromise() // 11. if (innerResponse.body != null) { // 11.1 const stream = innerResponse.body.stream // 11.2 const reader = stream.getReader() // 11.3 readAllBytes(reader, bodyReadPromise.resolve, bodyReadPromise.reject) } else { bodyReadPromise.resolve(undefined) } // 12. /** @type {CacheBatchOperation[]} */ const operations = [] // 13. /** @type {CacheBatchOperation} */ const operation = { type: 'put', // 14. request: innerRequest, // 15. response: clonedResponse // 16. } // 17. operations.push(operation) // 19. const bytes = await bodyReadPromise.promise if (clonedResponse.body != null) { clonedResponse.body.source = bytes } // 19.1 const cacheJobPromise = createDeferredPromise() // 19.2.1 let errorData = null // 19.2.2 try { this.#batchCacheOperations(operations) } catch (e) { errorData = e } // 19.2.3 queueMicrotask(() => { // 19.2.3.1 if (errorData === null) { cacheJobPromise.resolve() } else { // 19.2.3.2 cacheJobPromise.reject(errorData) } }) return cacheJobPromise.promise } async delete (request, options = {}) { webidl.brandCheck(this, Cache) const prefix = 'Cache.delete' webidl.argumentLengthCheck(arguments, 1, prefix) request = webidl.converters.RequestInfo(request) options = webidl.converters.CacheQueryOptions(options, prefix, 'options') /** * @type {Request} */ let r = null if (webidl.is.Request(request)) { r = getRequestState(request) if (r.method !== 'GET' && !options.ignoreMethod) { return false } } else { assert(typeof request === 'string') r = getRequestState(new Request(request)) } /** @type {CacheBatchOperation[]} */ const operations = [] /** @type {CacheBatchOperation} */ const operation = { type: 'delete', request: r, options } operations.push(operation) const cacheJobPromise = createDeferredPromise() let errorData = null let requestResponses try { requestResponses = this.#batchCacheOperations(operations) } catch (e) { errorData = e } queueMicrotask(() => { if (errorData === null) { cacheJobPromise.resolve(!!requestResponses?.length) } else { cacheJobPromise.reject(errorData) } }) return cacheJobPromise.promise } /** * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys * @param {any} request * @param {import('../../types/cache').CacheQueryOptions} options * @returns {Promise} */ async keys (request = undefined, options = {}) { webidl.brandCheck(this, Cache) const prefix = 'Cache.keys' if (request !== undefined) request = webidl.converters.RequestInfo(request) options = webidl.converters.CacheQueryOptions(options, prefix, 'options') // 1. let r = null // 2. if (request !== undefined) { // 2.1 if (webidl.is.Request(request)) { // 2.1.1 r = getRequestState(request) // 2.1.2 if (r.method !== 'GET' && !options.ignoreMethod) { return [] } } else if (typeof request === 'string') { // 2.2 r = getRequestState(new Request(request)) } } // 4. const promise = createDeferredPromise() // 5. // 5.1 const requests = [] // 5.2 if (request === undefined) { // 5.2.1 for (const requestResponse of this.#relevantRequestResponseList) { // 5.2.1.1 requests.push(requestResponse[0]) } } else { // 5.3 // 5.3.1 const requestResponses = this.#queryCache(r, options) // 5.3.2 for (const requestResponse of requestResponses) { // 5.3.2.1 requests.push(requestResponse[0]) } } // 5.4 queueMicrotask(() => { // 5.4.1 const requestList = [] // 5.4.2 for (const request of requests) { const requestObject = fromInnerRequest( request, undefined, new AbortController().signal, 'immutable' ) // 5.4.2.1 requestList.push(requestObject) } // 5.4.3 promise.resolve(Object.freeze(requestList)) }) return promise.promise } /** * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm * @param {CacheBatchOperation[]} operations * @returns {requestResponseList} */ #batchCacheOperations (operations) { // 1. const cache = this.#relevantRequestResponseList // 2. const backupCache = [...cache] // 3. const addedItems = [] // 4.1 const resultList = [] try { // 4.2 for (const operation of operations) { // 4.2.1 if (operation.type !== 'delete' && operation.type !== 'put') { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'operation type does not match "delete" or "put"' }) } // 4.2.2 if (operation.type === 'delete' && operation.response != null) { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'delete operation should not have an associated response' }) } // 4.2.3 if (this.#queryCache(operation.request, operation.options, addedItems).length) { throw new DOMException('???', 'InvalidStateError') } // 4.2.4 let requestResponses // 4.2.5 if (operation.type === 'delete') { // 4.2.5.1 requestResponses = this.#queryCache(operation.request, operation.options) // TODO: the spec is wrong, this is needed to pass WPTs if (requestResponses.length === 0) { return [] } // 4.2.5.2 for (const requestResponse of requestResponses) { const idx = cache.indexOf(requestResponse) assert(idx !== -1) // 4.2.5.2.1 cache.splice(idx, 1) } } else if (operation.type === 'put') { // 4.2.6 // 4.2.6.1 if (operation.response == null) { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'put operation should have an associated response' }) } // 4.2.6.2 const r = operation.request // 4.2.6.3 if (!urlIsHttpHttpsScheme(r.url)) { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'expected http or https scheme' }) } // 4.2.6.4 if (r.method !== 'GET') { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'not get method' }) } // 4.2.6.5 if (operation.options != null) { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'options must not be defined' }) } // 4.2.6.6 requestResponses = this.#queryCache(operation.request) // 4.2.6.7 for (const requestResponse of requestResponses) { const idx = cache.indexOf(requestResponse) assert(idx !== -1) // 4.2.6.7.1 cache.splice(idx, 1) } // 4.2.6.8 cache.push([operation.request, operation.response]) // 4.2.6.10 addedItems.push([operation.request, operation.response]) } // 4.2.7 resultList.push([operation.request, operation.response]) } // 4.3 return resultList } catch (e) { // 5. // 5.1 this.#relevantRequestResponseList.length = 0 // 5.2 this.#relevantRequestResponseList = backupCache // 5.3 throw e } } /** * @see https://w3c.github.io/ServiceWorker/#query-cache * @param {any} requestQuery * @param {import('../../types/cache').CacheQueryOptions} options * @param {requestResponseList} targetStorage * @returns {requestResponseList} */ #queryCache (requestQuery, options, targetStorage) { /** @type {requestResponseList} */ const resultList = [] const storage = targetStorage ?? this.#relevantRequestResponseList for (const requestResponse of storage) { const [cachedRequest, cachedResponse] = requestResponse if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { resultList.push(requestResponse) } } return resultList } /** * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm * @param {any} requestQuery * @param {any} request * @param {any | null} response * @param {import('../../types/cache').CacheQueryOptions | undefined} options * @returns {boolean} */ #requestMatchesCachedItem (requestQuery, request, response = null, options) { // if (options?.ignoreMethod === false && request.method === 'GET') { // return false // } const queryURL = new URL(requestQuery.url) const cachedURL = new URL(request.url) if (options?.ignoreSearch) { cachedURL.search = '' queryURL.search = '' } if (!urlEquals(queryURL, cachedURL, true)) { return false } if ( response == null || options?.ignoreVary || !response.headersList.contains('vary') ) { return true } const fieldValues = getFieldValues(response.headersList.get('vary')) for (const fieldValue of fieldValues) { if (fieldValue === '*') { return false } const requestValue = request.headersList.get(fieldValue) const queryValue = requestQuery.headersList.get(fieldValue) // If one has the header and the other doesn't, or one has // a different value than the other, return false if (requestValue !== queryValue) { return false } } return true } #internalMatchAll (request, options, maxResponses = Infinity) { // 1. let r = null // 2. if (request !== undefined) { if (webidl.is.Request(request)) { // 2.1.1 r = getRequestState(request) // 2.1.2 if (r.method !== 'GET' && !options.ignoreMethod) { return [] } } else if (typeof request === 'string') { // 2.2.1 r = getRequestState(new Request(request)) } } // 5. // 5.1 const responses = [] // 5.2 if (request === undefined) { // 5.2.1 for (const requestResponse of this.#relevantRequestResponseList) { responses.push(requestResponse[1]) } } else { // 5.3 // 5.3.1 const requestResponses = this.#queryCache(r, options) // 5.3.2 for (const requestResponse of requestResponses) { responses.push(requestResponse[1]) } } // 5.4 // We don't implement CORs so we don't need to loop over the responses, yay! // 5.5.1 const responseList = [] // 5.5.2 for (const response of responses) { // 5.5.2.1 const responseObject = fromInnerResponse(response, 'immutable') responseList.push(responseObject.clone()) if (responseList.length >= maxResponses) { break } } // 6. return Object.freeze(responseList) } } Object.defineProperties(Cache.prototype, { [Symbol.toStringTag]: { value: 'Cache', configurable: true }, match: kEnumerableProperty, matchAll: kEnumerableProperty, add: kEnumerableProperty, addAll: kEnumerableProperty, put: kEnumerableProperty, delete: kEnumerableProperty, keys: kEnumerableProperty }) const cacheQueryOptionConverters = [ { key: 'ignoreSearch', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'ignoreMethod', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'ignoreVary', converter: webidl.converters.boolean, defaultValue: () => false } ] webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters) webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ ...cacheQueryOptionConverters, { key: 'cacheName', converter: webidl.converters.DOMString } ]) webidl.converters.Response = webidl.interfaceConverter( webidl.is.Response, 'Response' ) webidl.converters['sequence'] = webidl.sequenceConverter( webidl.converters.RequestInfo ) module.exports = { Cache } /***/ }), /***/ 39886: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Cache } = __nccwpck_require__(41667) const { webidl } = __nccwpck_require__(16480) const { kEnumerableProperty } = __nccwpck_require__(46425) const { kConstruct } = __nccwpck_require__(83112) class CacheStorage { /** * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map * @type {Map} */ async has (cacheName) { webidl.brandCheck(this, CacheStorage) const prefix = 'CacheStorage.has' webidl.argumentLengthCheck(arguments, 1, prefix) cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName') // 2.1.1 // 2.2 return this.#caches.has(cacheName) } /** * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open * @param {string} cacheName * @returns {Promise} */ async open (cacheName) { webidl.brandCheck(this, CacheStorage) const prefix = 'CacheStorage.open' webidl.argumentLengthCheck(arguments, 1, prefix) cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName') // 2.1 if (this.#caches.has(cacheName)) { // await caches.open('v1') !== await caches.open('v1') // 2.1.1 const cache = this.#caches.get(cacheName) // 2.1.1.1 return new Cache(kConstruct, cache) } // 2.2 const cache = [] // 2.3 this.#caches.set(cacheName, cache) // 2.4 return new Cache(kConstruct, cache) } /** * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete * @param {string} cacheName * @returns {Promise} */ async delete (cacheName) { webidl.brandCheck(this, CacheStorage) const prefix = 'CacheStorage.delete' webidl.argumentLengthCheck(arguments, 1, prefix) cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName') return this.#caches.delete(cacheName) } /** * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys * @returns {Promise} */ async keys () { webidl.brandCheck(this, CacheStorage) // 2.1 const keys = this.#caches.keys() // 2.2 return [...keys] } } Object.defineProperties(CacheStorage.prototype, { [Symbol.toStringTag]: { value: 'CacheStorage', configurable: true }, match: kEnumerableProperty, has: kEnumerableProperty, open: kEnumerableProperty, delete: kEnumerableProperty, keys: kEnumerableProperty }) module.exports = { CacheStorage } /***/ }), /***/ 60293: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(34589) const { URLSerializer } = __nccwpck_require__(38675) const { isValidHeaderName } = __nccwpck_require__(58799) /** * @see https://url.spec.whatwg.org/#concept-url-equals * @param {URL} A * @param {URL} B * @param {boolean | undefined} excludeFragment * @returns {boolean} */ function urlEquals (A, B, excludeFragment = false) { const serializedA = URLSerializer(A, excludeFragment) const serializedB = URLSerializer(B, excludeFragment) return serializedA === serializedB } /** * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262 * @param {string} header */ function getFieldValues (header) { assert(header !== null) const values = [] for (let value of header.split(',')) { value = value.trim() if (isValidHeaderName(value)) { values.push(value) } } return values } module.exports = { urlEquals, getFieldValues } /***/ }), /***/ 39417: /***/ ((module) => { "use strict"; // https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size const maxAttributeValueSize = 1024 // https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size const maxNameValuePairSize = 4096 module.exports = { maxAttributeValueSize, maxNameValuePairSize } /***/ }), /***/ 17236: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { parseSetCookie } = __nccwpck_require__(39575) const { stringify } = __nccwpck_require__(42134) const { webidl } = __nccwpck_require__(16480) const { Headers } = __nccwpck_require__(289) const brandChecks = webidl.brandCheckMultiple([Headers, globalThis.Headers].filter(Boolean)) /** * @typedef {Object} Cookie * @property {string} name * @property {string} value * @property {Date|number} [expires] * @property {number} [maxAge] * @property {string} [domain] * @property {string} [path] * @property {boolean} [secure] * @property {boolean} [httpOnly] * @property {'Strict'|'Lax'|'None'} [sameSite] * @property {string[]} [unparsed] */ /** * @param {Headers} headers * @returns {Record} */ function getCookies (headers) { webidl.argumentLengthCheck(arguments, 1, 'getCookies') brandChecks(headers) const cookie = headers.get('cookie') /** @type {Record} */ const out = {} if (!cookie) { return out } for (const piece of cookie.split(';')) { const [name, ...value] = piece.split('=') out[name.trim()] = value.join('=') } return out } /** * @param {Headers} headers * @param {string} name * @param {{ path?: string, domain?: string }|undefined} attributes * @returns {void} */ function deleteCookie (headers, name, attributes) { brandChecks(headers) const prefix = 'deleteCookie' webidl.argumentLengthCheck(arguments, 2, prefix) name = webidl.converters.DOMString(name, prefix, 'name') attributes = webidl.converters.DeleteCookieAttributes(attributes) // Matches behavior of // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 setCookie(headers, { name, value: '', expires: new Date(0), ...attributes }) } /** * @param {Headers} headers * @returns {Cookie[]} */ function getSetCookies (headers) { webidl.argumentLengthCheck(arguments, 1, 'getSetCookies') brandChecks(headers) const cookies = headers.getSetCookie() if (!cookies) { return [] } return cookies.map((pair) => parseSetCookie(pair)) } /** * Parses a cookie string * @param {string} cookie */ function parseCookie (cookie) { cookie = webidl.converters.DOMString(cookie) return parseSetCookie(cookie) } /** * @param {Headers} headers * @param {Cookie} cookie * @returns {void} */ function setCookie (headers, cookie) { webidl.argumentLengthCheck(arguments, 2, 'setCookie') brandChecks(headers) cookie = webidl.converters.Cookie(cookie) const str = stringify(cookie) if (str) { headers.append('set-cookie', str, true) } } webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([ { converter: webidl.nullableConverter(webidl.converters.DOMString), key: 'path', defaultValue: () => null }, { converter: webidl.nullableConverter(webidl.converters.DOMString), key: 'domain', defaultValue: () => null } ]) webidl.converters.Cookie = webidl.dictionaryConverter([ { converter: webidl.converters.DOMString, key: 'name' }, { converter: webidl.converters.DOMString, key: 'value' }, { converter: webidl.nullableConverter((value) => { if (typeof value === 'number') { return webidl.converters['unsigned long long'](value) } return new Date(value) }), key: 'expires', defaultValue: () => null }, { converter: webidl.nullableConverter(webidl.converters['long long']), key: 'maxAge', defaultValue: () => null }, { converter: webidl.nullableConverter(webidl.converters.DOMString), key: 'domain', defaultValue: () => null }, { converter: webidl.nullableConverter(webidl.converters.DOMString), key: 'path', defaultValue: () => null }, { converter: webidl.nullableConverter(webidl.converters.boolean), key: 'secure', defaultValue: () => null }, { converter: webidl.nullableConverter(webidl.converters.boolean), key: 'httpOnly', defaultValue: () => null }, { converter: webidl.converters.USVString, key: 'sameSite', allowedValues: ['Strict', 'Lax', 'None'] }, { converter: webidl.sequenceConverter(webidl.converters.DOMString), key: 'unparsed', defaultValue: () => new Array(0) } ]) module.exports = { getCookies, deleteCookie, getSetCookies, setCookie, parseCookie } /***/ }), /***/ 39575: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(39417) const { isCTLExcludingHtab } = __nccwpck_require__(42134) const { collectASequenceOfCodePointsFast } = __nccwpck_require__(38675) const assert = __nccwpck_require__(34589) const { unescape } = __nccwpck_require__(41792) /** * @description Parses the field-value attributes of a set-cookie header string. * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 * @param {string} header * @returns {import('./index').Cookie|null} if the header is invalid, null will be returned */ function parseSetCookie (header) { // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F // character (CTL characters excluding HTAB): Abort these steps and // ignore the set-cookie-string entirely. if (isCTLExcludingHtab(header)) { return null } let nameValuePair = '' let unparsedAttributes = '' let name = '' let value = '' // 2. If the set-cookie-string contains a %x3B (";") character: if (header.includes(';')) { // 1. The name-value-pair string consists of the characters up to, // but not including, the first %x3B (";"), and the unparsed- // attributes consist of the remainder of the set-cookie-string // (including the %x3B (";") in question). const position = { position: 0 } nameValuePair = collectASequenceOfCodePointsFast(';', header, position) unparsedAttributes = header.slice(position.position) } else { // Otherwise: // 1. The name-value-pair string consists of all the characters // contained in the set-cookie-string, and the unparsed- // attributes is the empty string. nameValuePair = header } // 3. If the name-value-pair string lacks a %x3D ("=") character, then // the name string is empty, and the value string is the value of // name-value-pair. if (!nameValuePair.includes('=')) { value = nameValuePair } else { // Otherwise, the name string consists of the characters up to, but // not including, the first %x3D ("=") character, and the (possibly // empty) value string consists of the characters after the first // %x3D ("=") character. const position = { position: 0 } name = collectASequenceOfCodePointsFast( '=', nameValuePair, position ) value = nameValuePair.slice(position.position + 1) } // 4. Remove any leading or trailing WSP characters from the name // string and the value string. name = name.trim() value = value.trim() // 5. If the sum of the lengths of the name string and the value string // is more than 4096 octets, abort these steps and ignore the set- // cookie-string entirely. if (name.length + value.length > maxNameValuePairSize) { return null } // 6. The cookie-name is the name string, and the cookie-value is the // value string. // https://datatracker.ietf.org/doc/html/rfc6265 // To maximize compatibility with user agents, servers that wish to // store arbitrary data in a cookie-value SHOULD encode that data, for // example, using Base64 [RFC4648]. return { name, value: unescape(value), ...parseUnparsedAttributes(unparsedAttributes) } } /** * Parses the remaining attributes of a set-cookie header * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 * @param {string} unparsedAttributes * @param {Object.} [cookieAttributeList={}] */ function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) { // 1. If the unparsed-attributes string is empty, skip the rest of // these steps. if (unparsedAttributes.length === 0) { return cookieAttributeList } // 2. Discard the first character of the unparsed-attributes (which // will be a %x3B (";") character). assert(unparsedAttributes[0] === ';') unparsedAttributes = unparsedAttributes.slice(1) let cookieAv = '' // 3. If the remaining unparsed-attributes contains a %x3B (";") // character: if (unparsedAttributes.includes(';')) { // 1. Consume the characters of the unparsed-attributes up to, but // not including, the first %x3B (";") character. cookieAv = collectASequenceOfCodePointsFast( ';', unparsedAttributes, { position: 0 } ) unparsedAttributes = unparsedAttributes.slice(cookieAv.length) } else { // Otherwise: // 1. Consume the remainder of the unparsed-attributes. cookieAv = unparsedAttributes unparsedAttributes = '' } // Let the cookie-av string be the characters consumed in this step. let attributeName = '' let attributeValue = '' // 4. If the cookie-av string contains a %x3D ("=") character: if (cookieAv.includes('=')) { // 1. The (possibly empty) attribute-name string consists of the // characters up to, but not including, the first %x3D ("=") // character, and the (possibly empty) attribute-value string // consists of the characters after the first %x3D ("=") // character. const position = { position: 0 } attributeName = collectASequenceOfCodePointsFast( '=', cookieAv, position ) attributeValue = cookieAv.slice(position.position + 1) } else { // Otherwise: // 1. The attribute-name string consists of the entire cookie-av // string, and the attribute-value string is empty. attributeName = cookieAv } // 5. Remove any leading or trailing WSP characters from the attribute- // name string and the attribute-value string. attributeName = attributeName.trim() attributeValue = attributeValue.trim() // 6. If the attribute-value is longer than 1024 octets, ignore the // cookie-av string and return to Step 1 of this algorithm. if (attributeValue.length > maxAttributeValueSize) { return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) } // 7. Process the attribute-name and attribute-value according to the // requirements in the following subsections. (Notice that // attributes with unrecognized attribute-names are ignored.) const attributeNameLowercase = attributeName.toLowerCase() // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1 // If the attribute-name case-insensitively matches the string // "Expires", the user agent MUST process the cookie-av as follows. if (attributeNameLowercase === 'expires') { // 1. Let the expiry-time be the result of parsing the attribute-value // as cookie-date (see Section 5.1.1). const expiryTime = new Date(attributeValue) // 2. If the attribute-value failed to parse as a cookie date, ignore // the cookie-av. cookieAttributeList.expires = expiryTime } else if (attributeNameLowercase === 'max-age') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2 // If the attribute-name case-insensitively matches the string "Max- // Age", the user agent MUST process the cookie-av as follows. // 1. If the first character of the attribute-value is not a DIGIT or a // "-" character, ignore the cookie-av. const charCode = attributeValue.charCodeAt(0) if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) } // 2. If the remainder of attribute-value contains a non-DIGIT // character, ignore the cookie-av. if (!/^\d+$/.test(attributeValue)) { return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) } // 3. Let delta-seconds be the attribute-value converted to an integer. const deltaSeconds = Number(attributeValue) // 4. Let cookie-age-limit be the maximum age of the cookie (which // SHOULD be 400 days or less, see Section 4.1.2.2). // 5. Set delta-seconds to the smaller of its present value and cookie- // age-limit. // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) // 6. If delta-seconds is less than or equal to zero (0), let expiry- // time be the earliest representable date and time. Otherwise, let // the expiry-time be the current date and time plus delta-seconds // seconds. // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds // 7. Append an attribute to the cookie-attribute-list with an // attribute-name of Max-Age and an attribute-value of expiry-time. cookieAttributeList.maxAge = deltaSeconds } else if (attributeNameLowercase === 'domain') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3 // If the attribute-name case-insensitively matches the string "Domain", // the user agent MUST process the cookie-av as follows. // 1. Let cookie-domain be the attribute-value. let cookieDomain = attributeValue // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be // cookie-domain without its leading %x2E ("."). if (cookieDomain[0] === '.') { cookieDomain = cookieDomain.slice(1) } // 3. Convert the cookie-domain to lower case. cookieDomain = cookieDomain.toLowerCase() // 4. Append an attribute to the cookie-attribute-list with an // attribute-name of Domain and an attribute-value of cookie-domain. cookieAttributeList.domain = cookieDomain } else if (attributeNameLowercase === 'path') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4 // If the attribute-name case-insensitively matches the string "Path", // the user agent MUST process the cookie-av as follows. // 1. If the attribute-value is empty or if the first character of the // attribute-value is not %x2F ("/"): let cookiePath = '' if (attributeValue.length === 0 || attributeValue[0] !== '/') { // 1. Let cookie-path be the default-path. cookiePath = '/' } else { // Otherwise: // 1. Let cookie-path be the attribute-value. cookiePath = attributeValue } // 2. Append an attribute to the cookie-attribute-list with an // attribute-name of Path and an attribute-value of cookie-path. cookieAttributeList.path = cookiePath } else if (attributeNameLowercase === 'secure') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5 // If the attribute-name case-insensitively matches the string "Secure", // the user agent MUST append an attribute to the cookie-attribute-list // with an attribute-name of Secure and an empty attribute-value. cookieAttributeList.secure = true } else if (attributeNameLowercase === 'httponly') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6 // If the attribute-name case-insensitively matches the string // "HttpOnly", the user agent MUST append an attribute to the cookie- // attribute-list with an attribute-name of HttpOnly and an empty // attribute-value. cookieAttributeList.httpOnly = true } else if (attributeNameLowercase === 'samesite') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7 // If the attribute-name case-insensitively matches the string // "SameSite", the user agent MUST process the cookie-av as follows: // 1. Let enforcement be "Default". let enforcement = 'Default' const attributeValueLowercase = attributeValue.toLowerCase() // 2. If cookie-av's attribute-value is a case-insensitive match for // "None", set enforcement to "None". if (attributeValueLowercase.includes('none')) { enforcement = 'None' } // 3. If cookie-av's attribute-value is a case-insensitive match for // "Strict", set enforcement to "Strict". if (attributeValueLowercase.includes('strict')) { enforcement = 'Strict' } // 4. If cookie-av's attribute-value is a case-insensitive match for // "Lax", set enforcement to "Lax". if (attributeValueLowercase.includes('lax')) { enforcement = 'Lax' } // 5. Append an attribute to the cookie-attribute-list with an // attribute-name of "SameSite" and an attribute-value of // enforcement. cookieAttributeList.sameSite = enforcement } else { cookieAttributeList.unparsed ??= [] cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) } // 8. Return to Step 1 of this algorithm. return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) } module.exports = { parseSetCookie, parseUnparsedAttributes } /***/ }), /***/ 42134: /***/ ((module) => { "use strict"; /** * @param {string} value * @returns {boolean} */ function isCTLExcludingHtab (value) { for (let i = 0; i < value.length; ++i) { const code = value.charCodeAt(i) if ( (code >= 0x00 && code <= 0x08) || (code >= 0x0A && code <= 0x1F) || code === 0x7F ) { return true } } return false } /** CHAR = token = 1* separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT * @param {string} name */ function validateCookieName (name) { for (let i = 0; i < name.length; ++i) { const code = name.charCodeAt(i) if ( code < 0x21 || // exclude CTLs (0-31), SP and HT code > 0x7E || // exclude non-ascii and DEL code === 0x22 || // " code === 0x28 || // ( code === 0x29 || // ) code === 0x3C || // < code === 0x3E || // > code === 0x40 || // @ code === 0x2C || // , code === 0x3B || // ; code === 0x3A || // : code === 0x5C || // \ code === 0x2F || // / code === 0x5B || // [ code === 0x5D || // ] code === 0x3F || // ? code === 0x3D || // = code === 0x7B || // { code === 0x7D // } ) { throw new Error('Invalid cookie name') } } } /** cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E ; US-ASCII characters excluding CTLs, ; whitespace DQUOTE, comma, semicolon, ; and backslash * @param {string} value */ function validateCookieValue (value) { let len = value.length let i = 0 // if the value is wrapped in DQUOTE if (value[0] === '"') { if (len === 1 || value[len - 1] !== '"') { throw new Error('Invalid cookie value') } --len ++i } while (i < len) { const code = value.charCodeAt(i++) if ( code < 0x21 || // exclude CTLs (0-31) code > 0x7E || // non-ascii and DEL (127) code === 0x22 || // " code === 0x2C || // , code === 0x3B || // ; code === 0x5C // \ ) { throw new Error('Invalid cookie value') } } } /** * path-value = * @param {string} path */ function validateCookiePath (path) { for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i) if ( code < 0x20 || // exclude CTLs (0-31) code === 0x7F || // DEL code === 0x3B // ; ) { throw new Error('Invalid cookie path') } } } /** * I have no idea why these values aren't allowed to be honest, * but Deno tests these. - Khafra * @param {string} domain */ function validateCookieDomain (domain) { if ( domain.startsWith('-') || domain.endsWith('.') || domain.endsWith('-') ) { throw new Error('Invalid cookie domain') } } const IMFDays = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ] const IMFMonths = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] const IMFPaddedNumbers = Array(61).fill(0).map((_, i) => i.toString().padStart(2, '0')) /** * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1 * @param {number|Date} date IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT ; fixed length/zone/capitalization subset of the format ; see Section 3.3 of [RFC5322] day-name = %x4D.6F.6E ; "Mon", case-sensitive / %x54.75.65 ; "Tue", case-sensitive / %x57.65.64 ; "Wed", case-sensitive / %x54.68.75 ; "Thu", case-sensitive / %x46.72.69 ; "Fri", case-sensitive / %x53.61.74 ; "Sat", case-sensitive / %x53.75.6E ; "Sun", case-sensitive date1 = day SP month SP year ; e.g., 02 Jun 1982 day = 2DIGIT month = %x4A.61.6E ; "Jan", case-sensitive / %x46.65.62 ; "Feb", case-sensitive / %x4D.61.72 ; "Mar", case-sensitive / %x41.70.72 ; "Apr", case-sensitive / %x4D.61.79 ; "May", case-sensitive / %x4A.75.6E ; "Jun", case-sensitive / %x4A.75.6C ; "Jul", case-sensitive / %x41.75.67 ; "Aug", case-sensitive / %x53.65.70 ; "Sep", case-sensitive / %x4F.63.74 ; "Oct", case-sensitive / %x4E.6F.76 ; "Nov", case-sensitive / %x44.65.63 ; "Dec", case-sensitive year = 4DIGIT GMT = %x47.4D.54 ; "GMT", case-sensitive time-of-day = hour ":" minute ":" second ; 00:00:00 - 23:59:60 (leap second) hour = 2DIGIT minute = 2DIGIT second = 2DIGIT */ function toIMFDate (date) { if (typeof date === 'number') { date = new Date(date) } return `${IMFDays[date.getUTCDay()]}, ${IMFPaddedNumbers[date.getUTCDate()]} ${IMFMonths[date.getUTCMonth()]} ${date.getUTCFullYear()} ${IMFPaddedNumbers[date.getUTCHours()]}:${IMFPaddedNumbers[date.getUTCMinutes()]}:${IMFPaddedNumbers[date.getUTCSeconds()]} GMT` } /** max-age-av = "Max-Age=" non-zero-digit *DIGIT ; In practice, both expires-av and max-age-av ; are limited to dates representable by the ; user agent. * @param {number} maxAge */ function validateCookieMaxAge (maxAge) { if (maxAge < 0) { throw new Error('Invalid cookie max-age') } } /** * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 * @param {import('./index').Cookie} cookie */ function stringify (cookie) { if (cookie.name.length === 0) { return null } validateCookieName(cookie.name) validateCookieValue(cookie.value) const out = [`${cookie.name}=${cookie.value}`] // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2 if (cookie.name.startsWith('__Secure-')) { cookie.secure = true } if (cookie.name.startsWith('__Host-')) { cookie.secure = true cookie.domain = null cookie.path = '/' } if (cookie.secure) { out.push('Secure') } if (cookie.httpOnly) { out.push('HttpOnly') } if (typeof cookie.maxAge === 'number') { validateCookieMaxAge(cookie.maxAge) out.push(`Max-Age=${cookie.maxAge}`) } if (cookie.domain) { validateCookieDomain(cookie.domain) out.push(`Domain=${cookie.domain}`) } if (cookie.path) { validateCookiePath(cookie.path) out.push(`Path=${cookie.path}`) } if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { out.push(`Expires=${toIMFDate(cookie.expires)}`) } if (cookie.sameSite) { out.push(`SameSite=${cookie.sameSite}`) } for (const part of cookie.unparsed) { if (!part.includes('=')) { throw new Error('Invalid unparsed') } const [key, ...value] = part.split('=') out.push(`${key.trim()}=${value.join('=')}`) } return out.join('; ') } module.exports = { isCTLExcludingHtab, validateCookieName, validateCookiePath, validateCookieValue, toIMFDate, stringify } /***/ }), /***/ 89228: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Transform } = __nccwpck_require__(57075) const { isASCIINumber, isValidLastEventId } = __nccwpck_require__(30976) /** * @type {number[]} BOM */ const BOM = [0xEF, 0xBB, 0xBF] /** * @type {10} LF */ const LF = 0x0A /** * @type {13} CR */ const CR = 0x0D /** * @type {58} COLON */ const COLON = 0x3A /** * @type {32} SPACE */ const SPACE = 0x20 /** * @typedef {object} EventSourceStreamEvent * @type {object} * @property {string} [event] The event type. * @property {string} [data] The data of the message. * @property {string} [id] A unique ID for the event. * @property {string} [retry] The reconnection time, in milliseconds. */ /** * @typedef eventSourceSettings * @type {object} * @property {string} [lastEventId] The last event ID received from the server. * @property {string} [origin] The origin of the event source. * @property {number} [reconnectionTime] The reconnection time, in milliseconds. */ class EventSourceStream extends Transform { /** * @type {eventSourceSettings} */ state /** * Leading byte-order-mark check. * @type {boolean} */ checkBOM = true /** * @type {boolean} */ crlfCheck = false /** * @type {boolean} */ eventEndCheck = false /** * @type {Buffer|null} */ buffer = null pos = 0 event = { data: undefined, event: undefined, id: undefined, retry: undefined } /** * @param {object} options * @param {boolean} [options.readableObjectMode] * @param {eventSourceSettings} [options.eventSourceSettings] * @param {(chunk: any, encoding?: BufferEncoding | undefined) => boolean} [options.push] */ constructor (options = {}) { // Enable object mode as EventSourceStream emits objects of shape // EventSourceStreamEvent options.readableObjectMode = true super(options) this.state = options.eventSourceSettings || {} if (options.push) { this.push = options.push } } /** * @param {Buffer} chunk * @param {string} _encoding * @param {Function} callback * @returns {void} */ _transform (chunk, _encoding, callback) { if (chunk.length === 0) { callback() return } // Cache the chunk in the buffer, as the data might not be complete while // processing it // TODO: Investigate if there is a more performant way to handle // incoming chunks // see: https://github.com/nodejs/undici/issues/2630 if (this.buffer) { this.buffer = Buffer.concat([this.buffer, chunk]) } else { this.buffer = chunk } // Strip leading byte-order-mark if we opened the stream and started // the processing of the incoming data if (this.checkBOM) { switch (this.buffer.length) { case 1: // Check if the first byte is the same as the first byte of the BOM if (this.buffer[0] === BOM[0]) { // If it is, we need to wait for more data callback() return } // Set the checkBOM flag to false as we don't need to check for the // BOM anymore this.checkBOM = false // The buffer only contains one byte so we need to wait for more data callback() return case 2: // Check if the first two bytes are the same as the first two bytes // of the BOM if ( this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] ) { // If it is, we need to wait for more data, because the third byte // is needed to determine if it is the BOM or not callback() return } // Set the checkBOM flag to false as we don't need to check for the // BOM anymore this.checkBOM = false break case 3: // Check if the first three bytes are the same as the first three // bytes of the BOM if ( this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2] ) { // If it is, we can drop the buffered data, as it is only the BOM this.buffer = Buffer.alloc(0) // Set the checkBOM flag to false as we don't need to check for the // BOM anymore this.checkBOM = false // Await more data callback() return } // If it is not the BOM, we can start processing the data this.checkBOM = false break default: // The buffer is longer than 3 bytes, so we can drop the BOM if it is // present if ( this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2] ) { // Remove the BOM from the buffer this.buffer = this.buffer.subarray(3) } // Set the checkBOM flag to false as we don't need to check for the this.checkBOM = false break } } while (this.pos < this.buffer.length) { // If the previous line ended with an end-of-line, we need to check // if the next character is also an end-of-line. if (this.eventEndCheck) { // If the the current character is an end-of-line, then the event // is finished and we can process it // If the previous line ended with a carriage return, we need to // check if the current character is a line feed and remove it // from the buffer. if (this.crlfCheck) { // If the current character is a line feed, we can remove it // from the buffer and reset the crlfCheck flag if (this.buffer[this.pos] === LF) { this.buffer = this.buffer.subarray(this.pos + 1) this.pos = 0 this.crlfCheck = false // It is possible that the line feed is not the end of the // event. We need to check if the next character is an // end-of-line character to determine if the event is // finished. We simply continue the loop to check the next // character. // As we removed the line feed from the buffer and set the // crlfCheck flag to false, we basically don't make any // distinction between a line feed and a carriage return. continue } this.crlfCheck = false } if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { // If the current character is a carriage return, we need to // set the crlfCheck flag to true, as we need to check if the // next character is a line feed so we can remove it from the // buffer if (this.buffer[this.pos] === CR) { this.crlfCheck = true } this.buffer = this.buffer.subarray(this.pos + 1) this.pos = 0 if ( this.event.data !== undefined || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event) } this.clearEvent() continue } // If the current character is not an end-of-line, then the event // is not finished and we have to reset the eventEndCheck flag this.eventEndCheck = false continue } // If the current character is an end-of-line, we can process the // line if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { // If the current character is a carriage return, we need to // set the crlfCheck flag to true, as we need to check if the // next character is a line feed if (this.buffer[this.pos] === CR) { this.crlfCheck = true } // In any case, we can process the line as we reached an // end-of-line character this.parseLine(this.buffer.subarray(0, this.pos), this.event) // Remove the processed line from the buffer this.buffer = this.buffer.subarray(this.pos + 1) // Reset the position as we removed the processed line from the buffer this.pos = 0 // A line was processed and this could be the end of the event. We need // to check if the next line is empty to determine if the event is // finished. this.eventEndCheck = true continue } this.pos++ } callback() } /** * @param {Buffer} line * @param {EventSourceStreamEvent} event */ parseLine (line, event) { // If the line is empty (a blank line) // Dispatch the event, as defined below. // This will be handled in the _transform method if (line.length === 0) { return } // If the line starts with a U+003A COLON character (:) // Ignore the line. const colonPosition = line.indexOf(COLON) if (colonPosition === 0) { return } let field = '' let value = '' // If the line contains a U+003A COLON character (:) if (colonPosition !== -1) { // Collect the characters on the line before the first U+003A COLON // character (:), and let field be that string. // TODO: Investigate if there is a more performant way to extract the // field // see: https://github.com/nodejs/undici/issues/2630 field = line.subarray(0, colonPosition).toString('utf8') // Collect the characters on the line after the first U+003A COLON // character (:), and let value be that string. // If value starts with a U+0020 SPACE character, remove it from value. let valueStart = colonPosition + 1 if (line[valueStart] === SPACE) { ++valueStart } // TODO: Investigate if there is a more performant way to extract the // value // see: https://github.com/nodejs/undici/issues/2630 value = line.subarray(valueStart).toString('utf8') // Otherwise, the string is not empty but does not contain a U+003A COLON // character (:) } else { // Process the field using the steps described below, using the whole // line as the field name, and the empty string as the field value. field = line.toString('utf8') value = '' } // Modify the event with the field name and value. The value is also // decoded as UTF-8 switch (field) { case 'data': if (event[field] === undefined) { event[field] = value } else { event[field] += `\n${value}` } break case 'retry': if (isASCIINumber(value)) { event[field] = value } break case 'id': if (isValidLastEventId(value)) { event[field] = value } break case 'event': if (value.length > 0) { event[field] = value } break } } /** * @param {EventSourceStreamEvent} event */ processEvent (event) { if (event.retry && isASCIINumber(event.retry)) { this.state.reconnectionTime = parseInt(event.retry, 10) } if (event.id && isValidLastEventId(event.id)) { this.state.lastEventId = event.id } // only dispatch event, when data is provided if (event.data !== undefined) { this.push({ type: event.event || 'message', options: { data: event.data, lastEventId: this.state.lastEventId, origin: this.state.origin } }) } } clearEvent () { this.event = { data: undefined, event: undefined, id: undefined, retry: undefined } } } module.exports = { EventSourceStream } /***/ }), /***/ 303: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { pipeline } = __nccwpck_require__(57075) const { fetching } = __nccwpck_require__(25071) const { makeRequest } = __nccwpck_require__(7622) const { webidl } = __nccwpck_require__(16480) const { EventSourceStream } = __nccwpck_require__(89228) const { parseMIMEType } = __nccwpck_require__(38675) const { createFastMessageEvent } = __nccwpck_require__(91979) const { isNetworkError } = __nccwpck_require__(46632) const { delay } = __nccwpck_require__(30976) const { kEnumerableProperty } = __nccwpck_require__(46425) const { environmentSettingsObject } = __nccwpck_require__(58799) let experimentalWarned = false /** * A reconnection time, in milliseconds. This must initially be an implementation-defined value, * probably in the region of a few seconds. * * In Comparison: * - Chrome uses 3000ms. * - Deno uses 5000ms. * * @type {3000} */ const defaultReconnectionTime = 3000 /** * The readyState attribute represents the state of the connection. * @typedef ReadyState * @type {0|1|2} * @readonly * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-readystate-dev */ /** * The connection has not yet been established, or it was closed and the user * agent is reconnecting. * @type {0} */ const CONNECTING = 0 /** * The user agent has an open connection and is dispatching events as it * receives them. * @type {1} */ const OPEN = 1 /** * The connection is not open, and the user agent is not trying to reconnect. * @type {2} */ const CLOSED = 2 /** * Requests for the element will have their mode set to "cors" and their credentials mode set to "same-origin". * @type {'anonymous'} */ const ANONYMOUS = 'anonymous' /** * Requests for the element will have their mode set to "cors" and their credentials mode set to "include". * @type {'use-credentials'} */ const USE_CREDENTIALS = 'use-credentials' /** * The EventSource interface is used to receive server-sent events. It * connects to a server over HTTP and receives events in text/event-stream * format without closing the connection. * @extends {EventTarget} * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events * @api public */ class EventSource extends EventTarget { #events = { open: null, error: null, message: null } #url #withCredentials = false /** * @type {ReadyState} */ #readyState = CONNECTING #request = null #controller = null #dispatcher /** * @type {import('./eventsource-stream').eventSourceSettings} */ #state /** * Creates a new EventSource object. * @param {string} url * @param {EventSourceInit} [eventSourceInitDict={}] * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface */ constructor (url, eventSourceInitDict = {}) { // 1. Let ev be a new EventSource object. super() webidl.util.markAsUncloneable(this) const prefix = 'EventSource constructor' webidl.argumentLengthCheck(arguments, 1, prefix) if (!experimentalWarned) { experimentalWarned = true process.emitWarning('EventSource is experimental, expect them to change at any time.', { code: 'UNDICI-ES' }) } url = webidl.converters.USVString(url) eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, 'eventSourceInitDict') this.#dispatcher = eventSourceInitDict.dispatcher this.#state = { lastEventId: '', reconnectionTime: defaultReconnectionTime } // 2. Let settings be ev's relevant settings object. // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object const settings = environmentSettingsObject let urlRecord try { // 3. Let urlRecord be the result of encoding-parsing a URL given url, relative to settings. urlRecord = new URL(url, settings.settingsObject.baseUrl) this.#state.origin = urlRecord.origin } catch (e) { // 4. If urlRecord is failure, then throw a "SyntaxError" DOMException. throw new DOMException(e, 'SyntaxError') } // 5. Set ev's url to urlRecord. this.#url = urlRecord.href // 6. Let corsAttributeState be Anonymous. let corsAttributeState = ANONYMOUS // 7. If the value of eventSourceInitDict's withCredentials member is true, // then set corsAttributeState to Use Credentials and set ev's // withCredentials attribute to true. if (eventSourceInitDict.withCredentials === true) { corsAttributeState = USE_CREDENTIALS this.#withCredentials = true } // 8. Let request be the result of creating a potential-CORS request given // urlRecord, the empty string, and corsAttributeState. const initRequest = { redirect: 'follow', keepalive: true, // @see https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes mode: 'cors', credentials: corsAttributeState === 'anonymous' ? 'same-origin' : 'omit', referrer: 'no-referrer' } // 9. Set request's client to settings. initRequest.client = environmentSettingsObject.settingsObject // 10. User agents may set (`Accept`, `text/event-stream`) in request's header list. initRequest.headersList = [['accept', { name: 'accept', value: 'text/event-stream' }]] // 11. Set request's cache mode to "no-store". initRequest.cache = 'no-store' // 12. Set request's initiator type to "other". initRequest.initiator = 'other' initRequest.urlList = [new URL(this.#url)] // 13. Set ev's request to request. this.#request = makeRequest(initRequest) this.#connect() } /** * Returns the state of this EventSource object's connection. It can have the * values described below. * @returns {ReadyState} * @readonly */ get readyState () { return this.#readyState } /** * Returns the URL providing the event stream. * @readonly * @returns {string} */ get url () { return this.#url } /** * Returns a boolean indicating whether the EventSource object was * instantiated with CORS credentials set (true), or not (false, the default). */ get withCredentials () { return this.#withCredentials } #connect () { if (this.#readyState === CLOSED) return this.#readyState = CONNECTING const fetchParams = { request: this.#request, dispatcher: this.#dispatcher } // 14. Let processEventSourceEndOfBody given response res be the following step: if res is not a network error, then reestablish the connection. const processEventSourceEndOfBody = (response) => { if (!isNetworkError(response)) { return this.#reconnect() } } // 15. Fetch request, with processResponseEndOfBody set to processEventSourceEndOfBody... fetchParams.processResponseEndOfBody = processEventSourceEndOfBody // and processResponse set to the following steps given response res: fetchParams.processResponse = (response) => { // 1. If res is an aborted network error, then fail the connection. if (isNetworkError(response)) { // 1. When a user agent is to fail the connection, the user agent // must queue a task which, if the readyState attribute is set to a // value other than CLOSED, sets the readyState attribute to CLOSED // and fires an event named error at the EventSource object. Once the // user agent has failed the connection, it does not attempt to // reconnect. if (response.aborted) { this.close() this.dispatchEvent(new Event('error')) return // 2. Otherwise, if res is a network error, then reestablish the // connection, unless the user agent knows that to be futile, in // which case the user agent may fail the connection. } else { this.#reconnect() return } } // 3. Otherwise, if res's status is not 200, or if res's `Content-Type` // is not `text/event-stream`, then fail the connection. const contentType = response.headersList.get('content-type', true) const mimeType = contentType !== null ? parseMIMEType(contentType) : 'failure' const contentTypeValid = mimeType !== 'failure' && mimeType.essence === 'text/event-stream' if ( response.status !== 200 || contentTypeValid === false ) { this.close() this.dispatchEvent(new Event('error')) return } // 4. Otherwise, announce the connection and interpret res's body // line by line. // When a user agent is to announce the connection, the user agent // must queue a task which, if the readyState attribute is set to a // value other than CLOSED, sets the readyState attribute to OPEN // and fires an event named open at the EventSource object. // @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model this.#readyState = OPEN this.dispatchEvent(new Event('open')) // If redirected to a different origin, set the origin to the new origin. this.#state.origin = response.urlList[response.urlList.length - 1].origin const eventSourceStream = new EventSourceStream({ eventSourceSettings: this.#state, push: (event) => { this.dispatchEvent(createFastMessageEvent( event.type, event.options )) } }) pipeline(response.body.stream, eventSourceStream, (error) => { if ( error?.aborted === false ) { this.close() this.dispatchEvent(new Event('error')) } }) } this.#controller = fetching(fetchParams) } /** * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model * @returns {Promise} */ async #reconnect () { // When a user agent is to reestablish the connection, the user agent must // run the following steps. These steps are run in parallel, not as part of // a task. (The tasks that it queues, of course, are run like normal tasks // and not themselves in parallel.) // 1. Queue a task to run the following steps: // 1. If the readyState attribute is set to CLOSED, abort the task. if (this.#readyState === CLOSED) return // 2. Set the readyState attribute to CONNECTING. this.#readyState = CONNECTING // 3. Fire an event named error at the EventSource object. this.dispatchEvent(new Event('error')) // 2. Wait a delay equal to the reconnection time of the event source. await delay(this.#state.reconnectionTime) // 5. Queue a task to run the following steps: // 1. If the EventSource object's readyState attribute is not set to // CONNECTING, then return. if (this.#readyState !== CONNECTING) return // 2. Let request be the EventSource object's request. // 3. If the EventSource object's last event ID string is not the empty // string, then: // 1. Let lastEventIDValue be the EventSource object's last event ID // string, encoded as UTF-8. // 2. Set (`Last-Event-ID`, lastEventIDValue) in request's header // list. if (this.#state.lastEventId.length) { this.#request.headersList.set('last-event-id', this.#state.lastEventId, true) } // 4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this section. this.#connect() } /** * Closes the connection, if any, and sets the readyState attribute to * CLOSED. */ close () { webidl.brandCheck(this, EventSource) if (this.#readyState === CLOSED) return this.#readyState = CLOSED this.#controller.abort() this.#request = null } get onopen () { return this.#events.open } set onopen (fn) { if (this.#events.open) { this.removeEventListener('open', this.#events.open) } if (typeof fn === 'function') { this.#events.open = fn this.addEventListener('open', fn) } else { this.#events.open = null } } get onmessage () { return this.#events.message } set onmessage (fn) { if (this.#events.message) { this.removeEventListener('message', this.#events.message) } if (typeof fn === 'function') { this.#events.message = fn this.addEventListener('message', fn) } else { this.#events.message = null } } get onerror () { return this.#events.error } set onerror (fn) { if (this.#events.error) { this.removeEventListener('error', this.#events.error) } if (typeof fn === 'function') { this.#events.error = fn this.addEventListener('error', fn) } else { this.#events.error = null } } } const constantsPropertyDescriptors = { CONNECTING: { __proto__: null, configurable: false, enumerable: true, value: CONNECTING, writable: false }, OPEN: { __proto__: null, configurable: false, enumerable: true, value: OPEN, writable: false }, CLOSED: { __proto__: null, configurable: false, enumerable: true, value: CLOSED, writable: false } } Object.defineProperties(EventSource, constantsPropertyDescriptors) Object.defineProperties(EventSource.prototype, constantsPropertyDescriptors) Object.defineProperties(EventSource.prototype, { close: kEnumerableProperty, onerror: kEnumerableProperty, onmessage: kEnumerableProperty, onopen: kEnumerableProperty, readyState: kEnumerableProperty, url: kEnumerableProperty, withCredentials: kEnumerableProperty }) webidl.converters.EventSourceInitDict = webidl.dictionaryConverter([ { key: 'withCredentials', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'dispatcher', // undici only converter: webidl.converters.any } ]) module.exports = { EventSource, defaultReconnectionTime } /***/ }), /***/ 30976: /***/ ((module) => { "use strict"; /** * Checks if the given value is a valid LastEventId. * @param {string} value * @returns {boolean} */ function isValidLastEventId (value) { // LastEventId should not contain U+0000 NULL return value.indexOf('\u0000') === -1 } /** * Checks if the given value is a base 10 digit. * @param {string} value * @returns {boolean} */ function isASCIINumber (value) { if (value.length === 0) return false for (let i = 0; i < value.length; i++) { if (value.charCodeAt(i) < 0x30 || value.charCodeAt(i) > 0x39) return false } return true } // https://github.com/nodejs/undici/issues/2664 function delay (ms) { return new Promise((resolve) => { setTimeout(resolve, ms) }) } module.exports = { isValidLastEventId, isASCIINumber, delay } /***/ }), /***/ 27679: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const util = __nccwpck_require__(46425) const { ReadableStreamFrom, readableStreamClose, fullyReadBody, extractMimeType, utf8DecodeBytes } = __nccwpck_require__(58799) const { FormData, setFormDataState } = __nccwpck_require__(30717) const { webidl } = __nccwpck_require__(16480) const { Blob } = __nccwpck_require__(4573) const assert = __nccwpck_require__(34589) const { isErrored, isDisturbed } = __nccwpck_require__(57075) const { isArrayBuffer } = __nccwpck_require__(73429) const { serializeAMimeType } = __nccwpck_require__(38675) const { multipartFormDataParser } = __nccwpck_require__(46389) const { createDeferredPromise } = __nccwpck_require__(78499) let random try { const crypto = __nccwpck_require__(77598) random = (max) => crypto.randomInt(0, max) } catch { random = (max) => Math.floor(Math.random() * max) } const textEncoder = new TextEncoder() function noop () {} const streamRegistry = new FinalizationRegistry((weakRef) => { const stream = weakRef.deref() if (stream && !stream.locked && !isDisturbed(stream) && !isErrored(stream)) { stream.cancel('Response object has been garbage collected').catch(noop) } }) /** * Extract a body with type from a byte sequence or BodyInit object * * @param {import('../../../types').BodyInit} object - The BodyInit object to extract from * @param {boolean} [keepalive=false] - If true, indicates that the body * @returns {[{stream: ReadableStream, source: any, length: number | null}, string | null]} - Returns a tuple containing the body and its type * * @see https://fetch.spec.whatwg.org/#concept-bodyinit-extract */ function extractBody (object, keepalive = false) { // 1. Let stream be null. let stream = null // 2. If object is a ReadableStream object, then set stream to object. if (webidl.is.ReadableStream(object)) { stream = object } else if (webidl.is.Blob(object)) { // 3. Otherwise, if object is a Blob object, set stream to the // result of running object’s get stream. stream = object.stream() } else { // 4. Otherwise, set stream to a new ReadableStream object, and set // up stream with byte reading support. stream = new ReadableStream({ async pull (controller) { const buffer = typeof source === 'string' ? textEncoder.encode(source) : source if (buffer.byteLength) { controller.enqueue(buffer) } queueMicrotask(() => readableStreamClose(controller)) }, start () {}, type: 'bytes' }) } // 5. Assert: stream is a ReadableStream object. assert(webidl.is.ReadableStream(stream)) // 6. Let action be null. let action = null // 7. Let source be null. let source = null // 8. Let length be null. let length = null // 9. Let type be null. let type = null // 10. Switch on object: if (typeof object === 'string') { // Set source to the UTF-8 encoding of object. // Note: setting source to a Uint8Array here breaks some mocking assumptions. source = object // Set type to `text/plain;charset=UTF-8`. type = 'text/plain;charset=UTF-8' } else if (webidl.is.URLSearchParams(object)) { // URLSearchParams // spec says to run application/x-www-form-urlencoded on body.list // this is implemented in Node.js as apart of an URLSearchParams instance toString method // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490 // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100 // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. source = object.toString() // Set type to `application/x-www-form-urlencoded;charset=UTF-8`. type = 'application/x-www-form-urlencoded;charset=UTF-8' } else if (isArrayBuffer(object)) { // BufferSource/ArrayBuffer // Set source to a copy of the bytes held by object. source = new Uint8Array(object.slice()) } else if (ArrayBuffer.isView(object)) { // BufferSource/ArrayBufferView // Set source to a copy of the bytes held by object. source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)) } else if (webidl.is.FormData(object)) { const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}` const prefix = `--${boundary}\r\nContent-Disposition: form-data` /*! formdata-polyfill. MIT License. Jimmy Wärting */ const escape = (str) => str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22') const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n') // Set action to this step: run the multipart/form-data // encoding algorithm, with object’s entry list and UTF-8. // - This ensures that the body is immutable and can't be changed afterwords // - That the content-length is calculated in advance. // - And that all parts are pre-encoded and ready to be sent. const blobParts = [] const rn = new Uint8Array([13, 10]) // '\r\n' length = 0 let hasUnknownSizeValue = false for (const [name, value] of object) { if (typeof value === 'string') { const chunk = textEncoder.encode(prefix + `; name="${escape(normalizeLinefeeds(name))}"` + `\r\n\r\n${normalizeLinefeeds(value)}\r\n`) blobParts.push(chunk) length += chunk.byteLength } else { const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + `Content-Type: ${ value.type || 'application/octet-stream' }\r\n\r\n`) blobParts.push(chunk, value, rn) if (typeof value.size === 'number') { length += chunk.byteLength + value.size + rn.byteLength } else { hasUnknownSizeValue = true } } } // CRLF is appended to the body to function with legacy servers and match other implementations. // https://github.com/curl/curl/blob/3434c6b46e682452973972e8313613dfa58cd690/lib/mime.c#L1029-L1030 // https://github.com/form-data/form-data/issues/63 const chunk = textEncoder.encode(`--${boundary}--\r\n`) blobParts.push(chunk) length += chunk.byteLength if (hasUnknownSizeValue) { length = null } // Set source to object. source = object action = async function * () { for (const part of blobParts) { if (part.stream) { yield * part.stream() } else { yield part } } } // Set type to `multipart/form-data; boundary=`, // followed by the multipart/form-data boundary string generated // by the multipart/form-data encoding algorithm. type = `multipart/form-data; boundary=${boundary}` } else if (webidl.is.Blob(object)) { // Blob // Set source to object. source = object // Set length to object’s size. length = object.size // If object’s type attribute is not the empty byte sequence, set // type to its value. if (object.type) { type = object.type } } else if (typeof object[Symbol.asyncIterator] === 'function') { // If keepalive is true, then throw a TypeError. if (keepalive) { throw new TypeError('keepalive') } // If object is disturbed or locked, then throw a TypeError. if (util.isDisturbed(object) || object.locked) { throw new TypeError( 'Response body object should not be disturbed or locked' ) } stream = webidl.is.ReadableStream(object) ? object : ReadableStreamFrom(object) } // 11. If source is a byte sequence, then set action to a // step that returns source and length to source’s length. if (typeof source === 'string' || util.isBuffer(source)) { length = Buffer.byteLength(source) } // 12. If action is non-null, then run these steps in in parallel: if (action != null) { // Run action. let iterator stream = new ReadableStream({ async start () { iterator = action(object)[Symbol.asyncIterator]() }, async pull (controller) { const { value, done } = await iterator.next() if (done) { // When running action is done, close stream. queueMicrotask(() => { controller.close() controller.byobRequest?.respond(0) }) } else { // Whenever one or more bytes are available and stream is not errored, // enqueue a Uint8Array wrapping an ArrayBuffer containing the available // bytes into stream. if (!isErrored(stream)) { const buffer = new Uint8Array(value) if (buffer.byteLength) { controller.enqueue(buffer) } } } return controller.desiredSize > 0 }, async cancel (reason) { await iterator.return() }, type: 'bytes' }) } // 13. Let body be a body whose stream is stream, source is source, // and length is length. const body = { stream, source, length } // 14. Return (body, type). return [body, type] } /** * @typedef {object} ExtractBodyResult * @property {ReadableStream>} stream - The ReadableStream containing the body data * @property {any} source - The original source of the body data * @property {number | null} length - The length of the body data, or null */ /** * Safely extract a body with type from a byte sequence or BodyInit object. * * @param {import('../../../types').BodyInit} object - The BodyInit object to extract from * @param {boolean} [keepalive=false] - If true, indicates that the body * @returns {[ExtractBodyResult, string | null]} - Returns a tuple containing the body and its type * * @see https://fetch.spec.whatwg.org/#bodyinit-safely-extract */ function safelyExtractBody (object, keepalive = false) { // To safely extract a body and a `Content-Type` value from // a byte sequence or BodyInit object object, run these steps: // 1. If object is a ReadableStream object, then: if (webidl.is.ReadableStream(object)) { // Assert: object is neither disturbed nor locked. assert(!util.isDisturbed(object), 'The body has already been consumed.') assert(!object.locked, 'The stream is locked.') } // 2. Return the results of extracting object. return extractBody(object, keepalive) } function cloneBody (body) { // To clone a body body, run these steps: // https://fetch.spec.whatwg.org/#concept-body-clone // 1. Let « out1, out2 » be the result of teeing body’s stream. const { 0: out1, 1: out2 } = body.stream.tee() // 2. Set body’s stream to out1. body.stream = out1 // 3. Return a body whose stream is out2 and other members are copied from body. return { stream: out2, length: body.length, source: body.source } } function throwIfAborted (state) { if (state.aborted) { throw new DOMException('The operation was aborted.', 'AbortError') } } function bodyMixinMethods (instance, getInternalState) { const methods = { blob () { // The blob() method steps are to return the result of // running consume body with this and the following step // given a byte sequence bytes: return a Blob whose // contents are bytes and whose type attribute is this’s // MIME type. return consumeBody(this, (bytes) => { let mimeType = bodyMimeType(getInternalState(this)) if (mimeType === null) { mimeType = '' } else if (mimeType) { mimeType = serializeAMimeType(mimeType) } // Return a Blob whose contents are bytes and type attribute // is mimeType. return new Blob([bytes], { type: mimeType }) }, instance, getInternalState) }, arrayBuffer () { // The arrayBuffer() method steps are to return the result // of running consume body with this and the following step // given a byte sequence bytes: return a new ArrayBuffer // whose contents are bytes. return consumeBody(this, (bytes) => { return new Uint8Array(bytes).buffer }, instance, getInternalState) }, text () { // The text() method steps are to return the result of running // consume body with this and UTF-8 decode. return consumeBody(this, utf8DecodeBytes, instance, getInternalState) }, json () { // The json() method steps are to return the result of running // consume body with this and parse JSON from bytes. return consumeBody(this, parseJSONFromBytes, instance, getInternalState) }, formData () { // The formData() method steps are to return the result of running // consume body with this and the following step given a byte sequence bytes: return consumeBody(this, (value) => { // 1. Let mimeType be the result of get the MIME type with this. const mimeType = bodyMimeType(getInternalState(this)) // 2. If mimeType is non-null, then switch on mimeType’s essence and run // the corresponding steps: if (mimeType !== null) { switch (mimeType.essence) { case 'multipart/form-data': { // 1. ... [long step] // 2. If that fails for some reason, then throw a TypeError. const parsed = multipartFormDataParser(value, mimeType) // 3. Return a new FormData object, appending each entry, // resulting from the parsing operation, to its entry list. const fd = new FormData() setFormDataState(fd, parsed) return fd } case 'application/x-www-form-urlencoded': { // 1. Let entries be the result of parsing bytes. const entries = new URLSearchParams(value.toString()) // 2. If entries is failure, then throw a TypeError. // 3. Return a new FormData object whose entry list is entries. const fd = new FormData() for (const [name, value] of entries) { fd.append(name, value) } return fd } } } // 3. Throw a TypeError. throw new TypeError( 'Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".' ) }, instance, getInternalState) }, bytes () { // The bytes() method steps are to return the result of running consume body // with this and the following step given a byte sequence bytes: return the // result of creating a Uint8Array from bytes in this’s relevant realm. return consumeBody(this, (bytes) => { return new Uint8Array(bytes) }, instance, getInternalState) } } return methods } function mixinBody (prototype, getInternalState) { Object.assign(prototype.prototype, bodyMixinMethods(prototype, getInternalState)) } /** * @see https://fetch.spec.whatwg.org/#concept-body-consume-body * @param {any} object internal state * @param {(value: unknown) => unknown} convertBytesToJSValue * @param {any} instance * @param {(target: any) => any} getInternalState */ async function consumeBody (object, convertBytesToJSValue, instance, getInternalState) { webidl.brandCheck(object, instance) const state = getInternalState(object) // 1. If object is unusable, then return a promise rejected // with a TypeError. if (bodyUnusable(state)) { throw new TypeError('Body is unusable: Body has already been read') } throwIfAborted(state) // 2. Let promise be a new promise. const promise = createDeferredPromise() // 3. Let errorSteps given error be to reject promise with error. const errorSteps = (error) => promise.reject(error) // 4. Let successSteps given a byte sequence data be to resolve // promise with the result of running convertBytesToJSValue // with data. If that threw an exception, then run errorSteps // with that exception. const successSteps = (data) => { try { promise.resolve(convertBytesToJSValue(data)) } catch (e) { errorSteps(e) } } // 5. If object’s body is null, then run successSteps with an // empty byte sequence. if (state.body == null) { successSteps(Buffer.allocUnsafe(0)) return promise.promise } // 6. Otherwise, fully read object’s body given successSteps, // errorSteps, and object’s relevant global object. fullyReadBody(state.body, successSteps, errorSteps) // 7. Return promise. return promise.promise } /** * @see https://fetch.spec.whatwg.org/#body-unusable * @param {any} object internal state */ function bodyUnusable (object) { const body = object.body // An object including the Body interface mixin is // said to be unusable if its body is non-null and // its body’s stream is disturbed or locked. return body != null && (body.stream.locked || util.isDisturbed(body.stream)) } /** * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value * @param {Uint8Array} bytes */ function parseJSONFromBytes (bytes) { return JSON.parse(utf8DecodeBytes(bytes)) } /** * @see https://fetch.spec.whatwg.org/#concept-body-mime-type * @param {any} requestOrResponse internal state */ function bodyMimeType (requestOrResponse) { // 1. Let headers be null. // 2. If requestOrResponse is a Request object, then set headers to requestOrResponse’s request’s header list. // 3. Otherwise, set headers to requestOrResponse’s response’s header list. /** @type {import('./headers').HeadersList} */ const headers = requestOrResponse.headersList // 4. Let mimeType be the result of extracting a MIME type from headers. const mimeType = extractMimeType(headers) // 5. If mimeType is failure, then return null. if (mimeType === 'failure') { return null } // 6. Return mimeType. return mimeType } module.exports = { extractBody, safelyExtractBody, cloneBody, mixinBody, streamRegistry, bodyUnusable } /***/ }), /***/ 10546: /***/ ((module) => { "use strict"; const corsSafeListedMethods = /** @type {const} */ (['GET', 'HEAD', 'POST']) const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) const nullBodyStatus = /** @type {const} */ ([101, 204, 205, 304]) const redirectStatus = /** @type {const} */ ([301, 302, 303, 307, 308]) const redirectStatusSet = new Set(redirectStatus) /** * @see https://fetch.spec.whatwg.org/#block-bad-port */ const badPorts = /** @type {const} */ ([ '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79', '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137', '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532', '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723', '2049', '3659', '4045', '4190', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6679', '6697', '10080' ]) const badPortsSet = new Set(badPorts) /** * @see https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-header */ const referrerPolicyTokens = /** @type {const} */ ([ 'no-referrer', 'no-referrer-when-downgrade', 'same-origin', 'origin', 'strict-origin', 'origin-when-cross-origin', 'strict-origin-when-cross-origin', 'unsafe-url' ]) /** * @see https://w3c.github.io/webappsec-referrer-policy/#referrer-policies */ const referrerPolicy = /** @type {const} */ ([ '', ...referrerPolicyTokens ]) const referrerPolicyTokensSet = new Set(referrerPolicyTokens) const requestRedirect = /** @type {const} */ (['follow', 'manual', 'error']) const safeMethods = /** @type {const} */ (['GET', 'HEAD', 'OPTIONS', 'TRACE']) const safeMethodsSet = new Set(safeMethods) const requestMode = /** @type {const} */ (['navigate', 'same-origin', 'no-cors', 'cors']) const requestCredentials = /** @type {const} */ (['omit', 'same-origin', 'include']) const requestCache = /** @type {const} */ ([ 'default', 'no-store', 'reload', 'no-cache', 'force-cache', 'only-if-cached' ]) /** * @see https://fetch.spec.whatwg.org/#request-body-header-name */ const requestBodyHeader = /** @type {const} */ ([ 'content-encoding', 'content-language', 'content-location', 'content-type', // See https://github.com/nodejs/undici/issues/2021 // 'Content-Length' is a forbidden header name, which is typically // removed in the Headers implementation. However, undici doesn't // filter out headers, so we add it here. 'content-length' ]) /** * @see https://fetch.spec.whatwg.org/#enumdef-requestduplex */ const requestDuplex = /** @type {const} */ ([ 'half' ]) /** * @see http://fetch.spec.whatwg.org/#forbidden-method */ const forbiddenMethods = /** @type {const} */ (['CONNECT', 'TRACE', 'TRACK']) const forbiddenMethodsSet = new Set(forbiddenMethods) const subresource = /** @type {const} */ ([ 'audio', 'audioworklet', 'font', 'image', 'manifest', 'paintworklet', 'script', 'style', 'track', 'video', 'xslt', '' ]) const subresourceSet = new Set(subresource) module.exports = { subresource, forbiddenMethods, requestBodyHeader, referrerPolicy, requestRedirect, requestMode, requestCredentials, requestCache, redirectStatus, corsSafeListedMethods, nullBodyStatus, safeMethods, badPorts, requestDuplex, subresourceSet, badPortsSet, redirectStatusSet, corsSafeListedMethodsSet, safeMethodsSet, forbiddenMethodsSet, referrerPolicyTokens: referrerPolicyTokensSet } /***/ }), /***/ 38675: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(34589) const encoder = new TextEncoder() /** * @see https://mimesniff.spec.whatwg.org/#http-token-code-point */ const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+\-.^_|~A-Za-z0-9]+$/ const HTTP_WHITESPACE_REGEX = /[\u000A\u000D\u0009\u0020]/ // eslint-disable-line const ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g // eslint-disable-line /** * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point */ const HTTP_QUOTED_STRING_TOKENS = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/ // eslint-disable-line // https://fetch.spec.whatwg.org/#data-url-processor /** @param {URL} dataURL */ function dataURLProcessor (dataURL) { // 1. Assert: dataURL’s scheme is "data". assert(dataURL.protocol === 'data:') // 2. Let input be the result of running the URL // serializer on dataURL with exclude fragment // set to true. let input = URLSerializer(dataURL, true) // 3. Remove the leading "data:" string from input. input = input.slice(5) // 4. Let position point at the start of input. const position = { position: 0 } // 5. Let mimeType be the result of collecting a // sequence of code points that are not equal // to U+002C (,), given position. let mimeType = collectASequenceOfCodePointsFast( ',', input, position ) // 6. Strip leading and trailing ASCII whitespace // from mimeType. // Undici implementation note: we need to store the // length because if the mimetype has spaces removed, // the wrong amount will be sliced from the input in // step #9 const mimeTypeLength = mimeType.length mimeType = removeASCIIWhitespace(mimeType, true, true) // 7. If position is past the end of input, then // return failure if (position.position >= input.length) { return 'failure' } // 8. Advance position by 1. position.position++ // 9. Let encodedBody be the remainder of input. const encodedBody = input.slice(mimeTypeLength + 1) // 10. Let body be the percent-decoding of encodedBody. let body = stringPercentDecode(encodedBody) // 11. If mimeType ends with U+003B (;), followed by // zero or more U+0020 SPACE, followed by an ASCII // case-insensitive match for "base64", then: if (/;(\u0020){0,}base64$/i.test(mimeType)) { // 1. Let stringBody be the isomorphic decode of body. const stringBody = isomorphicDecode(body) // 2. Set body to the forgiving-base64 decode of // stringBody. body = forgivingBase64(stringBody) // 3. If body is failure, then return failure. if (body === 'failure') { return 'failure' } // 4. Remove the last 6 code points from mimeType. mimeType = mimeType.slice(0, -6) // 5. Remove trailing U+0020 SPACE code points from mimeType, // if any. mimeType = mimeType.replace(/(\u0020)+$/, '') // 6. Remove the last U+003B (;) code point from mimeType. mimeType = mimeType.slice(0, -1) } // 12. If mimeType starts with U+003B (;), then prepend // "text/plain" to mimeType. if (mimeType.startsWith(';')) { mimeType = 'text/plain' + mimeType } // 13. Let mimeTypeRecord be the result of parsing // mimeType. let mimeTypeRecord = parseMIMEType(mimeType) // 14. If mimeTypeRecord is failure, then set // mimeTypeRecord to text/plain;charset=US-ASCII. if (mimeTypeRecord === 'failure') { mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII') } // 15. Return a new data: URL struct whose MIME // type is mimeTypeRecord and body is body. // https://fetch.spec.whatwg.org/#data-url-struct return { mimeType: mimeTypeRecord, body } } // https://url.spec.whatwg.org/#concept-url-serializer /** * @param {URL} url * @param {boolean} excludeFragment */ function URLSerializer (url, excludeFragment = false) { if (!excludeFragment) { return url.href } const href = url.href const hashLength = url.hash.length const serialized = hashLength === 0 ? href : href.substring(0, href.length - hashLength) if (!hashLength && href.endsWith('#')) { return serialized.slice(0, -1) } return serialized } // https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points /** * @param {(char: string) => boolean} condition * @param {string} input * @param {{ position: number }} position */ function collectASequenceOfCodePoints (condition, input, position) { // 1. Let result be the empty string. let result = '' // 2. While position doesn’t point past the end of input and the // code point at position within input meets the condition condition: while (position.position < input.length && condition(input[position.position])) { // 1. Append that code point to the end of result. result += input[position.position] // 2. Advance position by 1. position.position++ } // 3. Return result. return result } /** * A faster collectASequenceOfCodePoints that only works when comparing a single character. * @param {string} char * @param {string} input * @param {{ position: number }} position */ function collectASequenceOfCodePointsFast (char, input, position) { const idx = input.indexOf(char, position.position) const start = position.position if (idx === -1) { position.position = input.length return input.slice(start) } position.position = idx return input.slice(start, position.position) } // https://url.spec.whatwg.org/#string-percent-decode /** @param {string} input */ function stringPercentDecode (input) { // 1. Let bytes be the UTF-8 encoding of input. const bytes = encoder.encode(input) // 2. Return the percent-decoding of bytes. return percentDecode(bytes) } /** * @param {number} byte */ function isHexCharByte (byte) { // 0-9 A-F a-f return (byte >= 0x30 && byte <= 0x39) || (byte >= 0x41 && byte <= 0x46) || (byte >= 0x61 && byte <= 0x66) } /** * @param {number} byte */ function hexByteToNumber (byte) { return ( // 0-9 byte >= 0x30 && byte <= 0x39 ? (byte - 48) // Convert to uppercase // ((byte & 0xDF) - 65) + 10 : ((byte & 0xDF) - 55) ) } // https://url.spec.whatwg.org/#percent-decode /** @param {Uint8Array} input */ function percentDecode (input) { const length = input.length // 1. Let output be an empty byte sequence. /** @type {Uint8Array} */ const output = new Uint8Array(length) let j = 0 // 2. For each byte byte in input: for (let i = 0; i < length; ++i) { const byte = input[i] // 1. If byte is not 0x25 (%), then append byte to output. if (byte !== 0x25) { output[j++] = byte // 2. Otherwise, if byte is 0x25 (%) and the next two bytes // after byte in input are not in the ranges // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F), // and 0x61 (a) to 0x66 (f), all inclusive, append byte // to output. } else if ( byte === 0x25 && !(isHexCharByte(input[i + 1]) && isHexCharByte(input[i + 2])) ) { output[j++] = 0x25 // 3. Otherwise: } else { // 1. Let bytePoint be the two bytes after byte in input, // decoded, and then interpreted as hexadecimal number. // 2. Append a byte whose value is bytePoint to output. output[j++] = (hexByteToNumber(input[i + 1]) << 4) | hexByteToNumber(input[i + 2]) // 3. Skip the next two bytes in input. i += 2 } } // 3. Return output. return length === j ? output : output.subarray(0, j) } // https://mimesniff.spec.whatwg.org/#parse-a-mime-type /** @param {string} input */ function parseMIMEType (input) { // 1. Remove any leading and trailing HTTP whitespace // from input. input = removeHTTPWhitespace(input, true, true) // 2. Let position be a position variable for input, // initially pointing at the start of input. const position = { position: 0 } // 3. Let type be the result of collecting a sequence // of code points that are not U+002F (/) from // input, given position. const type = collectASequenceOfCodePointsFast( '/', input, position ) // 4. If type is the empty string or does not solely // contain HTTP token code points, then return failure. // https://mimesniff.spec.whatwg.org/#http-token-code-point if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) { return 'failure' } // 5. If position is past the end of input, then return // failure if (position.position >= input.length) { return 'failure' } // 6. Advance position by 1. (This skips past U+002F (/).) position.position++ // 7. Let subtype be the result of collecting a sequence of // code points that are not U+003B (;) from input, given // position. let subtype = collectASequenceOfCodePointsFast( ';', input, position ) // 8. Remove any trailing HTTP whitespace from subtype. subtype = removeHTTPWhitespace(subtype, false, true) // 9. If subtype is the empty string or does not solely // contain HTTP token code points, then return failure. if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) { return 'failure' } const typeLowercase = type.toLowerCase() const subtypeLowercase = subtype.toLowerCase() // 10. Let mimeType be a new MIME type record whose type // is type, in ASCII lowercase, and subtype is subtype, // in ASCII lowercase. // https://mimesniff.spec.whatwg.org/#mime-type const mimeType = { type: typeLowercase, subtype: subtypeLowercase, /** @type {Map} */ parameters: new Map(), // https://mimesniff.spec.whatwg.org/#mime-type-essence essence: `${typeLowercase}/${subtypeLowercase}` } // 11. While position is not past the end of input: while (position.position < input.length) { // 1. Advance position by 1. (This skips past U+003B (;).) position.position++ // 2. Collect a sequence of code points that are HTTP // whitespace from input given position. collectASequenceOfCodePoints( // https://fetch.spec.whatwg.org/#http-whitespace char => HTTP_WHITESPACE_REGEX.test(char), input, position ) // 3. Let parameterName be the result of collecting a // sequence of code points that are not U+003B (;) // or U+003D (=) from input, given position. let parameterName = collectASequenceOfCodePoints( (char) => char !== ';' && char !== '=', input, position ) // 4. Set parameterName to parameterName, in ASCII // lowercase. parameterName = parameterName.toLowerCase() // 5. If position is not past the end of input, then: if (position.position < input.length) { // 1. If the code point at position within input is // U+003B (;), then continue. if (input[position.position] === ';') { continue } // 2. Advance position by 1. (This skips past U+003D (=).) position.position++ } // 6. If position is past the end of input, then break. if (position.position >= input.length) { break } // 7. Let parameterValue be null. let parameterValue = null // 8. If the code point at position within input is // U+0022 ("), then: if (input[position.position] === '"') { // 1. Set parameterValue to the result of collecting // an HTTP quoted string from input, given position // and the extract-value flag. parameterValue = collectAnHTTPQuotedString(input, position, true) // 2. Collect a sequence of code points that are not // U+003B (;) from input, given position. collectASequenceOfCodePointsFast( ';', input, position ) // 9. Otherwise: } else { // 1. Set parameterValue to the result of collecting // a sequence of code points that are not U+003B (;) // from input, given position. parameterValue = collectASequenceOfCodePointsFast( ';', input, position ) // 2. Remove any trailing HTTP whitespace from parameterValue. parameterValue = removeHTTPWhitespace(parameterValue, false, true) // 3. If parameterValue is the empty string, then continue. if (parameterValue.length === 0) { continue } } // 10. If all of the following are true // - parameterName is not the empty string // - parameterName solely contains HTTP token code points // - parameterValue solely contains HTTP quoted-string token code points // - mimeType’s parameters[parameterName] does not exist // then set mimeType’s parameters[parameterName] to parameterValue. if ( parameterName.length !== 0 && HTTP_TOKEN_CODEPOINTS.test(parameterName) && (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && !mimeType.parameters.has(parameterName) ) { mimeType.parameters.set(parameterName, parameterValue) } } // 12. Return mimeType. return mimeType } // https://infra.spec.whatwg.org/#forgiving-base64-decode /** @param {string} data */ function forgivingBase64 (data) { // 1. Remove all ASCII whitespace from data. data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, '') let dataLength = data.length // 2. If data’s code point length divides by 4 leaving // no remainder, then: if (dataLength % 4 === 0) { // 1. If data ends with one or two U+003D (=) code points, // then remove them from data. if (data.charCodeAt(dataLength - 1) === 0x003D) { --dataLength if (data.charCodeAt(dataLength - 1) === 0x003D) { --dataLength } } } // 3. If data’s code point length divides by 4 leaving // a remainder of 1, then return failure. if (dataLength % 4 === 1) { return 'failure' } // 4. If data contains a code point that is not one of // U+002B (+) // U+002F (/) // ASCII alphanumeric // then return failure. if (/[^+/0-9A-Za-z]/.test(data.length === dataLength ? data : data.substring(0, dataLength))) { return 'failure' } const buffer = Buffer.from(data, 'base64') return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength) } // https://fetch.spec.whatwg.org/#collect-an-http-quoted-string // tests: https://fetch.spec.whatwg.org/#example-http-quoted-string /** * @param {string} input * @param {{ position: number }} position * @param {boolean} [extractValue=false] */ function collectAnHTTPQuotedString (input, position, extractValue = false) { // 1. Let positionStart be position. const positionStart = position.position // 2. Let value be the empty string. let value = '' // 3. Assert: the code point at position within input // is U+0022 ("). assert(input[position.position] === '"') // 4. Advance position by 1. position.position++ // 5. While true: while (true) { // 1. Append the result of collecting a sequence of code points // that are not U+0022 (") or U+005C (\) from input, given // position, to value. value += collectASequenceOfCodePoints( (char) => char !== '"' && char !== '\\', input, position ) // 2. If position is past the end of input, then break. if (position.position >= input.length) { break } // 3. Let quoteOrBackslash be the code point at position within // input. const quoteOrBackslash = input[position.position] // 4. Advance position by 1. position.position++ // 5. If quoteOrBackslash is U+005C (\), then: if (quoteOrBackslash === '\\') { // 1. If position is past the end of input, then append // U+005C (\) to value and break. if (position.position >= input.length) { value += '\\' break } // 2. Append the code point at position within input to value. value += input[position.position] // 3. Advance position by 1. position.position++ // 6. Otherwise: } else { // 1. Assert: quoteOrBackslash is U+0022 ("). assert(quoteOrBackslash === '"') // 2. Break. break } } // 6. If the extract-value flag is set, then return value. if (extractValue) { return value } // 7. Return the code points from positionStart to position, // inclusive, within input. return input.slice(positionStart, position.position) } /** * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type */ function serializeAMimeType (mimeType) { assert(mimeType !== 'failure') const { parameters, essence } = mimeType // 1. Let serialization be the concatenation of mimeType’s // type, U+002F (/), and mimeType’s subtype. let serialization = essence // 2. For each name → value of mimeType’s parameters: for (let [name, value] of parameters.entries()) { // 1. Append U+003B (;) to serialization. serialization += ';' // 2. Append name to serialization. serialization += name // 3. Append U+003D (=) to serialization. serialization += '=' // 4. If value does not solely contain HTTP token code // points or value is the empty string, then: if (!HTTP_TOKEN_CODEPOINTS.test(value)) { // 1. Precede each occurrence of U+0022 (") or // U+005C (\) in value with U+005C (\). value = value.replace(/(\\|")/g, '\\$1') // 2. Prepend U+0022 (") to value. value = '"' + value // 3. Append U+0022 (") to value. value += '"' } // 5. Append value to serialization. serialization += value } // 3. Return serialization. return serialization } /** * @see https://fetch.spec.whatwg.org/#http-whitespace * @param {number} char */ function isHTTPWhiteSpace (char) { // "\r\n\t " return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x020 } /** * @see https://fetch.spec.whatwg.org/#http-whitespace * @param {string} str * @param {boolean} [leading=true] * @param {boolean} [trailing=true] */ function removeHTTPWhitespace (str, leading = true, trailing = true) { return removeChars(str, leading, trailing, isHTTPWhiteSpace) } /** * @see https://infra.spec.whatwg.org/#ascii-whitespace * @param {number} char */ function isASCIIWhitespace (char) { // "\r\n\t\f " return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x00c || char === 0x020 } /** * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace * @param {string} str * @param {boolean} [leading=true] * @param {boolean} [trailing=true] */ function removeASCIIWhitespace (str, leading = true, trailing = true) { return removeChars(str, leading, trailing, isASCIIWhitespace) } /** * @param {string} str * @param {boolean} leading * @param {boolean} trailing * @param {(charCode: number) => boolean} predicate * @returns */ function removeChars (str, leading, trailing, predicate) { let lead = 0 let trail = str.length - 1 if (leading) { while (lead < str.length && predicate(str.charCodeAt(lead))) lead++ } if (trailing) { while (trail > 0 && predicate(str.charCodeAt(trail))) trail-- } return lead === 0 && trail === str.length - 1 ? str : str.slice(lead, trail + 1) } /** * @see https://infra.spec.whatwg.org/#isomorphic-decode * @param {Uint8Array} input * @returns {string} */ function isomorphicDecode (input) { // 1. To isomorphic decode a byte sequence input, return a string whose code point // length is equal to input’s length and whose code points have the same values // as the values of input’s bytes, in the same order. const length = input.length if ((2 << 15) - 1 > length) { return String.fromCharCode.apply(null, input) } let result = ''; let i = 0 let addition = (2 << 15) - 1 while (i < length) { if (i + addition > length) { addition = length - i } result += String.fromCharCode.apply(null, input.subarray(i, i += addition)) } return result } /** * @see https://mimesniff.spec.whatwg.org/#minimize-a-supported-mime-type * @param {Exclude, 'failure'>} mimeType */ function minimizeSupportedMimeType (mimeType) { switch (mimeType.essence) { case 'application/ecmascript': case 'application/javascript': case 'application/x-ecmascript': case 'application/x-javascript': case 'text/ecmascript': case 'text/javascript': case 'text/javascript1.0': case 'text/javascript1.1': case 'text/javascript1.2': case 'text/javascript1.3': case 'text/javascript1.4': case 'text/javascript1.5': case 'text/jscript': case 'text/livescript': case 'text/x-ecmascript': case 'text/x-javascript': // 1. If mimeType is a JavaScript MIME type, then return "text/javascript". return 'text/javascript' case 'application/json': case 'text/json': // 2. If mimeType is a JSON MIME type, then return "application/json". return 'application/json' case 'image/svg+xml': // 3. If mimeType’s essence is "image/svg+xml", then return "image/svg+xml". return 'image/svg+xml' case 'text/xml': case 'application/xml': // 4. If mimeType is an XML MIME type, then return "application/xml". return 'application/xml' } // 2. If mimeType is a JSON MIME type, then return "application/json". if (mimeType.subtype.endsWith('+json')) { return 'application/json' } // 4. If mimeType is an XML MIME type, then return "application/xml". if (mimeType.subtype.endsWith('+xml')) { return 'application/xml' } // 5. If mimeType is supported by the user agent, then return mimeType’s essence. // Technically, node doesn't support any mimetypes. // 6. Return the empty string. return '' } module.exports = { dataURLProcessor, URLSerializer, collectASequenceOfCodePoints, collectASequenceOfCodePointsFast, stringPercentDecode, parseMIMEType, collectAnHTTPQuotedString, serializeAMimeType, removeChars, removeHTTPWhitespace, minimizeSupportedMimeType, HTTP_TOKEN_CODEPOINTS, isomorphicDecode } /***/ }), /***/ 46389: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { bufferToLowerCasedHeaderName } = __nccwpck_require__(46425) const { utf8DecodeBytes } = __nccwpck_require__(58799) const { HTTP_TOKEN_CODEPOINTS, isomorphicDecode } = __nccwpck_require__(38675) const { makeEntry } = __nccwpck_require__(30717) const { webidl } = __nccwpck_require__(16480) const assert = __nccwpck_require__(34589) const { File: NodeFile } = __nccwpck_require__(4573) const File = globalThis.File ?? NodeFile const formDataNameBuffer = Buffer.from('form-data; name="') const filenameBuffer = Buffer.from('filename') const dd = Buffer.from('--') const ddcrlf = Buffer.from('--\r\n') /** * @param {string} chars */ function isAsciiString (chars) { for (let i = 0; i < chars.length; ++i) { if ((chars.charCodeAt(i) & ~0x7F) !== 0) { return false } } return true } /** * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-boundary * @param {string} boundary */ function validateBoundary (boundary) { const length = boundary.length // - its length is greater or equal to 27 and lesser or equal to 70, and if (length < 27 || length > 70) { return false } // - it is composed by bytes in the ranges 0x30 to 0x39, 0x41 to 0x5A, or // 0x61 to 0x7A, inclusive (ASCII alphanumeric), or which are 0x27 ('), // 0x2D (-) or 0x5F (_). for (let i = 0; i < length; ++i) { const cp = boundary.charCodeAt(i) if (!( (cp >= 0x30 && cp <= 0x39) || (cp >= 0x41 && cp <= 0x5a) || (cp >= 0x61 && cp <= 0x7a) || cp === 0x27 || cp === 0x2d || cp === 0x5f )) { return false } } return true } /** * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-parser * @param {Buffer} input * @param {ReturnType} mimeType */ function multipartFormDataParser (input, mimeType) { // 1. Assert: mimeType’s essence is "multipart/form-data". assert(mimeType !== 'failure' && mimeType.essence === 'multipart/form-data') const boundaryString = mimeType.parameters.get('boundary') // 2. If mimeType’s parameters["boundary"] does not exist, return failure. // Otherwise, let boundary be the result of UTF-8 decoding mimeType’s // parameters["boundary"]. if (boundaryString === undefined) { throw parsingError('missing boundary in content-type header') } const boundary = Buffer.from(`--${boundaryString}`, 'utf8') // 3. Let entry list be an empty entry list. const entryList = [] // 4. Let position be a pointer to a byte in input, initially pointing at // the first byte. const position = { position: 0 } // Note: undici addition, allows leading and trailing CRLFs. while (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) { position.position += 2 } let trailing = input.length while (input[trailing - 1] === 0x0a && input[trailing - 2] === 0x0d) { trailing -= 2 } if (trailing !== input.length) { input = input.subarray(0, trailing) } // 5. While true: while (true) { // 5.1. If position points to a sequence of bytes starting with 0x2D 0x2D // (`--`) followed by boundary, advance position by 2 + the length of // boundary. Otherwise, return failure. // Note: boundary is padded with 2 dashes already, no need to add 2. if (input.subarray(position.position, position.position + boundary.length).equals(boundary)) { position.position += boundary.length } else { throw parsingError('expected a value starting with -- and the boundary') } // 5.2. If position points to the sequence of bytes 0x2D 0x2D 0x0D 0x0A // (`--` followed by CR LF) followed by the end of input, return entry list. // Note: a body does NOT need to end with CRLF. It can end with --. if ( (position.position === input.length - 2 && bufferStartsWith(input, dd, position)) || (position.position === input.length - 4 && bufferStartsWith(input, ddcrlf, position)) ) { return entryList } // 5.3. If position does not point to a sequence of bytes starting with 0x0D // 0x0A (CR LF), return failure. if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) { throw parsingError('expected CRLF') } // 5.4. Advance position by 2. (This skips past the newline.) position.position += 2 // 5.5. Let name, filename and contentType be the result of parsing // multipart/form-data headers on input and position, if the result // is not failure. Otherwise, return failure. const result = parseMultipartFormDataHeaders(input, position) let { name, filename, contentType, encoding } = result // 5.6. Advance position by 2. (This skips past the empty line that marks // the end of the headers.) position.position += 2 // 5.7. Let body be the empty byte sequence. let body // 5.8. Body loop: While position is not past the end of input: // TODO: the steps here are completely wrong { const boundaryIndex = input.indexOf(boundary.subarray(2), position.position) if (boundaryIndex === -1) { throw parsingError('expected boundary after body') } body = input.subarray(position.position, boundaryIndex - 4) position.position += body.length // Note: position must be advanced by the body's length before being // decoded, otherwise the parsing will fail. if (encoding === 'base64') { body = Buffer.from(body.toString(), 'base64') } } // 5.9. If position does not point to a sequence of bytes starting with // 0x0D 0x0A (CR LF), return failure. Otherwise, advance position by 2. if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) { throw parsingError('expected CRLF') } else { position.position += 2 } // 5.10. If filename is not null: let value if (filename !== null) { // 5.10.1. If contentType is null, set contentType to "text/plain". contentType ??= 'text/plain' // 5.10.2. If contentType is not an ASCII string, set contentType to the empty string. // Note: `buffer.isAscii` can be used at zero-cost, but converting a string to a buffer is a high overhead. // Content-Type is a relatively small string, so it is faster to use `String#charCodeAt`. if (!isAsciiString(contentType)) { contentType = '' } // 5.10.3. Let value be a new File object with name filename, type contentType, and body body. value = new File([body], filename, { type: contentType }) } else { // 5.11. Otherwise: // 5.11.1. Let value be the UTF-8 decoding without BOM of body. value = utf8DecodeBytes(Buffer.from(body)) } // 5.12. Assert: name is a scalar value string and value is either a scalar value string or a File object. assert(webidl.is.USVString(name)) assert((typeof value === 'string' && webidl.is.USVString(value)) || webidl.is.File(value)) // 5.13. Create an entry with name and value, and append it to entry list. entryList.push(makeEntry(name, value, filename)) } } /** * @see https://andreubotella.github.io/multipart-form-data/#parse-multipart-form-data-headers * @param {Buffer} input * @param {{ position: number }} position */ function parseMultipartFormDataHeaders (input, position) { // 1. Let name, filename and contentType be null. let name = null let filename = null let contentType = null let encoding = null // 2. While true: while (true) { // 2.1. If position points to a sequence of bytes starting with 0x0D 0x0A (CR LF): if (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) { // 2.1.1. If name is null, return failure. if (name === null) { throw parsingError('header name is null') } // 2.1.2. Return name, filename and contentType. return { name, filename, contentType, encoding } } // 2.2. Let header name be the result of collecting a sequence of bytes that are // not 0x0A (LF), 0x0D (CR) or 0x3A (:), given position. let headerName = collectASequenceOfBytes( (char) => char !== 0x0a && char !== 0x0d && char !== 0x3a, input, position ) // 2.3. Remove any HTTP tab or space bytes from the start or end of header name. headerName = removeChars(headerName, true, true, (char) => char === 0x9 || char === 0x20) // 2.4. If header name does not match the field-name token production, return failure. if (!HTTP_TOKEN_CODEPOINTS.test(headerName.toString())) { throw parsingError('header name does not match the field-name token production') } // 2.5. If the byte at position is not 0x3A (:), return failure. if (input[position.position] !== 0x3a) { throw parsingError('expected :') } // 2.6. Advance position by 1. position.position++ // 2.7. Collect a sequence of bytes that are HTTP tab or space bytes given position. // (Do nothing with those bytes.) collectASequenceOfBytes( (char) => char === 0x20 || char === 0x09, input, position ) // 2.8. Byte-lowercase header name and switch on the result: switch (bufferToLowerCasedHeaderName(headerName)) { case 'content-disposition': { // 1. Set name and filename to null. name = filename = null // 2. If position does not point to a sequence of bytes starting with // `form-data; name="`, return failure. if (!bufferStartsWith(input, formDataNameBuffer, position)) { throw parsingError('expected form-data; name=" for content-disposition header') } // 3. Advance position so it points at the byte after the next 0x22 (") // byte (the one in the sequence of bytes matched above). position.position += 17 // 4. Set name to the result of parsing a multipart/form-data name given // input and position, if the result is not failure. Otherwise, return // failure. name = parseMultipartFormDataName(input, position) // 5. If position points to a sequence of bytes starting with `; filename="`: if (input[position.position] === 0x3b /* ; */ && input[position.position + 1] === 0x20 /* ' ' */) { const at = { position: position.position + 2 } if (bufferStartsWith(input, filenameBuffer, at)) { if (input[at.position + 8] === 0x2a /* '*' */) { at.position += 10 // skip past filename*= // Remove leading http tab and spaces. See RFC for examples. // https://datatracker.ietf.org/doc/html/rfc6266#section-5 collectASequenceOfBytes( (char) => char === 0x20 || char === 0x09, input, at ) const headerValue = collectASequenceOfBytes( (char) => char !== 0x20 && char !== 0x0d && char !== 0x0a, // ' ' or CRLF input, at ) if ( (headerValue[0] !== 0x75 && headerValue[0] !== 0x55) || // u or U (headerValue[1] !== 0x74 && headerValue[1] !== 0x54) || // t or T (headerValue[2] !== 0x66 && headerValue[2] !== 0x46) || // f or F headerValue[3] !== 0x2d || // - headerValue[4] !== 0x38 // 8 ) { throw parsingError('unknown encoding, expected utf-8\'\'') } // skip utf-8'' filename = decodeURIComponent(new TextDecoder().decode(headerValue.subarray(7))) position.position = at.position } else { // 1. Advance position so it points at the byte after the next 0x22 (") byte // (the one in the sequence of bytes matched above). position.position += 11 // Remove leading http tab and spaces. See RFC for examples. // https://datatracker.ietf.org/doc/html/rfc6266#section-5 collectASequenceOfBytes( (char) => char === 0x20 || char === 0x09, input, position ) position.position++ // skip past " after removing whitespace // 2. Set filename to the result of parsing a multipart/form-data name given // input and position, if the result is not failure. Otherwise, return failure. filename = parseMultipartFormDataName(input, position) } } } break } case 'content-type': { // 1. Let header value be the result of collecting a sequence of bytes that are // not 0x0A (LF) or 0x0D (CR), given position. let headerValue = collectASequenceOfBytes( (char) => char !== 0x0a && char !== 0x0d, input, position ) // 2. Remove any HTTP tab or space bytes from the end of header value. headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20) // 3. Set contentType to the isomorphic decoding of header value. contentType = isomorphicDecode(headerValue) break } case 'content-transfer-encoding': { let headerValue = collectASequenceOfBytes( (char) => char !== 0x0a && char !== 0x0d, input, position ) headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20) encoding = isomorphicDecode(headerValue) break } default: { // Collect a sequence of bytes that are not 0x0A (LF) or 0x0D (CR), given position. // (Do nothing with those bytes.) collectASequenceOfBytes( (char) => char !== 0x0a && char !== 0x0d, input, position ) } } // 2.9. If position does not point to a sequence of bytes starting with 0x0D 0x0A // (CR LF), return failure. Otherwise, advance position by 2 (past the newline). if (input[position.position] !== 0x0d && input[position.position + 1] !== 0x0a) { throw parsingError('expected CRLF') } else { position.position += 2 } } } /** * @see https://andreubotella.github.io/multipart-form-data/#parse-a-multipart-form-data-name * @param {Buffer} input * @param {{ position: number }} position */ function parseMultipartFormDataName (input, position) { // 1. Assert: The byte at (position - 1) is 0x22 ("). assert(input[position.position - 1] === 0x22) // 2. Let name be the result of collecting a sequence of bytes that are not 0x0A (LF), 0x0D (CR) or 0x22 ("), given position. /** @type {string | Buffer} */ let name = collectASequenceOfBytes( (char) => char !== 0x0a && char !== 0x0d && char !== 0x22, input, position ) // 3. If the byte at position is not 0x22 ("), return failure. Otherwise, advance position by 1. if (input[position.position] !== 0x22) { throw parsingError('expected "') } else { position.position++ } // 4. Replace any occurrence of the following subsequences in name with the given byte: // - `%0A`: 0x0A (LF) // - `%0D`: 0x0D (CR) // - `%22`: 0x22 (") name = new TextDecoder().decode(name) .replace(/%0A/ig, '\n') .replace(/%0D/ig, '\r') .replace(/%22/g, '"') // 5. Return the UTF-8 decoding without BOM of name. return name } /** * @param {(char: number) => boolean} condition * @param {Buffer} input * @param {{ position: number }} position */ function collectASequenceOfBytes (condition, input, position) { let start = position.position while (start < input.length && condition(input[start])) { ++start } return input.subarray(position.position, (position.position = start)) } /** * @param {Buffer} buf * @param {boolean} leading * @param {boolean} trailing * @param {(charCode: number) => boolean} predicate * @returns {Buffer} */ function removeChars (buf, leading, trailing, predicate) { let lead = 0 let trail = buf.length - 1 if (leading) { while (lead < buf.length && predicate(buf[lead])) lead++ } if (trailing) { while (trail > 0 && predicate(buf[trail])) trail-- } return lead === 0 && trail === buf.length - 1 ? buf : buf.subarray(lead, trail + 1) } /** * Checks if {@param buffer} starts with {@param start} * @param {Buffer} buffer * @param {Buffer} start * @param {{ position: number }} position */ function bufferStartsWith (buffer, start, position) { if (buffer.length < start.length) { return false } for (let i = 0; i < start.length; i++) { if (start[i] !== buffer[position.position + i]) { return false } } return true } function parsingError (cause) { return new TypeError('Failed to parse body as FormData.', { cause: new TypeError(cause) }) } module.exports = { multipartFormDataParser, validateBoundary } /***/ }), /***/ 30717: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { iteratorMixin } = __nccwpck_require__(58799) const { kEnumerableProperty } = __nccwpck_require__(46425) const { webidl } = __nccwpck_require__(16480) const { File: NativeFile } = __nccwpck_require__(4573) const nodeUtil = __nccwpck_require__(57975) /** @type {globalThis['File']} */ const File = globalThis.File ?? NativeFile // https://xhr.spec.whatwg.org/#formdata class FormData { #state = [] constructor (form) { webidl.util.markAsUncloneable(this) if (form !== undefined) { throw webidl.errors.conversionFailed({ prefix: 'FormData constructor', argument: 'Argument 1', types: ['undefined'] }) } } append (name, value, filename = undefined) { webidl.brandCheck(this, FormData) const prefix = 'FormData.append' webidl.argumentLengthCheck(arguments, 2, prefix) name = webidl.converters.USVString(name) if (arguments.length === 3 || webidl.is.Blob(value)) { value = webidl.converters.Blob(value, prefix, 'value') if (filename !== undefined) { filename = webidl.converters.USVString(filename) } } else { value = webidl.converters.USVString(value) } // 1. Let value be value if given; otherwise blobValue. // 2. Let entry be the result of creating an entry with // name, value, and filename if given. const entry = makeEntry(name, value, filename) // 3. Append entry to this’s entry list. this.#state.push(entry) } delete (name) { webidl.brandCheck(this, FormData) const prefix = 'FormData.delete' webidl.argumentLengthCheck(arguments, 1, prefix) name = webidl.converters.USVString(name) // The delete(name) method steps are to remove all entries whose name // is name from this’s entry list. this.#state = this.#state.filter(entry => entry.name !== name) } get (name) { webidl.brandCheck(this, FormData) const prefix = 'FormData.get' webidl.argumentLengthCheck(arguments, 1, prefix) name = webidl.converters.USVString(name) // 1. If there is no entry whose name is name in this’s entry list, // then return null. const idx = this.#state.findIndex((entry) => entry.name === name) if (idx === -1) { return null } // 2. Return the value of the first entry whose name is name from // this’s entry list. return this.#state[idx].value } getAll (name) { webidl.brandCheck(this, FormData) const prefix = 'FormData.getAll' webidl.argumentLengthCheck(arguments, 1, prefix) name = webidl.converters.USVString(name) // 1. If there is no entry whose name is name in this’s entry list, // then return the empty list. // 2. Return the values of all entries whose name is name, in order, // from this’s entry list. return this.#state .filter((entry) => entry.name === name) .map((entry) => entry.value) } has (name) { webidl.brandCheck(this, FormData) const prefix = 'FormData.has' webidl.argumentLengthCheck(arguments, 1, prefix) name = webidl.converters.USVString(name) // The has(name) method steps are to return true if there is an entry // whose name is name in this’s entry list; otherwise false. return this.#state.findIndex((entry) => entry.name === name) !== -1 } set (name, value, filename = undefined) { webidl.brandCheck(this, FormData) const prefix = 'FormData.set' webidl.argumentLengthCheck(arguments, 2, prefix) name = webidl.converters.USVString(name) if (arguments.length === 3 || webidl.is.Blob(value)) { value = webidl.converters.Blob(value, prefix, 'value') if (filename !== undefined) { filename = webidl.converters.USVString(filename) } } else { value = webidl.converters.USVString(value) } // The set(name, value) and set(name, blobValue, filename) method steps // are: // 1. Let value be value if given; otherwise blobValue. // 2. Let entry be the result of creating an entry with name, value, and // filename if given. const entry = makeEntry(name, value, filename) // 3. If there are entries in this’s entry list whose name is name, then // replace the first such entry with entry and remove the others. const idx = this.#state.findIndex((entry) => entry.name === name) if (idx !== -1) { this.#state = [ ...this.#state.slice(0, idx), entry, ...this.#state.slice(idx + 1).filter((entry) => entry.name !== name) ] } else { // 4. Otherwise, append entry to this’s entry list. this.#state.push(entry) } } [nodeUtil.inspect.custom] (depth, options) { const state = this.#state.reduce((a, b) => { if (a[b.name]) { if (Array.isArray(a[b.name])) { a[b.name].push(b.value) } else { a[b.name] = [a[b.name], b.value] } } else { a[b.name] = b.value } return a }, { __proto__: null }) options.depth ??= depth options.colors ??= true const output = nodeUtil.formatWithOptions(options, state) // remove [Object null prototype] return `FormData ${output.slice(output.indexOf(']') + 2)}` } /** * @param {FormData} formData */ static getFormDataState (formData) { return formData.#state } /** * @param {FormData} formData * @param {any[]} newState */ static setFormDataState (formData, newState) { formData.#state = newState } } const { getFormDataState, setFormDataState } = FormData Reflect.deleteProperty(FormData, 'getFormDataState') Reflect.deleteProperty(FormData, 'setFormDataState') iteratorMixin('FormData', FormData, getFormDataState, 'name', 'value') Object.defineProperties(FormData.prototype, { append: kEnumerableProperty, delete: kEnumerableProperty, get: kEnumerableProperty, getAll: kEnumerableProperty, has: kEnumerableProperty, set: kEnumerableProperty, [Symbol.toStringTag]: { value: 'FormData', configurable: true } }) /** * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry * @param {string} name * @param {string|Blob} value * @param {?string} filename * @returns */ function makeEntry (name, value, filename) { // 1. Set name to the result of converting name into a scalar value string. // Note: This operation was done by the webidl converter USVString. // 2. If value is a string, then set value to the result of converting // value into a scalar value string. if (typeof value === 'string') { // Note: This operation was done by the webidl converter USVString. } else { // 3. Otherwise: // 1. If value is not a File object, then set value to a new File object, // representing the same bytes, whose name attribute value is "blob" if (!webidl.is.File(value)) { value = new File([value], 'blob', { type: value.type }) } // 2. If filename is given, then set value to a new File object, // representing the same bytes, whose name attribute is filename. if (filename !== undefined) { /** @type {FilePropertyBag} */ const options = { type: value.type, lastModified: value.lastModified } value = new File([value], filename, options) } } // 4. Return an entry whose name is name and whose value is value. return { name, value } } webidl.is.FormData = webidl.util.MakeTypeAssertion(FormData) module.exports = { FormData, makeEntry, setFormDataState } /***/ }), /***/ 53072: /***/ ((module) => { "use strict"; // In case of breaking changes, increase the version // number to avoid conflicts. const globalOrigin = Symbol.for('undici.globalOrigin.1') function getGlobalOrigin () { return globalThis[globalOrigin] } function setGlobalOrigin (newOrigin) { if (newOrigin === undefined) { Object.defineProperty(globalThis, globalOrigin, { value: undefined, writable: true, enumerable: false, configurable: false }) return } const parsedURL = new URL(newOrigin) if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) } Object.defineProperty(globalThis, globalOrigin, { value: parsedURL, writable: true, enumerable: false, configurable: false }) } module.exports = { getGlobalOrigin, setGlobalOrigin } /***/ }), /***/ 289: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // https://github.com/Ethan-Arrowood/undici-fetch const { kConstruct } = __nccwpck_require__(83112) const { kEnumerableProperty } = __nccwpck_require__(46425) const { iteratorMixin, isValidHeaderName, isValidHeaderValue } = __nccwpck_require__(58799) const { webidl } = __nccwpck_require__(16480) const assert = __nccwpck_require__(34589) const util = __nccwpck_require__(57975) /** * @param {number} code * @returns {code is (0x0a | 0x0d | 0x09 | 0x20)} */ function isHTTPWhiteSpaceCharCode (code) { return code === 0x0a || code === 0x0d || code === 0x09 || code === 0x20 } /** * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize * @param {string} potentialValue * @returns {string} */ function headerValueNormalize (potentialValue) { // To normalize a byte sequence potentialValue, remove // any leading and trailing HTTP whitespace bytes from // potentialValue. let i = 0; let j = potentialValue.length while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j) } /** * @param {Headers} headers * @param {Array|Object} object */ function fill (headers, object) { // To fill a Headers object headers with a given object object, run these steps: // 1. If object is a sequence, then for each header in object: // Note: webidl conversion to array has already been done. if (Array.isArray(object)) { for (let i = 0; i < object.length; ++i) { const header = object[i] // 1. If header does not contain exactly two items, then throw a TypeError. if (header.length !== 2) { throw webidl.errors.exception({ header: 'Headers constructor', message: `expected name/value pair to be length 2, found ${header.length}.` }) } // 2. Append (header’s first item, header’s second item) to headers. appendHeader(headers, header[0], header[1]) } } else if (typeof object === 'object' && object !== null) { // Note: null should throw // 2. Otherwise, object is a record, then for each key → value in object, // append (key, value) to headers const keys = Object.keys(object) for (let i = 0; i < keys.length; ++i) { appendHeader(headers, keys[i], object[keys[i]]) } } else { throw webidl.errors.conversionFailed({ prefix: 'Headers constructor', argument: 'Argument 1', types: ['sequence>', 'record'] }) } } /** * @see https://fetch.spec.whatwg.org/#concept-headers-append * @param {Headers} headers * @param {string} name * @param {string} value */ function appendHeader (headers, name, value) { // 1. Normalize value. value = headerValueNormalize(value) // 2. If name is not a header name or value is not a // header value, then throw a TypeError. if (!isValidHeaderName(name)) { throw webidl.errors.invalidArgument({ prefix: 'Headers.append', value: name, type: 'header name' }) } else if (!isValidHeaderValue(value)) { throw webidl.errors.invalidArgument({ prefix: 'Headers.append', value, type: 'header value' }) } // 3. If headers’s guard is "immutable", then throw a TypeError. // 4. Otherwise, if headers’s guard is "request" and name is a // forbidden header name, return. // 5. Otherwise, if headers’s guard is "request-no-cors": // TODO // Note: undici does not implement forbidden header names if (getHeadersGuard(headers) === 'immutable') { throw new TypeError('immutable') } // 6. Otherwise, if headers’s guard is "response" and name is a // forbidden response-header name, return. // 7. Append (name, value) to headers’s header list. return getHeadersList(headers).append(name, value, false) // 8. If headers’s guard is "request-no-cors", then remove // privileged no-CORS request headers from headers } // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine /** * @param {Headers} target */ function headersListSortAndCombine (target) { const headersList = getHeadersList(target) if (!headersList) { return [] } if (headersList.sortedMap) { return headersList.sortedMap } // 1. Let headers be an empty list of headers with the key being the name // and value the value. const headers = [] // 2. Let names be the result of convert header names to a sorted-lowercase // set with all the names of the headers in list. const names = headersList.toSortedArray() const cookies = headersList.cookies // fast-path if (cookies === null || cookies.length === 1) { // Note: The non-null assertion of value has already been done by `HeadersList#toSortedArray` return (headersList.sortedMap = names) } // 3. For each name of names: for (let i = 0; i < names.length; ++i) { const { 0: name, 1: value } = names[i] // 1. If name is `set-cookie`, then: if (name === 'set-cookie') { // 1. Let values be a list of all values of headers in list whose name // is a byte-case-insensitive match for name, in order. // 2. For each value of values: // 1. Append (name, value) to headers. for (let j = 0; j < cookies.length; ++j) { headers.push([name, cookies[j]]) } } else { // 2. Otherwise: // 1. Let value be the result of getting name from list. // 2. Assert: value is non-null. // Note: This operation was done by `HeadersList#toSortedArray`. // 3. Append (name, value) to headers. headers.push([name, value]) } } // 4. Return headers. return (headersList.sortedMap = headers) } function compareHeaderName (a, b) { return a[0] < b[0] ? -1 : 1 } class HeadersList { /** @type {[string, string][]|null} */ cookies = null sortedMap headersMap constructor (init) { if (init instanceof HeadersList) { this.headersMap = new Map(init.headersMap) this.sortedMap = init.sortedMap this.cookies = init.cookies === null ? null : [...init.cookies] } else { this.headersMap = new Map(init) this.sortedMap = null } } /** * @see https://fetch.spec.whatwg.org/#header-list-contains * @param {string} name * @param {boolean} isLowerCase */ contains (name, isLowerCase) { // A header list list contains a header name name if list // contains a header whose name is a byte-case-insensitive // match for name. return this.headersMap.has(isLowerCase ? name : name.toLowerCase()) } clear () { this.headersMap.clear() this.sortedMap = null this.cookies = null } /** * @see https://fetch.spec.whatwg.org/#concept-header-list-append * @param {string} name * @param {string} value * @param {boolean} isLowerCase */ append (name, value, isLowerCase) { this.sortedMap = null // 1. If list contains name, then set name to the first such // header’s name. const lowercaseName = isLowerCase ? name : name.toLowerCase() const exists = this.headersMap.get(lowercaseName) // 2. Append (name, value) to list. if (exists) { const delimiter = lowercaseName === 'cookie' ? '; ' : ', ' this.headersMap.set(lowercaseName, { name: exists.name, value: `${exists.value}${delimiter}${value}` }) } else { this.headersMap.set(lowercaseName, { name, value }) } if (lowercaseName === 'set-cookie') { (this.cookies ??= []).push(value) } } /** * @see https://fetch.spec.whatwg.org/#concept-header-list-set * @param {string} name * @param {string} value * @param {boolean} isLowerCase */ set (name, value, isLowerCase) { this.sortedMap = null const lowercaseName = isLowerCase ? name : name.toLowerCase() if (lowercaseName === 'set-cookie') { this.cookies = [value] } // 1. If list contains name, then set the value of // the first such header to value and remove the // others. // 2. Otherwise, append header (name, value) to list. this.headersMap.set(lowercaseName, { name, value }) } /** * @see https://fetch.spec.whatwg.org/#concept-header-list-delete * @param {string} name * @param {boolean} isLowerCase */ delete (name, isLowerCase) { this.sortedMap = null if (!isLowerCase) name = name.toLowerCase() if (name === 'set-cookie') { this.cookies = null } this.headersMap.delete(name) } /** * @see https://fetch.spec.whatwg.org/#concept-header-list-get * @param {string} name * @param {boolean} isLowerCase * @returns {string | null} */ get (name, isLowerCase) { // 1. If list does not contain name, then return null. // 2. Return the values of all headers in list whose name // is a byte-case-insensitive match for name, // separated from each other by 0x2C 0x20, in order. return this.headersMap.get(isLowerCase ? name : name.toLowerCase())?.value ?? null } * [Symbol.iterator] () { // use the lowercased name for (const { 0: name, 1: { value } } of this.headersMap) { yield [name, value] } } get entries () { const headers = {} if (this.headersMap.size !== 0) { for (const { name, value } of this.headersMap.values()) { headers[name] = value } } return headers } rawValues () { return this.headersMap.values() } get entriesList () { const headers = [] if (this.headersMap.size !== 0) { for (const { 0: lowerName, 1: { name, value } } of this.headersMap) { if (lowerName === 'set-cookie') { for (const cookie of this.cookies) { headers.push([name, cookie]) } } else { headers.push([name, value]) } } } return headers } // https://fetch.spec.whatwg.org/#convert-header-names-to-a-sorted-lowercase-set toSortedArray () { const size = this.headersMap.size const array = new Array(size) // In most cases, you will use the fast-path. // fast-path: Use binary insertion sort for small arrays. if (size <= 32) { if (size === 0) { // If empty, it is an empty array. To avoid the first index assignment. return array } // Improve performance by unrolling loop and avoiding double-loop. // Double-loop-less version of the binary insertion sort. const iterator = this.headersMap[Symbol.iterator]() const firstValue = iterator.next().value // set [name, value] to first index. array[0] = [firstValue[0], firstValue[1].value] // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine // 3.2.2. Assert: value is non-null. assert(firstValue[1].value !== null) for ( let i = 1, j = 0, right = 0, left = 0, pivot = 0, x, value; i < size; ++i ) { // get next value value = iterator.next().value // set [name, value] to current index. x = array[i] = [value[0], value[1].value] // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine // 3.2.2. Assert: value is non-null. assert(x[1] !== null) left = 0 right = i // binary search while (left < right) { // middle index pivot = left + ((right - left) >> 1) // compare header name if (array[pivot][0] <= x[0]) { left = pivot + 1 } else { right = pivot } } if (i !== pivot) { j = i while (j > left) { array[j] = array[--j] } array[left] = x } } /* c8 ignore next 4 */ if (!iterator.next().done) { // This is for debugging and will never be called. throw new TypeError('Unreachable') } return array } else { // This case would be a rare occurrence. // slow-path: fallback let i = 0 for (const { 0: name, 1: { value } } of this.headersMap) { array[i++] = [name, value] // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine // 3.2.2. Assert: value is non-null. assert(value !== null) } return array.sort(compareHeaderName) } } } // https://fetch.spec.whatwg.org/#headers-class class Headers { #guard /** * @type {HeadersList} */ #headersList /** * @param {HeadersInit|Symbol} [init] * @returns */ constructor (init = undefined) { webidl.util.markAsUncloneable(this) if (init === kConstruct) { return } this.#headersList = new HeadersList() // The new Headers(init) constructor steps are: // 1. Set this’s guard to "none". this.#guard = 'none' // 2. If init is given, then fill this with init. if (init !== undefined) { init = webidl.converters.HeadersInit(init, 'Headers constructor', 'init') fill(this, init) } } // https://fetch.spec.whatwg.org/#dom-headers-append append (name, value) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 2, 'Headers.append') const prefix = 'Headers.append' name = webidl.converters.ByteString(name, prefix, 'name') value = webidl.converters.ByteString(value, prefix, 'value') return appendHeader(this, name, value) } // https://fetch.spec.whatwg.org/#dom-headers-delete delete (name) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 1, 'Headers.delete') const prefix = 'Headers.delete' name = webidl.converters.ByteString(name, prefix, 'name') // 1. If name is not a header name, then throw a TypeError. if (!isValidHeaderName(name)) { throw webidl.errors.invalidArgument({ prefix: 'Headers.delete', value: name, type: 'header name' }) } // 2. If this’s guard is "immutable", then throw a TypeError. // 3. Otherwise, if this’s guard is "request" and name is a // forbidden header name, return. // 4. Otherwise, if this’s guard is "request-no-cors", name // is not a no-CORS-safelisted request-header name, and // name is not a privileged no-CORS request-header name, // return. // 5. Otherwise, if this’s guard is "response" and name is // a forbidden response-header name, return. // Note: undici does not implement forbidden header names if (this.#guard === 'immutable') { throw new TypeError('immutable') } // 6. If this’s header list does not contain name, then // return. if (!this.#headersList.contains(name, false)) { return } // 7. Delete name from this’s header list. // 8. If this’s guard is "request-no-cors", then remove // privileged no-CORS request headers from this. this.#headersList.delete(name, false) } // https://fetch.spec.whatwg.org/#dom-headers-get get (name) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 1, 'Headers.get') const prefix = 'Headers.get' name = webidl.converters.ByteString(name, prefix, 'name') // 1. If name is not a header name, then throw a TypeError. if (!isValidHeaderName(name)) { throw webidl.errors.invalidArgument({ prefix, value: name, type: 'header name' }) } // 2. Return the result of getting name from this’s header // list. return this.#headersList.get(name, false) } // https://fetch.spec.whatwg.org/#dom-headers-has has (name) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 1, 'Headers.has') const prefix = 'Headers.has' name = webidl.converters.ByteString(name, prefix, 'name') // 1. If name is not a header name, then throw a TypeError. if (!isValidHeaderName(name)) { throw webidl.errors.invalidArgument({ prefix, value: name, type: 'header name' }) } // 2. Return true if this’s header list contains name; // otherwise false. return this.#headersList.contains(name, false) } // https://fetch.spec.whatwg.org/#dom-headers-set set (name, value) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 2, 'Headers.set') const prefix = 'Headers.set' name = webidl.converters.ByteString(name, prefix, 'name') value = webidl.converters.ByteString(value, prefix, 'value') // 1. Normalize value. value = headerValueNormalize(value) // 2. If name is not a header name or value is not a // header value, then throw a TypeError. if (!isValidHeaderName(name)) { throw webidl.errors.invalidArgument({ prefix, value: name, type: 'header name' }) } else if (!isValidHeaderValue(value)) { throw webidl.errors.invalidArgument({ prefix, value, type: 'header value' }) } // 3. If this’s guard is "immutable", then throw a TypeError. // 4. Otherwise, if this’s guard is "request" and name is a // forbidden header name, return. // 5. Otherwise, if this’s guard is "request-no-cors" and // name/value is not a no-CORS-safelisted request-header, // return. // 6. Otherwise, if this’s guard is "response" and name is a // forbidden response-header name, return. // Note: undici does not implement forbidden header names if (this.#guard === 'immutable') { throw new TypeError('immutable') } // 7. Set (name, value) in this’s header list. // 8. If this’s guard is "request-no-cors", then remove // privileged no-CORS request headers from this this.#headersList.set(name, value, false) } // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie getSetCookie () { webidl.brandCheck(this, Headers) // 1. If this’s header list does not contain `Set-Cookie`, then return « ». // 2. Return the values of all headers in this’s header list whose name is // a byte-case-insensitive match for `Set-Cookie`, in order. const list = this.#headersList.cookies if (list) { return [...list] } return [] } [util.inspect.custom] (depth, options) { options.depth ??= depth return `Headers ${util.formatWithOptions(options, this.#headersList.entries)}` } static getHeadersGuard (o) { return o.#guard } static setHeadersGuard (o, guard) { o.#guard = guard } /** * @param {Headers} o */ static getHeadersList (o) { return o.#headersList } /** * @param {Headers} target * @param {HeadersList} list */ static setHeadersList (target, list) { target.#headersList = list } } const { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers Reflect.deleteProperty(Headers, 'getHeadersGuard') Reflect.deleteProperty(Headers, 'setHeadersGuard') Reflect.deleteProperty(Headers, 'getHeadersList') Reflect.deleteProperty(Headers, 'setHeadersList') iteratorMixin('Headers', Headers, headersListSortAndCombine, 0, 1) Object.defineProperties(Headers.prototype, { append: kEnumerableProperty, delete: kEnumerableProperty, get: kEnumerableProperty, has: kEnumerableProperty, set: kEnumerableProperty, getSetCookie: kEnumerableProperty, [Symbol.toStringTag]: { value: 'Headers', configurable: true }, [util.inspect.custom]: { enumerable: false } }) webidl.converters.HeadersInit = function (V, prefix, argument) { if (webidl.util.Type(V) === webidl.util.Types.OBJECT) { const iterator = Reflect.get(V, Symbol.iterator) // A work-around to ensure we send the properly-cased Headers when V is a Headers object. // Read https://github.com/nodejs/undici/pull/3159#issuecomment-2075537226 before touching, please. if (!util.types.isProxy(V) && iterator === Headers.prototype.entries) { // Headers object try { return getHeadersList(V).entriesList } catch { // fall-through } } if (typeof iterator === 'function') { return webidl.converters['sequence>'](V, prefix, argument, iterator.bind(V)) } return webidl.converters['record'](V, prefix, argument) } throw webidl.errors.conversionFailed({ prefix: 'Headers constructor', argument: 'Argument 1', types: ['sequence>', 'record'] }) } module.exports = { fill, // for test. compareHeaderName, Headers, HeadersList, getHeadersGuard, setHeadersGuard, setHeadersList, getHeadersList } /***/ }), /***/ 25071: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // https://github.com/Ethan-Arrowood/undici-fetch const { makeNetworkError, makeAppropriateNetworkError, filterResponse, makeResponse, fromInnerResponse, getResponseState } = __nccwpck_require__(46632) const { HeadersList } = __nccwpck_require__(289) const { Request, cloneRequest, getRequestDispatcher, getRequestState } = __nccwpck_require__(7622) const zlib = __nccwpck_require__(38522) const { bytesMatch, makePolicyContainer, clonePolicyContainer, requestBadPort, TAOCheck, appendRequestOriginHeader, responseLocationURL, requestCurrentURL, setRequestReferrerPolicyOnRedirect, tryUpgradeRequestToAPotentiallyTrustworthyURL, createOpaqueTimingInfo, appendFetchMetadata, corsCheck, crossOriginResourcePolicyCheck, determineRequestsReferrer, coarsenedSharedCurrentTime, sameOrigin, isCancelled, isAborted, isErrorLike, fullyReadBody, readableStreamClose, isomorphicEncode, urlIsLocal, urlIsHttpHttpsScheme, urlHasHttpsScheme, clampAndCoarsenConnectionTimingInfo, simpleRangeHeaderValue, buildContentRange, createInflate, extractMimeType } = __nccwpck_require__(58799) const assert = __nccwpck_require__(34589) const { safelyExtractBody, extractBody } = __nccwpck_require__(27679) const { redirectStatusSet, nullBodyStatus, safeMethodsSet, requestBodyHeader, subresourceSet } = __nccwpck_require__(10546) const EE = __nccwpck_require__(78474) const { Readable, pipeline, finished, isErrored, isReadable } = __nccwpck_require__(57075) const { addAbortListener, bufferToLowerCasedHeaderName } = __nccwpck_require__(46425) const { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = __nccwpck_require__(38675) const { getGlobalDispatcher } = __nccwpck_require__(14266) const { webidl } = __nccwpck_require__(16480) const { STATUS_CODES } = __nccwpck_require__(37067) const { createDeferredPromise } = __nccwpck_require__(78499) const GET_OR_HEAD = ['GET', 'HEAD'] const defaultUserAgent = typeof __UNDICI_IS_NODE__ !== 'undefined' || typeof esbuildDetection !== 'undefined' ? 'node' : 'undici' /** @type {import('buffer').resolveObjectURL} */ let resolveObjectURL class Fetch extends EE { constructor (dispatcher) { super() this.dispatcher = dispatcher this.connection = null this.dump = false this.state = 'ongoing' } terminate (reason) { if (this.state !== 'ongoing') { return } this.state = 'terminated' this.connection?.destroy(reason) this.emit('terminated', reason) } // https://fetch.spec.whatwg.org/#fetch-controller-abort abort (error) { if (this.state !== 'ongoing') { return } // 1. Set controller’s state to "aborted". this.state = 'aborted' // 2. Let fallbackError be an "AbortError" DOMException. // 3. Set error to fallbackError if it is not given. if (!error) { error = new DOMException('The operation was aborted.', 'AbortError') } // 4. Let serializedError be StructuredSerialize(error). // If that threw an exception, catch it, and let // serializedError be StructuredSerialize(fallbackError). // 5. Set controller’s serialized abort reason to serializedError. this.serializedAbortReason = error this.connection?.destroy(error) this.emit('terminated', error) } } function handleFetchDone (response) { finalizeAndReportTiming(response, 'fetch') } // https://fetch.spec.whatwg.org/#fetch-method function fetch (input, init = undefined) { webidl.argumentLengthCheck(arguments, 1, 'globalThis.fetch') // 1. Let p be a new promise. let p = createDeferredPromise() // 2. Let requestObject be the result of invoking the initial value of // Request as constructor with input and init as arguments. If this throws // an exception, reject p with it and return p. let requestObject try { requestObject = new Request(input, init) } catch (e) { p.reject(e) return p.promise } // 3. Let request be requestObject’s request. const request = getRequestState(requestObject) // 4. If requestObject’s signal’s aborted flag is set, then: if (requestObject.signal.aborted) { // 1. Abort the fetch() call with p, request, null, and // requestObject’s signal’s abort reason. abortFetch(p, request, null, requestObject.signal.reason) // 2. Return p. return p.promise } // 5. Let globalObject be request’s client’s global object. const globalObject = request.client.globalObject // 6. If globalObject is a ServiceWorkerGlobalScope object, then set // request’s service-workers mode to "none". if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { request.serviceWorkers = 'none' } // 7. Let responseObject be null. let responseObject = null // 8. Let relevantRealm be this’s relevant Realm. // 9. Let locallyAborted be false. let locallyAborted = false // 10. Let controller be null. let controller = null // 11. Add the following abort steps to requestObject’s signal: addAbortListener( requestObject.signal, () => { // 1. Set locallyAborted to true. locallyAborted = true // 2. Assert: controller is non-null. assert(controller != null) // 3. Abort controller with requestObject’s signal’s abort reason. controller.abort(requestObject.signal.reason) const realResponse = responseObject?.deref() // 4. Abort the fetch() call with p, request, responseObject, // and requestObject’s signal’s abort reason. abortFetch(p, request, realResponse, requestObject.signal.reason) } ) // 12. Let handleFetchDone given response response be to finalize and // report timing with response, globalObject, and "fetch". // see function handleFetchDone // 13. Set controller to the result of calling fetch given request, // with processResponseEndOfBody set to handleFetchDone, and processResponse // given response being these substeps: const processResponse = (response) => { // 1. If locallyAborted is true, terminate these substeps. if (locallyAborted) { return } // 2. If response’s aborted flag is set, then: if (response.aborted) { // 1. Let deserializedError be the result of deserialize a serialized // abort reason given controller’s serialized abort reason and // relevantRealm. // 2. Abort the fetch() call with p, request, responseObject, and // deserializedError. abortFetch(p, request, responseObject, controller.serializedAbortReason) return } // 3. If response is a network error, then reject p with a TypeError // and terminate these substeps. if (response.type === 'error') { p.reject(new TypeError('fetch failed', { cause: response.error })) return } // 4. Set responseObject to the result of creating a Response object, // given response, "immutable", and relevantRealm. responseObject = new WeakRef(fromInnerResponse(response, 'immutable')) // 5. Resolve p with responseObject. p.resolve(responseObject.deref()) p = null } controller = fetching({ request, processResponseEndOfBody: handleFetchDone, processResponse, dispatcher: getRequestDispatcher(requestObject) // undici }) // 14. Return p. return p.promise } // https://fetch.spec.whatwg.org/#finalize-and-report-timing function finalizeAndReportTiming (response, initiatorType = 'other') { // 1. If response is an aborted network error, then return. if (response.type === 'error' && response.aborted) { return } // 2. If response’s URL list is null or empty, then return. if (!response.urlList?.length) { return } // 3. Let originalURL be response’s URL list[0]. const originalURL = response.urlList[0] // 4. Let timingInfo be response’s timing info. let timingInfo = response.timingInfo // 5. Let cacheState be response’s cache state. let cacheState = response.cacheState // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. if (!urlIsHttpHttpsScheme(originalURL)) { return } // 7. If timingInfo is null, then return. if (timingInfo === null) { return } // 8. If response’s timing allow passed flag is not set, then: if (!response.timingAllowPassed) { // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. timingInfo = createOpaqueTimingInfo({ startTime: timingInfo.startTime }) // 2. Set cacheState to the empty string. cacheState = '' } // 9. Set timingInfo’s end time to the coarsened shared current time // given global’s relevant settings object’s cross-origin isolated // capability. // TODO: given global’s relevant settings object’s cross-origin isolated // capability? timingInfo.endTime = coarsenedSharedCurrentTime() // 10. Set response’s timing info to timingInfo. response.timingInfo = timingInfo // 11. Mark resource timing for timingInfo, originalURL, initiatorType, // global, and cacheState. markResourceTiming( timingInfo, originalURL.href, initiatorType, globalThis, cacheState, '', // bodyType response.status ) } // https://w3c.github.io/resource-timing/#dfn-mark-resource-timing const markResourceTiming = performance.markResourceTiming // https://fetch.spec.whatwg.org/#abort-fetch function abortFetch (p, request, responseObject, error) { // 1. Reject promise with error. if (p) { // We might have already resolved the promise at this stage p.reject(error) } // 2. If request’s body is not null and is readable, then cancel request’s // body with error. if (request.body?.stream != null && isReadable(request.body.stream)) { request.body.stream.cancel(error).catch((err) => { if (err.code === 'ERR_INVALID_STATE') { // Node bug? return } throw err }) } // 3. If responseObject is null, then return. if (responseObject == null) { return } // 4. Let response be responseObject’s response. const response = getResponseState(responseObject) // 5. If response’s body is not null and is readable, then error response’s // body with error. if (response.body?.stream != null && isReadable(response.body.stream)) { response.body.stream.cancel(error).catch((err) => { if (err.code === 'ERR_INVALID_STATE') { // Node bug? return } throw err }) } } // https://fetch.spec.whatwg.org/#fetching function fetching ({ request, processRequestBodyChunkLength, processRequestEndOfBody, processResponse, processResponseEndOfBody, processResponseConsumeBody, useParallelQueue = false, dispatcher = getGlobalDispatcher() // undici }) { // Ensure that the dispatcher is set accordingly assert(dispatcher) // 1. Let taskDestination be null. let taskDestination = null // 2. Let crossOriginIsolatedCapability be false. let crossOriginIsolatedCapability = false // 3. If request’s client is non-null, then: if (request.client != null) { // 1. Set taskDestination to request’s client’s global object. taskDestination = request.client.globalObject // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin // isolated capability. crossOriginIsolatedCapability = request.client.crossOriginIsolatedCapability } // 4. If useParallelQueue is true, then set taskDestination to the result of // starting a new parallel queue. // TODO // 5. Let timingInfo be a new fetch timing info whose start time and // post-redirect start time are the coarsened shared current time given // crossOriginIsolatedCapability. const currentTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability) const timingInfo = createOpaqueTimingInfo({ startTime: currentTime }) // 6. Let fetchParams be a new fetch params whose // request is request, // timing info is timingInfo, // process request body chunk length is processRequestBodyChunkLength, // process request end-of-body is processRequestEndOfBody, // process response is processResponse, // process response consume body is processResponseConsumeBody, // process response end-of-body is processResponseEndOfBody, // task destination is taskDestination, // and cross-origin isolated capability is crossOriginIsolatedCapability. const fetchParams = { controller: new Fetch(dispatcher), request, timingInfo, processRequestBodyChunkLength, processRequestEndOfBody, processResponse, processResponseConsumeBody, processResponseEndOfBody, taskDestination, crossOriginIsolatedCapability } // 7. If request’s body is a byte sequence, then set request’s body to // request’s body as a body. // NOTE: Since fetching is only called from fetch, body should already be // extracted. assert(!request.body || request.body.stream) // 8. If request’s window is "client", then set request’s window to request’s // client, if request’s client’s global object is a Window object; otherwise // "no-window". if (request.window === 'client') { // TODO: What if request.client is null? request.window = request.client?.globalObject?.constructor?.name === 'Window' ? request.client : 'no-window' } // 9. If request’s origin is "client", then set request’s origin to request’s // client’s origin. if (request.origin === 'client') { request.origin = request.client.origin } // 10. If all of the following conditions are true: // TODO // 11. If request’s policy container is "client", then: if (request.policyContainer === 'client') { // 1. If request’s client is non-null, then set request’s policy // container to a clone of request’s client’s policy container. [HTML] if (request.client != null) { request.policyContainer = clonePolicyContainer( request.client.policyContainer ) } else { // 2. Otherwise, set request’s policy container to a new policy // container. request.policyContainer = makePolicyContainer() } } // 12. If request’s header list does not contain `Accept`, then: if (!request.headersList.contains('accept', true)) { // 1. Let value be `*/*`. const value = '*/*' // 2. A user agent should set value to the first matching statement, if // any, switching on request’s destination: // "document" // "frame" // "iframe" // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` // "image" // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5` // "style" // `text/css,*/*;q=0.1` // TODO // 3. Append `Accept`/value to request’s header list. request.headersList.append('accept', value, true) } // 13. If request’s header list does not contain `Accept-Language`, then // user agents should append `Accept-Language`/an appropriate value to // request’s header list. if (!request.headersList.contains('accept-language', true)) { request.headersList.append('accept-language', '*', true) } // 14. If request’s priority is null, then use request’s initiator and // destination appropriately in setting request’s priority to a // user-agent-defined object. if (request.priority === null) { // TODO } // 15. If request is a subresource request, then: if (subresourceSet.has(request.destination)) { // TODO } // 16. Run main fetch given fetchParams. mainFetch(fetchParams, false) // 17. Return fetchParam's controller return fetchParams.controller } // https://fetch.spec.whatwg.org/#concept-main-fetch async function mainFetch (fetchParams, recursive) { try { // 1. Let request be fetchParams’s request. const request = fetchParams.request // 2. Let response be null. let response = null // 3. If request’s local-URLs-only flag is set and request’s current URL is // not local, then set response to a network error. if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) { response = makeNetworkError('local URLs only') } // 4. Run report Content Security Policy violations for request. // TODO // 5. Upgrade request to a potentially trustworthy URL, if appropriate. tryUpgradeRequestToAPotentiallyTrustworthyURL(request) // 6. If should request be blocked due to a bad port, should fetching request // be blocked as mixed content, or should request be blocked by Content // Security Policy returns blocked, then set response to a network error. if (requestBadPort(request) === 'blocked') { response = makeNetworkError('bad port') } // TODO: should fetching request be blocked as mixed content? // TODO: should request be blocked by Content Security Policy? // 7. If request’s referrer policy is the empty string, then set request’s // referrer policy to request’s policy container’s referrer policy. if (request.referrerPolicy === '') { request.referrerPolicy = request.policyContainer.referrerPolicy } // 8. If request’s referrer is not "no-referrer", then set request’s // referrer to the result of invoking determine request’s referrer. if (request.referrer !== 'no-referrer') { request.referrer = determineRequestsReferrer(request) } // 9. Set request’s current URL’s scheme to "https" if all of the following // conditions are true: // - request’s current URL’s scheme is "http" // - request’s current URL’s host is a domain // - Matching request’s current URL’s host per Known HSTS Host Domain Name // Matching results in either a superdomain match with an asserted // includeSubDomains directive or a congruent match (with or without an // asserted includeSubDomains directive). [HSTS] // TODO // 10. If recursive is false, then run the remaining steps in parallel. // TODO // 11. If response is null, then set response to the result of running // the steps corresponding to the first matching statement: if (response === null) { const currentURL = requestCurrentURL(request) if ( // - request’s current URL’s origin is same origin with request’s origin, // and request’s response tainting is "basic" (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') || // request’s current URL’s scheme is "data" (currentURL.protocol === 'data:') || // - request’s mode is "navigate" or "websocket" (request.mode === 'navigate' || request.mode === 'websocket') ) { // 1. Set request’s response tainting to "basic". request.responseTainting = 'basic' // 2. Return the result of running scheme fetch given fetchParams. response = await schemeFetch(fetchParams) // request’s mode is "same-origin" } else if (request.mode === 'same-origin') { // 1. Return a network error. response = makeNetworkError('request mode cannot be "same-origin"') // request’s mode is "no-cors" } else if (request.mode === 'no-cors') { // 1. If request’s redirect mode is not "follow", then return a network // error. if (request.redirect !== 'follow') { response = makeNetworkError( 'redirect mode cannot be "follow" for "no-cors" request' ) } else { // 2. Set request’s response tainting to "opaque". request.responseTainting = 'opaque' // 3. Return the result of running scheme fetch given fetchParams. response = await schemeFetch(fetchParams) } // request’s current URL’s scheme is not an HTTP(S) scheme } else if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) { // Return a network error. response = makeNetworkError('URL scheme must be a HTTP(S) scheme') // - request’s use-CORS-preflight flag is set // - request’s unsafe-request flag is set and either request’s method is // not a CORS-safelisted method or CORS-unsafe request-header names with // request’s header list is not empty // 1. Set request’s response tainting to "cors". // 2. Let corsWithPreflightResponse be the result of running HTTP fetch // given fetchParams and true. // 3. If corsWithPreflightResponse is a network error, then clear cache // entries using request. // 4. Return corsWithPreflightResponse. // TODO // Otherwise } else { // 1. Set request’s response tainting to "cors". request.responseTainting = 'cors' // 2. Return the result of running HTTP fetch given fetchParams. response = await httpFetch(fetchParams) } } // 12. If recursive is true, then return response. if (recursive) { return response } // 13. If response is not a network error and response is not a filtered // response, then: if (response.status !== 0 && !response.internalResponse) { // If request’s response tainting is "cors", then: if (request.responseTainting === 'cors') { // 1. Let headerNames be the result of extracting header list values // given `Access-Control-Expose-Headers` and response’s header list. // TODO // 2. If request’s credentials mode is not "include" and headerNames // contains `*`, then set response’s CORS-exposed header-name list to // all unique header names in response’s header list. // TODO // 3. Otherwise, if headerNames is not null or failure, then set // response’s CORS-exposed header-name list to headerNames. // TODO } // Set response to the following filtered response with response as its // internal response, depending on request’s response tainting: if (request.responseTainting === 'basic') { response = filterResponse(response, 'basic') } else if (request.responseTainting === 'cors') { response = filterResponse(response, 'cors') } else if (request.responseTainting === 'opaque') { response = filterResponse(response, 'opaque') } else { assert(false) } } // 14. Let internalResponse be response, if response is a network error, // and response’s internal response otherwise. let internalResponse = response.status === 0 ? response : response.internalResponse // 15. If internalResponse’s URL list is empty, then set it to a clone of // request’s URL list. if (internalResponse.urlList.length === 0) { internalResponse.urlList.push(...request.urlList) } // 16. If request’s timing allow failed flag is unset, then set // internalResponse’s timing allow passed flag. if (!request.timingAllowFailed) { response.timingAllowPassed = true } // 17. If response is not a network error and any of the following returns // blocked // - should internalResponse to request be blocked as mixed content // - should internalResponse to request be blocked by Content Security Policy // - should internalResponse to request be blocked due to its MIME type // - should internalResponse to request be blocked due to nosniff // TODO // 18. If response’s type is "opaque", internalResponse’s status is 206, // internalResponse’s range-requested flag is set, and request’s header // list does not contain `Range`, then set response and internalResponse // to a network error. if ( response.type === 'opaque' && internalResponse.status === 206 && internalResponse.rangeRequested && !request.headers.contains('range', true) ) { response = internalResponse = makeNetworkError() } // 19. If response is not a network error and either request’s method is // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status, // set internalResponse’s body to null and disregard any enqueuing toward // it (if any). if ( response.status !== 0 && (request.method === 'HEAD' || request.method === 'CONNECT' || nullBodyStatus.includes(internalResponse.status)) ) { internalResponse.body = null fetchParams.controller.dump = true } // 20. If request’s integrity metadata is not the empty string, then: if (request.integrity) { // 1. Let processBodyError be this step: run fetch finale given fetchParams // and a network error. const processBodyError = (reason) => fetchFinale(fetchParams, makeNetworkError(reason)) // 2. If request’s response tainting is "opaque", or response’s body is null, // then run processBodyError and abort these steps. if (request.responseTainting === 'opaque' || response.body == null) { processBodyError(response.error) return } // 3. Let processBody given bytes be these steps: const processBody = (bytes) => { // 1. If bytes do not match request’s integrity metadata, // then run processBodyError and abort these steps. [SRI] if (!bytesMatch(bytes, request.integrity)) { processBodyError('integrity mismatch') return } // 2. Set response’s body to bytes as a body. response.body = safelyExtractBody(bytes)[0] // 3. Run fetch finale given fetchParams and response. fetchFinale(fetchParams, response) } // 4. Fully read response’s body given processBody and processBodyError. fullyReadBody(response.body, processBody, processBodyError) } else { // 21. Otherwise, run fetch finale given fetchParams and response. fetchFinale(fetchParams, response) } } catch (err) { fetchParams.controller.terminate(err) } } // https://fetch.spec.whatwg.org/#concept-scheme-fetch // given a fetch params fetchParams function schemeFetch (fetchParams) { // Note: since the connection is destroyed on redirect, which sets fetchParams to a // cancelled state, we do not want this condition to trigger *unless* there have been // no redirects. See https://github.com/nodejs/undici/issues/1776 // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { return Promise.resolve(makeAppropriateNetworkError(fetchParams)) } // 2. Let request be fetchParams’s request. const { request } = fetchParams const { protocol: scheme } = requestCurrentURL(request) // 3. Switch on request’s current URL’s scheme and run the associated steps: switch (scheme) { case 'about:': { // If request’s current URL’s path is the string "blank", then return a new response // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », // and body is the empty byte sequence as a body. // Otherwise, return a network error. return Promise.resolve(makeNetworkError('about scheme is not supported')) } case 'blob:': { if (!resolveObjectURL) { resolveObjectURL = (__nccwpck_require__(4573).resolveObjectURL) } // 1. Let blobURLEntry be request’s current URL’s blob URL entry. const blobURLEntry = requestCurrentURL(request) // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56 // Buffer.resolveObjectURL does not ignore URL queries. if (blobURLEntry.search.length !== 0) { return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) } const blob = resolveObjectURL(blobURLEntry.toString()) // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s // object is not a Blob object, then return a network error. if (request.method !== 'GET' || !webidl.is.Blob(blob)) { return Promise.resolve(makeNetworkError('invalid method')) } // 3. Let blob be blobURLEntry’s object. // Note: done above // 4. Let response be a new response. const response = makeResponse() // 5. Let fullLength be blob’s size. const fullLength = blob.size // 6. Let serializedFullLength be fullLength, serialized and isomorphic encoded. const serializedFullLength = isomorphicEncode(`${fullLength}`) // 7. Let type be blob’s type. const type = blob.type // 8. If request’s header list does not contain `Range`: // 9. Otherwise: if (!request.headersList.contains('range', true)) { // 1. Let bodyWithType be the result of safely extracting blob. // Note: in the FileAPI a blob "object" is a Blob *or* a MediaSource. // In node, this can only ever be a Blob. Therefore we can safely // use extractBody directly. const bodyWithType = extractBody(blob) // 2. Set response’s status message to `OK`. response.statusText = 'OK' // 3. Set response’s body to bodyWithType’s body. response.body = bodyWithType[0] // 4. Set response’s header list to « (`Content-Length`, serializedFullLength), (`Content-Type`, type) ». response.headersList.set('content-length', serializedFullLength, true) response.headersList.set('content-type', type, true) } else { // 1. Set response’s range-requested flag. response.rangeRequested = true // 2. Let rangeHeader be the result of getting `Range` from request’s header list. const rangeHeader = request.headersList.get('range', true) // 3. Let rangeValue be the result of parsing a single range header value given rangeHeader and true. const rangeValue = simpleRangeHeaderValue(rangeHeader, true) // 4. If rangeValue is failure, then return a network error. if (rangeValue === 'failure') { return Promise.resolve(makeNetworkError('failed to fetch the data URL')) } // 5. Let (rangeStart, rangeEnd) be rangeValue. let { rangeStartValue: rangeStart, rangeEndValue: rangeEnd } = rangeValue // 6. If rangeStart is null: // 7. Otherwise: if (rangeStart === null) { // 1. Set rangeStart to fullLength − rangeEnd. rangeStart = fullLength - rangeEnd // 2. Set rangeEnd to rangeStart + rangeEnd − 1. rangeEnd = rangeStart + rangeEnd - 1 } else { // 1. If rangeStart is greater than or equal to fullLength, then return a network error. if (rangeStart >= fullLength) { return Promise.resolve(makeNetworkError('Range start is greater than the blob\'s size.')) } // 2. If rangeEnd is null or rangeEnd is greater than or equal to fullLength, then set // rangeEnd to fullLength − 1. if (rangeEnd === null || rangeEnd >= fullLength) { rangeEnd = fullLength - 1 } } // 8. Let slicedBlob be the result of invoking slice blob given blob, rangeStart, // rangeEnd + 1, and type. const slicedBlob = blob.slice(rangeStart, rangeEnd, type) // 9. Let slicedBodyWithType be the result of safely extracting slicedBlob. // Note: same reason as mentioned above as to why we use extractBody const slicedBodyWithType = extractBody(slicedBlob) // 10. Set response’s body to slicedBodyWithType’s body. response.body = slicedBodyWithType[0] // 11. Let serializedSlicedLength be slicedBlob’s size, serialized and isomorphic encoded. const serializedSlicedLength = isomorphicEncode(`${slicedBlob.size}`) // 12. Let contentRange be the result of invoking build a content range given rangeStart, // rangeEnd, and fullLength. const contentRange = buildContentRange(rangeStart, rangeEnd, fullLength) // 13. Set response’s status to 206. response.status = 206 // 14. Set response’s status message to `Partial Content`. response.statusText = 'Partial Content' // 15. Set response’s header list to « (`Content-Length`, serializedSlicedLength), // (`Content-Type`, type), (`Content-Range`, contentRange) ». response.headersList.set('content-length', serializedSlicedLength, true) response.headersList.set('content-type', type, true) response.headersList.set('content-range', contentRange, true) } // 10. Return response. return Promise.resolve(response) } case 'data:': { // 1. Let dataURLStruct be the result of running the // data: URL processor on request’s current URL. const currentURL = requestCurrentURL(request) const dataURLStruct = dataURLProcessor(currentURL) // 2. If dataURLStruct is failure, then return a // network error. if (dataURLStruct === 'failure') { return Promise.resolve(makeNetworkError('failed to fetch the data URL')) } // 3. Let mimeType be dataURLStruct’s MIME type, serialized. const mimeType = serializeAMimeType(dataURLStruct.mimeType) // 4. Return a response whose status message is `OK`, // header list is « (`Content-Type`, mimeType) », // and body is dataURLStruct’s body as a body. return Promise.resolve(makeResponse({ statusText: 'OK', headersList: [ ['content-type', { name: 'Content-Type', value: mimeType }] ], body: safelyExtractBody(dataURLStruct.body)[0] })) } case 'file:': { // For now, unfortunate as it is, file URLs are left as an exercise for the reader. // When in doubt, return a network error. return Promise.resolve(makeNetworkError('not implemented... yet...')) } case 'http:': case 'https:': { // Return the result of running HTTP fetch given fetchParams. return httpFetch(fetchParams) .catch((err) => makeNetworkError(err)) } default: { return Promise.resolve(makeNetworkError('unknown scheme')) } } } // https://fetch.spec.whatwg.org/#finalize-response function finalizeResponse (fetchParams, response) { // 1. Set fetchParams’s request’s done flag. fetchParams.request.done = true // 2, If fetchParams’s process response done is not null, then queue a fetch // task to run fetchParams’s process response done given response, with // fetchParams’s task destination. if (fetchParams.processResponseDone != null) { queueMicrotask(() => fetchParams.processResponseDone(response)) } } // https://fetch.spec.whatwg.org/#fetch-finale function fetchFinale (fetchParams, response) { // 1. Let timingInfo be fetchParams’s timing info. let timingInfo = fetchParams.timingInfo // 2. If response is not a network error and fetchParams’s request’s client is a secure context, // then set timingInfo’s server-timing headers to the result of getting, decoding, and splitting // `Server-Timing` from response’s internal response’s header list. // TODO // 3. Let processResponseEndOfBody be the following steps: const processResponseEndOfBody = () => { // 1. Let unsafeEndTime be the unsafe shared current time. const unsafeEndTime = Date.now() // ? // 2. If fetchParams’s request’s destination is "document", then set fetchParams’s controller’s // full timing info to fetchParams’s timing info. if (fetchParams.request.destination === 'document') { fetchParams.controller.fullTimingInfo = timingInfo } // 3. Set fetchParams’s controller’s report timing steps to the following steps given a global object global: fetchParams.controller.reportTimingSteps = () => { // 1. If fetchParams’s request’s URL’s scheme is not an HTTP(S) scheme, then return. if (!urlIsHttpHttpsScheme(fetchParams.request.url)) { return } // 2. Set timingInfo’s end time to the relative high resolution time given unsafeEndTime and global. timingInfo.endTime = unsafeEndTime // 3. Let cacheState be response’s cache state. let cacheState = response.cacheState // 4. Let bodyInfo be response’s body info. const bodyInfo = response.bodyInfo // 5. If response’s timing allow passed flag is not set, then set timingInfo to the result of creating an // opaque timing info for timingInfo and set cacheState to the empty string. if (!response.timingAllowPassed) { timingInfo = createOpaqueTimingInfo(timingInfo) cacheState = '' } // 6. Let responseStatus be 0. let responseStatus = 0 // 7. If fetchParams’s request’s mode is not "navigate" or response’s has-cross-origin-redirects is false: if (fetchParams.request.mode !== 'navigator' || !response.hasCrossOriginRedirects) { // 1. Set responseStatus to response’s status. responseStatus = response.status // 2. Let mimeType be the result of extracting a MIME type from response’s header list. const mimeType = extractMimeType(response.headersList) // 3. If mimeType is not failure, then set bodyInfo’s content type to the result of minimizing a supported MIME type given mimeType. if (mimeType !== 'failure') { bodyInfo.contentType = minimizeSupportedMimeType(mimeType) } } // 8. If fetchParams’s request’s initiator type is non-null, then mark resource timing given timingInfo, // fetchParams’s request’s URL, fetchParams’s request’s initiator type, global, cacheState, bodyInfo, // and responseStatus. if (fetchParams.request.initiatorType != null) { markResourceTiming(timingInfo, fetchParams.request.url.href, fetchParams.request.initiatorType, globalThis, cacheState, bodyInfo, responseStatus) } } // 4. Let processResponseEndOfBodyTask be the following steps: const processResponseEndOfBodyTask = () => { // 1. Set fetchParams’s request’s done flag. fetchParams.request.done = true // 2. If fetchParams’s process response end-of-body is non-null, then run fetchParams’s process // response end-of-body given response. if (fetchParams.processResponseEndOfBody != null) { queueMicrotask(() => fetchParams.processResponseEndOfBody(response)) } // 3. If fetchParams’s request’s initiator type is non-null and fetchParams’s request’s client’s // global object is fetchParams’s task destination, then run fetchParams’s controller’s report // timing steps given fetchParams’s request’s client’s global object. if (fetchParams.request.initiatorType != null) { fetchParams.controller.reportTimingSteps() } } // 5. Queue a fetch task to run processResponseEndOfBodyTask with fetchParams’s task destination queueMicrotask(() => processResponseEndOfBodyTask()) } // 4. If fetchParams’s process response is non-null, then queue a fetch task to run fetchParams’s // process response given response, with fetchParams’s task destination. if (fetchParams.processResponse != null) { queueMicrotask(() => { fetchParams.processResponse(response) fetchParams.processResponse = null }) } // 5. Let internalResponse be response, if response is a network error; otherwise response’s internal response. const internalResponse = response.type === 'error' ? response : (response.internalResponse ?? response) // 6. If internalResponse’s body is null, then run processResponseEndOfBody. // 7. Otherwise: if (internalResponse.body == null) { processResponseEndOfBody() } else { // mcollina: all the following steps of the specs are skipped. // The internal transform stream is not needed. // See https://github.com/nodejs/undici/pull/3093#issuecomment-2050198541 // 1. Let transformStream be a new TransformStream. // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream. // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm and flushAlgorithm // set to processResponseEndOfBody. // 4. Set internalResponse’s body’s stream to the result of internalResponse’s body’s stream piped through transformStream. finished(internalResponse.body.stream, () => { processResponseEndOfBody() }) } } // https://fetch.spec.whatwg.org/#http-fetch async function httpFetch (fetchParams) { // 1. Let request be fetchParams’s request. const request = fetchParams.request // 2. Let response be null. let response = null // 3. Let actualResponse be null. let actualResponse = null // 4. Let timingInfo be fetchParams’s timing info. const timingInfo = fetchParams.timingInfo // 5. If request’s service-workers mode is "all", then: if (request.serviceWorkers === 'all') { // TODO } // 6. If response is null, then: if (response === null) { // 1. If makeCORSPreflight is true and one of these conditions is true: // TODO // 2. If request’s redirect mode is "follow", then set request’s // service-workers mode to "none". if (request.redirect === 'follow') { request.serviceWorkers = 'none' } // 3. Set response and actualResponse to the result of running // HTTP-network-or-cache fetch given fetchParams. actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) // 4. If request’s response tainting is "cors" and a CORS check // for request and response returns failure, then return a network error. if ( request.responseTainting === 'cors' && corsCheck(request, response) === 'failure' ) { return makeNetworkError('cors failure') } // 5. If the TAO check for request and response returns failure, then set // request’s timing allow failed flag. if (TAOCheck(request, response) === 'failure') { request.timingAllowFailed = true } } // 7. If either request’s response tainting or response’s type // is "opaque", and the cross-origin resource policy check with // request’s origin, request’s client, request’s destination, // and actualResponse returns blocked, then return a network error. if ( (request.responseTainting === 'opaque' || response.type === 'opaque') && crossOriginResourcePolicyCheck( request.origin, request.client, request.destination, actualResponse ) === 'blocked' ) { return makeNetworkError('blocked') } // 8. If actualResponse’s status is a redirect status, then: if (redirectStatusSet.has(actualResponse.status)) { // 1. If actualResponse’s status is not 303, request’s body is not null, // and the connection uses HTTP/2, then user agents may, and are even // encouraged to, transmit an RST_STREAM frame. // See, https://github.com/whatwg/fetch/issues/1288 if (request.redirect !== 'manual') { fetchParams.controller.connection.destroy(undefined, false) } // 2. Switch on request’s redirect mode: if (request.redirect === 'error') { // Set response to a network error. response = makeNetworkError('unexpected redirect') } else if (request.redirect === 'manual') { // Set response to an opaque-redirect filtered response whose internal // response is actualResponse. // NOTE(spec): On the web this would return an `opaqueredirect` response, // but that doesn't make sense server side. // See https://github.com/nodejs/undici/issues/1193. response = actualResponse } else if (request.redirect === 'follow') { // Set response to the result of running HTTP-redirect fetch given // fetchParams and response. response = await httpRedirectFetch(fetchParams, response) } else { assert(false) } } // 9. Set response’s timing info to timingInfo. response.timingInfo = timingInfo // 10. Return response. return response } // https://fetch.spec.whatwg.org/#http-redirect-fetch function httpRedirectFetch (fetchParams, response) { // 1. Let request be fetchParams’s request. const request = fetchParams.request // 2. Let actualResponse be response, if response is not a filtered response, // and response’s internal response otherwise. const actualResponse = response.internalResponse ? response.internalResponse : response // 3. Let locationURL be actualResponse’s location URL given request’s current // URL’s fragment. let locationURL try { locationURL = responseLocationURL( actualResponse, requestCurrentURL(request).hash ) // 4. If locationURL is null, then return response. if (locationURL == null) { return response } } catch (err) { // 5. If locationURL is failure, then return a network error. return Promise.resolve(makeNetworkError(err)) } // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network // error. if (!urlIsHttpHttpsScheme(locationURL)) { return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) } // 7. If request’s redirect count is 20, then return a network error. if (request.redirectCount === 20) { return Promise.resolve(makeNetworkError('redirect count exceeded')) } // 8. Increase request’s redirect count by 1. request.redirectCount += 1 // 9. If request’s mode is "cors", locationURL includes credentials, and // request’s origin is not same origin with locationURL’s origin, then return // a network error. if ( request.mode === 'cors' && (locationURL.username || locationURL.password) && !sameOrigin(request, locationURL) ) { return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) } // 10. If request’s response tainting is "cors" and locationURL includes // credentials, then return a network error. if ( request.responseTainting === 'cors' && (locationURL.username || locationURL.password) ) { return Promise.resolve(makeNetworkError( 'URL cannot contain credentials for request mode "cors"' )) } // 11. If actualResponse’s status is not 303, request’s body is non-null, // and request’s body’s source is null, then return a network error. if ( actualResponse.status !== 303 && request.body != null && request.body.source == null ) { return Promise.resolve(makeNetworkError()) } // 12. If one of the following is true // - actualResponse’s status is 301 or 302 and request’s method is `POST` // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD` if ( ([301, 302].includes(actualResponse.status) && request.method === 'POST') || (actualResponse.status === 303 && !GET_OR_HEAD.includes(request.method)) ) { // then: // 1. Set request’s method to `GET` and request’s body to null. request.method = 'GET' request.body = null // 2. For each headerName of request-body-header name, delete headerName from // request’s header list. for (const headerName of requestBodyHeader) { request.headersList.delete(headerName) } } // 13. If request’s current URL’s origin is not same origin with locationURL’s // origin, then for each headerName of CORS non-wildcard request-header name, // delete headerName from request’s header list. if (!sameOrigin(requestCurrentURL(request), locationURL)) { // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name request.headersList.delete('authorization', true) // https://fetch.spec.whatwg.org/#authentication-entries request.headersList.delete('proxy-authorization', true) // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. request.headersList.delete('cookie', true) request.headersList.delete('host', true) } // 14. If request’s body is non-null, then set request’s body to the first return // value of safely extracting request’s body’s source. if (request.body != null) { assert(request.body.source != null) request.body = safelyExtractBody(request.body.source)[0] } // 15. Let timingInfo be fetchParams’s timing info. const timingInfo = fetchParams.timingInfo // 16. Set timingInfo’s redirect end time and post-redirect start time to the // coarsened shared current time given fetchParams’s cross-origin isolated // capability. timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s // redirect start time to timingInfo’s start time. if (timingInfo.redirectStartTime === 0) { timingInfo.redirectStartTime = timingInfo.startTime } // 18. Append locationURL to request’s URL list. request.urlList.push(locationURL) // 19. Invoke set request’s referrer policy on redirect on request and // actualResponse. setRequestReferrerPolicyOnRedirect(request, actualResponse) // 20. Return the result of running main fetch given fetchParams and true. return mainFetch(fetchParams, true) } // https://fetch.spec.whatwg.org/#http-network-or-cache-fetch async function httpNetworkOrCacheFetch ( fetchParams, isAuthenticationFetch = false, isNewConnectionFetch = false ) { // 1. Let request be fetchParams’s request. const request = fetchParams.request // 2. Let httpFetchParams be null. let httpFetchParams = null // 3. Let httpRequest be null. let httpRequest = null // 4. Let response be null. let response = null // 5. Let storedResponse be null. // TODO: cache // 6. Let httpCache be null. const httpCache = null // 7. Let the revalidatingFlag be unset. const revalidatingFlag = false // 8. Run these steps, but abort when the ongoing fetch is terminated: // 1. If request’s window is "no-window" and request’s redirect mode is // "error", then set httpFetchParams to fetchParams and httpRequest to // request. if (request.window === 'no-window' && request.redirect === 'error') { httpFetchParams = fetchParams httpRequest = request } else { // Otherwise: // 1. Set httpRequest to a clone of request. httpRequest = cloneRequest(request) // 2. Set httpFetchParams to a copy of fetchParams. httpFetchParams = { ...fetchParams } // 3. Set httpFetchParams’s request to httpRequest. httpFetchParams.request = httpRequest } // 3. Let includeCredentials be true if one of const includeCredentials = request.credentials === 'include' || (request.credentials === 'same-origin' && request.responseTainting === 'basic') // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s // body is non-null; otherwise null. const contentLength = httpRequest.body ? httpRequest.body.length : null // 5. Let contentLengthHeaderValue be null. let contentLengthHeaderValue = null // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or // `PUT`, then set contentLengthHeaderValue to `0`. if ( httpRequest.body == null && ['POST', 'PUT'].includes(httpRequest.method) ) { contentLengthHeaderValue = '0' } // 7. If contentLength is non-null, then set contentLengthHeaderValue to // contentLength, serialized and isomorphic encoded. if (contentLength != null) { contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) } // 8. If contentLengthHeaderValue is non-null, then append // `Content-Length`/contentLengthHeaderValue to httpRequest’s header // list. if (contentLengthHeaderValue != null) { httpRequest.headersList.append('content-length', contentLengthHeaderValue, true) } // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, // contentLengthHeaderValue) to httpRequest’s header list. // 10. If contentLength is non-null and httpRequest’s keepalive is true, // then: if (contentLength != null && httpRequest.keepalive) { // NOTE: keepalive is a noop outside of browser context. } // 11. If httpRequest’s referrer is a URL, then append // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded, // to httpRequest’s header list. if (webidl.is.URL(httpRequest.referrer)) { httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href), true) } // 12. Append a request `Origin` header for httpRequest. appendRequestOriginHeader(httpRequest) // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] appendFetchMetadata(httpRequest) // 14. If httpRequest’s header list does not contain `User-Agent`, then // user agents should append `User-Agent`/default `User-Agent` value to // httpRequest’s header list. if (!httpRequest.headersList.contains('user-agent', true)) { httpRequest.headersList.append('user-agent', defaultUserAgent, true) } // 15. If httpRequest’s cache mode is "default" and httpRequest’s header // list contains `If-Modified-Since`, `If-None-Match`, // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set // httpRequest’s cache mode to "no-store". if ( httpRequest.cache === 'default' && (httpRequest.headersList.contains('if-modified-since', true) || httpRequest.headersList.contains('if-none-match', true) || httpRequest.headersList.contains('if-unmodified-since', true) || httpRequest.headersList.contains('if-match', true) || httpRequest.headersList.contains('if-range', true)) ) { httpRequest.cache = 'no-store' } // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent // no-cache cache-control header modification flag is unset, and // httpRequest’s header list does not contain `Cache-Control`, then append // `Cache-Control`/`max-age=0` to httpRequest’s header list. if ( httpRequest.cache === 'no-cache' && !httpRequest.preventNoCacheCacheControlHeaderModification && !httpRequest.headersList.contains('cache-control', true) ) { httpRequest.headersList.append('cache-control', 'max-age=0', true) } // 17. If httpRequest’s cache mode is "no-store" or "reload", then: if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') { // 1. If httpRequest’s header list does not contain `Pragma`, then append // `Pragma`/`no-cache` to httpRequest’s header list. if (!httpRequest.headersList.contains('pragma', true)) { httpRequest.headersList.append('pragma', 'no-cache', true) } // 2. If httpRequest’s header list does not contain `Cache-Control`, // then append `Cache-Control`/`no-cache` to httpRequest’s header list. if (!httpRequest.headersList.contains('cache-control', true)) { httpRequest.headersList.append('cache-control', 'no-cache', true) } } // 18. If httpRequest’s header list contains `Range`, then append // `Accept-Encoding`/`identity` to httpRequest’s header list. if (httpRequest.headersList.contains('range', true)) { httpRequest.headersList.append('accept-encoding', 'identity', true) } // 19. Modify httpRequest’s header list per HTTP. Do not append a given // header if httpRequest’s header list contains that header’s name. // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129 if (!httpRequest.headersList.contains('accept-encoding', true)) { if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) { httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate', true) } else { httpRequest.headersList.append('accept-encoding', 'gzip, deflate', true) } } httpRequest.headersList.delete('host', true) // 20. If includeCredentials is true, then: if (includeCredentials) { // 1. If the user agent is not configured to block cookies for httpRequest // (see section 7 of [COOKIES]), then: // TODO: credentials // 2. If httpRequest’s header list does not contain `Authorization`, then: // TODO: credentials } // 21. If there’s a proxy-authentication entry, use it as appropriate. // TODO: proxy-authentication // 22. Set httpCache to the result of determining the HTTP cache // partition, given httpRequest. // TODO: cache // 23. If httpCache is null, then set httpRequest’s cache mode to // "no-store". if (httpCache == null) { httpRequest.cache = 'no-store' } // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", // then: if (httpRequest.cache !== 'no-store' && httpRequest.cache !== 'reload') { // TODO: cache } // 9. If aborted, then return the appropriate network error for fetchParams. // TODO // 10. If response is null, then: if (response == null) { // 1. If httpRequest’s cache mode is "only-if-cached", then return a // network error. if (httpRequest.cache === 'only-if-cached') { return makeNetworkError('only if cached') } // 2. Let forwardResponse be the result of running HTTP-network fetch // given httpFetchParams, includeCredentials, and isNewConnectionFetch. const forwardResponse = await httpNetworkFetch( httpFetchParams, includeCredentials, isNewConnectionFetch ) // 3. If httpRequest’s method is unsafe and forwardResponse’s status is // in the range 200 to 399, inclusive, invalidate appropriate stored // responses in httpCache, as per the "Invalidation" chapter of HTTP // Caching, and set storedResponse to null. [HTTP-CACHING] if ( !safeMethodsSet.has(httpRequest.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399 ) { // TODO: cache } // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, // then: if (revalidatingFlag && forwardResponse.status === 304) { // TODO: cache } // 5. If response is null, then: if (response == null) { // 1. Set response to forwardResponse. response = forwardResponse // 2. Store httpRequest and forwardResponse in httpCache, as per the // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] // TODO: cache } } // 11. Set response’s URL list to a clone of httpRequest’s URL list. response.urlList = [...httpRequest.urlList] // 12. If httpRequest’s header list contains `Range`, then set response’s // range-requested flag. if (httpRequest.headersList.contains('range', true)) { response.rangeRequested = true } // 13. Set response’s request-includes-credentials to includeCredentials. response.requestIncludesCredentials = includeCredentials // 14. If response’s status is 401, httpRequest’s response tainting is not // "cors", includeCredentials is true, and request’s window is an environment // settings object, then: // TODO // 15. If response’s status is 407, then: if (response.status === 407) { // 1. If request’s window is "no-window", then return a network error. if (request.window === 'no-window') { return makeNetworkError() } // 2. ??? // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. if (isCancelled(fetchParams)) { return makeAppropriateNetworkError(fetchParams) } // 4. Prompt the end user as appropriate in request’s window and store // the result as a proxy-authentication entry. [HTTP-AUTH] // TODO: Invoke some kind of callback? // 5. Set response to the result of running HTTP-network-or-cache fetch given // fetchParams. // TODO return makeNetworkError('proxy authentication required') } // 16. If all of the following are true if ( // response’s status is 421 response.status === 421 && // isNewConnectionFetch is false !isNewConnectionFetch && // request’s body is null, or request’s body is non-null and request’s body’s source is non-null (request.body == null || request.body.source != null) ) { // then: // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. if (isCancelled(fetchParams)) { return makeAppropriateNetworkError(fetchParams) } // 2. Set response to the result of running HTTP-network-or-cache // fetch given fetchParams, isAuthenticationFetch, and true. // TODO (spec): The spec doesn't specify this but we need to cancel // the active response before we can start a new one. // https://github.com/whatwg/fetch/issues/1293 fetchParams.controller.connection.destroy() response = await httpNetworkOrCacheFetch( fetchParams, isAuthenticationFetch, true ) } // 17. If isAuthenticationFetch is true, then create an authentication entry if (isAuthenticationFetch) { // TODO } // 18. Return response. return response } // https://fetch.spec.whatwg.org/#http-network-fetch async function httpNetworkFetch ( fetchParams, includeCredentials = false, forceNewConnection = false ) { assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) fetchParams.controller.connection = { abort: null, destroyed: false, destroy (err, abort = true) { if (!this.destroyed) { this.destroyed = true if (abort) { this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError')) } } } } // 1. Let request be fetchParams’s request. const request = fetchParams.request // 2. Let response be null. let response = null // 3. Let timingInfo be fetchParams’s timing info. const timingInfo = fetchParams.timingInfo // 4. Let httpCache be the result of determining the HTTP cache partition, // given request. // TODO: cache const httpCache = null // 5. If httpCache is null, then set request’s cache mode to "no-store". if (httpCache == null) { request.cache = 'no-store' } // 6. Let networkPartitionKey be the result of determining the network // partition key given request. // TODO // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise // "no". const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars // 8. Switch on request’s mode: if (request.mode === 'websocket') { // Let connection be the result of obtaining a WebSocket connection, // given request’s current URL. // TODO } else { // Let connection be the result of obtaining a connection, given // networkPartitionKey, request’s current URL’s origin, // includeCredentials, and forceNewConnection. // TODO } // 9. Run these steps, but abort when the ongoing fetch is terminated: // 1. If connection is failure, then return a network error. // 2. Set timingInfo’s final connection timing info to the result of // calling clamp and coarsen connection timing info with connection’s // timing info, timingInfo’s post-redirect start time, and fetchParams’s // cross-origin isolated capability. // 3. If connection is not an HTTP/2 connection, request’s body is non-null, // and request’s body’s source is null, then append (`Transfer-Encoding`, // `chunked`) to request’s header list. // 4. Set timingInfo’s final network-request start time to the coarsened // shared current time given fetchParams’s cross-origin isolated // capability. // 5. Set response to the result of making an HTTP request over connection // using request with the following caveats: // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] // - If request’s body is non-null, and request’s body’s source is null, // then the user agent may have a buffer of up to 64 kibibytes and store // a part of request’s body in that buffer. If the user agent reads from // request’s body beyond that buffer’s size and the user agent needs to // resend request, then instead return a network error. // - Set timingInfo’s final network-response start time to the coarsened // shared current time given fetchParams’s cross-origin isolated capability, // immediately after the user agent’s HTTP parser receives the first byte // of the response (e.g., frame header bytes for HTTP/2 or response status // line for HTTP/1.x). // - Wait until all the headers are transmitted. // - Any responses whose status is in the range 100 to 199, inclusive, // and is not 101, are to be ignored, except for the purposes of setting // timingInfo’s final network-response start time above. // - If request’s header list contains `Transfer-Encoding`/`chunked` and // response is transferred via HTTP/1.0 or older, then return a network // error. // - If the HTTP request results in a TLS client certificate dialog, then: // 1. If request’s window is an environment settings object, make the // dialog available in request’s window. // 2. Otherwise, return a network error. // To transmit request’s body body, run these steps: let requestBody = null // 1. If body is null and fetchParams’s process request end-of-body is // non-null, then queue a fetch task given fetchParams’s process request // end-of-body and fetchParams’s task destination. if (request.body == null && fetchParams.processRequestEndOfBody) { queueMicrotask(() => fetchParams.processRequestEndOfBody()) } else if (request.body != null) { // 2. Otherwise, if body is non-null: // 1. Let processBodyChunk given bytes be these steps: const processBodyChunk = async function * (bytes) { // 1. If the ongoing fetch is terminated, then abort these steps. if (isCancelled(fetchParams)) { return } // 2. Run this step in parallel: transmit bytes. yield bytes // 3. If fetchParams’s process request body is non-null, then run // fetchParams’s process request body given bytes’s length. fetchParams.processRequestBodyChunkLength?.(bytes.byteLength) } // 2. Let processEndOfBody be these steps: const processEndOfBody = () => { // 1. If fetchParams is canceled, then abort these steps. if (isCancelled(fetchParams)) { return } // 2. If fetchParams’s process request end-of-body is non-null, // then run fetchParams’s process request end-of-body. if (fetchParams.processRequestEndOfBody) { fetchParams.processRequestEndOfBody() } } // 3. Let processBodyError given e be these steps: const processBodyError = (e) => { // 1. If fetchParams is canceled, then abort these steps. if (isCancelled(fetchParams)) { return } // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. if (e.name === 'AbortError') { fetchParams.controller.abort() } else { fetchParams.controller.terminate(e) } } // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, // processBodyError, and fetchParams’s task destination. requestBody = (async function * () { try { for await (const bytes of request.body.stream) { yield * processBodyChunk(bytes) } processEndOfBody() } catch (err) { processBodyError(err) } })() } try { // socket is only provided for websockets const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) if (socket) { response = makeResponse({ status, statusText, headersList, socket }) } else { const iterator = body[Symbol.asyncIterator]() fetchParams.controller.next = () => iterator.next() response = makeResponse({ status, statusText, headersList }) } } catch (err) { // 10. If aborted, then: if (err.name === 'AbortError') { // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame. fetchParams.controller.connection.destroy() // 2. Return the appropriate network error for fetchParams. return makeAppropriateNetworkError(fetchParams, err) } return makeNetworkError(err) } // 11. Let pullAlgorithm be an action that resumes the ongoing fetch // if it is suspended. const pullAlgorithm = () => { return fetchParams.controller.resume() } // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s // controller with reason, given reason. const cancelAlgorithm = (reason) => { // If the aborted fetch was already terminated, then we do not // need to do anything. if (!isCancelled(fetchParams)) { fetchParams.controller.abort(reason) } } // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by // the user agent. // TODO // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent. // TODO // 15. Let stream be a new ReadableStream. // 16. Set up stream with byte reading support with pullAlgorithm set to pullAlgorithm, // cancelAlgorithm set to cancelAlgorithm. const stream = new ReadableStream( { start (controller) { fetchParams.controller.controller = controller }, pull: pullAlgorithm, cancel: cancelAlgorithm, type: 'bytes' } ) // 17. Run these steps, but abort when the ongoing fetch is terminated: // 1. Set response’s body to a new body whose stream is stream. response.body = { stream, source: null, length: null } // 2. If response is not a network error and request’s cache mode is // not "no-store", then update response in httpCache for request. // TODO // 3. If includeCredentials is true and the user agent is not configured // to block cookies for request (see section 7 of [COOKIES]), then run the // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on // the value of each header whose name is a byte-case-insensitive match for // `Set-Cookie` in response’s header list, if any, and request’s current URL. // TODO // 18. If aborted, then: // TODO // 19. Run these steps in parallel: // 1. Run these steps, but abort when fetchParams is canceled: if (!fetchParams.controller.resume) { fetchParams.controller.on('terminated', onAborted) } fetchParams.controller.resume = async () => { // 1. While true while (true) { // 1-3. See onData... // 4. Set bytes to the result of handling content codings given // codings and bytes. let bytes let isFailure try { const { done, value } = await fetchParams.controller.next() if (isAborted(fetchParams)) { break } bytes = done ? undefined : value } catch (err) { if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { // zlib doesn't like empty streams. bytes = undefined } else { bytes = err // err may be propagated from the result of calling readablestream.cancel, // which might not be an error. https://github.com/nodejs/undici/issues/2009 isFailure = true } } if (bytes === undefined) { // 2. Otherwise, if the bytes transmission for response’s message // body is done normally and stream is readable, then close // stream, finalize response for fetchParams and response, and // abort these in-parallel steps. readableStreamClose(fetchParams.controller.controller) finalizeResponse(fetchParams, response) return } // 5. Increase timingInfo’s decoded body size by bytes’s length. timingInfo.decodedBodySize += bytes?.byteLength ?? 0 // 6. If bytes is failure, then terminate fetchParams’s controller. if (isFailure) { fetchParams.controller.terminate(bytes) return } // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes // into stream. const buffer = new Uint8Array(bytes) if (buffer.byteLength) { fetchParams.controller.controller.enqueue(buffer) } // 8. If stream is errored, then terminate the ongoing fetch. if (isErrored(stream)) { fetchParams.controller.terminate() return } // 9. If stream doesn’t need more data ask the user agent to suspend // the ongoing fetch. if (fetchParams.controller.controller.desiredSize <= 0) { return } } } // 2. If aborted, then: function onAborted (reason) { // 2. If fetchParams is aborted, then: if (isAborted(fetchParams)) { // 1. Set response’s aborted flag. response.aborted = true // 2. If stream is readable, then error stream with the result of // deserialize a serialized abort reason given fetchParams’s // controller’s serialized abort reason and an // implementation-defined realm. if (isReadable(stream)) { fetchParams.controller.controller.error( fetchParams.controller.serializedAbortReason ) } } else { // 3. Otherwise, if stream is readable, error stream with a TypeError. if (isReadable(stream)) { fetchParams.controller.controller.error(new TypeError('terminated', { cause: isErrorLike(reason) ? reason : undefined })) } } // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame. // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so. fetchParams.controller.connection.destroy() } // 20. Return response. return response function dispatch ({ body }) { const url = requestCurrentURL(request) /** @type {import('../../..').Agent} */ const agent = fetchParams.controller.dispatcher return new Promise((resolve, reject) => agent.dispatch( { path: url.pathname + url.search, origin: url.origin, method: request.method, body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body, headers: request.headersList.entries, maxRedirections: 0, upgrade: request.mode === 'websocket' ? 'websocket' : undefined }, { body: null, abort: null, onConnect (abort) { // TODO (fix): Do we need connection here? const { connection } = fetchParams.controller // Set timingInfo’s final connection timing info to the result of calling clamp and coarsen // connection timing info with connection’s timing info, timingInfo’s post-redirect start // time, and fetchParams’s cross-origin isolated capability. // TODO: implement connection timing timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(undefined, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability) if (connection.destroyed) { abort(new DOMException('The operation was aborted.', 'AbortError')) } else { fetchParams.controller.on('terminated', abort) this.abort = connection.abort = abort } // Set timingInfo’s final network-request start time to the coarsened shared current time given // fetchParams’s cross-origin isolated capability. timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) }, onResponseStarted () { // Set timingInfo’s final network-response start time to the coarsened shared current // time given fetchParams’s cross-origin isolated capability, immediately after the // user agent’s HTTP parser receives the first byte of the response (e.g., frame header // bytes for HTTP/2 or response status line for HTTP/1.x). timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) }, onHeaders (status, rawHeaders, resume, statusText) { if (status < 200) { return false } /** @type {string[]} */ let codings = [] const headersList = new HeadersList() for (let i = 0; i < rawHeaders.length; i += 2) { headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true) } const contentEncoding = headersList.get('content-encoding', true) if (contentEncoding) { // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 // "All content-coding values are case-insensitive..." codings = contentEncoding.toLowerCase().split(',').map((x) => x.trim()) } const location = headersList.get('location', true) this.body = new Readable({ read: resume }) const decoders = [] const willFollow = location && request.redirect === 'follow' && redirectStatusSet.has(status) // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding if (codings.length !== 0 && request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { for (let i = codings.length - 1; i >= 0; --i) { const coding = codings[i] // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2 if (coding === 'x-gzip' || coding === 'gzip') { decoders.push(zlib.createGunzip({ // Be less strict when decoding compressed responses, since sometimes // servers send slightly invalid responses that are still accepted // by common browsers. // Always using Z_SYNC_FLUSH is what cURL does. flush: zlib.constants.Z_SYNC_FLUSH, finishFlush: zlib.constants.Z_SYNC_FLUSH })) } else if (coding === 'deflate') { decoders.push(createInflate({ flush: zlib.constants.Z_SYNC_FLUSH, finishFlush: zlib.constants.Z_SYNC_FLUSH })) } else if (coding === 'br') { decoders.push(zlib.createBrotliDecompress({ flush: zlib.constants.BROTLI_OPERATION_FLUSH, finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH })) } else if (coding === 'zstd' && typeof zlib.createZstdDecompress === 'function') { // Node.js v23.8.0+ and v22.15.0+ supports Zstandard decoders.push(zlib.createZstdDecompress({ flush: zlib.constants.ZSTD_e_continue, finishFlush: zlib.constants.ZSTD_e_end })) } else { decoders.length = 0 break } } } const onError = this.onError.bind(this) resolve({ status, statusText, headersList, body: decoders.length ? pipeline(this.body, ...decoders, (err) => { if (err) { this.onError(err) } }).on('error', onError) : this.body.on('error', onError) }) return true }, onData (chunk) { if (fetchParams.controller.dump) { return } // 1. If one or more bytes have been transmitted from response’s // message body, then: // 1. Let bytes be the transmitted bytes. const bytes = chunk // 2. Let codings be the result of extracting header list values // given `Content-Encoding` and response’s header list. // See pullAlgorithm. // 3. Increase timingInfo’s encoded body size by bytes’s length. timingInfo.encodedBodySize += bytes.byteLength // 4. See pullAlgorithm... return this.body.push(bytes) }, onComplete () { if (this.abort) { fetchParams.controller.off('terminated', this.abort) } fetchParams.controller.ended = true this.body.push(null) }, onError (error) { if (this.abort) { fetchParams.controller.off('terminated', this.abort) } this.body?.destroy(error) fetchParams.controller.terminate(error) reject(error) }, onUpgrade (status, rawHeaders, socket) { if (status !== 101) { return } const headersList = new HeadersList() for (let i = 0; i < rawHeaders.length; i += 2) { headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true) } resolve({ status, statusText: STATUS_CODES[status], headersList, socket }) return true } } )) } } module.exports = { fetch, Fetch, fetching, finalizeAndReportTiming } /***/ }), /***/ 7622: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* globals AbortController */ const { extractBody, mixinBody, cloneBody, bodyUnusable } = __nccwpck_require__(27679) const { Headers, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = __nccwpck_require__(289) const util = __nccwpck_require__(46425) const nodeUtil = __nccwpck_require__(57975) const { isValidHTTPToken, sameOrigin, environmentSettingsObject } = __nccwpck_require__(58799) const { forbiddenMethodsSet, corsSafeListedMethodsSet, referrerPolicy, requestRedirect, requestMode, requestCredentials, requestCache, requestDuplex } = __nccwpck_require__(10546) const { kEnumerableProperty, normalizedMethodRecordsBase, normalizedMethodRecords } = util const { webidl } = __nccwpck_require__(16480) const { URLSerializer } = __nccwpck_require__(38675) const { kConstruct } = __nccwpck_require__(83112) const assert = __nccwpck_require__(34589) const { getMaxListeners, setMaxListeners, defaultMaxListeners } = __nccwpck_require__(78474) const kAbortController = Symbol('abortController') const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { signal.removeEventListener('abort', abort) }) const dependentControllerMap = new WeakMap() let abortSignalHasEventHandlerLeakWarning try { abortSignalHasEventHandlerLeakWarning = getMaxListeners(new AbortController().signal) > 0 } catch { abortSignalHasEventHandlerLeakWarning = false } function buildAbort (acRef) { return abort function abort () { const ac = acRef.deref() if (ac !== undefined) { // Currently, there is a problem with FinalizationRegistry. // https://github.com/nodejs/node/issues/49344 // https://github.com/nodejs/node/issues/47748 // In the case of abort, the first step is to unregister from it. // If the controller can refer to it, it is still registered. // It will be removed in the future. requestFinalizer.unregister(abort) // Unsubscribe a listener. // FinalizationRegistry will no longer be called, so this must be done. this.removeEventListener('abort', abort) ac.abort(this.reason) const controllerList = dependentControllerMap.get(ac.signal) if (controllerList !== undefined) { if (controllerList.size !== 0) { for (const ref of controllerList) { const ctrl = ref.deref() if (ctrl !== undefined) { ctrl.abort(this.reason) } } controllerList.clear() } dependentControllerMap.delete(ac.signal) } } } } let patchMethodWarning = false // https://fetch.spec.whatwg.org/#request-class class Request { /** @type {AbortSignal} */ #signal /** @type {import('../../dispatcher/dispatcher')} */ #dispatcher /** @type {Headers} */ #headers #state // https://fetch.spec.whatwg.org/#dom-request constructor (input, init = undefined) { webidl.util.markAsUncloneable(this) if (input === kConstruct) { return } const prefix = 'Request constructor' webidl.argumentLengthCheck(arguments, 1, prefix) input = webidl.converters.RequestInfo(input) init = webidl.converters.RequestInit(init) // 1. Let request be null. let request = null // 2. Let fallbackMode be null. let fallbackMode = null // 3. Let baseURL be this’s relevant settings object’s API base URL. const baseUrl = environmentSettingsObject.settingsObject.baseUrl // 4. Let signal be null. let signal = null // 5. If input is a string, then: if (typeof input === 'string') { this.#dispatcher = init.dispatcher // 1. Let parsedURL be the result of parsing input with baseURL. // 2. If parsedURL is failure, then throw a TypeError. let parsedURL try { parsedURL = new URL(input, baseUrl) } catch (err) { throw new TypeError('Failed to parse URL from ' + input, { cause: err }) } // 3. If parsedURL includes credentials, then throw a TypeError. if (parsedURL.username || parsedURL.password) { throw new TypeError( 'Request cannot be constructed from a URL that includes credentials: ' + input ) } // 4. Set request to a new request whose URL is parsedURL. request = makeRequest({ urlList: [parsedURL] }) // 5. Set fallbackMode to "cors". fallbackMode = 'cors' } else { // 6. Otherwise: // 7. Assert: input is a Request object. assert(webidl.is.Request(input)) // 8. Set request to input’s request. request = input.#state // 9. Set signal to input’s signal. signal = input.#signal this.#dispatcher = init.dispatcher || input.#dispatcher } // 7. Let origin be this’s relevant settings object’s origin. const origin = environmentSettingsObject.settingsObject.origin // 8. Let window be "client". let window = 'client' // 9. If request’s window is an environment settings object and its origin // is same origin with origin, then set window to request’s window. if ( request.window?.constructor?.name === 'EnvironmentSettingsObject' && sameOrigin(request.window, origin) ) { window = request.window } // 10. If init["window"] exists and is non-null, then throw a TypeError. if (init.window != null) { throw new TypeError(`'window' option '${window}' must be null`) } // 11. If init["window"] exists, then set window to "no-window". if ('window' in init) { window = 'no-window' } // 12. Set request to a new request with the following properties: request = makeRequest({ // URL request’s URL. // undici implementation note: this is set as the first item in request's urlList in makeRequest // method request’s method. method: request.method, // header list A copy of request’s header list. // undici implementation note: headersList is cloned in makeRequest headersList: request.headersList, // unsafe-request flag Set. unsafeRequest: request.unsafeRequest, // client This’s relevant settings object. client: environmentSettingsObject.settingsObject, // window window. window, // priority request’s priority. priority: request.priority, // origin request’s origin. The propagation of the origin is only significant for navigation requests // being handled by a service worker. In this scenario a request can have an origin that is different // from the current client. origin: request.origin, // referrer request’s referrer. referrer: request.referrer, // referrer policy request’s referrer policy. referrerPolicy: request.referrerPolicy, // mode request’s mode. mode: request.mode, // credentials mode request’s credentials mode. credentials: request.credentials, // cache mode request’s cache mode. cache: request.cache, // redirect mode request’s redirect mode. redirect: request.redirect, // integrity metadata request’s integrity metadata. integrity: request.integrity, // keepalive request’s keepalive. keepalive: request.keepalive, // reload-navigation flag request’s reload-navigation flag. reloadNavigation: request.reloadNavigation, // history-navigation flag request’s history-navigation flag. historyNavigation: request.historyNavigation, // URL list A clone of request’s URL list. urlList: [...request.urlList] }) const initHasKey = Object.keys(init).length !== 0 // 13. If init is not empty, then: if (initHasKey) { // 1. If request’s mode is "navigate", then set it to "same-origin". if (request.mode === 'navigate') { request.mode = 'same-origin' } // 2. Unset request’s reload-navigation flag. request.reloadNavigation = false // 3. Unset request’s history-navigation flag. request.historyNavigation = false // 4. Set request’s origin to "client". request.origin = 'client' // 5. Set request’s referrer to "client" request.referrer = 'client' // 6. Set request’s referrer policy to the empty string. request.referrerPolicy = '' // 7. Set request’s URL to request’s current URL. request.url = request.urlList[request.urlList.length - 1] // 8. Set request’s URL list to « request’s URL ». request.urlList = [request.url] } // 14. If init["referrer"] exists, then: if (init.referrer !== undefined) { // 1. Let referrer be init["referrer"]. const referrer = init.referrer // 2. If referrer is the empty string, then set request’s referrer to "no-referrer". if (referrer === '') { request.referrer = 'no-referrer' } else { // 1. Let parsedReferrer be the result of parsing referrer with // baseURL. // 2. If parsedReferrer is failure, then throw a TypeError. let parsedReferrer try { parsedReferrer = new URL(referrer, baseUrl) } catch (err) { throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err }) } // 3. If one of the following is true // - parsedReferrer’s scheme is "about" and path is the string "client" // - parsedReferrer’s origin is not same origin with origin // then set request’s referrer to "client". if ( (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') || (origin && !sameOrigin(parsedReferrer, environmentSettingsObject.settingsObject.baseUrl)) ) { request.referrer = 'client' } else { // 4. Otherwise, set request’s referrer to parsedReferrer. request.referrer = parsedReferrer } } } // 15. If init["referrerPolicy"] exists, then set request’s referrer policy // to it. if (init.referrerPolicy !== undefined) { request.referrerPolicy = init.referrerPolicy } // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. let mode if (init.mode !== undefined) { mode = init.mode } else { mode = fallbackMode } // 17. If mode is "navigate", then throw a TypeError. if (mode === 'navigate') { throw webidl.errors.exception({ header: 'Request constructor', message: 'invalid request mode navigate.' }) } // 18. If mode is non-null, set request’s mode to mode. if (mode != null) { request.mode = mode } // 19. If init["credentials"] exists, then set request’s credentials mode // to it. if (init.credentials !== undefined) { request.credentials = init.credentials } // 18. If init["cache"] exists, then set request’s cache mode to it. if (init.cache !== undefined) { request.cache = init.cache } // 21. If request’s cache mode is "only-if-cached" and request’s mode is // not "same-origin", then throw a TypeError. if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { throw new TypeError( "'only-if-cached' can be set only with 'same-origin' mode" ) } // 22. If init["redirect"] exists, then set request’s redirect mode to it. if (init.redirect !== undefined) { request.redirect = init.redirect } // 23. If init["integrity"] exists, then set request’s integrity metadata to it. if (init.integrity != null) { request.integrity = String(init.integrity) } // 24. If init["keepalive"] exists, then set request’s keepalive to it. if (init.keepalive !== undefined) { request.keepalive = Boolean(init.keepalive) } // 25. If init["method"] exists, then: if (init.method !== undefined) { // 1. Let method be init["method"]. let method = init.method const mayBeNormalized = normalizedMethodRecords[method] if (mayBeNormalized !== undefined) { // Note: Bypass validation DELETE, GET, HEAD, OPTIONS, POST, PUT, PATCH and these lowercase ones request.method = mayBeNormalized } else { // 2. If method is not a method or method is a forbidden method, then // throw a TypeError. if (!isValidHTTPToken(method)) { throw new TypeError(`'${method}' is not a valid HTTP method.`) } const upperCase = method.toUpperCase() if (forbiddenMethodsSet.has(upperCase)) { throw new TypeError(`'${method}' HTTP method is unsupported.`) } // 3. Normalize method. // https://fetch.spec.whatwg.org/#concept-method-normalize // Note: must be in uppercase method = normalizedMethodRecordsBase[upperCase] ?? method // 4. Set request’s method to method. request.method = method } if (!patchMethodWarning && request.method === 'patch') { process.emitWarning('Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.', { code: 'UNDICI-FETCH-patch' }) patchMethodWarning = true } } // 26. If init["signal"] exists, then set signal to it. if (init.signal !== undefined) { signal = init.signal } // 27. Set this’s request to request. this.#state = request // 28. Set this’s signal to a new AbortSignal object with this’s relevant // Realm. // TODO: could this be simplified with AbortSignal.any // (https://dom.spec.whatwg.org/#dom-abortsignal-any) const ac = new AbortController() this.#signal = ac.signal // 29. If signal is not null, then make this’s signal follow signal. if (signal != null) { if (signal.aborted) { ac.abort(signal.reason) } else { // Keep a strong ref to ac while request object // is alive. This is needed to prevent AbortController // from being prematurely garbage collected. // See, https://github.com/nodejs/undici/issues/1926. this[kAbortController] = ac const acRef = new WeakRef(ac) const abort = buildAbort(acRef) // If the max amount of listeners is equal to the default, increase it if (abortSignalHasEventHandlerLeakWarning && getMaxListeners(signal) === defaultMaxListeners) { setMaxListeners(1500, signal) } util.addAbortListener(signal, abort) // The third argument must be a registry key to be unregistered. // Without it, you cannot unregister. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry // abort is used as the unregister key. (because it is unique) requestFinalizer.register(ac, { signal, abort }, abort) } } // 30. Set this’s headers to a new Headers object with this’s relevant // Realm, whose header list is request’s header list and guard is // "request". this.#headers = new Headers(kConstruct) setHeadersList(this.#headers, request.headersList) setHeadersGuard(this.#headers, 'request') // 31. If this’s request’s mode is "no-cors", then: if (mode === 'no-cors') { // 1. If this’s request’s method is not a CORS-safelisted method, // then throw a TypeError. if (!corsSafeListedMethodsSet.has(request.method)) { throw new TypeError( `'${request.method} is unsupported in no-cors mode.` ) } // 2. Set this’s headers’s guard to "request-no-cors". setHeadersGuard(this.#headers, 'request-no-cors') } // 32. If init is not empty, then: if (initHasKey) { /** @type {HeadersList} */ const headersList = getHeadersList(this.#headers) // 1. Let headers be a copy of this’s headers and its associated header // list. // 2. If init["headers"] exists, then set headers to init["headers"]. const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList) // 3. Empty this’s headers’s header list. headersList.clear() // 4. If headers is a Headers object, then for each header in its header // list, append header’s name/header’s value to this’s headers. if (headers instanceof HeadersList) { for (const { name, value } of headers.rawValues()) { headersList.append(name, value, false) } // Note: Copy the `set-cookie` meta-data. headersList.cookies = headers.cookies } else { // 5. Otherwise, fill this’s headers with headers. fillHeaders(this.#headers, headers) } } // 33. Let inputBody be input’s request’s body if input is a Request // object; otherwise null. const inputBody = webidl.is.Request(input) ? input.#state.body : null // 34. If either init["body"] exists and is non-null or inputBody is // non-null, and request’s method is `GET` or `HEAD`, then throw a // TypeError. if ( (init.body != null || inputBody != null) && (request.method === 'GET' || request.method === 'HEAD') ) { throw new TypeError('Request with GET/HEAD method cannot have body.') } // 35. Let initBody be null. let initBody = null // 36. If init["body"] exists and is non-null, then: if (init.body != null) { // 1. Let Content-Type be null. // 2. Set initBody and Content-Type to the result of extracting // init["body"], with keepalive set to request’s keepalive. const [extractedBody, contentType] = extractBody( init.body, request.keepalive ) initBody = extractedBody // 3, If Content-Type is non-null and this’s headers’s header list does // not contain `Content-Type`, then append `Content-Type`/Content-Type to // this’s headers. if (contentType && !getHeadersList(this.#headers).contains('content-type', true)) { this.#headers.append('content-type', contentType, true) } } // 37. Let inputOrInitBody be initBody if it is non-null; otherwise // inputBody. const inputOrInitBody = initBody ?? inputBody // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is // null, then: if (inputOrInitBody != null && inputOrInitBody.source == null) { // 1. If initBody is non-null and init["duplex"] does not exist, // then throw a TypeError. if (initBody != null && init.duplex == null) { throw new TypeError('RequestInit: duplex option is required when sending a body.') } // 2. If this’s request’s mode is neither "same-origin" nor "cors", // then throw a TypeError. if (request.mode !== 'same-origin' && request.mode !== 'cors') { throw new TypeError( 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' ) } // 3. Set this’s request’s use-CORS-preflight flag. request.useCORSPreflightFlag = true } // 39. Let finalBody be inputOrInitBody. let finalBody = inputOrInitBody // 40. If initBody is null and inputBody is non-null, then: if (initBody == null && inputBody != null) { // 1. If input is unusable, then throw a TypeError. if (bodyUnusable(input.#state)) { throw new TypeError( 'Cannot construct a Request with a Request object that has already been used.' ) } // 2. Set finalBody to the result of creating a proxy for inputBody. // https://streams.spec.whatwg.org/#readablestream-create-a-proxy const identityTransform = new TransformStream() inputBody.stream.pipeThrough(identityTransform) finalBody = { source: inputBody.source, length: inputBody.length, stream: identityTransform.readable } } // 41. Set this’s request’s body to finalBody. this.#state.body = finalBody } // Returns request’s HTTP method, which is "GET" by default. get method () { webidl.brandCheck(this, Request) // The method getter steps are to return this’s request’s method. return this.#state.method } // Returns the URL of request as a string. get url () { webidl.brandCheck(this, Request) // The url getter steps are to return this’s request’s URL, serialized. return URLSerializer(this.#state.url) } // Returns a Headers object consisting of the headers associated with request. // Note that headers added in the network layer by the user agent will not // be accounted for in this object, e.g., the "Host" header. get headers () { webidl.brandCheck(this, Request) // The headers getter steps are to return this’s headers. return this.#headers } // Returns the kind of resource requested by request, e.g., "document" // or "script". get destination () { webidl.brandCheck(this, Request) // The destination getter are to return this’s request’s destination. return this.#state.destination } // Returns the referrer of request. Its value can be a same-origin URL if // explicitly set in init, the empty string to indicate no referrer, and // "about:client" when defaulting to the global’s default. This is used // during fetching to determine the value of the `Referer` header of the // request being made. get referrer () { webidl.brandCheck(this, Request) // 1. If this’s request’s referrer is "no-referrer", then return the // empty string. if (this.#state.referrer === 'no-referrer') { return '' } // 2. If this’s request’s referrer is "client", then return // "about:client". if (this.#state.referrer === 'client') { return 'about:client' } // Return this’s request’s referrer, serialized. return this.#state.referrer.toString() } // Returns the referrer policy associated with request. // This is used during fetching to compute the value of the request’s // referrer. get referrerPolicy () { webidl.brandCheck(this, Request) // The referrerPolicy getter steps are to return this’s request’s referrer policy. return this.#state.referrerPolicy } // Returns the mode associated with request, which is a string indicating // whether the request will use CORS, or will be restricted to same-origin // URLs. get mode () { webidl.brandCheck(this, Request) // The mode getter steps are to return this’s request’s mode. return this.#state.mode } // Returns the credentials mode associated with request, // which is a string indicating whether credentials will be sent with the // request always, never, or only when sent to a same-origin URL. get credentials () { webidl.brandCheck(this, Request) // The credentials getter steps are to return this’s request’s credentials mode. return this.#state.credentials } // Returns the cache mode associated with request, // which is a string indicating how the request will // interact with the browser’s cache when fetching. get cache () { webidl.brandCheck(this, Request) // The cache getter steps are to return this’s request’s cache mode. return this.#state.cache } // Returns the redirect mode associated with request, // which is a string indicating how redirects for the // request will be handled during fetching. A request // will follow redirects by default. get redirect () { webidl.brandCheck(this, Request) // The redirect getter steps are to return this’s request’s redirect mode. return this.#state.redirect } // Returns request’s subresource integrity metadata, which is a // cryptographic hash of the resource being fetched. Its value // consists of multiple hashes separated by whitespace. [SRI] get integrity () { webidl.brandCheck(this, Request) // The integrity getter steps are to return this’s request’s integrity // metadata. return this.#state.integrity } // Returns a boolean indicating whether or not request can outlive the // global in which it was created. get keepalive () { webidl.brandCheck(this, Request) // The keepalive getter steps are to return this’s request’s keepalive. return this.#state.keepalive } // Returns a boolean indicating whether or not request is for a reload // navigation. get isReloadNavigation () { webidl.brandCheck(this, Request) // The isReloadNavigation getter steps are to return true if this’s // request’s reload-navigation flag is set; otherwise false. return this.#state.reloadNavigation } // Returns a boolean indicating whether or not request is for a history // navigation (a.k.a. back-forward navigation). get isHistoryNavigation () { webidl.brandCheck(this, Request) // The isHistoryNavigation getter steps are to return true if this’s request’s // history-navigation flag is set; otherwise false. return this.#state.historyNavigation } // Returns the signal associated with request, which is an AbortSignal // object indicating whether or not request has been aborted, and its // abort event handler. get signal () { webidl.brandCheck(this, Request) // The signal getter steps are to return this’s signal. return this.#signal } get body () { webidl.brandCheck(this, Request) return this.#state.body ? this.#state.body.stream : null } get bodyUsed () { webidl.brandCheck(this, Request) return !!this.#state.body && util.isDisturbed(this.#state.body.stream) } get duplex () { webidl.brandCheck(this, Request) return 'half' } // Returns a clone of request. clone () { webidl.brandCheck(this, Request) // 1. If this is unusable, then throw a TypeError. if (bodyUnusable(this.#state)) { throw new TypeError('unusable') } // 2. Let clonedRequest be the result of cloning this’s request. const clonedRequest = cloneRequest(this.#state) // 3. Let clonedRequestObject be the result of creating a Request object, // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. // 4. Make clonedRequestObject’s signal follow this’s signal. const ac = new AbortController() if (this.signal.aborted) { ac.abort(this.signal.reason) } else { let list = dependentControllerMap.get(this.signal) if (list === undefined) { list = new Set() dependentControllerMap.set(this.signal, list) } const acRef = new WeakRef(ac) list.add(acRef) util.addAbortListener( ac.signal, buildAbort(acRef) ) } // 4. Return clonedRequestObject. return fromInnerRequest(clonedRequest, this.#dispatcher, ac.signal, getHeadersGuard(this.#headers)) } [nodeUtil.inspect.custom] (depth, options) { if (options.depth === null) { options.depth = 2 } options.colors ??= true const properties = { method: this.method, url: this.url, headers: this.headers, destination: this.destination, referrer: this.referrer, referrerPolicy: this.referrerPolicy, mode: this.mode, credentials: this.credentials, cache: this.cache, redirect: this.redirect, integrity: this.integrity, keepalive: this.keepalive, isReloadNavigation: this.isReloadNavigation, isHistoryNavigation: this.isHistoryNavigation, signal: this.signal } return `Request ${nodeUtil.formatWithOptions(options, properties)}` } /** * @param {Request} request * @param {AbortSignal} newSignal */ static setRequestSignal (request, newSignal) { request.#signal = newSignal return request } /** * @param {Request} request */ static getRequestDispatcher (request) { return request.#dispatcher } /** * @param {Request} request * @param {import('../../dispatcher/dispatcher')} newDispatcher */ static setRequestDispatcher (request, newDispatcher) { request.#dispatcher = newDispatcher } /** * @param {Request} request * @param {Headers} newHeaders */ static setRequestHeaders (request, newHeaders) { request.#headers = newHeaders } /** * @param {Request} request */ static getRequestState (request) { return request.#state } /** * @param {Request} request * @param {any} newState */ static setRequestState (request, newState) { request.#state = newState } } const { setRequestSignal, getRequestDispatcher, setRequestDispatcher, setRequestHeaders, getRequestState, setRequestState } = Request Reflect.deleteProperty(Request, 'setRequestSignal') Reflect.deleteProperty(Request, 'getRequestDispatcher') Reflect.deleteProperty(Request, 'setRequestDispatcher') Reflect.deleteProperty(Request, 'setRequestHeaders') Reflect.deleteProperty(Request, 'getRequestState') Reflect.deleteProperty(Request, 'setRequestState') mixinBody(Request, getRequestState) // https://fetch.spec.whatwg.org/#requests function makeRequest (init) { return { method: init.method ?? 'GET', localURLsOnly: init.localURLsOnly ?? false, unsafeRequest: init.unsafeRequest ?? false, body: init.body ?? null, client: init.client ?? null, reservedClient: init.reservedClient ?? null, replacesClientId: init.replacesClientId ?? '', window: init.window ?? 'client', keepalive: init.keepalive ?? false, serviceWorkers: init.serviceWorkers ?? 'all', initiator: init.initiator ?? '', destination: init.destination ?? '', priority: init.priority ?? null, origin: init.origin ?? 'client', policyContainer: init.policyContainer ?? 'client', referrer: init.referrer ?? 'client', referrerPolicy: init.referrerPolicy ?? '', mode: init.mode ?? 'no-cors', useCORSPreflightFlag: init.useCORSPreflightFlag ?? false, credentials: init.credentials ?? 'same-origin', useCredentials: init.useCredentials ?? false, cache: init.cache ?? 'default', redirect: init.redirect ?? 'follow', integrity: init.integrity ?? '', cryptoGraphicsNonceMetadata: init.cryptoGraphicsNonceMetadata ?? '', parserMetadata: init.parserMetadata ?? '', reloadNavigation: init.reloadNavigation ?? false, historyNavigation: init.historyNavigation ?? false, userActivation: init.userActivation ?? false, taintedOrigin: init.taintedOrigin ?? false, redirectCount: init.redirectCount ?? 0, responseTainting: init.responseTainting ?? 'basic', preventNoCacheCacheControlHeaderModification: init.preventNoCacheCacheControlHeaderModification ?? false, done: init.done ?? false, timingAllowFailed: init.timingAllowFailed ?? false, urlList: init.urlList, url: init.urlList[0], headersList: init.headersList ? new HeadersList(init.headersList) : new HeadersList() } } // https://fetch.spec.whatwg.org/#concept-request-clone function cloneRequest (request) { // To clone a request request, run these steps: // 1. Let newRequest be a copy of request, except for its body. const newRequest = makeRequest({ ...request, body: null }) // 2. If request’s body is non-null, set newRequest’s body to the // result of cloning request’s body. if (request.body != null) { newRequest.body = cloneBody(request.body) } // 3. Return newRequest. return newRequest } /** * @see https://fetch.spec.whatwg.org/#request-create * @param {any} innerRequest * @param {import('../../dispatcher/agent')} dispatcher * @param {AbortSignal} signal * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard * @returns {Request} */ function fromInnerRequest (innerRequest, dispatcher, signal, guard) { const request = new Request(kConstruct) setRequestState(request, innerRequest) setRequestDispatcher(request, dispatcher) setRequestSignal(request, signal) const headers = new Headers(kConstruct) setRequestHeaders(request, headers) setHeadersList(headers, innerRequest.headersList) setHeadersGuard(headers, guard) return request } Object.defineProperties(Request.prototype, { method: kEnumerableProperty, url: kEnumerableProperty, headers: kEnumerableProperty, redirect: kEnumerableProperty, clone: kEnumerableProperty, signal: kEnumerableProperty, duplex: kEnumerableProperty, destination: kEnumerableProperty, body: kEnumerableProperty, bodyUsed: kEnumerableProperty, isHistoryNavigation: kEnumerableProperty, isReloadNavigation: kEnumerableProperty, keepalive: kEnumerableProperty, integrity: kEnumerableProperty, cache: kEnumerableProperty, credentials: kEnumerableProperty, attribute: kEnumerableProperty, referrerPolicy: kEnumerableProperty, referrer: kEnumerableProperty, mode: kEnumerableProperty, [Symbol.toStringTag]: { value: 'Request', configurable: true } }) webidl.is.Request = webidl.util.MakeTypeAssertion(Request) /** * @param {*} V * @returns {import('../../../types/fetch').Request|string} * * @see https://fetch.spec.whatwg.org/#requestinfo */ webidl.converters.RequestInfo = function (V) { if (typeof V === 'string') { return webidl.converters.USVString(V) } if (webidl.is.Request(V)) { return V } return webidl.converters.USVString(V) } /** * @param {*} V * @returns {import('../../../types/fetch').RequestInit} * @see https://fetch.spec.whatwg.org/#requestinit */ webidl.converters.RequestInit = webidl.dictionaryConverter([ { key: 'method', converter: webidl.converters.ByteString }, { key: 'headers', converter: webidl.converters.HeadersInit }, { key: 'body', converter: webidl.nullableConverter( webidl.converters.BodyInit ) }, { key: 'referrer', converter: webidl.converters.USVString }, { key: 'referrerPolicy', converter: webidl.converters.DOMString, // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy allowedValues: referrerPolicy }, { key: 'mode', converter: webidl.converters.DOMString, // https://fetch.spec.whatwg.org/#concept-request-mode allowedValues: requestMode }, { key: 'credentials', converter: webidl.converters.DOMString, // https://fetch.spec.whatwg.org/#requestcredentials allowedValues: requestCredentials }, { key: 'cache', converter: webidl.converters.DOMString, // https://fetch.spec.whatwg.org/#requestcache allowedValues: requestCache }, { key: 'redirect', converter: webidl.converters.DOMString, // https://fetch.spec.whatwg.org/#requestredirect allowedValues: requestRedirect }, { key: 'integrity', converter: webidl.converters.DOMString }, { key: 'keepalive', converter: webidl.converters.boolean }, { key: 'signal', converter: webidl.nullableConverter( (signal) => webidl.converters.AbortSignal( signal, 'RequestInit', 'signal' ) ) }, { key: 'window', converter: webidl.converters.any }, { key: 'duplex', converter: webidl.converters.DOMString, allowedValues: requestDuplex }, { key: 'dispatcher', // undici specific option converter: webidl.converters.any } ]) module.exports = { Request, makeRequest, fromInnerRequest, cloneRequest, getRequestDispatcher, getRequestState } /***/ }), /***/ 46632: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Headers, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = __nccwpck_require__(289) const { extractBody, cloneBody, mixinBody, streamRegistry, bodyUnusable } = __nccwpck_require__(27679) const util = __nccwpck_require__(46425) const nodeUtil = __nccwpck_require__(57975) const { kEnumerableProperty } = util const { isValidReasonPhrase, isCancelled, isAborted, serializeJavascriptValueToJSONString, isErrorLike, isomorphicEncode, environmentSettingsObject: relevantRealm } = __nccwpck_require__(58799) const { redirectStatusSet, nullBodyStatus } = __nccwpck_require__(10546) const { webidl } = __nccwpck_require__(16480) const { URLSerializer } = __nccwpck_require__(38675) const { kConstruct } = __nccwpck_require__(83112) const assert = __nccwpck_require__(34589) const { types } = __nccwpck_require__(57975) const textEncoder = new TextEncoder('utf-8') // https://fetch.spec.whatwg.org/#response-class class Response { /** @type {Headers} */ #headers #state // Creates network error Response. static error () { // The static error() method steps are to return the result of creating a // Response object, given a new network error, "immutable", and this’s // relevant Realm. const responseObject = fromInnerResponse(makeNetworkError(), 'immutable') return responseObject } // https://fetch.spec.whatwg.org/#dom-response-json static json (data, init = undefined) { webidl.argumentLengthCheck(arguments, 1, 'Response.json') if (init !== null) { init = webidl.converters.ResponseInit(init) } // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. const bytes = textEncoder.encode( serializeJavascriptValueToJSONString(data) ) // 2. Let body be the result of extracting bytes. const body = extractBody(bytes) // 3. Let responseObject be the result of creating a Response object, given a new response, // "response", and this’s relevant Realm. const responseObject = fromInnerResponse(makeResponse({}), 'response') // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) // 5. Return responseObject. return responseObject } // Creates a redirect Response that redirects to url with status status. static redirect (url, status = 302) { webidl.argumentLengthCheck(arguments, 1, 'Response.redirect') url = webidl.converters.USVString(url) status = webidl.converters['unsigned short'](status) // 1. Let parsedURL be the result of parsing url with current settings // object’s API base URL. // 2. If parsedURL is failure, then throw a TypeError. // TODO: base-URL? let parsedURL try { parsedURL = new URL(url, relevantRealm.settingsObject.baseUrl) } catch (err) { throw new TypeError(`Failed to parse URL from ${url}`, { cause: err }) } // 3. If status is not a redirect status, then throw a RangeError. if (!redirectStatusSet.has(status)) { throw new RangeError(`Invalid status code ${status}`) } // 4. Let responseObject be the result of creating a Response object, // given a new response, "immutable", and this’s relevant Realm. const responseObject = fromInnerResponse(makeResponse({}), 'immutable') // 5. Set responseObject’s response’s status to status. responseObject.#state.status = status // 6. Let value be parsedURL, serialized and isomorphic encoded. const value = isomorphicEncode(URLSerializer(parsedURL)) // 7. Append `Location`/value to responseObject’s response’s header list. responseObject.#state.headersList.append('location', value, true) // 8. Return responseObject. return responseObject } // https://fetch.spec.whatwg.org/#dom-response constructor (body = null, init = undefined) { webidl.util.markAsUncloneable(this) if (body === kConstruct) { return } if (body !== null) { body = webidl.converters.BodyInit(body) } init = webidl.converters.ResponseInit(init) // 1. Set this’s response to a new response. this.#state = makeResponse({}) // 2. Set this’s headers to a new Headers object with this’s relevant // Realm, whose header list is this’s response’s header list and guard // is "response". this.#headers = new Headers(kConstruct) setHeadersGuard(this.#headers, 'response') setHeadersList(this.#headers, this.#state.headersList) // 3. Let bodyWithType be null. let bodyWithType = null // 4. If body is non-null, then set bodyWithType to the result of extracting body. if (body != null) { const [extractedBody, type] = extractBody(body) bodyWithType = { body: extractedBody, type } } // 5. Perform initialize a response given this, init, and bodyWithType. initializeResponse(this, init, bodyWithType) } // Returns response’s type, e.g., "cors". get type () { webidl.brandCheck(this, Response) // The type getter steps are to return this’s response’s type. return this.#state.type } // Returns response’s URL, if it has one; otherwise the empty string. get url () { webidl.brandCheck(this, Response) const urlList = this.#state.urlList // The url getter steps are to return the empty string if this’s // response’s URL is null; otherwise this’s response’s URL, // serialized with exclude fragment set to true. const url = urlList[urlList.length - 1] ?? null if (url === null) { return '' } return URLSerializer(url, true) } // Returns whether response was obtained through a redirect. get redirected () { webidl.brandCheck(this, Response) // The redirected getter steps are to return true if this’s response’s URL // list has more than one item; otherwise false. return this.#state.urlList.length > 1 } // Returns response’s status. get status () { webidl.brandCheck(this, Response) // The status getter steps are to return this’s response’s status. return this.#state.status } // Returns whether response’s status is an ok status. get ok () { webidl.brandCheck(this, Response) // The ok getter steps are to return true if this’s response’s status is an // ok status; otherwise false. return this.#state.status >= 200 && this.#state.status <= 299 } // Returns response’s status message. get statusText () { webidl.brandCheck(this, Response) // The statusText getter steps are to return this’s response’s status // message. return this.#state.statusText } // Returns response’s headers as Headers. get headers () { webidl.brandCheck(this, Response) // The headers getter steps are to return this’s headers. return this.#headers } get body () { webidl.brandCheck(this, Response) return this.#state.body ? this.#state.body.stream : null } get bodyUsed () { webidl.brandCheck(this, Response) return !!this.#state.body && util.isDisturbed(this.#state.body.stream) } // Returns a clone of response. clone () { webidl.brandCheck(this, Response) // 1. If this is unusable, then throw a TypeError. if (bodyUnusable(this.#state)) { throw webidl.errors.exception({ header: 'Response.clone', message: 'Body has already been consumed.' }) } // 2. Let clonedResponse be the result of cloning this’s response. const clonedResponse = cloneResponse(this.#state) // 3. Return the result of creating a Response object, given // clonedResponse, this’s headers’s guard, and this’s relevant Realm. return fromInnerResponse(clonedResponse, getHeadersGuard(this.#headers)) } [nodeUtil.inspect.custom] (depth, options) { if (options.depth === null) { options.depth = 2 } options.colors ??= true const properties = { status: this.status, statusText: this.statusText, headers: this.headers, body: this.body, bodyUsed: this.bodyUsed, ok: this.ok, redirected: this.redirected, type: this.type, url: this.url } return `Response ${nodeUtil.formatWithOptions(options, properties)}` } /** * @param {Response} response */ static getResponseHeaders (response) { return response.#headers } /** * @param {Response} response * @param {Headers} newHeaders */ static setResponseHeaders (response, newHeaders) { response.#headers = newHeaders } /** * @param {Response} response */ static getResponseState (response) { return response.#state } /** * @param {Response} response * @param {any} newState */ static setResponseState (response, newState) { response.#state = newState } } const { getResponseHeaders, setResponseHeaders, getResponseState, setResponseState } = Response Reflect.deleteProperty(Response, 'getResponseHeaders') Reflect.deleteProperty(Response, 'setResponseHeaders') Reflect.deleteProperty(Response, 'getResponseState') Reflect.deleteProperty(Response, 'setResponseState') mixinBody(Response, getResponseState) Object.defineProperties(Response.prototype, { type: kEnumerableProperty, url: kEnumerableProperty, status: kEnumerableProperty, ok: kEnumerableProperty, redirected: kEnumerableProperty, statusText: kEnumerableProperty, headers: kEnumerableProperty, clone: kEnumerableProperty, body: kEnumerableProperty, bodyUsed: kEnumerableProperty, [Symbol.toStringTag]: { value: 'Response', configurable: true } }) Object.defineProperties(Response, { json: kEnumerableProperty, redirect: kEnumerableProperty, error: kEnumerableProperty }) // https://fetch.spec.whatwg.org/#concept-response-clone function cloneResponse (response) { // To clone a response response, run these steps: // 1. If response is a filtered response, then return a new identical // filtered response whose internal response is a clone of response’s // internal response. if (response.internalResponse) { return filterResponse( cloneResponse(response.internalResponse), response.type ) } // 2. Let newResponse be a copy of response, except for its body. const newResponse = makeResponse({ ...response, body: null }) // 3. If response’s body is non-null, then set newResponse’s body to the // result of cloning response’s body. if (response.body != null) { newResponse.body = cloneBody(response.body) streamRegistry.register(newResponse, new WeakRef(response.body.stream)) } // 4. Return newResponse. return newResponse } function makeResponse (init) { return { aborted: false, rangeRequested: false, timingAllowPassed: false, requestIncludesCredentials: false, type: 'default', status: 200, timingInfo: null, cacheState: '', statusText: '', ...init, headersList: init?.headersList ? new HeadersList(init?.headersList) : new HeadersList(), urlList: init?.urlList ? [...init.urlList] : [] } } function makeNetworkError (reason) { const isError = isErrorLike(reason) return makeResponse({ type: 'error', status: 0, error: isError ? reason : new Error(reason ? String(reason) : reason), aborted: reason && reason.name === 'AbortError' }) } // @see https://fetch.spec.whatwg.org/#concept-network-error function isNetworkError (response) { return ( // A network error is a response whose type is "error", response.type === 'error' && // status is 0 response.status === 0 ) } function makeFilteredResponse (response, state) { state = { internalResponse: response, ...state } return new Proxy(response, { get (target, p) { return p in state ? state[p] : target[p] }, set (target, p, value) { assert(!(p in state)) target[p] = value return true } }) } // https://fetch.spec.whatwg.org/#concept-filtered-response function filterResponse (response, type) { // Set response to the following filtered response with response as its // internal response, depending on request’s response tainting: if (type === 'basic') { // A basic filtered response is a filtered response whose type is "basic" // and header list excludes any headers in internal response’s header list // whose name is a forbidden response-header name. // Note: undici does not implement forbidden response-header names return makeFilteredResponse(response, { type: 'basic', headersList: response.headersList }) } else if (type === 'cors') { // A CORS filtered response is a filtered response whose type is "cors" // and header list excludes any headers in internal response’s header // list whose name is not a CORS-safelisted response-header name, given // internal response’s CORS-exposed header-name list. // Note: undici does not implement CORS-safelisted response-header names return makeFilteredResponse(response, { type: 'cors', headersList: response.headersList }) } else if (type === 'opaque') { // An opaque filtered response is a filtered response whose type is // "opaque", URL list is the empty list, status is 0, status message // is the empty byte sequence, header list is empty, and body is null. return makeFilteredResponse(response, { type: 'opaque', urlList: Object.freeze([]), status: 0, statusText: '', body: null }) } else if (type === 'opaqueredirect') { // An opaque-redirect filtered response is a filtered response whose type // is "opaqueredirect", status is 0, status message is the empty byte // sequence, header list is empty, and body is null. return makeFilteredResponse(response, { type: 'opaqueredirect', status: 0, statusText: '', headersList: [], body: null }) } else { assert(false) } } // https://fetch.spec.whatwg.org/#appropriate-network-error function makeAppropriateNetworkError (fetchParams, err = null) { // 1. Assert: fetchParams is canceled. assert(isCancelled(fetchParams)) // 2. Return an aborted network error if fetchParams is aborted; // otherwise return a network error. return isAborted(fetchParams) ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err })) : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err })) } // https://whatpr.org/fetch/1392.html#initialize-a-response function initializeResponse (response, init, body) { // 1. If init["status"] is not in the range 200 to 599, inclusive, then // throw a RangeError. if (init.status !== null && (init.status < 200 || init.status > 599)) { throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.') } // 2. If init["statusText"] does not match the reason-phrase token production, // then throw a TypeError. if ('statusText' in init && init.statusText != null) { // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2: // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) if (!isValidReasonPhrase(String(init.statusText))) { throw new TypeError('Invalid statusText') } } // 3. Set response’s response’s status to init["status"]. if ('status' in init && init.status != null) { getResponseState(response).status = init.status } // 4. Set response’s response’s status message to init["statusText"]. if ('statusText' in init && init.statusText != null) { getResponseState(response).statusText = init.statusText } // 5. If init["headers"] exists, then fill response’s headers with init["headers"]. if ('headers' in init && init.headers != null) { fill(getResponseHeaders(response), init.headers) } // 6. If body was given, then: if (body) { // 1. If response's status is a null body status, then throw a TypeError. if (nullBodyStatus.includes(response.status)) { throw webidl.errors.exception({ header: 'Response constructor', message: `Invalid response status code ${response.status}` }) } // 2. Set response's body to body's body. getResponseState(response).body = body.body // 3. If body's type is non-null and response's header list does not contain // `Content-Type`, then append (`Content-Type`, body's type) to response's header list. if (body.type != null && !getResponseState(response).headersList.contains('content-type', true)) { getResponseState(response).headersList.append('content-type', body.type, true) } } } /** * @see https://fetch.spec.whatwg.org/#response-create * @param {any} innerResponse * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard * @returns {Response} */ function fromInnerResponse (innerResponse, guard) { const response = new Response(kConstruct) setResponseState(response, innerResponse) const headers = new Headers(kConstruct) setResponseHeaders(response, headers) setHeadersList(headers, innerResponse.headersList) setHeadersGuard(headers, guard) if (innerResponse.body?.stream) { // If the target (response) is reclaimed, the cleanup callback may be called at some point with // the held value provided for it (innerResponse.body.stream). The held value can be any value: // a primitive or an object, even undefined. If the held value is an object, the registry keeps // a strong reference to it (so it can pass it to the cleanup callback later). Reworded from // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry streamRegistry.register(response, new WeakRef(innerResponse.body.stream)) } return response } // https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit webidl.converters.XMLHttpRequestBodyInit = function (V, prefix, name) { if (typeof V === 'string') { return webidl.converters.USVString(V, prefix, name) } if (webidl.is.Blob(V)) { return V } if (ArrayBuffer.isView(V) || types.isArrayBuffer(V)) { return V } if (webidl.is.FormData(V)) { return V } if (webidl.is.URLSearchParams(V)) { return V } return webidl.converters.DOMString(V, prefix, name) } // https://fetch.spec.whatwg.org/#bodyinit webidl.converters.BodyInit = function (V, prefix, argument) { if (webidl.is.ReadableStream(V)) { return V } // Note: the spec doesn't include async iterables, // this is an undici extension. if (V?.[Symbol.asyncIterator]) { return V } return webidl.converters.XMLHttpRequestBodyInit(V, prefix, argument) } webidl.converters.ResponseInit = webidl.dictionaryConverter([ { key: 'status', converter: webidl.converters['unsigned short'], defaultValue: () => 200 }, { key: 'statusText', converter: webidl.converters.ByteString, defaultValue: () => '' }, { key: 'headers', converter: webidl.converters.HeadersInit } ]) webidl.is.Response = webidl.util.MakeTypeAssertion(Response) module.exports = { isNetworkError, makeNetworkError, makeResponse, makeAppropriateNetworkError, filterResponse, Response, cloneResponse, fromInnerResponse, getResponseState } /***/ }), /***/ 58799: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Transform } = __nccwpck_require__(57075) const zlib = __nccwpck_require__(38522) const { redirectStatusSet, referrerPolicyTokens, badPortsSet } = __nccwpck_require__(10546) const { getGlobalOrigin } = __nccwpck_require__(53072) const { collectASequenceOfCodePoints, collectAnHTTPQuotedString, removeChars, parseMIMEType } = __nccwpck_require__(38675) const { performance } = __nccwpck_require__(643) const { ReadableStreamFrom, isValidHTTPToken, normalizedMethodRecordsBase } = __nccwpck_require__(46425) const assert = __nccwpck_require__(34589) const { isUint8Array } = __nccwpck_require__(73429) const { webidl } = __nccwpck_require__(16480) let supportedHashes = [] // https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable /** @type {import('crypto')} */ let crypto try { crypto = __nccwpck_require__(77598) const possibleRelevantHashes = ['sha256', 'sha384', 'sha512'] supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash)) /* c8 ignore next 3 */ } catch { } function responseURL (response) { // https://fetch.spec.whatwg.org/#responses // A response has an associated URL. It is a pointer to the last URL // in response’s URL list and null if response’s URL list is empty. const urlList = response.urlList const length = urlList.length return length === 0 ? null : urlList[length - 1].toString() } // https://fetch.spec.whatwg.org/#concept-response-location-url function responseLocationURL (response, requestFragment) { // 1. If response’s status is not a redirect status, then return null. if (!redirectStatusSet.has(response.status)) { return null } // 2. Let location be the result of extracting header list values given // `Location` and response’s header list. let location = response.headersList.get('location', true) // 3. If location is a header value, then set location to the result of // parsing location with response’s URL. if (location !== null && isValidHeaderValue(location)) { if (!isValidEncodedURL(location)) { // Some websites respond location header in UTF-8 form without encoding them as ASCII // and major browsers redirect them to correctly UTF-8 encoded addresses. // Here, we handle that behavior in the same way. location = normalizeBinaryStringToUtf8(location) } location = new URL(location, responseURL(response)) } // 4. If location is a URL whose fragment is null, then set location’s // fragment to requestFragment. if (location && !location.hash) { location.hash = requestFragment } // 5. Return location. return location } /** * @see https://www.rfc-editor.org/rfc/rfc1738#section-2.2 * @param {string} url * @returns {boolean} */ function isValidEncodedURL (url) { for (let i = 0; i < url.length; ++i) { const code = url.charCodeAt(i) if ( code > 0x7E || // Non-US-ASCII + DEL code < 0x20 // Control characters NUL - US ) { return false } } return true } /** * If string contains non-ASCII characters, assumes it's UTF-8 encoded and decodes it. * Since UTF-8 is a superset of ASCII, this will work for ASCII strings as well. * @param {string} value * @returns {string} */ function normalizeBinaryStringToUtf8 (value) { return Buffer.from(value, 'binary').toString('utf8') } /** @returns {URL} */ function requestCurrentURL (request) { return request.urlList[request.urlList.length - 1] } function requestBadPort (request) { // 1. Let url be request’s current URL. const url = requestCurrentURL(request) // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port, // then return blocked. if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { return 'blocked' } // 3. Return allowed. return 'allowed' } function isErrorLike (object) { return object instanceof Error || ( object?.constructor?.name === 'Error' || object?.constructor?.name === 'DOMException' ) } // Check whether |statusText| is a ByteString and // matches the Reason-Phrase token production. // RFC 2616: https://tools.ietf.org/html/rfc2616 // RFC 7230: https://tools.ietf.org/html/rfc7230 // "reason-phrase = *( HTAB / SP / VCHAR / obs-text )" // https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116 function isValidReasonPhrase (statusText) { for (let i = 0; i < statusText.length; ++i) { const c = statusText.charCodeAt(i) if ( !( ( c === 0x09 || // HTAB (c >= 0x20 && c <= 0x7e) || // SP / VCHAR (c >= 0x80 && c <= 0xff) ) // obs-text ) ) { return false } } return true } /** * @see https://fetch.spec.whatwg.org/#header-name * @param {string} potentialValue */ const isValidHeaderName = isValidHTTPToken /** * @see https://fetch.spec.whatwg.org/#header-value * @param {string} potentialValue */ function isValidHeaderValue (potentialValue) { // - Has no leading or trailing HTTP tab or space bytes. // - Contains no 0x00 (NUL) or HTTP newline bytes. return ( potentialValue[0] === '\t' || potentialValue[0] === ' ' || potentialValue[potentialValue.length - 1] === '\t' || potentialValue[potentialValue.length - 1] === ' ' || potentialValue.includes('\n') || potentialValue.includes('\r') || potentialValue.includes('\0') ) === false } /** * Parse a referrer policy from a Referrer-Policy header * @see https://w3c.github.io/webappsec-referrer-policy/#parse-referrer-policy-from-header */ function parseReferrerPolicy (actualResponse) { // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list. const policyHeader = (actualResponse.headersList.get('referrer-policy', true) ?? '').split(',') // 2. Let policy be the empty string. let policy = '' // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token. // Note: As the referrer-policy can contain multiple policies // separated by comma, we need to loop through all of them // and pick the first valid one. // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy if (policyHeader.length) { // The right-most policy takes precedence. // The left-most policy is the fallback. for (let i = policyHeader.length; i !== 0; i--) { const token = policyHeader[i - 1].trim() if (referrerPolicyTokens.has(token)) { policy = token break } } } // 4. Return policy. return policy } /** * Given a request request and a response actualResponse, this algorithm * updates request’s referrer policy according to the Referrer-Policy * header (if any) in actualResponse. * @see https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect * @param {import('./request').Request} request * @param {import('./response').Response} actualResponse */ function setRequestReferrerPolicyOnRedirect (request, actualResponse) { // 1. Let policy be the result of executing § 8.1 Parse a referrer policy // from a Referrer-Policy header on actualResponse. const policy = parseReferrerPolicy(actualResponse) // 2. If policy is not the empty string, then set request’s referrer policy to policy. if (policy !== '') { request.referrerPolicy = policy } } // https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check function crossOriginResourcePolicyCheck () { // TODO return 'allowed' } // https://fetch.spec.whatwg.org/#concept-cors-check function corsCheck () { // TODO return 'success' } // https://fetch.spec.whatwg.org/#concept-tao-check function TAOCheck () { // TODO return 'success' } function appendFetchMetadata (httpRequest) { // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header // TODO // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header // 1. Assert: r’s url is a potentially trustworthy URL. // TODO // 2. Let header be a Structured Header whose value is a token. let header = null // 3. Set header’s value to r’s mode. header = httpRequest.mode // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. httpRequest.headersList.set('sec-fetch-mode', header, true) // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header // TODO // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header // TODO } // https://fetch.spec.whatwg.org/#append-a-request-origin-header function appendRequestOriginHeader (request) { // 1. Let serializedOrigin be the result of byte-serializing a request origin // with request. // TODO: implement "byte-serializing a request origin" let serializedOrigin = request.origin // - "'client' is changed to an origin during fetching." // This doesn't happen in undici (in most cases) because undici, by default, // has no concept of origin. // - request.origin can also be set to request.client.origin (client being // an environment settings object), which is undefined without using // setGlobalOrigin. if (serializedOrigin === 'client' || serializedOrigin === undefined) { return } // 2. If request’s response tainting is "cors" or request’s mode is "websocket", // then append (`Origin`, serializedOrigin) to request’s header list. // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then: if (request.responseTainting === 'cors' || request.mode === 'websocket') { request.headersList.append('origin', serializedOrigin, true) } else if (request.method !== 'GET' && request.method !== 'HEAD') { // 1. Switch on request’s referrer policy: switch (request.referrerPolicy) { case 'no-referrer': // Set serializedOrigin to `null`. serializedOrigin = null break case 'no-referrer-when-downgrade': case 'strict-origin': case 'strict-origin-when-cross-origin': // If request’s origin is a tuple origin, its scheme is "https", and // request’s current URL’s scheme is not "https", then set // serializedOrigin to `null`. if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) { serializedOrigin = null } break case 'same-origin': // If request’s origin is not same origin with request’s current URL’s // origin, then set serializedOrigin to `null`. if (!sameOrigin(request, requestCurrentURL(request))) { serializedOrigin = null } break default: // Do nothing. } // 2. Append (`Origin`, serializedOrigin) to request’s header list. request.headersList.append('origin', serializedOrigin, true) } } // https://w3c.github.io/hr-time/#dfn-coarsen-time function coarsenTime (timestamp, crossOriginIsolatedCapability) { // TODO return timestamp } // https://fetch.spec.whatwg.org/#clamp-and-coarsen-connection-timing-info function clampAndCoarsenConnectionTimingInfo (connectionTimingInfo, defaultStartTime, crossOriginIsolatedCapability) { if (!connectionTimingInfo?.startTime || connectionTimingInfo.startTime < defaultStartTime) { return { domainLookupStartTime: defaultStartTime, domainLookupEndTime: defaultStartTime, connectionStartTime: defaultStartTime, connectionEndTime: defaultStartTime, secureConnectionStartTime: defaultStartTime, ALPNNegotiatedProtocol: connectionTimingInfo?.ALPNNegotiatedProtocol } } return { domainLookupStartTime: coarsenTime(connectionTimingInfo.domainLookupStartTime, crossOriginIsolatedCapability), domainLookupEndTime: coarsenTime(connectionTimingInfo.domainLookupEndTime, crossOriginIsolatedCapability), connectionStartTime: coarsenTime(connectionTimingInfo.connectionStartTime, crossOriginIsolatedCapability), connectionEndTime: coarsenTime(connectionTimingInfo.connectionEndTime, crossOriginIsolatedCapability), secureConnectionStartTime: coarsenTime(connectionTimingInfo.secureConnectionStartTime, crossOriginIsolatedCapability), ALPNNegotiatedProtocol: connectionTimingInfo.ALPNNegotiatedProtocol } } // https://w3c.github.io/hr-time/#dfn-coarsened-shared-current-time function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { return coarsenTime(performance.now(), crossOriginIsolatedCapability) } // https://fetch.spec.whatwg.org/#create-an-opaque-timing-info function createOpaqueTimingInfo (timingInfo) { return { startTime: timingInfo.startTime ?? 0, redirectStartTime: 0, redirectEndTime: 0, postRedirectStartTime: timingInfo.startTime ?? 0, finalServiceWorkerStartTime: 0, finalNetworkResponseStartTime: 0, finalNetworkRequestStartTime: 0, endTime: 0, encodedBodySize: 0, decodedBodySize: 0, finalConnectionTimingInfo: null } } // https://html.spec.whatwg.org/multipage/origin.html#policy-container function makePolicyContainer () { // Note: the fetch spec doesn't make use of embedder policy or CSP list return { referrerPolicy: 'strict-origin-when-cross-origin' } } // https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container function clonePolicyContainer (policyContainer) { return { referrerPolicy: policyContainer.referrerPolicy } } /** * Determine request’s Referrer * * @see https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer */ function determineRequestsReferrer (request) { // Given a request request, we can determine the correct referrer information // to send by examining its referrer policy as detailed in the following // steps, which return either no referrer or a URL: // 1. Let policy be request's referrer policy. const policy = request.referrerPolicy // Note: policy cannot (shouldn't) be null or an empty string. assert(policy) // 2. Let environment be request’s client. let referrerSource = null // 3. Switch on request’s referrer: // "client" if (request.referrer === 'client') { // Note: node isn't a browser and doesn't implement document/iframes, // so we bypass this step and replace it with our own. const globalOrigin = getGlobalOrigin() if (!globalOrigin || globalOrigin.origin === 'null') { return 'no-referrer' } // Note: we need to clone it as it's mutated referrerSource = new URL(globalOrigin) // a URL } else if (webidl.is.URL(request.referrer)) { // Let referrerSource be request’s referrer. referrerSource = request.referrer } // 4. Let request’s referrerURL be the result of stripping referrerSource for // use as a referrer. let referrerURL = stripURLForReferrer(referrerSource) // 5. Let referrerOrigin be the result of stripping referrerSource for use as // a referrer, with the origin-only flag set to true. const referrerOrigin = stripURLForReferrer(referrerSource, true) // 6. If the result of serializing referrerURL is a string whose length is // greater than 4096, set referrerURL to referrerOrigin. if (referrerURL.toString().length > 4096) { referrerURL = referrerOrigin } // 7. The user agent MAY alter referrerURL or referrerOrigin at this point // to enforce arbitrary policy considerations in the interests of minimizing // data leakage. For example, the user agent could strip the URL down to an // origin, modify its host, replace it with an empty string, etc. // 8. Execute the switch statements corresponding to the value of policy: switch (policy) { case 'no-referrer': // Return no referrer return 'no-referrer' case 'origin': // Return referrerOrigin if (referrerOrigin != null) { return referrerOrigin } return stripURLForReferrer(referrerSource, true) case 'unsafe-url': // Return referrerURL. return referrerURL case 'strict-origin': { const currentURL = requestCurrentURL(request) // 1. If referrerURL is a potentially trustworthy URL and request’s // current URL is not a potentially trustworthy URL, then return no // referrer. if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { return 'no-referrer' } // 2. Return referrerOrigin return referrerOrigin } case 'strict-origin-when-cross-origin': { const currentURL = requestCurrentURL(request) // 1. If the origin of referrerURL and the origin of request’s current // URL are the same, then return referrerURL. if (sameOrigin(referrerURL, currentURL)) { return referrerURL } // 2. If referrerURL is a potentially trustworthy URL and request’s // current URL is not a potentially trustworthy URL, then return no // referrer. if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { return 'no-referrer' } // 3. Return referrerOrigin. return referrerOrigin } case 'same-origin': // 1. If the origin of referrerURL and the origin of request’s current // URL are the same, then return referrerURL. if (sameOrigin(request, referrerURL)) { return referrerURL } // 2. Return no referrer. return 'no-referrer' case 'origin-when-cross-origin': // 1. If the origin of referrerURL and the origin of request’s current // URL are the same, then return referrerURL. if (sameOrigin(request, referrerURL)) { return referrerURL } // 2. Return referrerOrigin. return referrerOrigin case 'no-referrer-when-downgrade': { const currentURL = requestCurrentURL(request) // 1. If referrerURL is a potentially trustworthy URL and request’s // current URL is not a potentially trustworthy URL, then return no // referrer. if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { return 'no-referrer' } // 2. Return referrerOrigin return referrerOrigin } } } /** * Certain portions of URLs must not be included when sending a URL as the * value of a `Referer` header: a URLs fragment, username, and password * components must be stripped from the URL before it’s sent out. This * algorithm accepts a origin-only flag, which defaults to false. If set to * true, the algorithm will additionally remove the URL’s path and query * components, leaving only the scheme, host, and port. * * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url * @param {URL} url * @param {boolean} [originOnly=false] */ function stripURLForReferrer (url, originOnly = false) { // 1. Assert: url is a URL. assert(webidl.is.URL(url)) // Note: Create a new URL instance to avoid mutating the original URL. url = new URL(url) // 2. If url’s scheme is a local scheme, then return no referrer. if (urlIsLocal(url)) { return 'no-referrer' } // 3. Set url’s username to the empty string. url.username = '' // 4. Set url’s password to the empty string. url.password = '' // 5. Set url’s fragment to null. url.hash = '' // 6. If the origin-only flag is true, then: if (originOnly === true) { // 1. Set url’s path to « the empty string ». url.pathname = '' // 2. Set url’s query to null. url.search = '' } // 7. Return url. return url } const potentialleTrustworthyIPv4RegExp = new RegExp('^(?:' + '(?:127\\.)' + '(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){2}' + '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])' + ')$') const potentialleTrustworthyIPv6RegExp = new RegExp('^(?:' + '(?:(?:0{1,4}):){7}(?:(?:0{0,3}1))|' + '(?:(?:0{1,4}):){1,6}(?::(?:0{0,3}1))|' + '(?:::(?:0{0,3}1))|' + ')$') /** * Check if host matches one of the CIDR notations 127.0.0.0/8 or ::1/128. * * @param {string} origin * @returns {boolean} */ function isOriginIPPotentiallyTrustworthy (origin) { // IPv6 if (origin.includes(':')) { // Remove brackets from IPv6 addresses if (origin[0] === '[' && origin[origin.length - 1] === ']') { origin = origin.slice(1, -1) } return potentialleTrustworthyIPv6RegExp.test(origin) } // IPv4 return potentialleTrustworthyIPv4RegExp.test(origin) } /** * A potentially trustworthy origin is one which a user agent can generally * trust as delivering data securely. * * Return value `true` means `Potentially Trustworthy`. * Return value `false` means `Not Trustworthy`. * * @see https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy * @param {string} origin * @returns {boolean} */ function isOriginPotentiallyTrustworthy (origin) { // 1. If origin is an opaque origin, return "Not Trustworthy". if (origin == null || origin === 'null') { return false } // 2. Assert: origin is a tuple origin. origin = new URL(origin) // 3. If origin’s scheme is either "https" or "wss", // return "Potentially Trustworthy". if (origin.protocol === 'https:' || origin.protocol === 'wss:') { return true } // 4. If origin’s host matches one of the CIDR notations 127.0.0.0/8 or // ::1/128 [RFC4632], return "Potentially Trustworthy". if (isOriginIPPotentiallyTrustworthy(origin.hostname)) { return true } // 5. If the user agent conforms to the name resolution rules in // [let-localhost-be-localhost] and one of the following is true: // origin’s host is "localhost" or "localhost." if (origin.hostname === 'localhost' || origin.hostname === 'localhost.') { return true } // origin’s host ends with ".localhost" or ".localhost." if (origin.hostname.endsWith('.localhost') || origin.hostname.endsWith('.localhost.')) { return true } // 6. If origin’s scheme is "file", return "Potentially Trustworthy". if (origin.protocol === 'file:') { return true } // 7. If origin’s scheme component is one which the user agent considers to // be authenticated, return "Potentially Trustworthy". // 8. If origin has been configured as a trustworthy origin, return // "Potentially Trustworthy". // 9. Return "Not Trustworthy". return false } /** * A potentially trustworthy URL is one which either inherits context from its * creator (about:blank, about:srcdoc, data) or one whose origin is a * potentially trustworthy origin. * * Return value `true` means `Potentially Trustworthy`. * Return value `false` means `Not Trustworthy`. * * @see https://www.w3.org/TR/secure-contexts/#is-url-trustworthy * @param {URL} url * @returns {boolean} */ function isURLPotentiallyTrustworthy (url) { // Given a URL record (url), the following algorithm returns "Potentially // Trustworthy" or "Not Trustworthy" as appropriate: if (!webidl.is.URL(url)) { return false } // 1. If url is "about:blank" or "about:srcdoc", // return "Potentially Trustworthy". if (url.href === 'about:blank' || url.href === 'about:srcdoc') { return true } // 2. If url’s scheme is "data", return "Potentially Trustworthy". if (url.protocol === 'data:') return true // Note: The origin of blob: URLs is the origin of the context in which they // were created. Therefore, blobs created in a trustworthy origin will // themselves be potentially trustworthy. if (url.protocol === 'blob:') return true // 3. Return the result of executing § 3.1 Is origin potentially trustworthy? // on url’s origin. return isOriginPotentiallyTrustworthy(url.origin) } /** * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist * @param {Uint8Array} bytes * @param {string} metadataList */ function bytesMatch (bytes, metadataList) { // If node is not built with OpenSSL support, we cannot check // a request's integrity, so allow it by default (the spec will // allow requests if an invalid hash is given, as precedence). /* istanbul ignore if: only if node is built with --without-ssl */ if (crypto === undefined) { return true } // 1. Let parsedMetadata be the result of parsing metadataList. const parsedMetadata = parseMetadata(metadataList) // 2. If parsedMetadata is no metadata, return true. if (parsedMetadata === 'no metadata') { return true } // 3. If response is not eligible for integrity validation, return false. // TODO // 4. If parsedMetadata is the empty set, return true. if (parsedMetadata.length === 0) { return true } // 5. Let metadata be the result of getting the strongest // metadata from parsedMetadata. const strongest = getStrongestMetadata(parsedMetadata) const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest) // 6. For each item in metadata: for (const item of metadata) { // 1. Let algorithm be the alg component of item. const algorithm = item.algo // 2. Let expectedValue be the val component of item. const expectedValue = item.hash // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e // "be liberal with padding". This is annoying, and it's not even in the spec. // 3. Let actualValue be the result of applying algorithm to bytes. let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') if (actualValue[actualValue.length - 1] === '=') { if (actualValue[actualValue.length - 2] === '=') { actualValue = actualValue.slice(0, -2) } else { actualValue = actualValue.slice(0, -1) } } // 4. If actualValue is a case-sensitive match for expectedValue, // return true. if (compareBase64Mixed(actualValue, expectedValue)) { return true } } // 7. Return false. return false } // https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options // https://www.w3.org/TR/CSP2/#source-list-syntax // https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1 const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i /** * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata * @param {string} metadata */ function parseMetadata (metadata) { // 1. Let result be the empty set. /** @type {{ algo: string, hash: string }[]} */ const result = [] // 2. Let empty be equal to true. let empty = true // 3. For each token returned by splitting metadata on spaces: for (const token of metadata.split(' ')) { // 1. Set empty to false. empty = false // 2. Parse token as a hash-with-options. const parsedToken = parseHashWithOptions.exec(token) // 3. If token does not parse, continue to the next token. if ( parsedToken === null || parsedToken.groups === undefined || parsedToken.groups.algo === undefined ) { // Note: Chromium blocks the request at this point, but Firefox // gives a warning that an invalid integrity was given. The // correct behavior is to ignore these, and subsequently not // check the integrity of the resource. continue } // 4. Let algorithm be the hash-algo component of token. const algorithm = parsedToken.groups.algo.toLowerCase() // 5. If algorithm is a hash function recognized by the user // agent, add the parsed token to result. if (supportedHashes.includes(algorithm)) { result.push(parsedToken.groups) } } // 4. Return no metadata if empty is true, otherwise return result. if (empty === true) { return 'no metadata' } return result } /** * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList */ function getStrongestMetadata (metadataList) { // Let algorithm be the algo component of the first item in metadataList. // Can be sha256 let algorithm = metadataList[0].algo // If the algorithm is sha512, then it is the strongest // and we can return immediately if (algorithm[3] === '5') { return algorithm } for (let i = 1; i < metadataList.length; ++i) { const metadata = metadataList[i] // If the algorithm is sha512, then it is the strongest // and we can break the loop immediately if (metadata.algo[3] === '5') { algorithm = 'sha512' break // If the algorithm is sha384, then a potential sha256 or sha384 is ignored } else if (algorithm[3] === '3') { continue // algorithm is sha256, check if algorithm is sha384 and if so, set it as // the strongest } else if (metadata.algo[3] === '3') { algorithm = 'sha384' } } return algorithm } function filterMetadataListByAlgorithm (metadataList, algorithm) { if (metadataList.length === 1) { return metadataList } let pos = 0 for (let i = 0; i < metadataList.length; ++i) { if (metadataList[i].algo === algorithm) { metadataList[pos++] = metadataList[i] } } metadataList.length = pos return metadataList } /** * Compares two base64 strings, allowing for base64url * in the second string. * * @param {string} actualValue always base64 * @param {string} expectedValue base64 or base64url * @returns {boolean} */ function compareBase64Mixed (actualValue, expectedValue) { if (actualValue.length !== expectedValue.length) { return false } for (let i = 0; i < actualValue.length; ++i) { if (actualValue[i] !== expectedValue[i]) { if ( (actualValue[i] === '+' && expectedValue[i] === '-') || (actualValue[i] === '/' && expectedValue[i] === '_') ) { continue } return false } } return true } // https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { // TODO } /** * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin} * @param {URL} A * @param {URL} B */ function sameOrigin (A, B) { // 1. If A and B are the same opaque origin, then return true. if (A.origin === B.origin && A.origin === 'null') { return true } // 2. If A and B are both tuple origins and their schemes, // hosts, and port are identical, then return true. if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) { return true } // 3. Return false. return false } function isAborted (fetchParams) { return fetchParams.controller.state === 'aborted' } function isCancelled (fetchParams) { return fetchParams.controller.state === 'aborted' || fetchParams.controller.state === 'terminated' } /** * @see https://fetch.spec.whatwg.org/#concept-method-normalize * @param {string} method */ function normalizeMethod (method) { return normalizedMethodRecordsBase[method.toLowerCase()] ?? method } // https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string function serializeJavascriptValueToJSONString (value) { // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »). const result = JSON.stringify(value) // 2. If result is undefined, then throw a TypeError. if (result === undefined) { throw new TypeError('Value is not JSON serializable') } // 3. Assert: result is a string. assert(typeof result === 'string') // 4. Return result. return result } // https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) /** * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object * @param {string} name name of the instance * @param {((target: any) => any)} kInternalIterator * @param {string | number} [keyIndex] * @param {string | number} [valueIndex] */ function createIterator (name, kInternalIterator, keyIndex = 0, valueIndex = 1) { class FastIterableIterator { /** @type {any} */ #target /** @type {'key' | 'value' | 'key+value'} */ #kind /** @type {number} */ #index /** * @see https://webidl.spec.whatwg.org/#dfn-default-iterator-object * @param {unknown} target * @param {'key' | 'value' | 'key+value'} kind */ constructor (target, kind) { this.#target = target this.#kind = kind this.#index = 0 } next () { // 1. Let interface be the interface for which the iterator prototype object exists. // 2. Let thisValue be the this value. // 3. Let object be ? ToObject(thisValue). // 4. If object is a platform object, then perform a security // check, passing: // 5. If object is not a default iterator object for interface, // then throw a TypeError. if (typeof this !== 'object' || this === null || !(#target in this)) { throw new TypeError( `'next' called on an object that does not implement interface ${name} Iterator.` ) } // 6. Let index be object’s index. // 7. Let kind be object’s kind. // 8. Let values be object’s target's value pairs to iterate over. const index = this.#index const values = kInternalIterator(this.#target) // 9. Let len be the length of values. const len = values.length // 10. If index is greater than or equal to len, then return // CreateIterResultObject(undefined, true). if (index >= len) { return { value: undefined, done: true } } // 11. Let pair be the entry in values at index index. const { [keyIndex]: key, [valueIndex]: value } = values[index] // 12. Set object’s index to index + 1. this.#index = index + 1 // 13. Return the iterator result for pair and kind. // https://webidl.spec.whatwg.org/#iterator-result // 1. Let result be a value determined by the value of kind: let result switch (this.#kind) { case 'key': // 1. Let idlKey be pair’s key. // 2. Let key be the result of converting idlKey to an // ECMAScript value. // 3. result is key. result = key break case 'value': // 1. Let idlValue be pair’s value. // 2. Let value be the result of converting idlValue to // an ECMAScript value. // 3. result is value. result = value break case 'key+value': // 1. Let idlKey be pair’s key. // 2. Let idlValue be pair’s value. // 3. Let key be the result of converting idlKey to an // ECMAScript value. // 4. Let value be the result of converting idlValue to // an ECMAScript value. // 5. Let array be ! ArrayCreate(2). // 6. Call ! CreateDataProperty(array, "0", key). // 7. Call ! CreateDataProperty(array, "1", value). // 8. result is array. result = [key, value] break } // 2. Return CreateIterResultObject(result, false). return { value: result, done: false } } } // https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object // @ts-ignore delete FastIterableIterator.prototype.constructor Object.setPrototypeOf(FastIterableIterator.prototype, esIteratorPrototype) Object.defineProperties(FastIterableIterator.prototype, { [Symbol.toStringTag]: { writable: false, enumerable: false, configurable: true, value: `${name} Iterator` }, next: { writable: true, enumerable: true, configurable: true } }) /** * @param {unknown} target * @param {'key' | 'value' | 'key+value'} kind * @returns {IterableIterator} */ return function (target, kind) { return new FastIterableIterator(target, kind) } } /** * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object * @param {string} name name of the instance * @param {any} object class * @param {(target: any) => any} kInternalIterator * @param {string | number} [keyIndex] * @param {string | number} [valueIndex] */ function iteratorMixin (name, object, kInternalIterator, keyIndex = 0, valueIndex = 1) { const makeIterator = createIterator(name, kInternalIterator, keyIndex, valueIndex) const properties = { keys: { writable: true, enumerable: true, configurable: true, value: function keys () { webidl.brandCheck(this, object) return makeIterator(this, 'key') } }, values: { writable: true, enumerable: true, configurable: true, value: function values () { webidl.brandCheck(this, object) return makeIterator(this, 'value') } }, entries: { writable: true, enumerable: true, configurable: true, value: function entries () { webidl.brandCheck(this, object) return makeIterator(this, 'key+value') } }, forEach: { writable: true, enumerable: true, configurable: true, value: function forEach (callbackfn, thisArg = globalThis) { webidl.brandCheck(this, object) webidl.argumentLengthCheck(arguments, 1, `${name}.forEach`) if (typeof callbackfn !== 'function') { throw new TypeError( `Failed to execute 'forEach' on '${name}': parameter 1 is not of type 'Function'.` ) } for (const { 0: key, 1: value } of makeIterator(this, 'key+value')) { callbackfn.call(thisArg, value, key, this) } } } } return Object.defineProperties(object.prototype, { ...properties, [Symbol.iterator]: { writable: true, enumerable: false, configurable: true, value: properties.entries.value } }) } /** * @param {import('./body').ExtractBodyResult} body * @param {(bytes: Uint8Array) => void} processBody * @param {(error: Error) => void} processBodyError * @returns {void} * * @see https://fetch.spec.whatwg.org/#body-fully-read */ function fullyReadBody (body, processBody, processBodyError) { // 1. If taskDestination is null, then set taskDestination to // the result of starting a new parallel queue. // 2. Let successSteps given a byte sequence bytes be to queue a // fetch task to run processBody given bytes, with taskDestination. const successSteps = processBody // 3. Let errorSteps be to queue a fetch task to run processBodyError, // with taskDestination. const errorSteps = processBodyError try { // 4. Let reader be the result of getting a reader for body’s stream. // If that threw an exception, then run errorSteps with that // exception and return. const reader = body.stream.getReader() // 5. Read all bytes from reader, given successSteps and errorSteps. readAllBytes(reader, successSteps, errorSteps) } catch (e) { errorSteps(e) } } /** * @param {ReadableStreamController} controller */ function readableStreamClose (controller) { try { controller.close() controller.byobRequest?.respond(0) } catch (err) { // TODO: add comment explaining why this error occurs. if (!err.message.includes('Controller is already closed') && !err.message.includes('ReadableStream is already closed')) { throw err } } } const invalidIsomorphicEncodeValueRegex = /[^\x00-\xFF]/ // eslint-disable-line /** * @see https://infra.spec.whatwg.org/#isomorphic-encode * @param {string} input */ function isomorphicEncode (input) { // 1. Assert: input contains no code points greater than U+00FF. assert(!invalidIsomorphicEncodeValueRegex.test(input)) // 2. Return a byte sequence whose length is equal to input’s code // point length and whose bytes have the same values as the // values of input’s code points, in the same order return input } /** * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes * @see https://streams.spec.whatwg.org/#read-loop * @param {ReadableStream>} reader * @param {(bytes: Uint8Array) => void} successSteps * @param {(error: Error) => void} failureSteps * @returns {Promise} */ async function readAllBytes (reader, successSteps, failureSteps) { try { const bytes = [] let byteLength = 0 do { const { done, value: chunk } = await reader.read() if (done) { // 1. Call successSteps with bytes. successSteps(Buffer.concat(bytes, byteLength)) return } // 1. If chunk is not a Uint8Array object, call failureSteps // with a TypeError and abort these steps. if (!isUint8Array(chunk)) { failureSteps(new TypeError('Received non-Uint8Array chunk')) return } // 2. Append the bytes represented by chunk to bytes. bytes.push(chunk) byteLength += chunk.length // 3. Read-loop given reader, bytes, successSteps, and failureSteps. } while (true) } catch (e) { // 1. Call failureSteps with e. failureSteps(e) } } /** * @see https://fetch.spec.whatwg.org/#is-local * @param {URL} url * @returns {boolean} */ function urlIsLocal (url) { assert('protocol' in url) // ensure it's a url object const protocol = url.protocol // A URL is local if its scheme is a local scheme. // A local scheme is "about", "blob", or "data". return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' } /** * @param {string|URL} url * @returns {boolean} */ function urlHasHttpsScheme (url) { return ( ( typeof url === 'string' && url[5] === ':' && url[0] === 'h' && url[1] === 't' && url[2] === 't' && url[3] === 'p' && url[4] === 's' ) || url.protocol === 'https:' ) } /** * @see https://fetch.spec.whatwg.org/#http-scheme * @param {URL} url */ function urlIsHttpHttpsScheme (url) { assert('protocol' in url) // ensure it's a url object const protocol = url.protocol return protocol === 'http:' || protocol === 'https:' } /** * @typedef {Object} RangeHeaderValue * @property {number|null} rangeStartValue * @property {number|null} rangeEndValue */ /** * @see https://fetch.spec.whatwg.org/#simple-range-header-value * @param {string} value * @param {boolean} allowWhitespace * @return {RangeHeaderValue|'failure'} */ function simpleRangeHeaderValue (value, allowWhitespace) { // 1. Let data be the isomorphic decoding of value. // Note: isomorphic decoding takes a sequence of bytes (ie. a Uint8Array) and turns it into a string, // nothing more. We obviously don't need to do that if value is a string already. const data = value // 2. If data does not start with "bytes", then return failure. if (!data.startsWith('bytes')) { return 'failure' } // 3. Let position be a position variable for data, initially pointing at the 5th code point of data. const position = { position: 5 } // 4. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, // from data given position. if (allowWhitespace) { collectASequenceOfCodePoints( (char) => char === '\t' || char === ' ', data, position ) } // 5. If the code point at position within data is not U+003D (=), then return failure. if (data.charCodeAt(position.position) !== 0x3D) { return 'failure' } // 6. Advance position by 1. position.position++ // 7. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, from // data given position. if (allowWhitespace) { collectASequenceOfCodePoints( (char) => char === '\t' || char === ' ', data, position ) } // 8. Let rangeStart be the result of collecting a sequence of code points that are ASCII digits, // from data given position. const rangeStart = collectASequenceOfCodePoints( (char) => { const code = char.charCodeAt(0) return code >= 0x30 && code <= 0x39 }, data, position ) // 9. Let rangeStartValue be rangeStart, interpreted as decimal number, if rangeStart is not the // empty string; otherwise null. const rangeStartValue = rangeStart.length ? Number(rangeStart) : null // 10. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, // from data given position. if (allowWhitespace) { collectASequenceOfCodePoints( (char) => char === '\t' || char === ' ', data, position ) } // 11. If the code point at position within data is not U+002D (-), then return failure. if (data.charCodeAt(position.position) !== 0x2D) { return 'failure' } // 12. Advance position by 1. position.position++ // 13. If allowWhitespace is true, collect a sequence of code points that are HTTP tab // or space, from data given position. // Note from Khafra: its the same step as in #8 again lol if (allowWhitespace) { collectASequenceOfCodePoints( (char) => char === '\t' || char === ' ', data, position ) } // 14. Let rangeEnd be the result of collecting a sequence of code points that are // ASCII digits, from data given position. // Note from Khafra: you wouldn't guess it, but this is also the same step as #8 const rangeEnd = collectASequenceOfCodePoints( (char) => { const code = char.charCodeAt(0) return code >= 0x30 && code <= 0x39 }, data, position ) // 15. Let rangeEndValue be rangeEnd, interpreted as decimal number, if rangeEnd // is not the empty string; otherwise null. // Note from Khafra: THE SAME STEP, AGAIN!!! // Note: why interpret as a decimal if we only collect ascii digits? const rangeEndValue = rangeEnd.length ? Number(rangeEnd) : null // 16. If position is not past the end of data, then return failure. if (position.position < data.length) { return 'failure' } // 17. If rangeEndValue and rangeStartValue are null, then return failure. if (rangeEndValue === null && rangeStartValue === null) { return 'failure' } // 18. If rangeStartValue and rangeEndValue are numbers, and rangeStartValue is // greater than rangeEndValue, then return failure. // Note: ... when can they not be numbers? if (rangeStartValue > rangeEndValue) { return 'failure' } // 19. Return (rangeStartValue, rangeEndValue). return { rangeStartValue, rangeEndValue } } /** * @see https://fetch.spec.whatwg.org/#build-a-content-range * @param {number} rangeStart * @param {number} rangeEnd * @param {number} fullLength */ function buildContentRange (rangeStart, rangeEnd, fullLength) { // 1. Let contentRange be `bytes `. let contentRange = 'bytes ' // 2. Append rangeStart, serialized and isomorphic encoded, to contentRange. contentRange += isomorphicEncode(`${rangeStart}`) // 3. Append 0x2D (-) to contentRange. contentRange += '-' // 4. Append rangeEnd, serialized and isomorphic encoded to contentRange. contentRange += isomorphicEncode(`${rangeEnd}`) // 5. Append 0x2F (/) to contentRange. contentRange += '/' // 6. Append fullLength, serialized and isomorphic encoded to contentRange. contentRange += isomorphicEncode(`${fullLength}`) // 7. Return contentRange. return contentRange } // A Stream, which pipes the response to zlib.createInflate() or // zlib.createInflateRaw() depending on the first byte of the Buffer. // If the lower byte of the first byte is 0x08, then the stream is // interpreted as a zlib stream, otherwise it's interpreted as a // raw deflate stream. class InflateStream extends Transform { #zlibOptions /** @param {zlib.ZlibOptions} [zlibOptions] */ constructor (zlibOptions) { super() this.#zlibOptions = zlibOptions } _transform (chunk, encoding, callback) { if (!this._inflateStream) { if (chunk.length === 0) { callback() return } this._inflateStream = (chunk[0] & 0x0F) === 0x08 ? zlib.createInflate(this.#zlibOptions) : zlib.createInflateRaw(this.#zlibOptions) this._inflateStream.on('data', this.push.bind(this)) this._inflateStream.on('end', () => this.push(null)) this._inflateStream.on('error', (err) => this.destroy(err)) } this._inflateStream.write(chunk, encoding, callback) } _final (callback) { if (this._inflateStream) { this._inflateStream.end() this._inflateStream = null } callback() } } /** * @param {zlib.ZlibOptions} [zlibOptions] * @returns {InflateStream} */ function createInflate (zlibOptions) { return new InflateStream(zlibOptions) } /** * @see https://fetch.spec.whatwg.org/#concept-header-extract-mime-type * @param {import('./headers').HeadersList} headers */ function extractMimeType (headers) { // 1. Let charset be null. let charset = null // 2. Let essence be null. let essence = null // 3. Let mimeType be null. let mimeType = null // 4. Let values be the result of getting, decoding, and splitting `Content-Type` from headers. const values = getDecodeSplit('content-type', headers) // 5. If values is null, then return failure. if (values === null) { return 'failure' } // 6. For each value of values: for (const value of values) { // 6.1. Let temporaryMimeType be the result of parsing value. const temporaryMimeType = parseMIMEType(value) // 6.2. If temporaryMimeType is failure or its essence is "*/*", then continue. if (temporaryMimeType === 'failure' || temporaryMimeType.essence === '*/*') { continue } // 6.3. Set mimeType to temporaryMimeType. mimeType = temporaryMimeType // 6.4. If mimeType’s essence is not essence, then: if (mimeType.essence !== essence) { // 6.4.1. Set charset to null. charset = null // 6.4.2. If mimeType’s parameters["charset"] exists, then set charset to // mimeType’s parameters["charset"]. if (mimeType.parameters.has('charset')) { charset = mimeType.parameters.get('charset') } // 6.4.3. Set essence to mimeType’s essence. essence = mimeType.essence } else if (!mimeType.parameters.has('charset') && charset !== null) { // 6.5. Otherwise, if mimeType’s parameters["charset"] does not exist, and // charset is non-null, set mimeType’s parameters["charset"] to charset. mimeType.parameters.set('charset', charset) } } // 7. If mimeType is null, then return failure. if (mimeType == null) { return 'failure' } // 8. Return mimeType. return mimeType } /** * @see https://fetch.spec.whatwg.org/#header-value-get-decode-and-split * @param {string|null} value */ function gettingDecodingSplitting (value) { // 1. Let input be the result of isomorphic decoding value. const input = value // 2. Let position be a position variable for input, initially pointing at the start of input. const position = { position: 0 } // 3. Let values be a list of strings, initially empty. const values = [] // 4. Let temporaryValue be the empty string. let temporaryValue = '' // 5. While position is not past the end of input: while (position.position < input.length) { // 5.1. Append the result of collecting a sequence of code points that are not U+0022 (") // or U+002C (,) from input, given position, to temporaryValue. temporaryValue += collectASequenceOfCodePoints( (char) => char !== '"' && char !== ',', input, position ) // 5.2. If position is not past the end of input, then: if (position.position < input.length) { // 5.2.1. If the code point at position within input is U+0022 ("), then: if (input.charCodeAt(position.position) === 0x22) { // 5.2.1.1. Append the result of collecting an HTTP quoted string from input, given position, to temporaryValue. temporaryValue += collectAnHTTPQuotedString( input, position ) // 5.2.1.2. If position is not past the end of input, then continue. if (position.position < input.length) { continue } } else { // 5.2.2. Otherwise: // 5.2.2.1. Assert: the code point at position within input is U+002C (,). assert(input.charCodeAt(position.position) === 0x2C) // 5.2.2.2. Advance position by 1. position.position++ } } // 5.3. Remove all HTTP tab or space from the start and end of temporaryValue. temporaryValue = removeChars(temporaryValue, true, true, (char) => char === 0x9 || char === 0x20) // 5.4. Append temporaryValue to values. values.push(temporaryValue) // 5.6. Set temporaryValue to the empty string. temporaryValue = '' } // 6. Return values. return values } /** * @see https://fetch.spec.whatwg.org/#concept-header-list-get-decode-split * @param {string} name lowercase header name * @param {import('./headers').HeadersList} list */ function getDecodeSplit (name, list) { // 1. Let value be the result of getting name from list. const value = list.get(name, true) // 2. If value is null, then return null. if (value === null) { return null } // 3. Return the result of getting, decoding, and splitting value. return gettingDecodingSplitting(value) } const textDecoder = new TextDecoder() /** * @see https://encoding.spec.whatwg.org/#utf-8-decode * @param {Buffer} buffer */ function utf8DecodeBytes (buffer) { if (buffer.length === 0) { return '' } // 1. Let buffer be the result of peeking three bytes from // ioQueue, converted to a byte sequence. // 2. If buffer is 0xEF 0xBB 0xBF, then read three // bytes from ioQueue. (Do nothing with those bytes.) if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { buffer = buffer.subarray(3) } // 3. Process a queue with an instance of UTF-8’s // decoder, ioQueue, output, and "replacement". const output = textDecoder.decode(buffer) // 4. Return output. return output } class EnvironmentSettingsObjectBase { get baseUrl () { return getGlobalOrigin() } get origin () { return this.baseUrl?.origin } policyContainer = makePolicyContainer() } class EnvironmentSettingsObject { settingsObject = new EnvironmentSettingsObjectBase() } const environmentSettingsObject = new EnvironmentSettingsObject() module.exports = { isAborted, isCancelled, isValidEncodedURL, ReadableStreamFrom, tryUpgradeRequestToAPotentiallyTrustworthyURL, clampAndCoarsenConnectionTimingInfo, coarsenedSharedCurrentTime, determineRequestsReferrer, makePolicyContainer, clonePolicyContainer, appendFetchMetadata, appendRequestOriginHeader, TAOCheck, corsCheck, crossOriginResourcePolicyCheck, createOpaqueTimingInfo, setRequestReferrerPolicyOnRedirect, isValidHTTPToken, requestBadPort, requestCurrentURL, responseURL, responseLocationURL, isURLPotentiallyTrustworthy, isValidReasonPhrase, sameOrigin, normalizeMethod, serializeJavascriptValueToJSONString, iteratorMixin, createIterator, isValidHeaderName, isValidHeaderValue, isErrorLike, fullyReadBody, bytesMatch, readableStreamClose, isomorphicEncode, urlIsLocal, urlHasHttpsScheme, urlIsHttpHttpsScheme, readAllBytes, simpleRangeHeaderValue, buildContentRange, parseMetadata, createInflate, extractMimeType, getDecodeSplit, utf8DecodeBytes, environmentSettingsObject, isOriginIPPotentiallyTrustworthy } /***/ }), /***/ 16480: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { types, inspect } = __nccwpck_require__(57975) const { markAsUncloneable } = __nccwpck_require__(75919) const UNDEFINED = 1 const BOOLEAN = 2 const STRING = 3 const SYMBOL = 4 const NUMBER = 5 const BIGINT = 6 const NULL = 7 const OBJECT = 8 // function and object const FunctionPrototypeSymbolHasInstance = Function.call.bind(Function.prototype[Symbol.hasInstance]) /** @type {import('../../../types/webidl').Webidl} */ const webidl = { converters: {}, util: {}, errors: {}, is: {} } /** * @description Instantiate an error. * * @param {Object} opts * @param {string} opts.header * @param {string} opts.message * @returns {TypeError} */ webidl.errors.exception = function (message) { return new TypeError(`${message.header}: ${message.message}`) } /** * @description Instantiate an error when conversion from one type to another has failed. * * @param {Object} opts * @param {string} opts.prefix * @param {string} opts.argument * @param {string[]} opts.types * @returns {TypeError} */ webidl.errors.conversionFailed = function (opts) { const plural = opts.types.length === 1 ? '' : ' one of' const message = `${opts.argument} could not be converted to` + `${plural}: ${opts.types.join(', ')}.` return webidl.errors.exception({ header: opts.prefix, message }) } /** * @description Instantiate an error when an invalid argument is provided * * @param {Object} context * @param {string} context.prefix * @param {string} context.value * @param {string} context.type * @returns {TypeError} */ webidl.errors.invalidArgument = function (context) { return webidl.errors.exception({ header: context.prefix, message: `"${context.value}" is an invalid ${context.type}.` }) } // https://webidl.spec.whatwg.org/#implements webidl.brandCheck = function (V, I) { if (!FunctionPrototypeSymbolHasInstance(I, V)) { const err = new TypeError('Illegal invocation') err.code = 'ERR_INVALID_THIS' // node compat. throw err } } webidl.brandCheckMultiple = function (List) { const prototypes = List.map((c) => webidl.util.MakeTypeAssertion(c)) return (V) => { if (prototypes.every(typeCheck => !typeCheck(V))) { const err = new TypeError('Illegal invocation') err.code = 'ERR_INVALID_THIS' // node compat. throw err } } } webidl.argumentLengthCheck = function ({ length }, min, ctx) { if (length < min) { throw webidl.errors.exception({ message: `${min} argument${min !== 1 ? 's' : ''} required, ` + `but${length ? ' only' : ''} ${length} found.`, header: ctx }) } } webidl.illegalConstructor = function () { throw webidl.errors.exception({ header: 'TypeError', message: 'Illegal constructor' }) } webidl.util.MakeTypeAssertion = function (I) { return (O) => FunctionPrototypeSymbolHasInstance(I, O) } // https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values webidl.util.Type = function (V) { switch (typeof V) { case 'undefined': return UNDEFINED case 'boolean': return BOOLEAN case 'string': return STRING case 'symbol': return SYMBOL case 'number': return NUMBER case 'bigint': return BIGINT case 'function': case 'object': { if (V === null) { return NULL } return OBJECT } } } webidl.util.Types = { UNDEFINED, BOOLEAN, STRING, SYMBOL, NUMBER, BIGINT, NULL, OBJECT } webidl.util.TypeValueToString = function (o) { switch (webidl.util.Type(o)) { case UNDEFINED: return 'Undefined' case BOOLEAN: return 'Boolean' case STRING: return 'String' case SYMBOL: return 'Symbol' case NUMBER: return 'Number' case BIGINT: return 'BigInt' case NULL: return 'Null' case OBJECT: return 'Object' } } webidl.util.markAsUncloneable = markAsUncloneable || (() => {}) // https://webidl.spec.whatwg.org/#abstract-opdef-converttoint webidl.util.ConvertToInt = function (V, bitLength, signedness, opts) { let upperBound let lowerBound // 1. If bitLength is 64, then: if (bitLength === 64) { // 1. Let upperBound be 2^53 − 1. upperBound = Math.pow(2, 53) - 1 // 2. If signedness is "unsigned", then let lowerBound be 0. if (signedness === 'unsigned') { lowerBound = 0 } else { // 3. Otherwise let lowerBound be −2^53 + 1. lowerBound = Math.pow(-2, 53) + 1 } } else if (signedness === 'unsigned') { // 2. Otherwise, if signedness is "unsigned", then: // 1. Let lowerBound be 0. lowerBound = 0 // 2. Let upperBound be 2^bitLength − 1. upperBound = Math.pow(2, bitLength) - 1 } else { // 3. Otherwise: // 1. Let lowerBound be -2^bitLength − 1. lowerBound = Math.pow(-2, bitLength) - 1 // 2. Let upperBound be 2^bitLength − 1 − 1. upperBound = Math.pow(2, bitLength - 1) - 1 } // 4. Let x be ? ToNumber(V). let x = Number(V) // 5. If x is −0, then set x to +0. if (x === 0) { x = 0 } // 6. If the conversion is to an IDL type associated // with the [EnforceRange] extended attribute, then: if (opts?.enforceRange === true) { // 1. If x is NaN, +∞, or −∞, then throw a TypeError. if ( Number.isNaN(x) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY ) { throw webidl.errors.exception({ header: 'Integer conversion', message: `Could not convert ${webidl.util.Stringify(V)} to an integer.` }) } // 2. Set x to IntegerPart(x). x = webidl.util.IntegerPart(x) // 3. If x < lowerBound or x > upperBound, then // throw a TypeError. if (x < lowerBound || x > upperBound) { throw webidl.errors.exception({ header: 'Integer conversion', message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.` }) } // 4. Return x. return x } // 7. If x is not NaN and the conversion is to an IDL // type associated with the [Clamp] extended // attribute, then: if (!Number.isNaN(x) && opts?.clamp === true) { // 1. Set x to min(max(x, lowerBound), upperBound). x = Math.min(Math.max(x, lowerBound), upperBound) // 2. Round x to the nearest integer, choosing the // even integer if it lies halfway between two, // and choosing +0 rather than −0. if (Math.floor(x) % 2 === 0) { x = Math.floor(x) } else { x = Math.ceil(x) } // 3. Return x. return x } // 8. If x is NaN, +0, +∞, or −∞, then return +0. if ( Number.isNaN(x) || (x === 0 && Object.is(0, x)) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY ) { return 0 } // 9. Set x to IntegerPart(x). x = webidl.util.IntegerPart(x) // 10. Set x to x modulo 2^bitLength. x = x % Math.pow(2, bitLength) // 11. If signedness is "signed" and x ≥ 2^bitLength − 1, // then return x − 2^bitLength. if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) { return x - Math.pow(2, bitLength) } // 12. Otherwise, return x. return x } // https://webidl.spec.whatwg.org/#abstract-opdef-integerpart webidl.util.IntegerPart = function (n) { // 1. Let r be floor(abs(n)). const r = Math.floor(Math.abs(n)) // 2. If n < 0, then return -1 × r. if (n < 0) { return -1 * r } // 3. Otherwise, return r. return r } webidl.util.Stringify = function (V) { const type = webidl.util.Type(V) switch (type) { case SYMBOL: return `Symbol(${V.description})` case OBJECT: return inspect(V) case STRING: return `"${V}"` case BIGINT: return `${V}n` default: return `${V}` } } // https://webidl.spec.whatwg.org/#es-sequence webidl.sequenceConverter = function (converter) { return (V, prefix, argument, Iterable) => { // 1. If Type(V) is not Object, throw a TypeError. if (webidl.util.Type(V) !== OBJECT) { throw webidl.errors.exception({ header: prefix, message: `${argument} (${webidl.util.Stringify(V)}) is not iterable.` }) } // 2. Let method be ? GetMethod(V, @@iterator). /** @type {Generator} */ const method = typeof Iterable === 'function' ? Iterable() : V?.[Symbol.iterator]?.() const seq = [] let index = 0 // 3. If method is undefined, throw a TypeError. if ( method === undefined || typeof method.next !== 'function' ) { throw webidl.errors.exception({ header: prefix, message: `${argument} is not iterable.` }) } // https://webidl.spec.whatwg.org/#create-sequence-from-iterable while (true) { const { done, value } = method.next() if (done) { break } seq.push(converter(value, prefix, `${argument}[${index++}]`)) } return seq } } // https://webidl.spec.whatwg.org/#es-to-record webidl.recordConverter = function (keyConverter, valueConverter) { return (O, prefix, argument) => { // 1. If Type(O) is not Object, throw a TypeError. if (webidl.util.Type(O) !== OBJECT) { throw webidl.errors.exception({ header: prefix, message: `${argument} ("${webidl.util.TypeValueToString(O)}") is not an Object.` }) } // 2. Let result be a new empty instance of record. const result = {} if (!types.isProxy(O)) { // 1. Let desc be ? O.[[GetOwnProperty]](key). const keys = [...Object.getOwnPropertyNames(O), ...Object.getOwnPropertySymbols(O)] for (const key of keys) { const keyName = webidl.util.Stringify(key) // 1. Let typedKey be key converted to an IDL value of type K. const typedKey = keyConverter(key, prefix, `Key ${keyName} in ${argument}`) // 2. Let value be ? Get(O, key). // 3. Let typedValue be value converted to an IDL value of type V. const typedValue = valueConverter(O[key], prefix, `${argument}[${keyName}]`) // 4. Set result[typedKey] to typedValue. result[typedKey] = typedValue } // 5. Return result. return result } // 3. Let keys be ? O.[[OwnPropertyKeys]](). const keys = Reflect.ownKeys(O) // 4. For each key of keys. for (const key of keys) { // 1. Let desc be ? O.[[GetOwnProperty]](key). const desc = Reflect.getOwnPropertyDescriptor(O, key) // 2. If desc is not undefined and desc.[[Enumerable]] is true: if (desc?.enumerable) { // 1. Let typedKey be key converted to an IDL value of type K. const typedKey = keyConverter(key, prefix, argument) // 2. Let value be ? Get(O, key). // 3. Let typedValue be value converted to an IDL value of type V. const typedValue = valueConverter(O[key], prefix, argument) // 4. Set result[typedKey] to typedValue. result[typedKey] = typedValue } } // 5. Return result. return result } } webidl.interfaceConverter = function (TypeCheck, name) { return (V, prefix, argument) => { if (!TypeCheck(V)) { throw webidl.errors.exception({ header: prefix, message: `Expected ${argument} ("${webidl.util.Stringify(V)}") to be an instance of ${name}.` }) } return V } } webidl.dictionaryConverter = function (converters) { return (dictionary, prefix, argument) => { const dict = {} if (dictionary != null && webidl.util.Type(dictionary) !== OBJECT) { throw webidl.errors.exception({ header: prefix, message: `Expected ${dictionary} to be one of: Null, Undefined, Object.` }) } for (const options of converters) { const { key, defaultValue, required, converter } = options if (required === true) { if (dictionary == null || !Object.hasOwn(dictionary, key)) { throw webidl.errors.exception({ header: prefix, message: `Missing required key "${key}".` }) } } let value = dictionary?.[key] const hasDefault = defaultValue !== undefined // Only use defaultValue if value is undefined and // a defaultValue options was provided. if (hasDefault && value === undefined) { value = defaultValue() } // A key can be optional and have no default value. // When this happens, do not perform a conversion, // and do not assign the key a value. if (required || hasDefault || value !== undefined) { value = converter(value, prefix, `${argument}.${key}`) if ( options.allowedValues && !options.allowedValues.includes(value) ) { throw webidl.errors.exception({ header: prefix, message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.` }) } dict[key] = value } } return dict } } webidl.nullableConverter = function (converter) { return (V, prefix, argument) => { if (V === null) { return V } return converter(V, prefix, argument) } } /** * @param {*} value * @returns {boolean} */ webidl.is.USVString = function (value) { return ( typeof value === 'string' && value.isWellFormed() ) } webidl.is.ReadableStream = webidl.util.MakeTypeAssertion(ReadableStream) webidl.is.Blob = webidl.util.MakeTypeAssertion(Blob) webidl.is.URLSearchParams = webidl.util.MakeTypeAssertion(URLSearchParams) webidl.is.File = webidl.util.MakeTypeAssertion(globalThis.File ?? (__nccwpck_require__(4573).File)) webidl.is.URL = webidl.util.MakeTypeAssertion(URL) webidl.is.AbortSignal = webidl.util.MakeTypeAssertion(AbortSignal) webidl.is.MessagePort = webidl.util.MakeTypeAssertion(MessagePort) // https://webidl.spec.whatwg.org/#es-DOMString webidl.converters.DOMString = function (V, prefix, argument, opts) { // 1. If V is null and the conversion is to an IDL type // associated with the [LegacyNullToEmptyString] // extended attribute, then return the DOMString value // that represents the empty string. if (V === null && opts?.legacyNullToEmptyString) { return '' } // 2. Let x be ? ToString(V). if (typeof V === 'symbol') { throw webidl.errors.exception({ header: prefix, message: `${argument} is a symbol, which cannot be converted to a DOMString.` }) } // 3. Return the IDL DOMString value that represents the // same sequence of code units as the one the // ECMAScript String value x represents. return String(V) } // https://webidl.spec.whatwg.org/#es-ByteString webidl.converters.ByteString = function (V, prefix, argument) { // 1. Let x be ? ToString(V). if (typeof V === 'symbol') { throw webidl.errors.exception({ header: prefix, message: `${argument} is a symbol, which cannot be converted to a ByteString.` }) } const x = String(V) // 2. If the value of any element of x is greater than // 255, then throw a TypeError. for (let index = 0; index < x.length; index++) { if (x.charCodeAt(index) > 255) { throw new TypeError( 'Cannot convert argument to a ByteString because the character at ' + `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` ) } } // 3. Return an IDL ByteString value whose length is the // length of x, and where the value of each element is // the value of the corresponding element of x. return x } /** * @param {unknown} value * @returns {string} * @see https://webidl.spec.whatwg.org/#es-USVString */ webidl.converters.USVString = function (value) { // TODO: rewrite this so we can control the errors thrown if (typeof value === 'string') { return value.toWellFormed() } return `${value}`.toWellFormed() } // https://webidl.spec.whatwg.org/#es-boolean webidl.converters.boolean = function (V) { // 1. Let x be the result of computing ToBoolean(V). // https://262.ecma-international.org/10.0/index.html#table-10 const x = Boolean(V) // 2. Return the IDL boolean value that is the one that represents // the same truth value as the ECMAScript Boolean value x. return x } // https://webidl.spec.whatwg.org/#es-any webidl.converters.any = function (V) { return V } // https://webidl.spec.whatwg.org/#es-long-long webidl.converters['long long'] = function (V, prefix, argument) { // 1. Let x be ? ConvertToInt(V, 64, "signed"). const x = webidl.util.ConvertToInt(V, 64, 'signed', undefined, prefix, argument) // 2. Return the IDL long long value that represents // the same numeric value as x. return x } // https://webidl.spec.whatwg.org/#es-unsigned-long-long webidl.converters['unsigned long long'] = function (V, prefix, argument) { // 1. Let x be ? ConvertToInt(V, 64, "unsigned"). const x = webidl.util.ConvertToInt(V, 64, 'unsigned', undefined, prefix, argument) // 2. Return the IDL unsigned long long value that // represents the same numeric value as x. return x } // https://webidl.spec.whatwg.org/#es-unsigned-long webidl.converters['unsigned long'] = function (V, prefix, argument) { // 1. Let x be ? ConvertToInt(V, 32, "unsigned"). const x = webidl.util.ConvertToInt(V, 32, 'unsigned', undefined, prefix, argument) // 2. Return the IDL unsigned long value that // represents the same numeric value as x. return x } // https://webidl.spec.whatwg.org/#es-unsigned-short webidl.converters['unsigned short'] = function (V, prefix, argument, opts) { // 1. Let x be ? ConvertToInt(V, 16, "unsigned"). const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts, prefix, argument) // 2. Return the IDL unsigned short value that represents // the same numeric value as x. return x } // https://webidl.spec.whatwg.org/#idl-ArrayBuffer webidl.converters.ArrayBuffer = function (V, prefix, argument, opts) { // 1. If Type(V) is not Object, or V does not have an // [[ArrayBufferData]] internal slot, then throw a // TypeError. // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances if ( webidl.util.Type(V) !== OBJECT || !types.isAnyArrayBuffer(V) ) { throw webidl.errors.conversionFailed({ prefix, argument: `${argument} ("${webidl.util.Stringify(V)}")`, types: ['ArrayBuffer'] }) } // 2. If the conversion is not to an IDL type associated // with the [AllowShared] extended attribute, and // IsSharedArrayBuffer(V) is true, then throw a // TypeError. if (opts?.allowShared === false && types.isSharedArrayBuffer(V)) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'SharedArrayBuffer is not allowed.' }) } // 3. If the conversion is not to an IDL type associated // with the [AllowResizable] extended attribute, and // IsResizableArrayBuffer(V) is true, then throw a // TypeError. if (V.resizable || V.growable) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'Received a resizable ArrayBuffer.' }) } // 4. Return the IDL ArrayBuffer value that is a // reference to the same object as V. return V } webidl.converters.TypedArray = function (V, T, prefix, name, opts) { // 1. Let T be the IDL type V is being converted to. // 2. If Type(V) is not Object, or V does not have a // [[TypedArrayName]] internal slot with a value // equal to T’s name, then throw a TypeError. if ( webidl.util.Type(V) !== OBJECT || !types.isTypedArray(V) || V.constructor.name !== T.name ) { throw webidl.errors.conversionFailed({ prefix, argument: `${name} ("${webidl.util.Stringify(V)}")`, types: [T.name] }) } // 3. If the conversion is not to an IDL type associated // with the [AllowShared] extended attribute, and // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is // true, then throw a TypeError. if (opts?.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'SharedArrayBuffer is not allowed.' }) } // 4. If the conversion is not to an IDL type associated // with the [AllowResizable] extended attribute, and // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is // true, then throw a TypeError. if (V.buffer.resizable || V.buffer.growable) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'Received a resizable ArrayBuffer.' }) } // 5. Return the IDL value of type T that is a reference // to the same object as V. return V } webidl.converters.DataView = function (V, prefix, name, opts) { // 1. If Type(V) is not Object, or V does not have a // [[DataView]] internal slot, then throw a TypeError. if (webidl.util.Type(V) !== OBJECT || !types.isDataView(V)) { throw webidl.errors.exception({ header: prefix, message: `${name} is not a DataView.` }) } // 2. If the conversion is not to an IDL type associated // with the [AllowShared] extended attribute, and // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, // then throw a TypeError. if (opts?.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'SharedArrayBuffer is not allowed.' }) } // 3. If the conversion is not to an IDL type associated // with the [AllowResizable] extended attribute, and // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is // true, then throw a TypeError. if (V.buffer.resizable || V.buffer.growable) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'Received a resizable ArrayBuffer.' }) } // 4. Return the IDL DataView value that is a reference // to the same object as V. return V } webidl.converters['sequence'] = webidl.sequenceConverter( webidl.converters.ByteString ) webidl.converters['sequence>'] = webidl.sequenceConverter( webidl.converters['sequence'] ) webidl.converters['record'] = webidl.recordConverter( webidl.converters.ByteString, webidl.converters.ByteString ) webidl.converters.Blob = webidl.interfaceConverter(webidl.is.Blob, 'Blob') webidl.converters.AbortSignal = webidl.interfaceConverter( webidl.is.AbortSignal, 'AbortSignal' ) module.exports = { webidl } /***/ }), /***/ 70770: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = __nccwpck_require__(69213) const { parseExtensions, isClosed, isClosing, isEstablished, validateCloseCodeAndReason } = __nccwpck_require__(19954) const { makeRequest } = __nccwpck_require__(7622) const { fetching } = __nccwpck_require__(25071) const { Headers, getHeadersList } = __nccwpck_require__(289) const { getDecodeSplit } = __nccwpck_require__(58799) const { WebsocketFrameSend } = __nccwpck_require__(35113) const assert = __nccwpck_require__(34589) /** @type {import('crypto')} */ let crypto try { crypto = __nccwpck_require__(77598) /* c8 ignore next 3 */ } catch { } /** * @see https://websockets.spec.whatwg.org/#concept-websocket-establish * @param {URL} url * @param {string|string[]} protocols * @param {import('./websocket').Handler} handler * @param {Partial} options */ function establishWebSocketConnection (url, protocols, client, handler, options) { // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s // scheme is "ws", and to "https" otherwise. const requestURL = url requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:' // 2. Let request be a new request, whose URL is requestURL, client is client, // service-workers mode is "none", referrer is "no-referrer", mode is // "websocket", credentials mode is "include", cache mode is "no-store" , // and redirect mode is "error". const request = makeRequest({ urlList: [requestURL], client, serviceWorkers: 'none', referrer: 'no-referrer', mode: 'websocket', credentials: 'include', cache: 'no-store', redirect: 'error' }) // Note: undici extension, allow setting custom headers. if (options.headers) { const headersList = getHeadersList(new Headers(options.headers)) request.headersList = headersList } // 3. Append (`Upgrade`, `websocket`) to request’s header list. // 4. Append (`Connection`, `Upgrade`) to request’s header list. // Note: both of these are handled by undici currently. // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397 // 5. Let keyValue be a nonce consisting of a randomly selected // 16-byte value that has been forgiving-base64-encoded and // isomorphic encoded. const keyValue = crypto.randomBytes(16).toString('base64') // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s // header list. request.headersList.append('sec-websocket-key', keyValue, true) // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s // header list. request.headersList.append('sec-websocket-version', '13', true) // 8. For each protocol in protocols, combine // (`Sec-WebSocket-Protocol`, protocol) in request’s header // list. for (const protocol of protocols) { request.headersList.append('sec-websocket-protocol', protocol, true) } // 9. Let permessageDeflate be a user-agent defined // "permessage-deflate" extension header value. // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673 const permessageDeflate = 'permessage-deflate; client_max_window_bits' // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to // request’s header list. request.headersList.append('sec-websocket-extensions', permessageDeflate, true) // 11. Fetch request with useParallelQueue set to true, and // processResponse given response being these steps: const controller = fetching({ request, useParallelQueue: true, dispatcher: options.dispatcher, processResponse (response) { if (response.type === 'error') { // If the WebSocket connection could not be established, it is also said // that _The WebSocket Connection is Closed_, but not _cleanly_. handler.readyState = states.CLOSED } // 1. If response is a network error or its status is not 101, // fail the WebSocket connection. if (response.type === 'error' || response.status !== 101) { failWebsocketConnection(handler, 1002, 'Received network error or non-101 status code.', response.error) return } // 2. If protocols is not the empty list and extracting header // list values given `Sec-WebSocket-Protocol` and response’s // header list results in null, failure, or the empty byte // sequence, then fail the WebSocket connection. if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) { failWebsocketConnection(handler, 1002, 'Server did not respond with sent protocols.') return } // 3. Follow the requirements stated step 2 to step 6, inclusive, // of the last set of steps in section 4.1 of The WebSocket // Protocol to validate response. This either results in fail // the WebSocket connection or the WebSocket connection is // established. // 2. If the response lacks an |Upgrade| header field or the |Upgrade| // header field contains a value that is not an ASCII case- // insensitive match for the value "websocket", the client MUST // _Fail the WebSocket Connection_. if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') { failWebsocketConnection(handler, 1002, 'Server did not set Upgrade header to "websocket".') return } // 3. If the response lacks a |Connection| header field or the // |Connection| header field doesn't contain a token that is an // ASCII case-insensitive match for the value "Upgrade", the client // MUST _Fail the WebSocket Connection_. if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') { failWebsocketConnection(handler, 1002, 'Server did not set Connection header to "upgrade".') return } // 4. If the response lacks a |Sec-WebSocket-Accept| header field or // the |Sec-WebSocket-Accept| contains a value other than the // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket- // Key| (as a string, not base64-decoded) with the string "258EAFA5- // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and // trailing whitespace, the client MUST _Fail the WebSocket // Connection_. const secWSAccept = response.headersList.get('Sec-WebSocket-Accept') const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64') if (secWSAccept !== digest) { failWebsocketConnection(handler, 1002, 'Incorrect hash received in Sec-WebSocket-Accept header.') return } // 5. If the response includes a |Sec-WebSocket-Extensions| header // field and this header field indicates the use of an extension // that was not present in the client's handshake (the server has // indicated an extension not requested by the client), the client // MUST _Fail the WebSocket Connection_. (The parsing of this // header field to determine which extensions are requested is // discussed in Section 9.1.) const secExtension = response.headersList.get('Sec-WebSocket-Extensions') let extensions if (secExtension !== null) { extensions = parseExtensions(secExtension) if (!extensions.has('permessage-deflate')) { failWebsocketConnection(handler, 1002, 'Sec-WebSocket-Extensions header does not match.') return } } // 6. If the response includes a |Sec-WebSocket-Protocol| header field // and this header field indicates the use of a subprotocol that was // not present in the client's handshake (the server has indicated a // subprotocol not requested by the client), the client MUST _Fail // the WebSocket Connection_. const secProtocol = response.headersList.get('Sec-WebSocket-Protocol') if (secProtocol !== null) { const requestProtocols = getDecodeSplit('sec-websocket-protocol', request.headersList) // The client can request that the server use a specific subprotocol by // including the |Sec-WebSocket-Protocol| field in its handshake. If it // is specified, the server needs to include the same field and one of // the selected subprotocol values in its response for the connection to // be established. if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(handler, 1002, 'Protocol was not set in the opening handshake.') return } } response.socket.on('data', handler.onSocketData) response.socket.on('close', handler.onSocketClose) response.socket.on('error', handler.onSocketError) handler.wasEverConnected = true handler.onConnectionEstablished(response, extensions) } }) return controller } /** * @see https://whatpr.org/websockets/48.html#close-the-websocket * @param {import('./websocket').Handler} object * @param {number} [code=null] * @param {string} [reason=''] */ function closeWebSocketConnection (object, code, reason, validate = false) { // 1. If code was not supplied, let code be null. code ??= null // 2. If reason was not supplied, let reason be the empty string. reason ??= '' // 3. Validate close code and reason with code and reason. if (validate) validateCloseCodeAndReason(code, reason) // 4. Run the first matching steps from the following list: // - If object’s ready state is CLOSING (2) or CLOSED (3) // - If the WebSocket connection is not yet established [WSP] // - If the WebSocket closing handshake has not yet been started [WSP] // - Otherwise if (isClosed(object.readyState) || isClosing(object.readyState)) { // Do nothing. } else if (!isEstablished(object.readyState)) { // Fail the WebSocket connection and set object’s ready state to CLOSING (2). [WSP] failWebsocketConnection(object) object.readyState = states.CLOSING } else if (!object.closeState.has(sentCloseFrameState.SENT) && !object.closeState.has(sentCloseFrameState.RECEIVED)) { // Upon either sending or receiving a Close control frame, it is said // that _The WebSocket Closing Handshake is Started_ and that the // WebSocket connection is in the CLOSING state. const frame = new WebsocketFrameSend() // If neither code nor reason is present, the WebSocket Close // message must not have a body. // If code is present, then the status code to use in the // WebSocket Close message must be the integer given by code. // If code is null and reason is the empty string, the WebSocket Close frame must not have a body. // If reason is non-empty but code is null, then set code to 1000 ("Normal Closure"). if (reason.length !== 0 && code === null) { code = 1000 } // If code is set, then the status code to use in the WebSocket Close frame must be the integer given by code. assert(code === null || Number.isInteger(code)) if (code === null && reason.length === 0) { frame.frameData = emptyBuffer } else if (code !== null && reason === null) { frame.frameData = Buffer.allocUnsafe(2) frame.frameData.writeUInt16BE(code, 0) } else if (code !== null && reason !== null) { // If reason is also present, then reasonBytes must be // provided in the Close message after the status code. frame.frameData = Buffer.allocUnsafe(2 + Buffer.byteLength(reason)) frame.frameData.writeUInt16BE(code, 0) // the body MAY contain UTF-8-encoded data with value /reason/ frame.frameData.write(reason, 2, 'utf-8') } else { frame.frameData = emptyBuffer } object.socket.write(frame.createFrame(opcodes.CLOSE)) object.closeState.add(sentCloseFrameState.SENT) // Upon either sending or receiving a Close control frame, it is said // that _The WebSocket Closing Handshake is Started_ and that the // WebSocket connection is in the CLOSING state. object.readyState = states.CLOSING } else { // Set object’s ready state to CLOSING (2). object.readyState = states.CLOSING } } /** * @param {import('./websocket').Handler} handler * @param {number} code * @param {string|undefined} reason * @param {unknown} cause * @returns {void} */ function failWebsocketConnection (handler, code, reason, cause) { // If _The WebSocket Connection is Established_ prior to the point where // the endpoint is required to _Fail the WebSocket Connection_, the // endpoint SHOULD send a Close frame with an appropriate status code // (Section 7.4) before proceeding to _Close the WebSocket Connection_. if (isEstablished(handler.readyState)) { closeWebSocketConnection(handler, code, reason, false) } handler.controller.abort() if (handler.socket?.destroyed === false) { handler.socket.destroy() } handler.onFail(code, reason, cause) } module.exports = { establishWebSocketConnection, failWebsocketConnection, closeWebSocketConnection } /***/ }), /***/ 69213: /***/ ((module) => { "use strict"; /** * This is a Globally Unique Identifier unique used to validate that the * endpoint accepts websocket connections. * @see https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3 * @type {'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'} */ const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' /** * @type {PropertyDescriptor} */ const staticPropertyDescriptors = { enumerable: true, writable: false, configurable: false } /** * The states of the WebSocket connection. * * @readonly * @enum * @property {0} CONNECTING * @property {1} OPEN * @property {2} CLOSING * @property {3} CLOSED */ const states = { CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3 } /** * @readonly * @enum * @property {0} NOT_SENT * @property {1} PROCESSING * @property {2} SENT */ const sentCloseFrameState = { SENT: 1, RECEIVED: 2 } /** * The WebSocket opcodes. * * @readonly * @enum * @property {0x0} CONTINUATION * @property {0x1} TEXT * @property {0x2} BINARY * @property {0x8} CLOSE * @property {0x9} PING * @property {0xA} PONG * @see https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 */ const opcodes = { CONTINUATION: 0x0, TEXT: 0x1, BINARY: 0x2, CLOSE: 0x8, PING: 0x9, PONG: 0xA } /** * The maximum value for an unsigned 16-bit integer. * * @type {65535} 2 ** 16 - 1 */ const maxUnsigned16Bit = 65535 /** * The states of the parser. * * @readonly * @enum * @property {0} INFO * @property {2} PAYLOADLENGTH_16 * @property {3} PAYLOADLENGTH_64 * @property {4} READ_DATA */ const parserStates = { INFO: 0, PAYLOADLENGTH_16: 2, PAYLOADLENGTH_64: 3, READ_DATA: 4 } /** * An empty buffer. * * @type {Buffer} */ const emptyBuffer = Buffer.allocUnsafe(0) /** * @readonly * @property {1} text * @property {2} typedArray * @property {3} arrayBuffer * @property {4} blob */ const sendHints = { text: 1, typedArray: 2, arrayBuffer: 3, blob: 4 } module.exports = { uid, sentCloseFrameState, staticPropertyDescriptors, states, opcodes, maxUnsigned16Bit, parserStates, emptyBuffer, sendHints } /***/ }), /***/ 91979: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { webidl } = __nccwpck_require__(16480) const { kEnumerableProperty } = __nccwpck_require__(46425) const { kConstruct } = __nccwpck_require__(83112) /** * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent */ class MessageEvent extends Event { #eventInit constructor (type, eventInitDict = {}) { if (type === kConstruct) { super(arguments[1], arguments[2]) webidl.util.markAsUncloneable(this) return } const prefix = 'MessageEvent constructor' webidl.argumentLengthCheck(arguments, 1, prefix) type = webidl.converters.DOMString(type, prefix, 'type') eventInitDict = webidl.converters.MessageEventInit(eventInitDict, prefix, 'eventInitDict') super(type, eventInitDict) this.#eventInit = eventInitDict webidl.util.markAsUncloneable(this) } get data () { webidl.brandCheck(this, MessageEvent) return this.#eventInit.data } get origin () { webidl.brandCheck(this, MessageEvent) return this.#eventInit.origin } get lastEventId () { webidl.brandCheck(this, MessageEvent) return this.#eventInit.lastEventId } get source () { webidl.brandCheck(this, MessageEvent) return this.#eventInit.source } get ports () { webidl.brandCheck(this, MessageEvent) if (!Object.isFrozen(this.#eventInit.ports)) { Object.freeze(this.#eventInit.ports) } return this.#eventInit.ports } initMessageEvent ( type, bubbles = false, cancelable = false, data = null, origin = '', lastEventId = '', source = null, ports = [] ) { webidl.brandCheck(this, MessageEvent) webidl.argumentLengthCheck(arguments, 1, 'MessageEvent.initMessageEvent') return new MessageEvent(type, { bubbles, cancelable, data, origin, lastEventId, source, ports }) } static createFastMessageEvent (type, init) { const messageEvent = new MessageEvent(kConstruct, type, init) messageEvent.#eventInit = init messageEvent.#eventInit.data ??= null messageEvent.#eventInit.origin ??= '' messageEvent.#eventInit.lastEventId ??= '' messageEvent.#eventInit.source ??= null messageEvent.#eventInit.ports ??= [] return messageEvent } } const { createFastMessageEvent } = MessageEvent delete MessageEvent.createFastMessageEvent /** * @see https://websockets.spec.whatwg.org/#the-closeevent-interface */ class CloseEvent extends Event { #eventInit constructor (type, eventInitDict = {}) { const prefix = 'CloseEvent constructor' webidl.argumentLengthCheck(arguments, 1, prefix) type = webidl.converters.DOMString(type, prefix, 'type') eventInitDict = webidl.converters.CloseEventInit(eventInitDict) super(type, eventInitDict) this.#eventInit = eventInitDict webidl.util.markAsUncloneable(this) } get wasClean () { webidl.brandCheck(this, CloseEvent) return this.#eventInit.wasClean } get code () { webidl.brandCheck(this, CloseEvent) return this.#eventInit.code } get reason () { webidl.brandCheck(this, CloseEvent) return this.#eventInit.reason } } // https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface class ErrorEvent extends Event { #eventInit constructor (type, eventInitDict) { const prefix = 'ErrorEvent constructor' webidl.argumentLengthCheck(arguments, 1, prefix) super(type, eventInitDict) webidl.util.markAsUncloneable(this) type = webidl.converters.DOMString(type, prefix, 'type') eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}) this.#eventInit = eventInitDict } get message () { webidl.brandCheck(this, ErrorEvent) return this.#eventInit.message } get filename () { webidl.brandCheck(this, ErrorEvent) return this.#eventInit.filename } get lineno () { webidl.brandCheck(this, ErrorEvent) return this.#eventInit.lineno } get colno () { webidl.brandCheck(this, ErrorEvent) return this.#eventInit.colno } get error () { webidl.brandCheck(this, ErrorEvent) return this.#eventInit.error } } Object.defineProperties(MessageEvent.prototype, { [Symbol.toStringTag]: { value: 'MessageEvent', configurable: true }, data: kEnumerableProperty, origin: kEnumerableProperty, lastEventId: kEnumerableProperty, source: kEnumerableProperty, ports: kEnumerableProperty, initMessageEvent: kEnumerableProperty }) Object.defineProperties(CloseEvent.prototype, { [Symbol.toStringTag]: { value: 'CloseEvent', configurable: true }, reason: kEnumerableProperty, code: kEnumerableProperty, wasClean: kEnumerableProperty }) Object.defineProperties(ErrorEvent.prototype, { [Symbol.toStringTag]: { value: 'ErrorEvent', configurable: true }, message: kEnumerableProperty, filename: kEnumerableProperty, lineno: kEnumerableProperty, colno: kEnumerableProperty, error: kEnumerableProperty }) webidl.converters.MessagePort = webidl.interfaceConverter( webidl.is.MessagePort, 'MessagePort' ) webidl.converters['sequence'] = webidl.sequenceConverter( webidl.converters.MessagePort ) const eventInit = [ { key: 'bubbles', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'cancelable', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'composed', converter: webidl.converters.boolean, defaultValue: () => false } ] webidl.converters.MessageEventInit = webidl.dictionaryConverter([ ...eventInit, { key: 'data', converter: webidl.converters.any, defaultValue: () => null }, { key: 'origin', converter: webidl.converters.USVString, defaultValue: () => '' }, { key: 'lastEventId', converter: webidl.converters.DOMString, defaultValue: () => '' }, { key: 'source', // Node doesn't implement WindowProxy or ServiceWorker, so the only // valid value for source is a MessagePort. converter: webidl.nullableConverter(webidl.converters.MessagePort), defaultValue: () => null }, { key: 'ports', converter: webidl.converters['sequence'], defaultValue: () => new Array(0) } ]) webidl.converters.CloseEventInit = webidl.dictionaryConverter([ ...eventInit, { key: 'wasClean', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'code', converter: webidl.converters['unsigned short'], defaultValue: () => 0 }, { key: 'reason', converter: webidl.converters.USVString, defaultValue: () => '' } ]) webidl.converters.ErrorEventInit = webidl.dictionaryConverter([ ...eventInit, { key: 'message', converter: webidl.converters.DOMString, defaultValue: () => '' }, { key: 'filename', converter: webidl.converters.USVString, defaultValue: () => '' }, { key: 'lineno', converter: webidl.converters['unsigned long'], defaultValue: () => 0 }, { key: 'colno', converter: webidl.converters['unsigned long'], defaultValue: () => 0 }, { key: 'error', converter: webidl.converters.any } ]) module.exports = { MessageEvent, CloseEvent, ErrorEvent, createFastMessageEvent } /***/ }), /***/ 35113: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { maxUnsigned16Bit, opcodes } = __nccwpck_require__(69213) const BUFFER_SIZE = 8 * 1024 /** @type {import('crypto')} */ let crypto let buffer = null let bufIdx = BUFFER_SIZE try { crypto = __nccwpck_require__(77598) /* c8 ignore next 3 */ } catch { crypto = { // not full compatibility, but minimum. randomFillSync: function randomFillSync (buffer, _offset, _size) { for (let i = 0; i < buffer.length; ++i) { buffer[i] = Math.random() * 255 | 0 } return buffer } } } function generateMask () { if (bufIdx === BUFFER_SIZE) { bufIdx = 0 crypto.randomFillSync((buffer ??= Buffer.allocUnsafeSlow(BUFFER_SIZE)), 0, BUFFER_SIZE) } return [buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++]] } class WebsocketFrameSend { /** * @param {Buffer|undefined} data */ constructor (data) { this.frameData = data } createFrame (opcode) { const frameData = this.frameData const maskKey = generateMask() const bodyLength = frameData?.byteLength ?? 0 /** @type {number} */ let payloadLength = bodyLength // 0-125 let offset = 6 if (bodyLength > maxUnsigned16Bit) { offset += 8 // payload length is next 8 bytes payloadLength = 127 } else if (bodyLength > 125) { offset += 2 // payload length is next 2 bytes payloadLength = 126 } const buffer = Buffer.allocUnsafe(bodyLength + offset) // Clear first 2 bytes, everything else is overwritten buffer[0] = buffer[1] = 0 buffer[0] |= 0x80 // FIN buffer[0] = (buffer[0] & 0xF0) + opcode // opcode /*! ws. MIT License. Einar Otto Stangvik */ buffer[offset - 4] = maskKey[0] buffer[offset - 3] = maskKey[1] buffer[offset - 2] = maskKey[2] buffer[offset - 1] = maskKey[3] buffer[1] = payloadLength if (payloadLength === 126) { buffer.writeUInt16BE(bodyLength, 2) } else if (payloadLength === 127) { // Clear extended payload length buffer[2] = buffer[3] = 0 buffer.writeUIntBE(bodyLength, 4, 6) } buffer[1] |= 0x80 // MASK // mask body for (let i = 0; i < bodyLength; ++i) { buffer[offset + i] = frameData[i] ^ maskKey[i & 3] } return buffer } /** * @param {Uint8Array} buffer */ static createFastTextFrame (buffer) { const maskKey = generateMask() const bodyLength = buffer.length // mask body for (let i = 0; i < bodyLength; ++i) { buffer[i] ^= maskKey[i & 3] } let payloadLength = bodyLength let offset = 6 if (bodyLength > maxUnsigned16Bit) { offset += 8 // payload length is next 8 bytes payloadLength = 127 } else if (bodyLength > 125) { offset += 2 // payload length is next 2 bytes payloadLength = 126 } const head = Buffer.allocUnsafeSlow(offset) head[0] = 0x80 /* FIN */ | opcodes.TEXT /* opcode TEXT */ head[1] = payloadLength | 0x80 /* MASK */ head[offset - 4] = maskKey[0] head[offset - 3] = maskKey[1] head[offset - 2] = maskKey[2] head[offset - 1] = maskKey[3] if (payloadLength === 126) { head.writeUInt16BE(bodyLength, 2) } else if (payloadLength === 127) { head[2] = head[3] = 0 head.writeUIntBE(bodyLength, 4, 6) } return [head, buffer] } } module.exports = { WebsocketFrameSend, generateMask // for benchmark } /***/ }), /***/ 39550: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { createInflateRaw, Z_DEFAULT_WINDOWBITS } = __nccwpck_require__(38522) const { isValidClientWindowBits } = __nccwpck_require__(19954) const tail = Buffer.from([0x00, 0x00, 0xff, 0xff]) const kBuffer = Symbol('kBuffer') const kLength = Symbol('kLength') class PerMessageDeflate { /** @type {import('node:zlib').InflateRaw} */ #inflate #options = {} constructor (extensions) { this.#options.serverNoContextTakeover = extensions.has('server_no_context_takeover') this.#options.serverMaxWindowBits = extensions.get('server_max_window_bits') } decompress (chunk, fin, callback) { // An endpoint uses the following algorithm to decompress a message. // 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the // payload of the message. // 2. Decompress the resulting data using DEFLATE. if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS if (this.#options.serverMaxWindowBits) { // empty values default to Z_DEFAULT_WINDOWBITS if (!isValidClientWindowBits(this.#options.serverMaxWindowBits)) { callback(new Error('Invalid server_max_window_bits')) return } windowBits = Number.parseInt(this.#options.serverMaxWindowBits) } this.#inflate = createInflateRaw({ windowBits }) this.#inflate[kBuffer] = [] this.#inflate[kLength] = 0 this.#inflate.on('data', (data) => { this.#inflate[kBuffer].push(data) this.#inflate[kLength] += data.length }) this.#inflate.on('error', (err) => { this.#inflate = null callback(err) }) } this.#inflate.write(chunk) if (fin) { this.#inflate.write(tail) } this.#inflate.flush(() => { const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]) this.#inflate[kBuffer].length = 0 this.#inflate[kLength] = 0 callback(null, full) }) } } module.exports = { PerMessageDeflate } /***/ }), /***/ 98663: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Writable } = __nccwpck_require__(57075) const assert = __nccwpck_require__(34589) const { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = __nccwpck_require__(69213) const { isValidStatusCode, isValidOpcode, websocketMessageReceived, utf8Decode, isControlFrame, isTextBinaryFrame, isContinuationFrame } = __nccwpck_require__(19954) const { failWebsocketConnection } = __nccwpck_require__(70770) const { WebsocketFrameSend } = __nccwpck_require__(35113) const { PerMessageDeflate } = __nccwpck_require__(39550) // This code was influenced by ws released under the MIT license. // Copyright (c) 2011 Einar Otto Stangvik // Copyright (c) 2013 Arnout Kazemier and contributors // Copyright (c) 2016 Luigi Pinca and contributors class ByteParser extends Writable { #buffers = [] #fragmentsBytes = 0 #byteOffset = 0 #loop = false #state = parserStates.INFO #info = {} #fragments = [] /** @type {Map} */ #extensions /** @type {import('./websocket').Handler} */ #handler constructor (handler, extensions) { super() this.#handler = handler this.#extensions = extensions == null ? new Map() : extensions if (this.#extensions.has('permessage-deflate')) { this.#extensions.set('permessage-deflate', new PerMessageDeflate(extensions)) } } /** * @param {Buffer} chunk * @param {() => void} callback */ _write (chunk, _, callback) { this.#buffers.push(chunk) this.#byteOffset += chunk.length this.#loop = true this.run(callback) } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, * or not enough bytes are buffered to parse. */ run (callback) { while (this.#loop) { if (this.#state === parserStates.INFO) { // If there aren't enough bytes to parse the payload length, etc. if (this.#byteOffset < 2) { return callback() } const buffer = this.consume(2) const fin = (buffer[0] & 0x80) !== 0 const opcode = buffer[0] & 0x0F const masked = (buffer[1] & 0x80) === 0x80 const fragmented = !fin && opcode !== opcodes.CONTINUATION const payloadLength = buffer[1] & 0x7F const rsv1 = buffer[0] & 0x40 const rsv2 = buffer[0] & 0x20 const rsv3 = buffer[0] & 0x10 if (!isValidOpcode(opcode)) { failWebsocketConnection(this.#handler, 1002, 'Invalid opcode received') return callback() } if (masked) { failWebsocketConnection(this.#handler, 1002, 'Frame cannot be masked') return callback() } // MUST be 0 unless an extension is negotiated that defines meanings // for non-zero values. If a nonzero value is received and none of // the negotiated extensions defines the meaning of such a nonzero // value, the receiving endpoint MUST _Fail the WebSocket // Connection_. // This document allocates the RSV1 bit of the WebSocket header for // PMCEs and calls the bit the "Per-Message Compressed" bit. On a // WebSocket connection where a PMCE is in use, this bit indicates // whether a message is compressed or not. if (rsv1 !== 0 && !this.#extensions.has('permessage-deflate')) { failWebsocketConnection(this.#handler, 1002, 'Expected RSV1 to be clear.') return } if (rsv2 !== 0 || rsv3 !== 0) { failWebsocketConnection(this.#handler, 1002, 'RSV1, RSV2, RSV3 must be clear') return } if (fragmented && !isTextBinaryFrame(opcode)) { // Only text and binary frames can be fragmented failWebsocketConnection(this.#handler, 1002, 'Invalid frame type was fragmented.') return } // If we are already parsing a text/binary frame and do not receive either // a continuation frame or close frame, fail the connection. if (isTextBinaryFrame(opcode) && this.#fragments.length > 0) { failWebsocketConnection(this.#handler, 1002, 'Expected continuation frame') return } if (this.#info.fragmented && fragmented) { // A fragmented frame can't be fragmented itself failWebsocketConnection(this.#handler, 1002, 'Fragmented frame exceeded 125 bytes.') return } // "All control frames MUST have a payload length of 125 bytes or less // and MUST NOT be fragmented." if ((payloadLength > 125 || fragmented) && isControlFrame(opcode)) { failWebsocketConnection(this.#handler, 1002, 'Control frame either too large or fragmented') return } if (isContinuationFrame(opcode) && this.#fragments.length === 0 && !this.#info.compressed) { failWebsocketConnection(this.#handler, 1002, 'Unexpected continuation frame') return } if (payloadLength <= 125) { this.#info.payloadLength = payloadLength this.#state = parserStates.READ_DATA } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16 } else if (payloadLength === 127) { this.#state = parserStates.PAYLOADLENGTH_64 } if (isTextBinaryFrame(opcode)) { this.#info.binaryType = opcode this.#info.compressed = rsv1 !== 0 } this.#info.opcode = opcode this.#info.masked = masked this.#info.fin = fin this.#info.fragmented = fragmented } else if (this.#state === parserStates.PAYLOADLENGTH_16) { if (this.#byteOffset < 2) { return callback() } const buffer = this.consume(2) this.#info.payloadLength = buffer.readUInt16BE(0) this.#state = parserStates.READ_DATA } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback() } const buffer = this.consume(8) const upper = buffer.readUInt32BE(0) // 2^31 is the maximum bytes an arraybuffer can contain // on 32-bit systems. Although, on 64-bit systems, this is // 2^53-1 bytes. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275 // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e if (upper > 2 ** 31 - 1) { failWebsocketConnection(this.#handler, 1009, 'Received payload length > 2^31 bytes.') return } const lower = buffer.readUInt32BE(4) this.#info.payloadLength = (upper << 8) + lower this.#state = parserStates.READ_DATA } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback() } const body = this.consume(this.#info.payloadLength) if (isControlFrame(this.#info.opcode)) { this.#loop = this.parseControlFrame(body) this.#state = parserStates.INFO } else { if (!this.#info.compressed) { this.writeFragments(body) // If the frame is not fragmented, a message has been received. // If the frame is fragmented, it will terminate with a fin bit set // and an opcode of 0 (continuation), therefore we handle that when // parsing continuation frames, not here. if (!this.#info.fragmented && this.#info.fin) { websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments()) } this.#state = parserStates.INFO } else { this.#extensions.get('permessage-deflate').decompress(body, this.#info.fin, (error, data) => { if (error) { failWebsocketConnection(this.#handler, 1007, error.message) return } this.writeFragments(data) if (!this.#info.fin) { this.#state = parserStates.INFO this.#loop = true this.run(callback) return } websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments()) this.#loop = true this.#state = parserStates.INFO this.run(callback) }) this.#loop = false break } } } } } /** * Take n bytes from the buffered Buffers * @param {number} n * @returns {Buffer} */ consume (n) { if (n > this.#byteOffset) { throw new Error('Called consume() before buffers satiated.') } else if (n === 0) { return emptyBuffer } this.#byteOffset -= n const first = this.#buffers[0] if (first.length > n) { // replace with remaining buffer this.#buffers[0] = first.subarray(n, first.length) return first.subarray(0, n) } else if (first.length === n) { // prefect match return this.#buffers.shift() } else { let offset = 0 // If Buffer.allocUnsafe is used, extra copies will be made because the offset is non-zero. const buffer = Buffer.allocUnsafeSlow(n) while (offset !== n) { const next = this.#buffers[0] const length = next.length if (length + offset === n) { buffer.set(this.#buffers.shift(), offset) break } else if (length + offset > n) { buffer.set(next.subarray(0, n - offset), offset) this.#buffers[0] = next.subarray(n - offset) break } else { buffer.set(this.#buffers.shift(), offset) offset += length } } return buffer } } writeFragments (fragment) { this.#fragmentsBytes += fragment.length this.#fragments.push(fragment) } consumeFragments () { const fragments = this.#fragments if (fragments.length === 1) { // single fragment this.#fragmentsBytes = 0 return fragments.shift() } let offset = 0 // If Buffer.allocUnsafe is used, extra copies will be made because the offset is non-zero. const output = Buffer.allocUnsafeSlow(this.#fragmentsBytes) for (let i = 0; i < fragments.length; ++i) { const buffer = fragments[i] output.set(buffer, offset) offset += buffer.length } this.#fragments = [] this.#fragmentsBytes = 0 return output } parseCloseBody (data) { assert(data.length !== 1) // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 /** @type {number|undefined} */ let code if (data.length >= 2) { // _The WebSocket Connection Close Code_ is // defined as the status code (Section 7.4) contained in the first Close // control frame received by the application code = data.readUInt16BE(0) } if (code !== undefined && !isValidStatusCode(code)) { return { code: 1002, reason: 'Invalid status code', error: true } } // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 /** @type {Buffer} */ let reason = data.subarray(2) // Remove BOM if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { reason = reason.subarray(3) } try { reason = utf8Decode(reason) } catch { return { code: 1007, reason: 'Invalid UTF-8', error: true } } return { code, reason, error: false } } /** * Parses control frames. * @param {Buffer} body */ parseControlFrame (body) { const { opcode, payloadLength } = this.#info if (opcode === opcodes.CLOSE) { if (payloadLength === 1) { failWebsocketConnection(this.#handler, 1002, 'Received close frame with a 1-byte body.') return false } this.#info.closeInfo = this.parseCloseBody(body) if (this.#info.closeInfo.error) { const { code, reason } = this.#info.closeInfo failWebsocketConnection(this.#handler, code, reason) return false } // Upon receiving such a frame, the other peer sends a // Close frame in response, if it hasn't already sent one. if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) { // If an endpoint receives a Close frame and did not previously send a // Close frame, the endpoint MUST send a Close frame in response. (When // sending a Close frame in response, the endpoint typically echos the // status code it received.) let body = emptyBuffer if (this.#info.closeInfo.code) { body = Buffer.allocUnsafe(2) body.writeUInt16BE(this.#info.closeInfo.code, 0) } const closeFrame = new WebsocketFrameSend(body) this.#handler.socket.write(closeFrame.createFrame(opcodes.CLOSE)) this.#handler.closeState.add(sentCloseFrameState.SENT) } // Upon either sending or receiving a Close control frame, it is said // that _The WebSocket Closing Handshake is Started_ and that the // WebSocket connection is in the CLOSING state. this.#handler.readyState = states.CLOSING this.#handler.closeState.add(sentCloseFrameState.RECEIVED) return false } else if (opcode === opcodes.PING) { // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in // response, unless it already received a Close frame. // A Pong frame sent in response to a Ping frame must have identical // "Application data" if (!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) { const frame = new WebsocketFrameSend(body) this.#handler.socket.write(frame.createFrame(opcodes.PONG)) this.#handler.onPing(body) } } else if (opcode === opcodes.PONG) { // A Pong frame MAY be sent unsolicited. This serves as a // unidirectional heartbeat. A response to an unsolicited Pong frame is // not expected. this.#handler.onPong(body) } return true } get closingInfo () { return this.#info.closeInfo } } module.exports = { ByteParser } /***/ }), /***/ 2179: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { WebsocketFrameSend } = __nccwpck_require__(35113) const { opcodes, sendHints } = __nccwpck_require__(69213) const FixedQueue = __nccwpck_require__(46335) /** * @typedef {object} SendQueueNode * @property {Promise | null} promise * @property {((...args: any[]) => any)} callback * @property {Buffer | null} frame */ class SendQueue { /** * @type {FixedQueue} */ #queue = new FixedQueue() /** * @type {boolean} */ #running = false /** @type {import('node:net').Socket} */ #socket constructor (socket) { this.#socket = socket } add (item, cb, hint) { if (hint !== sendHints.blob) { if (!this.#running) { // TODO(@tsctx): support fast-path for string on running if (hint === sendHints.text) { // special fast-path for string const { 0: head, 1: body } = WebsocketFrameSend.createFastTextFrame(item) this.#socket.cork() this.#socket.write(head) this.#socket.write(body, cb) this.#socket.uncork() } else { // direct writing this.#socket.write(createFrame(item, hint), cb) } } else { /** @type {SendQueueNode} */ const node = { promise: null, callback: cb, frame: createFrame(item, hint) } this.#queue.push(node) } return } /** @type {SendQueueNode} */ const node = { promise: item.arrayBuffer().then((ab) => { node.promise = null node.frame = createFrame(ab, hint) }), callback: cb, frame: null } this.#queue.push(node) if (!this.#running) { this.#run() } } async #run () { this.#running = true const queue = this.#queue while (!queue.isEmpty()) { const node = queue.shift() // wait pending promise if (node.promise !== null) { await node.promise } // write this.#socket.write(node.frame, node.callback) // cleanup node.callback = node.frame = null } this.#running = false } } function createFrame (data, hint) { return new WebsocketFrameSend(toBuffer(data, hint)).createFrame(hint === sendHints.text ? opcodes.TEXT : opcodes.BINARY) } function toBuffer (data, hint) { switch (hint) { case sendHints.text: case sendHints.typedArray: return new Uint8Array(data.buffer, data.byteOffset, data.byteLength) case sendHints.arrayBuffer: case sendHints.blob: return new Uint8Array(data) } } module.exports = { SendQueue } /***/ }), /***/ 60446: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { webidl } = __nccwpck_require__(16480) const { validateCloseCodeAndReason } = __nccwpck_require__(19954) const { kConstruct } = __nccwpck_require__(83112) const { kEnumerableProperty } = __nccwpck_require__(46425) class WebSocketError extends DOMException { #closeCode #reason constructor (message = '', init = undefined) { message = webidl.converters.DOMString(message, 'WebSocketError', 'message') // 1. Set this 's name to " WebSocketError ". // 2. Set this 's message to message . super(message, 'WebSocketError') if (init === kConstruct) { return } else if (init !== null) { init = webidl.converters.WebSocketCloseInfo(init) } // 3. Let code be init [" closeCode "] if it exists , or null otherwise. let code = init.closeCode ?? null // 4. Let reason be init [" reason "] if it exists , or the empty string otherwise. const reason = init.reason ?? '' // 5. Validate close code and reason with code and reason . validateCloseCodeAndReason(code, reason) // 6. If reason is non-empty, but code is not set, then set code to 1000 ("Normal Closure"). if (reason.length !== 0 && code === null) { code = 1000 } // 7. Set this 's closeCode to code . this.#closeCode = code // 8. Set this 's reason to reason . this.#reason = reason } get closeCode () { return this.#closeCode } get reason () { return this.#reason } /** * @param {string} message * @param {number|null} code * @param {string} reason */ static createUnvalidatedWebSocketError (message, code, reason) { const error = new WebSocketError(message, kConstruct) error.#closeCode = code error.#reason = reason return error } } const { createUnvalidatedWebSocketError } = WebSocketError delete WebSocketError.createUnvalidatedWebSocketError Object.defineProperties(WebSocketError.prototype, { closeCode: kEnumerableProperty, reason: kEnumerableProperty, [Symbol.toStringTag]: { value: 'WebSocketError', writable: false, enumerable: false, configurable: true } }) webidl.is.WebSocketError = webidl.util.MakeTypeAssertion(WebSocketError) module.exports = { WebSocketError, createUnvalidatedWebSocketError } /***/ }), /***/ 10794: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { createDeferredPromise } = __nccwpck_require__(78499) const { environmentSettingsObject } = __nccwpck_require__(58799) const { states, opcodes, sentCloseFrameState } = __nccwpck_require__(69213) const { webidl } = __nccwpck_require__(16480) const { getURLRecord, isValidSubprotocol, isEstablished, utf8Decode } = __nccwpck_require__(19954) const { establishWebSocketConnection, failWebsocketConnection, closeWebSocketConnection } = __nccwpck_require__(70770) const { types } = __nccwpck_require__(57975) const { channels } = __nccwpck_require__(69709) const { WebsocketFrameSend } = __nccwpck_require__(35113) const { ByteParser } = __nccwpck_require__(98663) const { WebSocketError, createUnvalidatedWebSocketError } = __nccwpck_require__(60446) const { utf8DecodeBytes } = __nccwpck_require__(58799) const { kEnumerableProperty } = __nccwpck_require__(46425) let emittedExperimentalWarning = false class WebSocketStream { // Each WebSocketStream object has an associated url , which is a URL record . /** @type {URL} */ #url // Each WebSocketStream object has an associated opened promise , which is a promise. /** @type {import('../../../util/promise').DeferredPromise} */ #openedPromise // Each WebSocketStream object has an associated closed promise , which is a promise. /** @type {import('../../../util/promise').DeferredPromise} */ #closedPromise // Each WebSocketStream object has an associated readable stream , which is a ReadableStream . /** @type {ReadableStream} */ #readableStream /** @type {ReadableStreamDefaultController} */ #readableStreamController // Each WebSocketStream object has an associated writable stream , which is a WritableStream . /** @type {WritableStream} */ #writableStream // Each WebSocketStream object has an associated boolean handshake aborted , which is initially false. #handshakeAborted = false /** @type {import('../websocket').Handler} */ #handler = { // https://whatpr.org/websockets/48/7b748d3...d5570f3.html#feedback-to-websocket-stream-from-the-protocol onConnectionEstablished: (response, extensions) => this.#onConnectionEstablished(response, extensions), onFail: (_code, _reason) => {}, onMessage: (opcode, data) => this.#onMessage(opcode, data), onParserError: (err) => failWebsocketConnection(this.#handler, null, err.message), onParserDrain: () => this.#handler.socket.resume(), onSocketData: (chunk) => { if (!this.#parser.write(chunk)) { this.#handler.socket.pause() } }, onSocketError: (err) => { this.#handler.readyState = states.CLOSING if (channels.socketError.hasSubscribers) { channels.socketError.publish(err) } this.#handler.socket.destroy() }, onSocketClose: () => this.#onSocketClose(), onPing: () => {}, onPong: () => {}, readyState: states.CONNECTING, socket: null, closeState: new Set(), controller: null, wasEverConnected: false } /** @type {import('../receiver').ByteParser} */ #parser constructor (url, options = undefined) { if (!emittedExperimentalWarning) { process.emitWarning('WebSocketStream is experimental! Expect it to change at any time.', { code: 'UNDICI-WSS' }) emittedExperimentalWarning = true } webidl.argumentLengthCheck(arguments, 1, 'WebSocket') url = webidl.converters.USVString(url) if (options !== null) { options = webidl.converters.WebSocketStreamOptions(options) } // 1. Let baseURL be this 's relevant settings object 's API base URL . const baseURL = environmentSettingsObject.settingsObject.baseUrl // 2. Let urlRecord be the result of getting a URL record given url and baseURL . const urlRecord = getURLRecord(url, baseURL) // 3. Let protocols be options [" protocols "] if it exists , otherwise an empty sequence. const protocols = options.protocols // 4. If any of the values in protocols occur more than once or otherwise fail to match the requirements for elements that comprise the value of ` Sec-WebSocket-Protocol ` fields as defined by The WebSocket Protocol , then throw a " SyntaxError " DOMException . [WSP] if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') } if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') } // 5. Set this 's url to urlRecord . this.#url = urlRecord.toString() // 6. Set this 's opened promise and closed promise to new promises. this.#openedPromise = createDeferredPromise() this.#closedPromise = createDeferredPromise() // 7. Apply backpressure to the WebSocket. // TODO // 8. If options [" signal "] exists , if (options.signal != null) { // 8.1. Let signal be options [" signal "]. const signal = options.signal // 8.2. If signal is aborted , then reject this 's opened promise and closed promise with signal ’s abort reason // and return. if (signal.aborted) { this.#openedPromise.reject(signal.reason) this.#closedPromise.reject(signal.reason) return } // 8.3. Add the following abort steps to signal : signal.addEventListener('abort', () => { // 8.3.1. If the WebSocket connection is not yet established : [WSP] if (!isEstablished(this.#handler.readyState)) { // 8.3.1.1. Fail the WebSocket connection . failWebsocketConnection(this.#handler) // Set this 's ready state to CLOSING . this.#handler.readyState = states.CLOSING // Reject this 's opened promise and closed promise with signal ’s abort reason . this.#openedPromise.reject(signal.reason) this.#closedPromise.reject(signal.reason) // Set this 's handshake aborted to true. this.#handshakeAborted = true } }, { once: true }) } // 9. Let client be this 's relevant settings object . const client = environmentSettingsObject.settingsObject // 10. Run this step in parallel : // 10.1. Establish a WebSocket connection given urlRecord , protocols , and client . [FETCH] this.#handler.controller = establishWebSocketConnection( urlRecord, protocols, client, this.#handler, options ) } // The url getter steps are to return this 's url , serialized . get url () { return this.#url.toString() } // The opened getter steps are to return this 's opened promise . get opened () { return this.#openedPromise.promise } // The closed getter steps are to return this 's closed promise . get closed () { return this.#closedPromise.promise } // The close( closeInfo ) method steps are: close (closeInfo = undefined) { if (closeInfo !== null) { closeInfo = webidl.converters.WebSocketCloseInfo(closeInfo) } // 1. Let code be closeInfo [" closeCode "] if present, or null otherwise. const code = closeInfo.closeCode ?? null // 2. Let reason be closeInfo [" reason "]. const reason = closeInfo.reason // 3. Close the WebSocket with this , code , and reason . closeWebSocketConnection(this.#handler, code, reason, true) } #write (chunk) { // 1. Let promise be a new promise created in stream ’s relevant realm . const promise = createDeferredPromise() // 2. Let data be null. let data = null // 3. Let opcode be null. let opcode = null // 4. If chunk is a BufferSource , if (ArrayBuffer.isView(chunk) || types.isArrayBuffer(chunk)) { // 4.1. Set data to a copy of the bytes given chunk . data = new Uint8Array(ArrayBuffer.isView(chunk) ? new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength) : chunk) // 4.2. Set opcode to a binary frame opcode. opcode = opcodes.BINARY } else { // 5. Otherwise, // 5.1. Let string be the result of converting chunk to an IDL USVString . // If this throws an exception, return a promise rejected with the exception. let string try { string = webidl.converters.DOMString(chunk) } catch (e) { promise.reject(e) return } // 5.2. Set data to the result of UTF-8 encoding string . data = new TextEncoder().encode(string) // 5.3. Set opcode to a text frame opcode. opcode = opcodes.TEXT } // 6. In parallel, // 6.1. Wait until there is sufficient buffer space in stream to send the message. // 6.2. If the closing handshake has not yet started , Send a WebSocket Message to stream comprised of data using opcode . if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) { const frame = new WebsocketFrameSend(data) this.#handler.socket.write(frame.createFrame(opcode), () => { promise.resolve(undefined) }) } // 6.3. Queue a global task on the WebSocket task source given stream ’s relevant global object to resolve promise with undefined. return promise } /** @type {import('../websocket').Handler['onConnectionEstablished']} */ #onConnectionEstablished (response, parsedExtensions) { this.#handler.socket = response.socket const parser = new ByteParser(this.#handler, parsedExtensions) parser.on('drain', () => this.#handler.onParserDrain()) parser.on('error', (err) => this.#handler.onParserError(err)) this.#parser = parser // 1. Change stream ’s ready state to OPEN (1). this.#handler.readyState = states.OPEN // 2. Set stream ’s was ever connected to true. // This is done in the opening handshake. // 3. Let extensions be the extensions in use . const extensions = parsedExtensions ?? '' // 4. Let protocol be the subprotocol in use . const protocol = response.headersList.get('sec-websocket-protocol') ?? '' // 5. Let pullAlgorithm be an action that pulls bytes from stream . // 6. Let cancelAlgorithm be an action that cancels stream with reason , given reason . // 7. Let readable be a new ReadableStream . // 8. Set up readable with pullAlgorithm and cancelAlgorithm . const readable = new ReadableStream({ start: (controller) => { this.#readableStreamController = controller }, pull (controller) { let chunk while (controller.desiredSize > 0 && (chunk = response.socket.read()) !== null) { controller.enqueue(chunk) } }, cancel: (reason) => this.#cancel(reason) }) // 9. Let writeAlgorithm be an action that writes chunk to stream , given chunk . // 10. Let closeAlgorithm be an action that closes stream . // 11. Let abortAlgorithm be an action that aborts stream with reason , given reason . // 12. Let writable be a new WritableStream . // 13. Set up writable with writeAlgorithm , closeAlgorithm , and abortAlgorithm . const writable = new WritableStream({ write: (chunk) => this.#write(chunk), close: () => closeWebSocketConnection(this.#handler, null, null), abort: (reason) => this.#closeUsingReason(reason) }) // Set stream ’s readable stream to readable . this.#readableStream = readable // Set stream ’s writable stream to writable . this.#writableStream = writable // Resolve stream ’s opened promise with WebSocketOpenInfo «[ " extensions " → extensions , " protocol " → protocol , " readable " → readable , " writable " → writable ]». this.#openedPromise.resolve({ extensions, protocol, readable, writable }) } /** @type {import('../websocket').Handler['onMessage']} */ #onMessage (type, data) { // 1. If stream’s ready state is not OPEN (1), then return. if (this.#handler.readyState !== states.OPEN) { return } // 2. Let chunk be determined by switching on type: // - type indicates that the data is Text // a new DOMString containing data // - type indicates that the data is Binary // a new Uint8Array object, created in the relevant Realm of the // WebSocketStream object, whose contents are data let chunk if (type === opcodes.TEXT) { try { chunk = utf8Decode(data) } catch { failWebsocketConnection(this.#handler, 'Received invalid UTF-8 in text frame.') return } } else if (type === opcodes.BINARY) { chunk = new Uint8Array(data.buffer, data.byteOffset, data.byteLength) } // 3. Enqueue chunk into stream’s readable stream. this.#readableStreamController.enqueue(chunk) // 4. Apply backpressure to the WebSocket. } /** @type {import('../websocket').Handler['onSocketClose']} */ #onSocketClose () { const wasClean = this.#handler.closeState.has(sentCloseFrameState.SENT) && this.#handler.closeState.has(sentCloseFrameState.RECEIVED) // 1. Change the ready state to CLOSED (3). this.#handler.readyState = states.CLOSED // 2. If stream ’s handshake aborted is true, then return. if (this.#handshakeAborted) { return } // 3. If stream ’s was ever connected is false, then reject stream ’s opened promise with a new WebSocketError. if (!this.#handler.wasEverConnected) { this.#openedPromise.reject(new WebSocketError('Socket never opened')) } const result = this.#parser.closingInfo // 4. Let code be the WebSocket connection close code . // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 // If this Close control frame contains no status code, _The WebSocket // Connection Close Code_ is considered to be 1005. If _The WebSocket // Connection is Closed_ and no Close control frame was received by the // endpoint (such as could occur if the underlying transport connection // is lost), _The WebSocket Connection Close Code_ is considered to be // 1006. let code = result?.code ?? 1005 if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) { code = 1006 } // 5. Let reason be the result of applying UTF-8 decode without BOM to the WebSocket connection close reason . const reason = result?.reason == null ? '' : utf8DecodeBytes(Buffer.from(result.reason)) // 6. If the connection was closed cleanly , if (wasClean) { // 6.1. Close stream ’s readable stream . this.#readableStreamController.close() // 6.2. Error stream ’s writable stream with an " InvalidStateError " DOMException indicating that a closed WebSocketStream cannot be written to. if (!this.#writableStream.locked) { this.#writableStream.abort(new DOMException('A closed WebSocketStream cannot be written to', 'InvalidStateError')) } // 6.3. Resolve stream ’s closed promise with WebSocketCloseInfo «[ " closeCode " → code , " reason " → reason ]». this.#closedPromise.resolve({ closeCode: code, reason }) } else { // 7. Otherwise, // 7.1. Let error be a new WebSocketError whose closeCode is code and reason is reason . const error = createUnvalidatedWebSocketError('unclean close', code, reason) // 7.2. Error stream ’s readable stream with error . this.#readableStreamController.error(error) // 7.3. Error stream ’s writable stream with error . this.#writableStream.abort(error) // 7.4. Reject stream ’s closed promise with error . this.#closedPromise.reject(error) } } #closeUsingReason (reason) { // 1. Let code be null. let code = null // 2. Let reasonString be the empty string. let reasonString = '' // 3. If reason implements WebSocketError , if (webidl.is.WebSocketError(reason)) { // 3.1. Set code to reason ’s closeCode . code = reason.closeCode // 3.2. Set reasonString to reason ’s reason . reasonString = reason.reason } // 4. Close the WebSocket with stream , code , and reasonString . If this throws an exception, // discard code and reasonString and close the WebSocket with stream . closeWebSocketConnection(this.#handler, code, reasonString) } // To cancel a WebSocketStream stream given reason , close using reason giving stream and reason . #cancel (reason) { this.#closeUsingReason(reason) } } Object.defineProperties(WebSocketStream.prototype, { url: kEnumerableProperty, opened: kEnumerableProperty, closed: kEnumerableProperty, close: kEnumerableProperty, [Symbol.toStringTag]: { value: 'WebSocketStream', writable: false, enumerable: false, configurable: true } }) webidl.converters.WebSocketStreamOptions = webidl.dictionaryConverter([ { key: 'protocols', converter: webidl.sequenceConverter(webidl.converters.USVString), defaultValue: () => [] }, { key: 'signal', converter: webidl.nullableConverter(webidl.converters.AbortSignal), defaultValue: () => null } ]) webidl.converters.WebSocketCloseInfo = webidl.dictionaryConverter([ { key: 'closeCode', converter: (V) => webidl.converters['unsigned short'](V, { enforceRange: true }) }, { key: 'reason', converter: webidl.converters.USVString, defaultValue: () => '' } ]) module.exports = { WebSocketStream } /***/ }), /***/ 19954: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { states, opcodes } = __nccwpck_require__(69213) const { isUtf8 } = __nccwpck_require__(4573) const { collectASequenceOfCodePointsFast, removeHTTPWhitespace } = __nccwpck_require__(38675) /** * @param {number} readyState * @returns {boolean} */ function isConnecting (readyState) { // If the WebSocket connection is not yet established, and the connection // is not yet closed, then the WebSocket connection is in the CONNECTING state. return readyState === states.CONNECTING } /** * @param {number} readyState * @returns {boolean} */ function isEstablished (readyState) { // If the server's response is validated as provided for above, it is // said that _The WebSocket Connection is Established_ and that the // WebSocket Connection is in the OPEN state. return readyState === states.OPEN } /** * @param {number} readyState * @returns {boolean} */ function isClosing (readyState) { // Upon either sending or receiving a Close control frame, it is said // that _The WebSocket Closing Handshake is Started_ and that the // WebSocket connection is in the CLOSING state. return readyState === states.CLOSING } /** * @param {number} readyState * @returns {boolean} */ function isClosed (readyState) { return readyState === states.CLOSED } /** * @see https://dom.spec.whatwg.org/#concept-event-fire * @param {string} e * @param {EventTarget} target * @param {(...args: ConstructorParameters) => Event} eventFactory * @param {EventInit | undefined} eventInitDict * @returns {void} */ function fireEvent (e, target, eventFactory = (type, init) => new Event(type, init), eventInitDict = {}) { // 1. If eventConstructor is not given, then let eventConstructor be Event. // 2. Let event be the result of creating an event given eventConstructor, // in the relevant realm of target. // 3. Initialize event’s type attribute to e. const event = eventFactory(e, eventInitDict) // 4. Initialize any other IDL attributes of event as described in the // invocation of this algorithm. // 5. Return the result of dispatching event at target, with legacy target // override flag set if set. target.dispatchEvent(event) } /** * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol * @param {import('./websocket').Handler} handler * @param {number} type Opcode * @param {Buffer} data application data * @returns {void} */ function websocketMessageReceived (handler, type, data) { handler.onMessage(type, data) } /** * @param {Buffer} buffer * @returns {ArrayBuffer} */ function toArrayBuffer (buffer) { if (buffer.byteLength === buffer.buffer.byteLength) { return buffer.buffer } return new Uint8Array(buffer).buffer } /** * @see https://datatracker.ietf.org/doc/html/rfc6455 * @see https://datatracker.ietf.org/doc/html/rfc2616 * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407 * @param {string} protocol * @returns {boolean} */ function isValidSubprotocol (protocol) { // If present, this value indicates one // or more comma-separated subprotocol the client wishes to speak, // ordered by preference. The elements that comprise this value // MUST be non-empty strings with characters in the range U+0021 to // U+007E not including separator characters as defined in // [RFC2616] and MUST all be unique strings. if (protocol.length === 0) { return false } for (let i = 0; i < protocol.length; ++i) { const code = protocol.charCodeAt(i) if ( code < 0x21 || // CTL, contains SP (0x20) and HT (0x09) code > 0x7E || code === 0x22 || // " code === 0x28 || // ( code === 0x29 || // ) code === 0x2C || // , code === 0x2F || // / code === 0x3A || // : code === 0x3B || // ; code === 0x3C || // < code === 0x3D || // = code === 0x3E || // > code === 0x3F || // ? code === 0x40 || // @ code === 0x5B || // [ code === 0x5C || // \ code === 0x5D || // ] code === 0x7B || // { code === 0x7D // } ) { return false } } return true } /** * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4 * @param {number} code * @returns {boolean} */ function isValidStatusCode (code) { if (code >= 1000 && code < 1015) { return ( code !== 1004 && // reserved code !== 1005 && // "MUST NOT be set as a status code" code !== 1006 // "MUST NOT be set as a status code" ) } return code >= 3000 && code <= 4999 } /** * @see https://datatracker.ietf.org/doc/html/rfc6455#section-5.5 * @param {number} opcode * @returns {boolean} */ function isControlFrame (opcode) { return ( opcode === opcodes.CLOSE || opcode === opcodes.PING || opcode === opcodes.PONG ) } /** * @param {number} opcode * @returns {boolean} */ function isContinuationFrame (opcode) { return opcode === opcodes.CONTINUATION } /** * @param {number} opcode * @returns {boolean} */ function isTextBinaryFrame (opcode) { return opcode === opcodes.TEXT || opcode === opcodes.BINARY } /** * * @param {number} opcode * @returns {boolean} */ function isValidOpcode (opcode) { return isTextBinaryFrame(opcode) || isContinuationFrame(opcode) || isControlFrame(opcode) } /** * Parses a Sec-WebSocket-Extensions header value. * @param {string} extensions * @returns {Map} */ // TODO(@Uzlopak, @KhafraDev): make compliant https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 function parseExtensions (extensions) { const position = { position: 0 } const extensionList = new Map() while (position.position < extensions.length) { const pair = collectASequenceOfCodePointsFast(';', extensions, position) const [name, value = ''] = pair.split('=', 2) extensionList.set( removeHTTPWhitespace(name, true, false), removeHTTPWhitespace(value, false, true) ) position.position++ } return extensionList } /** * @see https://www.rfc-editor.org/rfc/rfc7692#section-7.1.2.2 * @description "client-max-window-bits = 1*DIGIT" * @param {string} value * @returns {boolean} */ function isValidClientWindowBits (value) { for (let i = 0; i < value.length; i++) { const byte = value.charCodeAt(i) if (byte < 0x30 || byte > 0x39) { return false } } return true } /** * @see https://whatpr.org/websockets/48/7b748d3...d5570f3.html#get-a-url-record * @param {string} url * @param {string} [baseURL] */ function getURLRecord (url, baseURL) { // 1. Let urlRecord be the result of applying the URL parser to url with baseURL . // 2. If urlRecord is failure, then throw a " SyntaxError " DOMException . let urlRecord try { urlRecord = new URL(url, baseURL) } catch (e) { throw new DOMException(e, 'SyntaxError') } // 3. If urlRecord ’s scheme is " http ", then set urlRecord ’s scheme to " ws ". // 4. Otherwise, if urlRecord ’s scheme is " https ", set urlRecord ’s scheme to " wss ". if (urlRecord.protocol === 'http:') { urlRecord.protocol = 'ws:' } else if (urlRecord.protocol === 'https:') { urlRecord.protocol = 'wss:' } // 5. If urlRecord ’s scheme is not " ws " or " wss ", then throw a " SyntaxError " DOMException . if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') { throw new DOMException('expected a ws: or wss: url', 'SyntaxError') } // If urlRecord ’s fragment is non-null, then throw a " SyntaxError " DOMException . if (urlRecord.hash.length || urlRecord.href.endsWith('#')) { throw new DOMException('hash', 'SyntaxError') } // Return urlRecord . return urlRecord } // https://whatpr.org/websockets/48.html#validate-close-code-and-reason function validateCloseCodeAndReason (code, reason) { // 1. If code is not null, but is neither an integer equal to // 1000 nor an integer in the range 3000 to 4999, inclusive, // throw an "InvalidAccessError" DOMException. if (code !== null) { if (code !== 1000 && (code < 3000 || code > 4999)) { throw new DOMException('invalid code', 'InvalidAccessError') } } // 2. If reason is not null, then: if (reason !== null) { // 2.1. Let reasonBytes be the result of UTF-8 encoding reason. // 2.2. If reasonBytes is longer than 123 bytes, then throw a // "SyntaxError" DOMException. const reasonBytesLength = Buffer.byteLength(reason) if (reasonBytesLength > 123) { throw new DOMException(`Reason must be less than 123 bytes; received ${reasonBytesLength}`, 'SyntaxError') } } } /** * Converts a Buffer to utf-8, even on platforms without icu. * @type {(buffer: Buffer) => string} */ const utf8Decode = (() => { if (typeof process.versions.icu === 'string') { const fatalDecoder = new TextDecoder('utf-8', { fatal: true }) return fatalDecoder.decode.bind(fatalDecoder) } return function (buffer) { if (isUtf8(buffer)) { return buffer.toString('utf-8') } throw new TypeError('Invalid utf-8 received.') } })() module.exports = { isConnecting, isEstablished, isClosing, isClosed, fireEvent, isValidSubprotocol, isValidStatusCode, websocketMessageReceived, utf8Decode, isControlFrame, isContinuationFrame, isTextBinaryFrame, isValidOpcode, parseExtensions, isValidClientWindowBits, toArrayBuffer, getURLRecord, validateCloseCodeAndReason } /***/ }), /***/ 52279: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { webidl } = __nccwpck_require__(16480) const { URLSerializer } = __nccwpck_require__(38675) const { environmentSettingsObject } = __nccwpck_require__(58799) const { staticPropertyDescriptors, states, sentCloseFrameState, sendHints, opcodes } = __nccwpck_require__(69213) const { isConnecting, isEstablished, isClosing, isClosed, isValidSubprotocol, fireEvent, utf8Decode, toArrayBuffer, getURLRecord } = __nccwpck_require__(19954) const { establishWebSocketConnection, closeWebSocketConnection, failWebsocketConnection } = __nccwpck_require__(70770) const { ByteParser } = __nccwpck_require__(98663) const { kEnumerableProperty } = __nccwpck_require__(46425) const { getGlobalDispatcher } = __nccwpck_require__(14266) const { types } = __nccwpck_require__(57975) const { ErrorEvent, CloseEvent, createFastMessageEvent } = __nccwpck_require__(91979) const { SendQueue } = __nccwpck_require__(2179) const { WebsocketFrameSend } = __nccwpck_require__(35113) const { channels } = __nccwpck_require__(69709) /** * @typedef {object} Handler * @property {(response: any, extensions?: string[]) => void} onConnectionEstablished * @property {(code: number, reason: any) => void} onFail * @property {(opcode: number, data: Buffer) => void} onMessage * @property {(error: Error) => void} onParserError * @property {() => void} onParserDrain * @property {(chunk: Buffer) => void} onSocketData * @property {(err: Error) => void} onSocketError * @property {() => void} onSocketClose * @property {(body: Buffer) => void} onPing * @property {(body: Buffer) => void} onPong * * @property {number} readyState * @property {import('stream').Duplex} socket * @property {Set} closeState * @property {import('../fetch/index').Fetch} controller * @property {boolean} [wasEverConnected=false] */ // https://websockets.spec.whatwg.org/#interface-definition class WebSocket extends EventTarget { #events = { open: null, error: null, close: null, message: null } #bufferedAmount = 0 #protocol = '' #extensions = '' /** @type {SendQueue} */ #sendQueue /** @type {Handler} */ #handler = { onConnectionEstablished: (response, extensions) => this.#onConnectionEstablished(response, extensions), onFail: (code, reason, cause) => this.#onFail(code, reason, cause), onMessage: (opcode, data) => this.#onMessage(opcode, data), onParserError: (err) => failWebsocketConnection(this.#handler, null, err.message), onParserDrain: () => this.#onParserDrain(), onSocketData: (chunk) => { if (!this.#parser.write(chunk)) { this.#handler.socket.pause() } }, onSocketError: (err) => { this.#handler.readyState = states.CLOSING if (channels.socketError.hasSubscribers) { channels.socketError.publish(err) } this.#handler.socket.destroy() }, onSocketClose: () => this.#onSocketClose(), onPing: (body) => { if (channels.ping.hasSubscribers) { channels.ping.publish({ payload: body, websocket: this }) } }, onPong: (body) => { if (channels.pong.hasSubscribers) { channels.pong.publish({ payload: body, websocket: this }) } }, readyState: states.CONNECTING, socket: null, closeState: new Set(), controller: null, wasEverConnected: false } #url #binaryType /** @type {import('./receiver').ByteParser} */ #parser /** * @param {string} url * @param {string|string[]} protocols */ constructor (url, protocols = []) { super() webidl.util.markAsUncloneable(this) const prefix = 'WebSocket constructor' webidl.argumentLengthCheck(arguments, 1, prefix) const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols, prefix, 'options') url = webidl.converters.USVString(url) protocols = options.protocols // 1. Let baseURL be this's relevant settings object's API base URL. const baseURL = environmentSettingsObject.settingsObject.baseUrl // 2. Let urlRecord be the result of getting a URL record given url and baseURL. const urlRecord = getURLRecord(url, baseURL) // 3. If protocols is a string, set protocols to a sequence consisting // of just that string. if (typeof protocols === 'string') { protocols = [protocols] } // 4. If any of the values in protocols occur more than once or otherwise // fail to match the requirements for elements that comprise the value // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket // protocol, then throw a "SyntaxError" DOMException. if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') } if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') } // 5. Set this's url to urlRecord. this.#url = new URL(urlRecord.href) // 6. Let client be this's relevant settings object. const client = environmentSettingsObject.settingsObject // 7. Run this step in parallel: // 7.1. Establish a WebSocket connection given urlRecord, protocols, // and client. this.#handler.controller = establishWebSocketConnection( urlRecord, protocols, client, this.#handler, options ) // Each WebSocket object has an associated ready state, which is a // number representing the state of the connection. Initially it must // be CONNECTING (0). this.#handler.readyState = WebSocket.CONNECTING // The extensions attribute must initially return the empty string. // The protocol attribute must initially return the empty string. // Each WebSocket object has an associated binary type, which is a // BinaryType. Initially it must be "blob". this.#binaryType = 'blob' } /** * @see https://websockets.spec.whatwg.org/#dom-websocket-close * @param {number|undefined} code * @param {string|undefined} reason */ close (code = undefined, reason = undefined) { webidl.brandCheck(this, WebSocket) const prefix = 'WebSocket.close' if (code !== undefined) { code = webidl.converters['unsigned short'](code, prefix, 'code', { clamp: true }) } if (reason !== undefined) { reason = webidl.converters.USVString(reason) } // 1. If code is the special value "missing", then set code to null. code ??= null // 2. If reason is the special value "missing", then set reason to the empty string. reason ??= '' // 3. Close the WebSocket with this, code, and reason. closeWebSocketConnection(this.#handler, code, reason, true) } /** * @see https://websockets.spec.whatwg.org/#dom-websocket-send * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data */ send (data) { webidl.brandCheck(this, WebSocket) const prefix = 'WebSocket.send' webidl.argumentLengthCheck(arguments, 1, prefix) data = webidl.converters.WebSocketSendData(data, prefix, 'data') // 1. If this's ready state is CONNECTING, then throw an // "InvalidStateError" DOMException. if (isConnecting(this.#handler.readyState)) { throw new DOMException('Sent before connected.', 'InvalidStateError') } // 2. Run the appropriate set of steps from the following list: // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1 // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 if (!isEstablished(this.#handler.readyState) || isClosing(this.#handler.readyState)) { return } // If data is a string if (typeof data === 'string') { // If the WebSocket connection is established and the WebSocket // closing handshake has not yet started, then the user agent // must send a WebSocket Message comprised of the data argument // using a text frame opcode; if the data cannot be sent, e.g. // because it would need to be buffered but the buffer is full, // the user agent must flag the WebSocket as full and then close // the WebSocket connection. Any invocation of this method with a // string argument that does not throw an exception must increase // the bufferedAmount attribute by the number of bytes needed to // express the argument as UTF-8. const buffer = Buffer.from(data) this.#bufferedAmount += buffer.byteLength this.#sendQueue.add(buffer, () => { this.#bufferedAmount -= buffer.byteLength }, sendHints.text) } else if (types.isArrayBuffer(data)) { // If the WebSocket connection is established, and the WebSocket // closing handshake has not yet started, then the user agent must // send a WebSocket Message comprised of data using a binary frame // opcode; if the data cannot be sent, e.g. because it would need // to be buffered but the buffer is full, the user agent must flag // the WebSocket as full and then close the WebSocket connection. // The data to be sent is the data stored in the buffer described // by the ArrayBuffer object. Any invocation of this method with an // ArrayBuffer argument that does not throw an exception must // increase the bufferedAmount attribute by the length of the // ArrayBuffer in bytes. this.#bufferedAmount += data.byteLength this.#sendQueue.add(data, () => { this.#bufferedAmount -= data.byteLength }, sendHints.arrayBuffer) } else if (ArrayBuffer.isView(data)) { // If the WebSocket connection is established, and the WebSocket // closing handshake has not yet started, then the user agent must // send a WebSocket Message comprised of data using a binary frame // opcode; if the data cannot be sent, e.g. because it would need to // be buffered but the buffer is full, the user agent must flag the // WebSocket as full and then close the WebSocket connection. The // data to be sent is the data stored in the section of the buffer // described by the ArrayBuffer object that data references. Any // invocation of this method with this kind of argument that does // not throw an exception must increase the bufferedAmount attribute // by the length of data’s buffer in bytes. this.#bufferedAmount += data.byteLength this.#sendQueue.add(data, () => { this.#bufferedAmount -= data.byteLength }, sendHints.typedArray) } else if (webidl.is.Blob(data)) { // If the WebSocket connection is established, and the WebSocket // closing handshake has not yet started, then the user agent must // send a WebSocket Message comprised of data using a binary frame // opcode; if the data cannot be sent, e.g. because it would need to // be buffered but the buffer is full, the user agent must flag the // WebSocket as full and then close the WebSocket connection. The data // to be sent is the raw data represented by the Blob object. Any // invocation of this method with a Blob argument that does not throw // an exception must increase the bufferedAmount attribute by the size // of the Blob object’s raw data, in bytes. this.#bufferedAmount += data.size this.#sendQueue.add(data, () => { this.#bufferedAmount -= data.size }, sendHints.blob) } } get readyState () { webidl.brandCheck(this, WebSocket) // The readyState getter steps are to return this's ready state. return this.#handler.readyState } get bufferedAmount () { webidl.brandCheck(this, WebSocket) return this.#bufferedAmount } get url () { webidl.brandCheck(this, WebSocket) // The url getter steps are to return this's url, serialized. return URLSerializer(this.#url) } get extensions () { webidl.brandCheck(this, WebSocket) return this.#extensions } get protocol () { webidl.brandCheck(this, WebSocket) return this.#protocol } get onopen () { webidl.brandCheck(this, WebSocket) return this.#events.open } set onopen (fn) { webidl.brandCheck(this, WebSocket) if (this.#events.open) { this.removeEventListener('open', this.#events.open) } if (typeof fn === 'function') { this.#events.open = fn this.addEventListener('open', fn) } else { this.#events.open = null } } get onerror () { webidl.brandCheck(this, WebSocket) return this.#events.error } set onerror (fn) { webidl.brandCheck(this, WebSocket) if (this.#events.error) { this.removeEventListener('error', this.#events.error) } if (typeof fn === 'function') { this.#events.error = fn this.addEventListener('error', fn) } else { this.#events.error = null } } get onclose () { webidl.brandCheck(this, WebSocket) return this.#events.close } set onclose (fn) { webidl.brandCheck(this, WebSocket) if (this.#events.close) { this.removeEventListener('close', this.#events.close) } if (typeof fn === 'function') { this.#events.close = fn this.addEventListener('close', fn) } else { this.#events.close = null } } get onmessage () { webidl.brandCheck(this, WebSocket) return this.#events.message } set onmessage (fn) { webidl.brandCheck(this, WebSocket) if (this.#events.message) { this.removeEventListener('message', this.#events.message) } if (typeof fn === 'function') { this.#events.message = fn this.addEventListener('message', fn) } else { this.#events.message = null } } get binaryType () { webidl.brandCheck(this, WebSocket) return this.#binaryType } set binaryType (type) { webidl.brandCheck(this, WebSocket) if (type !== 'blob' && type !== 'arraybuffer') { this.#binaryType = 'blob' } else { this.#binaryType = type } } /** * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol */ #onConnectionEstablished (response, parsedExtensions) { // processResponse is called when the "response’s header list has been received and initialized." // once this happens, the connection is open this.#handler.socket = response.socket const parser = new ByteParser(this.#handler, parsedExtensions) parser.on('drain', () => this.#handler.onParserDrain()) parser.on('error', (err) => this.#handler.onParserError(err)) this.#parser = parser this.#sendQueue = new SendQueue(response.socket) // 1. Change the ready state to OPEN (1). this.#handler.readyState = states.OPEN // 2. Change the extensions attribute’s value to the extensions in use, if // it is not the null value. // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 const extensions = response.headersList.get('sec-websocket-extensions') if (extensions !== null) { this.#extensions = extensions } // 3. Change the protocol attribute’s value to the subprotocol in use, if // it is not the null value. // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9 const protocol = response.headersList.get('sec-websocket-protocol') if (protocol !== null) { this.#protocol = protocol } // 4. Fire an event named open at the WebSocket object. fireEvent('open', this) if (channels.open.hasSubscribers) { channels.open.publish({ address: response.socket.address(), protocol: this.#protocol, extensions: this.#extensions, websocket: this }) } } #onFail (code, reason, cause) { if (reason) { // TODO: process.nextTick fireEvent('error', this, (type, init) => new ErrorEvent(type, init), { error: new Error(reason, cause ? { cause } : undefined), message: reason }) } if (!this.#handler.wasEverConnected) { this.#handler.readyState = states.CLOSED // If the WebSocket connection could not be established, it is also said // that _The WebSocket Connection is Closed_, but not _cleanly_. fireEvent('close', this, (type, init) => new CloseEvent(type, init), { wasClean: false, code, reason }) } } #onMessage (type, data) { // 1. If ready state is not OPEN (1), then return. if (this.#handler.readyState !== states.OPEN) { return } // 2. Let dataForEvent be determined by switching on type and binary type: let dataForEvent if (type === opcodes.TEXT) { // -> type indicates that the data is Text // a new DOMString containing data try { dataForEvent = utf8Decode(data) } catch { failWebsocketConnection(this.#handler, 1007, 'Received invalid UTF-8 in text frame.') return } } else if (type === opcodes.BINARY) { if (this.#binaryType === 'blob') { // -> type indicates that the data is Binary and binary type is "blob" // a new Blob object, created in the relevant Realm of the WebSocket // object, that represents data as its raw data dataForEvent = new Blob([data]) } else { // -> type indicates that the data is Binary and binary type is "arraybuffer" // a new ArrayBuffer object, created in the relevant Realm of the // WebSocket object, whose contents are data dataForEvent = toArrayBuffer(data) } } // 3. Fire an event named message at the WebSocket object, using MessageEvent, // with the origin attribute initialized to the serialization of the WebSocket // object’s url's origin, and the data attribute initialized to dataForEvent. fireEvent('message', this, createFastMessageEvent, { origin: this.#url.origin, data: dataForEvent }) } #onParserDrain () { this.#handler.socket.resume() } /** * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 */ #onSocketClose () { // If the TCP connection was closed after the // WebSocket closing handshake was completed, the WebSocket connection // is said to have been closed _cleanly_. const wasClean = this.#handler.closeState.has(sentCloseFrameState.SENT) && this.#handler.closeState.has(sentCloseFrameState.RECEIVED) let code = 1005 let reason = '' const result = this.#parser.closingInfo if (result && !result.error) { code = result.code ?? 1005 reason = result.reason } else if (!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) { // If _The WebSocket // Connection is Closed_ and no Close control frame was received by the // endpoint (such as could occur if the underlying transport connection // is lost), _The WebSocket Connection Close Code_ is considered to be // 1006. code = 1006 } // 1. Change the ready state to CLOSED (3). this.#handler.readyState = states.CLOSED // 2. If the user agent was required to fail the WebSocket // connection, or if the WebSocket connection was closed // after being flagged as full, fire an event named error // at the WebSocket object. // TODO // 3. Fire an event named close at the WebSocket object, // using CloseEvent, with the wasClean attribute // initialized to true if the connection closed cleanly // and false otherwise, the code attribute initialized to // the WebSocket connection close code, and the reason // attribute initialized to the result of applying UTF-8 // decode without BOM to the WebSocket connection close // reason. // TODO: process.nextTick fireEvent('close', this, (type, init) => new CloseEvent(type, init), { wasClean, code, reason }) if (channels.close.hasSubscribers) { channels.close.publish({ websocket: this, code, reason }) } } /** * @param {WebSocket} ws * @param {Buffer|undefined} buffer */ static ping (ws, buffer) { if (Buffer.isBuffer(buffer)) { if (buffer.length > 125) { throw new TypeError('A PING frame cannot have a body larger than 125 bytes.') } } else if (buffer !== undefined) { throw new TypeError('Expected buffer payload') } // An endpoint MAY send a Ping frame any time after the connection is // established and before the connection is closed. const readyState = ws.#handler.readyState if (isEstablished(readyState) && !isClosing(readyState) && !isClosed(readyState)) { const frame = new WebsocketFrameSend(buffer) ws.#handler.socket.write(frame.createFrame(opcodes.PING)) } } } const { ping } = WebSocket Reflect.deleteProperty(WebSocket, 'ping') // https://websockets.spec.whatwg.org/#dom-websocket-connecting WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING // https://websockets.spec.whatwg.org/#dom-websocket-open WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN // https://websockets.spec.whatwg.org/#dom-websocket-closing WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING // https://websockets.spec.whatwg.org/#dom-websocket-closed WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED Object.defineProperties(WebSocket.prototype, { CONNECTING: staticPropertyDescriptors, OPEN: staticPropertyDescriptors, CLOSING: staticPropertyDescriptors, CLOSED: staticPropertyDescriptors, url: kEnumerableProperty, readyState: kEnumerableProperty, bufferedAmount: kEnumerableProperty, onopen: kEnumerableProperty, onerror: kEnumerableProperty, onclose: kEnumerableProperty, close: kEnumerableProperty, onmessage: kEnumerableProperty, binaryType: kEnumerableProperty, send: kEnumerableProperty, extensions: kEnumerableProperty, protocol: kEnumerableProperty, [Symbol.toStringTag]: { value: 'WebSocket', writable: false, enumerable: false, configurable: true } }) Object.defineProperties(WebSocket, { CONNECTING: staticPropertyDescriptors, OPEN: staticPropertyDescriptors, CLOSING: staticPropertyDescriptors, CLOSED: staticPropertyDescriptors }) webidl.converters['sequence'] = webidl.sequenceConverter( webidl.converters.DOMString ) webidl.converters['DOMString or sequence'] = function (V, prefix, argument) { if (webidl.util.Type(V) === webidl.util.Types.OBJECT && Symbol.iterator in V) { return webidl.converters['sequence'](V) } return webidl.converters.DOMString(V, prefix, argument) } // This implements the proposal made in https://github.com/whatwg/websockets/issues/42 webidl.converters.WebSocketInit = webidl.dictionaryConverter([ { key: 'protocols', converter: webidl.converters['DOMString or sequence'], defaultValue: () => new Array(0) }, { key: 'dispatcher', converter: webidl.converters.any, defaultValue: () => getGlobalDispatcher() }, { key: 'headers', converter: webidl.nullableConverter(webidl.converters.HeadersInit) } ]) webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) { if (webidl.util.Type(V) === webidl.util.Types.OBJECT && !(Symbol.iterator in V)) { return webidl.converters.WebSocketInit(V) } return { protocols: webidl.converters['DOMString or sequence'](V) } } webidl.converters.WebSocketSendData = function (V) { if (webidl.util.Type(V) === webidl.util.Types.OBJECT) { if (webidl.is.Blob(V)) { return V } if (ArrayBuffer.isView(V) || types.isArrayBuffer(V)) { return V } } return webidl.converters.USVString(V) } module.exports = { WebSocket, ping } /***/ }), /***/ 97087: /***/ ((module) => { module.exports = function (xs, fn) { var res = []; for (var i = 0; i < xs.length; i++) { var x = fn(xs[i], i); if (isArray(x)) res.push.apply(res, x); else res.push(x); } return res; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; /***/ }), /***/ 85353: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.attributeRules = void 0; var boolbase_1 = __importDefault(__nccwpck_require__(45265)); /** * All reserved characters in a regex, used for escaping. * * Taken from XRegExp, (c) 2007-2020 Steven Levithan under the MIT license * https://github.com/slevithan/xregexp/blob/95eeebeb8fac8754d54eafe2b4743661ac1cf028/src/xregexp.js#L794 */ var reChars = /[-[\]{}()*+?.,\\^$|#\s]/g; function escapeRegex(value) { return value.replace(reChars, "\\$&"); } /** * Attributes that are case-insensitive in HTML. * * @private * @see https://html.spec.whatwg.org/multipage/semantics-other.html#case-sensitivity-of-selectors */ var caseInsensitiveAttributes = new Set([ "accept", "accept-charset", "align", "alink", "axis", "bgcolor", "charset", "checked", "clear", "codetype", "color", "compact", "declare", "defer", "dir", "direction", "disabled", "enctype", "face", "frame", "hreflang", "http-equiv", "lang", "language", "link", "media", "method", "multiple", "nohref", "noresize", "noshade", "nowrap", "readonly", "rel", "rev", "rules", "scope", "scrolling", "selected", "shape", "target", "text", "type", "valign", "valuetype", "vlink", ]); function shouldIgnoreCase(selector, options) { return typeof selector.ignoreCase === "boolean" ? selector.ignoreCase : selector.ignoreCase === "quirks" ? !!options.quirksMode : !options.xmlMode && caseInsensitiveAttributes.has(selector.name); } /** * Attribute selectors */ exports.attributeRules = { equals: function (next, data, options) { var adapter = options.adapter; var name = data.name; var value = data.value; if (shouldIgnoreCase(data, options)) { value = value.toLowerCase(); return function (elem) { var attr = adapter.getAttributeValue(elem, name); return (attr != null && attr.length === value.length && attr.toLowerCase() === value && next(elem)); }; } return function (elem) { return adapter.getAttributeValue(elem, name) === value && next(elem); }; }, hyphen: function (next, data, options) { var adapter = options.adapter; var name = data.name; var value = data.value; var len = value.length; if (shouldIgnoreCase(data, options)) { value = value.toLowerCase(); return function hyphenIC(elem) { var attr = adapter.getAttributeValue(elem, name); return (attr != null && (attr.length === len || attr.charAt(len) === "-") && attr.substr(0, len).toLowerCase() === value && next(elem)); }; } return function hyphen(elem) { var attr = adapter.getAttributeValue(elem, name); return (attr != null && (attr.length === len || attr.charAt(len) === "-") && attr.substr(0, len) === value && next(elem)); }; }, element: function (next, data, options) { var adapter = options.adapter; var name = data.name, value = data.value; if (/\s/.test(value)) { return boolbase_1.default.falseFunc; } var regex = new RegExp("(?:^|\\s)".concat(escapeRegex(value), "(?:$|\\s)"), shouldIgnoreCase(data, options) ? "i" : ""); return function element(elem) { var attr = adapter.getAttributeValue(elem, name); return (attr != null && attr.length >= value.length && regex.test(attr) && next(elem)); }; }, exists: function (next, _a, _b) { var name = _a.name; var adapter = _b.adapter; return function (elem) { return adapter.hasAttrib(elem, name) && next(elem); }; }, start: function (next, data, options) { var adapter = options.adapter; var name = data.name; var value = data.value; var len = value.length; if (len === 0) { return boolbase_1.default.falseFunc; } if (shouldIgnoreCase(data, options)) { value = value.toLowerCase(); return function (elem) { var attr = adapter.getAttributeValue(elem, name); return (attr != null && attr.length >= len && attr.substr(0, len).toLowerCase() === value && next(elem)); }; } return function (elem) { var _a; return !!((_a = adapter.getAttributeValue(elem, name)) === null || _a === void 0 ? void 0 : _a.startsWith(value)) && next(elem); }; }, end: function (next, data, options) { var adapter = options.adapter; var name = data.name; var value = data.value; var len = -value.length; if (len === 0) { return boolbase_1.default.falseFunc; } if (shouldIgnoreCase(data, options)) { value = value.toLowerCase(); return function (elem) { var _a; return ((_a = adapter .getAttributeValue(elem, name)) === null || _a === void 0 ? void 0 : _a.substr(len).toLowerCase()) === value && next(elem); }; } return function (elem) { var _a; return !!((_a = adapter.getAttributeValue(elem, name)) === null || _a === void 0 ? void 0 : _a.endsWith(value)) && next(elem); }; }, any: function (next, data, options) { var adapter = options.adapter; var name = data.name, value = data.value; if (value === "") { return boolbase_1.default.falseFunc; } if (shouldIgnoreCase(data, options)) { var regex_1 = new RegExp(escapeRegex(value), "i"); return function anyIC(elem) { var attr = adapter.getAttributeValue(elem, name); return (attr != null && attr.length >= value.length && regex_1.test(attr) && next(elem)); }; } return function (elem) { var _a; return !!((_a = adapter.getAttributeValue(elem, name)) === null || _a === void 0 ? void 0 : _a.includes(value)) && next(elem); }; }, not: function (next, data, options) { var adapter = options.adapter; var name = data.name; var value = data.value; if (value === "") { return function (elem) { return !!adapter.getAttributeValue(elem, name) && next(elem); }; } else if (shouldIgnoreCase(data, options)) { value = value.toLowerCase(); return function (elem) { var attr = adapter.getAttributeValue(elem, name); return ((attr == null || attr.length !== value.length || attr.toLowerCase() !== value) && next(elem)); }; } return function (elem) { return adapter.getAttributeValue(elem, name) !== value && next(elem); }; }, }; //# sourceMappingURL=attributes.js.map /***/ }), /***/ 55599: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.compileToken = exports.compileUnsafe = exports.compile = void 0; var css_what_1 = __nccwpck_require__(75667); var boolbase_1 = __importDefault(__nccwpck_require__(45265)); var sort_js_1 = __importStar(__nccwpck_require__(84040)); var general_js_1 = __nccwpck_require__(70634); var subselects_js_1 = __nccwpck_require__(52287); /** * Compiles a selector to an executable function. * * @param selector Selector to compile. * @param options Compilation options. * @param context Optional context for the selector. */ function compile(selector, options, context) { var next = compileUnsafe(selector, options, context); return (0, subselects_js_1.ensureIsTag)(next, options.adapter); } exports.compile = compile; function compileUnsafe(selector, options, context) { var token = typeof selector === "string" ? (0, css_what_1.parse)(selector) : selector; return compileToken(token, options, context); } exports.compileUnsafe = compileUnsafe; function includesScopePseudo(t) { return (t.type === css_what_1.SelectorType.Pseudo && (t.name === "scope" || (Array.isArray(t.data) && t.data.some(function (data) { return data.some(includesScopePseudo); })))); } var DESCENDANT_TOKEN = { type: css_what_1.SelectorType.Descendant }; var FLEXIBLE_DESCENDANT_TOKEN = { type: "_flexibleDescendant", }; var SCOPE_TOKEN = { type: css_what_1.SelectorType.Pseudo, name: "scope", data: null, }; /* * CSS 4 Spec (Draft): 3.4.1. Absolutizing a Relative Selector * http://www.w3.org/TR/selectors4/#absolutizing */ function absolutize(token, _a, context) { var adapter = _a.adapter; // TODO Use better check if the context is a document var hasContext = !!(context === null || context === void 0 ? void 0 : context.every(function (e) { var parent = adapter.isTag(e) && adapter.getParent(e); return e === subselects_js_1.PLACEHOLDER_ELEMENT || (parent && adapter.isTag(parent)); })); for (var _i = 0, token_1 = token; _i < token_1.length; _i++) { var t = token_1[_i]; if (t.length > 0 && (0, sort_js_1.isTraversal)(t[0]) && t[0].type !== css_what_1.SelectorType.Descendant) { // Don't continue in else branch } else if (hasContext && !t.some(includesScopePseudo)) { t.unshift(DESCENDANT_TOKEN); } else { continue; } t.unshift(SCOPE_TOKEN); } } function compileToken(token, options, context) { var _a; token.forEach(sort_js_1.default); context = (_a = options.context) !== null && _a !== void 0 ? _a : context; var isArrayContext = Array.isArray(context); var finalContext = context && (Array.isArray(context) ? context : [context]); // Check if the selector is relative if (options.relativeSelector !== false) { absolutize(token, options, finalContext); } else if (token.some(function (t) { return t.length > 0 && (0, sort_js_1.isTraversal)(t[0]); })) { throw new Error("Relative selectors are not allowed when the `relativeSelector` option is disabled"); } var shouldTestNextSiblings = false; var query = token .map(function (rules) { if (rules.length >= 2) { var first = rules[0], second = rules[1]; if (first.type !== css_what_1.SelectorType.Pseudo || first.name !== "scope") { // Ignore } else if (isArrayContext && second.type === css_what_1.SelectorType.Descendant) { rules[1] = FLEXIBLE_DESCENDANT_TOKEN; } else if (second.type === css_what_1.SelectorType.Adjacent || second.type === css_what_1.SelectorType.Sibling) { shouldTestNextSiblings = true; } } return compileRules(rules, options, finalContext); }) .reduce(reduceRules, boolbase_1.default.falseFunc); query.shouldTestNextSiblings = shouldTestNextSiblings; return query; } exports.compileToken = compileToken; function compileRules(rules, options, context) { var _a; return rules.reduce(function (previous, rule) { return previous === boolbase_1.default.falseFunc ? boolbase_1.default.falseFunc : (0, general_js_1.compileGeneralSelector)(previous, rule, options, context, compileToken); }, (_a = options.rootFunc) !== null && _a !== void 0 ? _a : boolbase_1.default.trueFunc); } function reduceRules(a, b) { if (b === boolbase_1.default.falseFunc || a === boolbase_1.default.trueFunc) { return a; } if (a === boolbase_1.default.falseFunc || b === boolbase_1.default.trueFunc) { return b; } return function combine(elem) { return a(elem) || b(elem); }; } //# sourceMappingURL=compile.js.map /***/ }), /***/ 70634: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.compileGeneralSelector = void 0; var attributes_js_1 = __nccwpck_require__(85353); var index_js_1 = __nccwpck_require__(718); var css_what_1 = __nccwpck_require__(75667); function getElementParent(node, adapter) { var parent = adapter.getParent(node); if (parent && adapter.isTag(parent)) { return parent; } return null; } /* * All available rules */ function compileGeneralSelector(next, selector, options, context, compileToken) { var adapter = options.adapter, equals = options.equals; switch (selector.type) { case css_what_1.SelectorType.PseudoElement: { throw new Error("Pseudo-elements are not supported by css-select"); } case css_what_1.SelectorType.ColumnCombinator: { throw new Error("Column combinators are not yet supported by css-select"); } case css_what_1.SelectorType.Attribute: { if (selector.namespace != null) { throw new Error("Namespaced attributes are not yet supported by css-select"); } if (!options.xmlMode || options.lowerCaseAttributeNames) { selector.name = selector.name.toLowerCase(); } return attributes_js_1.attributeRules[selector.action](next, selector, options); } case css_what_1.SelectorType.Pseudo: { return (0, index_js_1.compilePseudoSelector)(next, selector, options, context, compileToken); } // Tags case css_what_1.SelectorType.Tag: { if (selector.namespace != null) { throw new Error("Namespaced tag names are not yet supported by css-select"); } var name_1 = selector.name; if (!options.xmlMode || options.lowerCaseTags) { name_1 = name_1.toLowerCase(); } return function tag(elem) { return adapter.getName(elem) === name_1 && next(elem); }; } // Traversal case css_what_1.SelectorType.Descendant: { if (options.cacheResults === false || typeof WeakSet === "undefined") { return function descendant(elem) { var current = elem; while ((current = getElementParent(current, adapter))) { if (next(current)) { return true; } } return false; }; } // @ts-expect-error `ElementNode` is not extending object var isFalseCache_1 = new WeakSet(); return function cachedDescendant(elem) { var current = elem; while ((current = getElementParent(current, adapter))) { if (!isFalseCache_1.has(current)) { if (adapter.isTag(current) && next(current)) { return true; } isFalseCache_1.add(current); } } return false; }; } case "_flexibleDescendant": { // Include element itself, only used while querying an array return function flexibleDescendant(elem) { var current = elem; do { if (next(current)) return true; } while ((current = getElementParent(current, adapter))); return false; }; } case css_what_1.SelectorType.Parent: { return function parent(elem) { return adapter .getChildren(elem) .some(function (elem) { return adapter.isTag(elem) && next(elem); }); }; } case css_what_1.SelectorType.Child: { return function child(elem) { var parent = adapter.getParent(elem); return parent != null && adapter.isTag(parent) && next(parent); }; } case css_what_1.SelectorType.Sibling: { return function sibling(elem) { var siblings = adapter.getSiblings(elem); for (var i = 0; i < siblings.length; i++) { var currentSibling = siblings[i]; if (equals(elem, currentSibling)) break; if (adapter.isTag(currentSibling) && next(currentSibling)) { return true; } } return false; }; } case css_what_1.SelectorType.Adjacent: { if (adapter.prevElementSibling) { return function adjacent(elem) { var previous = adapter.prevElementSibling(elem); return previous != null && next(previous); }; } return function adjacent(elem) { var siblings = adapter.getSiblings(elem); var lastElement; for (var i = 0; i < siblings.length; i++) { var currentSibling = siblings[i]; if (equals(elem, currentSibling)) break; if (adapter.isTag(currentSibling)) { lastElement = currentSibling; } } return !!lastElement && next(lastElement); }; } case css_what_1.SelectorType.Universal: { if (selector.namespace != null && selector.namespace !== "*") { throw new Error("Namespaced universal selectors are not yet supported by css-select"); } return next; } } } exports.compileGeneralSelector = compileGeneralSelector; //# sourceMappingURL=general.js.map /***/ }), /***/ 32842: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.aliases = exports.pseudos = exports.filters = exports.is = exports.selectOne = exports.selectAll = exports.prepareContext = exports._compileToken = exports._compileUnsafe = exports.compile = void 0; var DomUtils = __importStar(__nccwpck_require__(92357)); var boolbase_1 = __importDefault(__nccwpck_require__(45265)); var compile_js_1 = __nccwpck_require__(55599); var subselects_js_1 = __nccwpck_require__(52287); var defaultEquals = function (a, b) { return a === b; }; var defaultOptions = { adapter: DomUtils, equals: defaultEquals, }; function convertOptionFormats(options) { var _a, _b, _c, _d; /* * We force one format of options to the other one. */ // @ts-expect-error Default options may have incompatible `Node` / `ElementNode`. var opts = options !== null && options !== void 0 ? options : defaultOptions; // @ts-expect-error Same as above. (_a = opts.adapter) !== null && _a !== void 0 ? _a : (opts.adapter = DomUtils); // @ts-expect-error `equals` does not exist on `Options` (_b = opts.equals) !== null && _b !== void 0 ? _b : (opts.equals = (_d = (_c = opts.adapter) === null || _c === void 0 ? void 0 : _c.equals) !== null && _d !== void 0 ? _d : defaultEquals); return opts; } function wrapCompile(func) { return function addAdapter(selector, options, context) { var opts = convertOptionFormats(options); return func(selector, opts, context); }; } /** * Compiles the query, returns a function. */ exports.compile = wrapCompile(compile_js_1.compile); exports._compileUnsafe = wrapCompile(compile_js_1.compileUnsafe); exports._compileToken = wrapCompile(compile_js_1.compileToken); function getSelectorFunc(searchFunc) { return function select(query, elements, options) { var opts = convertOptionFormats(options); if (typeof query !== "function") { query = (0, compile_js_1.compileUnsafe)(query, opts, elements); } var filteredElements = prepareContext(elements, opts.adapter, query.shouldTestNextSiblings); return searchFunc(query, filteredElements, opts); }; } function prepareContext(elems, adapter, shouldTestNextSiblings) { if (shouldTestNextSiblings === void 0) { shouldTestNextSiblings = false; } /* * Add siblings if the query requires them. * See https://github.com/fb55/css-select/pull/43#issuecomment-225414692 */ if (shouldTestNextSiblings) { elems = appendNextSiblings(elems, adapter); } return Array.isArray(elems) ? adapter.removeSubsets(elems) : adapter.getChildren(elems); } exports.prepareContext = prepareContext; function appendNextSiblings(elem, adapter) { // Order matters because jQuery seems to check the children before the siblings var elems = Array.isArray(elem) ? elem.slice(0) : [elem]; var elemsLength = elems.length; for (var i = 0; i < elemsLength; i++) { var nextSiblings = (0, subselects_js_1.getNextSiblings)(elems[i], adapter); elems.push.apply(elems, nextSiblings); } return elems; } /** * @template Node The generic Node type for the DOM adapter being used. * @template ElementNode The Node type for elements for the DOM adapter being used. * @param elems Elements to query. If it is an element, its children will be queried.. * @param query can be either a CSS selector string or a compiled query function. * @param [options] options for querying the document. * @see compile for supported selector queries. * @returns All matching elements. * */ exports.selectAll = getSelectorFunc(function (query, elems, options) { return query === boolbase_1.default.falseFunc || !elems || elems.length === 0 ? [] : options.adapter.findAll(query, elems); }); /** * @template Node The generic Node type for the DOM adapter being used. * @template ElementNode The Node type for elements for the DOM adapter being used. * @param elems Elements to query. If it is an element, its children will be queried.. * @param query can be either a CSS selector string or a compiled query function. * @param [options] options for querying the document. * @see compile for supported selector queries. * @returns the first match, or null if there was no match. */ exports.selectOne = getSelectorFunc(function (query, elems, options) { return query === boolbase_1.default.falseFunc || !elems || elems.length === 0 ? null : options.adapter.findOne(query, elems); }); /** * Tests whether or not an element is matched by query. * * @template Node The generic Node type for the DOM adapter being used. * @template ElementNode The Node type for elements for the DOM adapter being used. * @param elem The element to test if it matches the query. * @param query can be either a CSS selector string or a compiled query function. * @param [options] options for querying the document. * @see compile for supported selector queries. * @returns */ function is(elem, query, options) { var opts = convertOptionFormats(options); return (typeof query === "function" ? query : (0, compile_js_1.compile)(query, opts))(elem); } exports.is = is; /** * Alias for selectAll(query, elems, options). * @see [compile] for supported selector queries. */ exports["default"] = exports.selectAll; // Export filters, pseudos and aliases to allow users to supply their own. /** @deprecated Use the `pseudos` option instead. */ var index_js_1 = __nccwpck_require__(718); Object.defineProperty(exports, "filters", ({ enumerable: true, get: function () { return index_js_1.filters; } })); Object.defineProperty(exports, "pseudos", ({ enumerable: true, get: function () { return index_js_1.pseudos; } })); Object.defineProperty(exports, "aliases", ({ enumerable: true, get: function () { return index_js_1.aliases; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 34998: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.aliases = void 0; /** * Aliases are pseudos that are expressed as selectors. */ exports.aliases = { // Links "any-link": ":is(a, area, link)[href]", link: ":any-link:not(:visited)", // Forms // https://html.spec.whatwg.org/multipage/scripting.html#disabled-elements disabled: ":is(\n :is(button, input, select, textarea, optgroup, option)[disabled],\n optgroup[disabled] > option,\n fieldset[disabled]:not(fieldset[disabled] legend:first-of-type *)\n )", enabled: ":not(:disabled)", checked: ":is(:is(input[type=radio], input[type=checkbox])[checked], option:selected)", required: ":is(input, select, textarea)[required]", optional: ":is(input, select, textarea):not([required])", // JQuery extensions // https://html.spec.whatwg.org/multipage/form-elements.html#concept-option-selectedness selected: "option:is([selected], select:not([multiple]):not(:has(> option[selected])) > :first-of-type)", checkbox: "[type=checkbox]", file: "[type=file]", password: "[type=password]", radio: "[type=radio]", reset: "[type=reset]", image: "[type=image]", submit: "[type=submit]", parent: ":not(:empty)", header: ":is(h1, h2, h3, h4, h5, h6)", button: ":is(button, input[type=button])", input: ":is(input, textarea, select, button)", text: "input:is(:not([type!='']), [type=text])", }; //# sourceMappingURL=aliases.js.map /***/ }), /***/ 21625: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.filters = void 0; var nth_check_1 = __importDefault(__nccwpck_require__(70187)); var boolbase_1 = __importDefault(__nccwpck_require__(45265)); function getChildFunc(next, adapter) { return function (elem) { var parent = adapter.getParent(elem); return parent != null && adapter.isTag(parent) && next(elem); }; } exports.filters = { contains: function (next, text, _a) { var adapter = _a.adapter; return function contains(elem) { return next(elem) && adapter.getText(elem).includes(text); }; }, icontains: function (next, text, _a) { var adapter = _a.adapter; var itext = text.toLowerCase(); return function icontains(elem) { return (next(elem) && adapter.getText(elem).toLowerCase().includes(itext)); }; }, // Location specific methods "nth-child": function (next, rule, _a) { var adapter = _a.adapter, equals = _a.equals; var func = (0, nth_check_1.default)(rule); if (func === boolbase_1.default.falseFunc) return boolbase_1.default.falseFunc; if (func === boolbase_1.default.trueFunc) return getChildFunc(next, adapter); return function nthChild(elem) { var siblings = adapter.getSiblings(elem); var pos = 0; for (var i = 0; i < siblings.length; i++) { if (equals(elem, siblings[i])) break; if (adapter.isTag(siblings[i])) { pos++; } } return func(pos) && next(elem); }; }, "nth-last-child": function (next, rule, _a) { var adapter = _a.adapter, equals = _a.equals; var func = (0, nth_check_1.default)(rule); if (func === boolbase_1.default.falseFunc) return boolbase_1.default.falseFunc; if (func === boolbase_1.default.trueFunc) return getChildFunc(next, adapter); return function nthLastChild(elem) { var siblings = adapter.getSiblings(elem); var pos = 0; for (var i = siblings.length - 1; i >= 0; i--) { if (equals(elem, siblings[i])) break; if (adapter.isTag(siblings[i])) { pos++; } } return func(pos) && next(elem); }; }, "nth-of-type": function (next, rule, _a) { var adapter = _a.adapter, equals = _a.equals; var func = (0, nth_check_1.default)(rule); if (func === boolbase_1.default.falseFunc) return boolbase_1.default.falseFunc; if (func === boolbase_1.default.trueFunc) return getChildFunc(next, adapter); return function nthOfType(elem) { var siblings = adapter.getSiblings(elem); var pos = 0; for (var i = 0; i < siblings.length; i++) { var currentSibling = siblings[i]; if (equals(elem, currentSibling)) break; if (adapter.isTag(currentSibling) && adapter.getName(currentSibling) === adapter.getName(elem)) { pos++; } } return func(pos) && next(elem); }; }, "nth-last-of-type": function (next, rule, _a) { var adapter = _a.adapter, equals = _a.equals; var func = (0, nth_check_1.default)(rule); if (func === boolbase_1.default.falseFunc) return boolbase_1.default.falseFunc; if (func === boolbase_1.default.trueFunc) return getChildFunc(next, adapter); return function nthLastOfType(elem) { var siblings = adapter.getSiblings(elem); var pos = 0; for (var i = siblings.length - 1; i >= 0; i--) { var currentSibling = siblings[i]; if (equals(elem, currentSibling)) break; if (adapter.isTag(currentSibling) && adapter.getName(currentSibling) === adapter.getName(elem)) { pos++; } } return func(pos) && next(elem); }; }, // TODO determine the actual root element root: function (next, _rule, _a) { var adapter = _a.adapter; return function (elem) { var parent = adapter.getParent(elem); return (parent == null || !adapter.isTag(parent)) && next(elem); }; }, scope: function (next, rule, options, context) { var equals = options.equals; if (!context || context.length === 0) { // Equivalent to :root return exports.filters["root"](next, rule, options); } if (context.length === 1) { // NOTE: can't be unpacked, as :has uses this for side-effects return function (elem) { return equals(context[0], elem) && next(elem); }; } return function (elem) { return context.includes(elem) && next(elem); }; }, hover: dynamicStatePseudo("isHovered"), visited: dynamicStatePseudo("isVisited"), active: dynamicStatePseudo("isActive"), }; /** * Dynamic state pseudos. These depend on optional Adapter methods. * * @param name The name of the adapter method to call. * @returns Pseudo for the `filters` object. */ function dynamicStatePseudo(name) { return function dynamicPseudo(next, _rule, _a) { var adapter = _a.adapter; var func = adapter[name]; if (typeof func !== "function") { return boolbase_1.default.falseFunc; } return function active(elem) { return func(elem) && next(elem); }; }; } //# sourceMappingURL=filters.js.map /***/ }), /***/ 718: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.compilePseudoSelector = exports.aliases = exports.pseudos = exports.filters = void 0; var css_what_1 = __nccwpck_require__(75667); var filters_js_1 = __nccwpck_require__(21625); Object.defineProperty(exports, "filters", ({ enumerable: true, get: function () { return filters_js_1.filters; } })); var pseudos_js_1 = __nccwpck_require__(50609); Object.defineProperty(exports, "pseudos", ({ enumerable: true, get: function () { return pseudos_js_1.pseudos; } })); var aliases_js_1 = __nccwpck_require__(34998); Object.defineProperty(exports, "aliases", ({ enumerable: true, get: function () { return aliases_js_1.aliases; } })); var subselects_js_1 = __nccwpck_require__(52287); function compilePseudoSelector(next, selector, options, context, compileToken) { var _a; var name = selector.name, data = selector.data; if (Array.isArray(data)) { if (!(name in subselects_js_1.subselects)) { throw new Error("Unknown pseudo-class :".concat(name, "(").concat(data, ")")); } return subselects_js_1.subselects[name](next, data, options, context, compileToken); } var userPseudo = (_a = options.pseudos) === null || _a === void 0 ? void 0 : _a[name]; var stringPseudo = typeof userPseudo === "string" ? userPseudo : aliases_js_1.aliases[name]; if (typeof stringPseudo === "string") { if (data != null) { throw new Error("Pseudo ".concat(name, " doesn't have any arguments")); } // The alias has to be parsed here, to make sure options are respected. var alias = (0, css_what_1.parse)(stringPseudo); return subselects_js_1.subselects["is"](next, alias, options, context, compileToken); } if (typeof userPseudo === "function") { (0, pseudos_js_1.verifyPseudoArgs)(userPseudo, name, data, 1); return function (elem) { return userPseudo(elem, data) && next(elem); }; } if (name in filters_js_1.filters) { return filters_js_1.filters[name](next, data, options, context); } if (name in pseudos_js_1.pseudos) { var pseudo_1 = pseudos_js_1.pseudos[name]; (0, pseudos_js_1.verifyPseudoArgs)(pseudo_1, name, data, 2); return function (elem) { return pseudo_1(elem, options, data) && next(elem); }; } throw new Error("Unknown pseudo-class :".concat(name)); } exports.compilePseudoSelector = compilePseudoSelector; //# sourceMappingURL=index.js.map /***/ }), /***/ 50609: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.verifyPseudoArgs = exports.pseudos = void 0; // While filters are precompiled, pseudos get called when they are needed exports.pseudos = { empty: function (elem, _a) { var adapter = _a.adapter; return !adapter.getChildren(elem).some(function (elem) { // FIXME: `getText` call is potentially expensive. return adapter.isTag(elem) || adapter.getText(elem) !== ""; }); }, "first-child": function (elem, _a) { var adapter = _a.adapter, equals = _a.equals; if (adapter.prevElementSibling) { return adapter.prevElementSibling(elem) == null; } var firstChild = adapter .getSiblings(elem) .find(function (elem) { return adapter.isTag(elem); }); return firstChild != null && equals(elem, firstChild); }, "last-child": function (elem, _a) { var adapter = _a.adapter, equals = _a.equals; var siblings = adapter.getSiblings(elem); for (var i = siblings.length - 1; i >= 0; i--) { if (equals(elem, siblings[i])) return true; if (adapter.isTag(siblings[i])) break; } return false; }, "first-of-type": function (elem, _a) { var adapter = _a.adapter, equals = _a.equals; var siblings = adapter.getSiblings(elem); var elemName = adapter.getName(elem); for (var i = 0; i < siblings.length; i++) { var currentSibling = siblings[i]; if (equals(elem, currentSibling)) return true; if (adapter.isTag(currentSibling) && adapter.getName(currentSibling) === elemName) { break; } } return false; }, "last-of-type": function (elem, _a) { var adapter = _a.adapter, equals = _a.equals; var siblings = adapter.getSiblings(elem); var elemName = adapter.getName(elem); for (var i = siblings.length - 1; i >= 0; i--) { var currentSibling = siblings[i]; if (equals(elem, currentSibling)) return true; if (adapter.isTag(currentSibling) && adapter.getName(currentSibling) === elemName) { break; } } return false; }, "only-of-type": function (elem, _a) { var adapter = _a.adapter, equals = _a.equals; var elemName = adapter.getName(elem); return adapter .getSiblings(elem) .every(function (sibling) { return equals(elem, sibling) || !adapter.isTag(sibling) || adapter.getName(sibling) !== elemName; }); }, "only-child": function (elem, _a) { var adapter = _a.adapter, equals = _a.equals; return adapter .getSiblings(elem) .every(function (sibling) { return equals(elem, sibling) || !adapter.isTag(sibling); }); }, }; function verifyPseudoArgs(func, name, subselect, argIndex) { if (subselect === null) { if (func.length > argIndex) { throw new Error("Pseudo-class :".concat(name, " requires an argument")); } } else if (func.length === argIndex) { throw new Error("Pseudo-class :".concat(name, " doesn't have any arguments")); } } exports.verifyPseudoArgs = verifyPseudoArgs; //# sourceMappingURL=pseudos.js.map /***/ }), /***/ 52287: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.subselects = exports.getNextSiblings = exports.ensureIsTag = exports.PLACEHOLDER_ELEMENT = void 0; var boolbase_1 = __importDefault(__nccwpck_require__(45265)); var sort_js_1 = __nccwpck_require__(84040); /** Used as a placeholder for :has. Will be replaced with the actual element. */ exports.PLACEHOLDER_ELEMENT = {}; function ensureIsTag(next, adapter) { if (next === boolbase_1.default.falseFunc) return boolbase_1.default.falseFunc; return function (elem) { return adapter.isTag(elem) && next(elem); }; } exports.ensureIsTag = ensureIsTag; function getNextSiblings(elem, adapter) { var siblings = adapter.getSiblings(elem); if (siblings.length <= 1) return []; var elemIndex = siblings.indexOf(elem); if (elemIndex < 0 || elemIndex === siblings.length - 1) return []; return siblings.slice(elemIndex + 1).filter(adapter.isTag); } exports.getNextSiblings = getNextSiblings; function copyOptions(options) { // Not copied: context, rootFunc return { xmlMode: !!options.xmlMode, lowerCaseAttributeNames: !!options.lowerCaseAttributeNames, lowerCaseTags: !!options.lowerCaseTags, quirksMode: !!options.quirksMode, cacheResults: !!options.cacheResults, pseudos: options.pseudos, adapter: options.adapter, equals: options.equals, }; } var is = function (next, token, options, context, compileToken) { var func = compileToken(token, copyOptions(options), context); return func === boolbase_1.default.trueFunc ? next : func === boolbase_1.default.falseFunc ? boolbase_1.default.falseFunc : function (elem) { return func(elem) && next(elem); }; }; /* * :not, :has, :is, :matches and :where have to compile selectors * doing this in src/pseudos.ts would lead to circular dependencies, * so we add them here */ exports.subselects = { is: is, /** * `:matches` and `:where` are aliases for `:is`. */ matches: is, where: is, not: function (next, token, options, context, compileToken) { var func = compileToken(token, copyOptions(options), context); return func === boolbase_1.default.falseFunc ? next : func === boolbase_1.default.trueFunc ? boolbase_1.default.falseFunc : function (elem) { return !func(elem) && next(elem); }; }, has: function (next, subselect, options, _context, compileToken) { var adapter = options.adapter; var opts = copyOptions(options); opts.relativeSelector = true; var context = subselect.some(function (s) { return s.some(sort_js_1.isTraversal); }) ? // Used as a placeholder. Will be replaced with the actual element. [exports.PLACEHOLDER_ELEMENT] : undefined; var compiled = compileToken(subselect, opts, context); if (compiled === boolbase_1.default.falseFunc) return boolbase_1.default.falseFunc; var hasElement = ensureIsTag(compiled, adapter); // If `compiled` is `trueFunc`, we can skip this. if (context && compiled !== boolbase_1.default.trueFunc) { /* * `shouldTestNextSiblings` will only be true if the query starts with * a traversal (sibling or adjacent). That means we will always have a context. */ var _a = compiled.shouldTestNextSiblings, shouldTestNextSiblings_1 = _a === void 0 ? false : _a; return function (elem) { if (!next(elem)) return false; context[0] = elem; var childs = adapter.getChildren(elem); var nextElements = shouldTestNextSiblings_1 ? __spreadArray(__spreadArray([], childs, true), getNextSiblings(elem, adapter), true) : childs; return adapter.existsOne(hasElement, nextElements); }; } return function (elem) { return next(elem) && adapter.existsOne(hasElement, adapter.getChildren(elem)); }; }, }; //# sourceMappingURL=subselects.js.map /***/ }), /***/ 84040: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isTraversal = void 0; var css_what_1 = __nccwpck_require__(75667); var procedure = new Map([ [css_what_1.SelectorType.Universal, 50], [css_what_1.SelectorType.Tag, 30], [css_what_1.SelectorType.Attribute, 1], [css_what_1.SelectorType.Pseudo, 0], ]); function isTraversal(token) { return !procedure.has(token.type); } exports.isTraversal = isTraversal; var attributes = new Map([ [css_what_1.AttributeAction.Exists, 10], [css_what_1.AttributeAction.Equals, 8], [css_what_1.AttributeAction.Not, 7], [css_what_1.AttributeAction.Start, 6], [css_what_1.AttributeAction.End, 6], [css_what_1.AttributeAction.Any, 5], ]); /** * Sort the parts of the passed selector, * as there is potential for optimization * (some types of selectors are faster than others) * * @param arr Selector to sort */ function sortByProcedure(arr) { var procs = arr.map(getProcedure); for (var i = 1; i < arr.length; i++) { var procNew = procs[i]; if (procNew < 0) continue; for (var j = i - 1; j >= 0 && procNew < procs[j]; j--) { var token = arr[j + 1]; arr[j + 1] = arr[j]; arr[j] = token; procs[j + 1] = procs[j]; procs[j] = procNew; } } } exports["default"] = sortByProcedure; function getProcedure(token) { var _a, _b; var proc = (_a = procedure.get(token.type)) !== null && _a !== void 0 ? _a : -1; if (token.type === css_what_1.SelectorType.Attribute) { proc = (_b = attributes.get(token.action)) !== null && _b !== void 0 ? _b : 4; if (token.action === css_what_1.AttributeAction.Equals && token.name === "id") { // Prefer ID selectors (eg. #ID) proc = 9; } if (token.ignoreCase) { /* * IgnoreCase adds some overhead, prefer "normal" token * this is a binary operation, to ensure it's still an int */ proc >>= 1; } } else if (token.type === css_what_1.SelectorType.Pseudo) { if (!token.data) { proc = 3; } else if (token.name === "has" || token.name === "contains") { proc = 0; // Expensive in any case } else if (Array.isArray(token.data)) { // Eg. :matches, :not proc = Math.min.apply(Math, token.data.map(function (d) { return Math.min.apply(Math, d.map(getProcedure)); })); // If we have traversals, try to avoid executing this selector if (proc < 0) { proc = 0; } } else { proc = 2; } } return proc; } //# sourceMappingURL=sort.js.map /***/ }), /***/ 75667: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.stringify = exports.parse = exports.isTraversal = void 0; __exportStar(__nccwpck_require__(74738), exports); var parse_1 = __nccwpck_require__(60748); Object.defineProperty(exports, "isTraversal", ({ enumerable: true, get: function () { return parse_1.isTraversal; } })); Object.defineProperty(exports, "parse", ({ enumerable: true, get: function () { return parse_1.parse; } })); var stringify_1 = __nccwpck_require__(29154); Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return stringify_1.stringify; } })); /***/ }), /***/ 60748: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parse = exports.isTraversal = void 0; var types_1 = __nccwpck_require__(74738); var reName = /^[^\\#]?(?:\\(?:[\da-f]{1,6}\s?|.)|[\w\-\u00b0-\uFFFF])+/; var reEscape = /\\([\da-f]{1,6}\s?|(\s)|.)/gi; var actionTypes = new Map([ [126 /* Tilde */, types_1.AttributeAction.Element], [94 /* Circumflex */, types_1.AttributeAction.Start], [36 /* Dollar */, types_1.AttributeAction.End], [42 /* Asterisk */, types_1.AttributeAction.Any], [33 /* ExclamationMark */, types_1.AttributeAction.Not], [124 /* Pipe */, types_1.AttributeAction.Hyphen], ]); // Pseudos, whose data property is parsed as well. var unpackPseudos = new Set([ "has", "not", "matches", "is", "where", "host", "host-context", ]); /** * Checks whether a specific selector is a traversal. * This is useful eg. in swapping the order of elements that * are not traversals. * * @param selector Selector to check. */ function isTraversal(selector) { switch (selector.type) { case types_1.SelectorType.Adjacent: case types_1.SelectorType.Child: case types_1.SelectorType.Descendant: case types_1.SelectorType.Parent: case types_1.SelectorType.Sibling: case types_1.SelectorType.ColumnCombinator: return true; default: return false; } } exports.isTraversal = isTraversal; var stripQuotesFromPseudos = new Set(["contains", "icontains"]); // Unescape function taken from https://github.com/jquery/sizzle/blob/master/src/sizzle.js#L152 function funescape(_, escaped, escapedWhitespace) { var high = parseInt(escaped, 16) - 0x10000; // NaN means non-codepoint return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode(high + 0x10000) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00); } function unescapeCSS(str) { return str.replace(reEscape, funescape); } function isQuote(c) { return c === 39 /* SingleQuote */ || c === 34 /* DoubleQuote */; } function isWhitespace(c) { return (c === 32 /* Space */ || c === 9 /* Tab */ || c === 10 /* NewLine */ || c === 12 /* FormFeed */ || c === 13 /* CarriageReturn */); } /** * Parses `selector`, optionally with the passed `options`. * * @param selector Selector to parse. * @param options Options for parsing. * @returns Returns a two-dimensional array. * The first dimension represents selectors separated by commas (eg. `sub1, sub2`), * the second contains the relevant tokens for that selector. */ function parse(selector) { var subselects = []; var endIndex = parseSelector(subselects, "".concat(selector), 0); if (endIndex < selector.length) { throw new Error("Unmatched selector: ".concat(selector.slice(endIndex))); } return subselects; } exports.parse = parse; function parseSelector(subselects, selector, selectorIndex) { var tokens = []; function getName(offset) { var match = selector.slice(selectorIndex + offset).match(reName); if (!match) { throw new Error("Expected name, found ".concat(selector.slice(selectorIndex))); } var name = match[0]; selectorIndex += offset + name.length; return unescapeCSS(name); } function stripWhitespace(offset) { selectorIndex += offset; while (selectorIndex < selector.length && isWhitespace(selector.charCodeAt(selectorIndex))) { selectorIndex++; } } function readValueWithParenthesis() { selectorIndex += 1; var start = selectorIndex; var counter = 1; for (; counter > 0 && selectorIndex < selector.length; selectorIndex++) { if (selector.charCodeAt(selectorIndex) === 40 /* LeftParenthesis */ && !isEscaped(selectorIndex)) { counter++; } else if (selector.charCodeAt(selectorIndex) === 41 /* RightParenthesis */ && !isEscaped(selectorIndex)) { counter--; } } if (counter) { throw new Error("Parenthesis not matched"); } return unescapeCSS(selector.slice(start, selectorIndex - 1)); } function isEscaped(pos) { var slashCount = 0; while (selector.charCodeAt(--pos) === 92 /* BackSlash */) slashCount++; return (slashCount & 1) === 1; } function ensureNotTraversal() { if (tokens.length > 0 && isTraversal(tokens[tokens.length - 1])) { throw new Error("Did not expect successive traversals."); } } function addTraversal(type) { if (tokens.length > 0 && tokens[tokens.length - 1].type === types_1.SelectorType.Descendant) { tokens[tokens.length - 1].type = type; return; } ensureNotTraversal(); tokens.push({ type: type }); } function addSpecialAttribute(name, action) { tokens.push({ type: types_1.SelectorType.Attribute, name: name, action: action, value: getName(1), namespace: null, ignoreCase: "quirks", }); } /** * We have finished parsing the current part of the selector. * * Remove descendant tokens at the end if they exist, * and return the last index, so that parsing can be * picked up from here. */ function finalizeSubselector() { if (tokens.length && tokens[tokens.length - 1].type === types_1.SelectorType.Descendant) { tokens.pop(); } if (tokens.length === 0) { throw new Error("Empty sub-selector"); } subselects.push(tokens); } stripWhitespace(0); if (selector.length === selectorIndex) { return selectorIndex; } loop: while (selectorIndex < selector.length) { var firstChar = selector.charCodeAt(selectorIndex); switch (firstChar) { // Whitespace case 32 /* Space */: case 9 /* Tab */: case 10 /* NewLine */: case 12 /* FormFeed */: case 13 /* CarriageReturn */: { if (tokens.length === 0 || tokens[0].type !== types_1.SelectorType.Descendant) { ensureNotTraversal(); tokens.push({ type: types_1.SelectorType.Descendant }); } stripWhitespace(1); break; } // Traversals case 62 /* GreaterThan */: { addTraversal(types_1.SelectorType.Child); stripWhitespace(1); break; } case 60 /* LessThan */: { addTraversal(types_1.SelectorType.Parent); stripWhitespace(1); break; } case 126 /* Tilde */: { addTraversal(types_1.SelectorType.Sibling); stripWhitespace(1); break; } case 43 /* Plus */: { addTraversal(types_1.SelectorType.Adjacent); stripWhitespace(1); break; } // Special attribute selectors: .class, #id case 46 /* Period */: { addSpecialAttribute("class", types_1.AttributeAction.Element); break; } case 35 /* Hash */: { addSpecialAttribute("id", types_1.AttributeAction.Equals); break; } case 91 /* LeftSquareBracket */: { stripWhitespace(1); // Determine attribute name and namespace var name_1 = void 0; var namespace = null; if (selector.charCodeAt(selectorIndex) === 124 /* Pipe */) { // Equivalent to no namespace name_1 = getName(1); } else if (selector.startsWith("*|", selectorIndex)) { namespace = "*"; name_1 = getName(2); } else { name_1 = getName(0); if (selector.charCodeAt(selectorIndex) === 124 /* Pipe */ && selector.charCodeAt(selectorIndex + 1) !== 61 /* Equal */) { namespace = name_1; name_1 = getName(1); } } stripWhitespace(0); // Determine comparison operation var action = types_1.AttributeAction.Exists; var possibleAction = actionTypes.get(selector.charCodeAt(selectorIndex)); if (possibleAction) { action = possibleAction; if (selector.charCodeAt(selectorIndex + 1) !== 61 /* Equal */) { throw new Error("Expected `=`"); } stripWhitespace(2); } else if (selector.charCodeAt(selectorIndex) === 61 /* Equal */) { action = types_1.AttributeAction.Equals; stripWhitespace(1); } // Determine value var value = ""; var ignoreCase = null; if (action !== "exists") { if (isQuote(selector.charCodeAt(selectorIndex))) { var quote = selector.charCodeAt(selectorIndex); var sectionEnd = selectorIndex + 1; while (sectionEnd < selector.length && (selector.charCodeAt(sectionEnd) !== quote || isEscaped(sectionEnd))) { sectionEnd += 1; } if (selector.charCodeAt(sectionEnd) !== quote) { throw new Error("Attribute value didn't end"); } value = unescapeCSS(selector.slice(selectorIndex + 1, sectionEnd)); selectorIndex = sectionEnd + 1; } else { var valueStart = selectorIndex; while (selectorIndex < selector.length && ((!isWhitespace(selector.charCodeAt(selectorIndex)) && selector.charCodeAt(selectorIndex) !== 93 /* RightSquareBracket */) || isEscaped(selectorIndex))) { selectorIndex += 1; } value = unescapeCSS(selector.slice(valueStart, selectorIndex)); } stripWhitespace(0); // See if we have a force ignore flag var forceIgnore = selector.charCodeAt(selectorIndex) | 0x20; // If the forceIgnore flag is set (either `i` or `s`), use that value if (forceIgnore === 115 /* LowerS */) { ignoreCase = false; stripWhitespace(1); } else if (forceIgnore === 105 /* LowerI */) { ignoreCase = true; stripWhitespace(1); } } if (selector.charCodeAt(selectorIndex) !== 93 /* RightSquareBracket */) { throw new Error("Attribute selector didn't terminate"); } selectorIndex += 1; var attributeSelector = { type: types_1.SelectorType.Attribute, name: name_1, action: action, value: value, namespace: namespace, ignoreCase: ignoreCase, }; tokens.push(attributeSelector); break; } case 58 /* Colon */: { if (selector.charCodeAt(selectorIndex + 1) === 58 /* Colon */) { tokens.push({ type: types_1.SelectorType.PseudoElement, name: getName(2).toLowerCase(), data: selector.charCodeAt(selectorIndex) === 40 /* LeftParenthesis */ ? readValueWithParenthesis() : null, }); continue; } var name_2 = getName(1).toLowerCase(); var data = null; if (selector.charCodeAt(selectorIndex) === 40 /* LeftParenthesis */) { if (unpackPseudos.has(name_2)) { if (isQuote(selector.charCodeAt(selectorIndex + 1))) { throw new Error("Pseudo-selector ".concat(name_2, " cannot be quoted")); } data = []; selectorIndex = parseSelector(data, selector, selectorIndex + 1); if (selector.charCodeAt(selectorIndex) !== 41 /* RightParenthesis */) { throw new Error("Missing closing parenthesis in :".concat(name_2, " (").concat(selector, ")")); } selectorIndex += 1; } else { data = readValueWithParenthesis(); if (stripQuotesFromPseudos.has(name_2)) { var quot = data.charCodeAt(0); if (quot === data.charCodeAt(data.length - 1) && isQuote(quot)) { data = data.slice(1, -1); } } data = unescapeCSS(data); } } tokens.push({ type: types_1.SelectorType.Pseudo, name: name_2, data: data }); break; } case 44 /* Comma */: { finalizeSubselector(); tokens = []; stripWhitespace(1); break; } default: { if (selector.startsWith("/*", selectorIndex)) { var endIndex = selector.indexOf("*/", selectorIndex + 2); if (endIndex < 0) { throw new Error("Comment was not terminated"); } selectorIndex = endIndex + 2; // Remove leading whitespace if (tokens.length === 0) { stripWhitespace(0); } break; } var namespace = null; var name_3 = void 0; if (firstChar === 42 /* Asterisk */) { selectorIndex += 1; name_3 = "*"; } else if (firstChar === 124 /* Pipe */) { name_3 = ""; if (selector.charCodeAt(selectorIndex + 1) === 124 /* Pipe */) { addTraversal(types_1.SelectorType.ColumnCombinator); stripWhitespace(2); break; } } else if (reName.test(selector.slice(selectorIndex))) { name_3 = getName(0); } else { break loop; } if (selector.charCodeAt(selectorIndex) === 124 /* Pipe */ && selector.charCodeAt(selectorIndex + 1) !== 124 /* Pipe */) { namespace = name_3; if (selector.charCodeAt(selectorIndex + 1) === 42 /* Asterisk */) { name_3 = "*"; selectorIndex += 2; } else { name_3 = getName(1); } } tokens.push(name_3 === "*" ? { type: types_1.SelectorType.Universal, namespace: namespace } : { type: types_1.SelectorType.Tag, name: name_3, namespace: namespace }); } } } finalizeSubselector(); return selectorIndex; } /***/ }), /***/ 29154: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.stringify = void 0; var types_1 = __nccwpck_require__(74738); var attribValChars = ["\\", '"']; var pseudoValChars = __spreadArray(__spreadArray([], attribValChars, true), ["(", ")"], false); var charsToEscapeInAttributeValue = new Set(attribValChars.map(function (c) { return c.charCodeAt(0); })); var charsToEscapeInPseudoValue = new Set(pseudoValChars.map(function (c) { return c.charCodeAt(0); })); var charsToEscapeInName = new Set(__spreadArray(__spreadArray([], pseudoValChars, true), [ "~", "^", "$", "*", "+", "!", "|", ":", "[", "]", " ", ".", ], false).map(function (c) { return c.charCodeAt(0); })); /** * Turns `selector` back into a string. * * @param selector Selector to stringify. */ function stringify(selector) { return selector .map(function (token) { return token.map(stringifyToken).join(""); }) .join(", "); } exports.stringify = stringify; function stringifyToken(token, index, arr) { switch (token.type) { // Simple types case types_1.SelectorType.Child: return index === 0 ? "> " : " > "; case types_1.SelectorType.Parent: return index === 0 ? "< " : " < "; case types_1.SelectorType.Sibling: return index === 0 ? "~ " : " ~ "; case types_1.SelectorType.Adjacent: return index === 0 ? "+ " : " + "; case types_1.SelectorType.Descendant: return " "; case types_1.SelectorType.ColumnCombinator: return index === 0 ? "|| " : " || "; case types_1.SelectorType.Universal: // Return an empty string if the selector isn't needed. return token.namespace === "*" && index + 1 < arr.length && "name" in arr[index + 1] ? "" : "".concat(getNamespace(token.namespace), "*"); case types_1.SelectorType.Tag: return getNamespacedName(token); case types_1.SelectorType.PseudoElement: return "::".concat(escapeName(token.name, charsToEscapeInName)).concat(token.data === null ? "" : "(".concat(escapeName(token.data, charsToEscapeInPseudoValue), ")")); case types_1.SelectorType.Pseudo: return ":".concat(escapeName(token.name, charsToEscapeInName)).concat(token.data === null ? "" : "(".concat(typeof token.data === "string" ? escapeName(token.data, charsToEscapeInPseudoValue) : stringify(token.data), ")")); case types_1.SelectorType.Attribute: { if (token.name === "id" && token.action === types_1.AttributeAction.Equals && token.ignoreCase === "quirks" && !token.namespace) { return "#".concat(escapeName(token.value, charsToEscapeInName)); } if (token.name === "class" && token.action === types_1.AttributeAction.Element && token.ignoreCase === "quirks" && !token.namespace) { return ".".concat(escapeName(token.value, charsToEscapeInName)); } var name_1 = getNamespacedName(token); if (token.action === types_1.AttributeAction.Exists) { return "[".concat(name_1, "]"); } return "[".concat(name_1).concat(getActionValue(token.action), "=\"").concat(escapeName(token.value, charsToEscapeInAttributeValue), "\"").concat(token.ignoreCase === null ? "" : token.ignoreCase ? " i" : " s", "]"); } } } function getActionValue(action) { switch (action) { case types_1.AttributeAction.Equals: return ""; case types_1.AttributeAction.Element: return "~"; case types_1.AttributeAction.Start: return "^"; case types_1.AttributeAction.End: return "$"; case types_1.AttributeAction.Any: return "*"; case types_1.AttributeAction.Not: return "!"; case types_1.AttributeAction.Hyphen: return "|"; case types_1.AttributeAction.Exists: throw new Error("Shouldn't be here"); } } function getNamespacedName(token) { return "".concat(getNamespace(token.namespace)).concat(escapeName(token.name, charsToEscapeInName)); } function getNamespace(namespace) { return namespace !== null ? "".concat(namespace === "*" ? "*" : escapeName(namespace, charsToEscapeInName), "|") : ""; } function escapeName(str, charsToEscape) { var lastIdx = 0; var ret = ""; for (var i = 0; i < str.length; i++) { if (charsToEscape.has(str.charCodeAt(i))) { ret += "".concat(str.slice(lastIdx, i), "\\").concat(str.charAt(i)); lastIdx = i + 1; } } return ret.length > 0 ? ret + str.slice(lastIdx) : str; } /***/ }), /***/ 74738: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AttributeAction = exports.IgnoreCaseMode = exports.SelectorType = void 0; var SelectorType; (function (SelectorType) { SelectorType["Attribute"] = "attribute"; SelectorType["Pseudo"] = "pseudo"; SelectorType["PseudoElement"] = "pseudo-element"; SelectorType["Tag"] = "tag"; SelectorType["Universal"] = "universal"; // Traversals SelectorType["Adjacent"] = "adjacent"; SelectorType["Child"] = "child"; SelectorType["Descendant"] = "descendant"; SelectorType["Parent"] = "parent"; SelectorType["Sibling"] = "sibling"; SelectorType["ColumnCombinator"] = "column-combinator"; })(SelectorType = exports.SelectorType || (exports.SelectorType = {})); /** * Modes for ignore case. * * This could be updated to an enum, and the object is * the current stand-in that will allow code to be updated * without big changes. */ exports.IgnoreCaseMode = { Unknown: null, QuirksMode: "quirks", IgnoreCase: true, CaseSensitive: false, }; var AttributeAction; (function (AttributeAction) { AttributeAction["Any"] = "any"; AttributeAction["Element"] = "element"; AttributeAction["End"] = "end"; AttributeAction["Equals"] = "equals"; AttributeAction["Exists"] = "exists"; AttributeAction["Hyphen"] = "hyphen"; AttributeAction["Not"] = "not"; AttributeAction["Start"] = "start"; })(AttributeAction = exports.AttributeAction || (exports.AttributeAction = {})); /***/ }), /***/ 6110: /***/ ((module, exports, __nccwpck_require__) => { /* eslint-env browser */ /** * This is the web browser implementation of `debug()`. */ exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); exports.destroy = (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } }; })(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ // eslint-disable-next-line complexity function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } let m; // Is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 // eslint-disable-next-line no-return-assign return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // Is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) || // Double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); if (!this.useColors) { return; } const c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, match => { if (match === '%%') { return; } index++; if (match === '%c') { // We only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.debug()` when available. * No-op when `console.debug` is not a "function". * If `console.debug` is not available, falls back * to `console.log`. * * @api public */ exports.log = console.debug || console.log || (() => {}); /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (namespaces) { exports.storage.setItem('debug', namespaces); } else { exports.storage.removeItem('debug'); } } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { let r; try { r = exports.storage.getItem('debug'); } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context // The Browser also has localStorage in the global context. return localStorage; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } module.exports = __nccwpck_require__(40897)(exports); const {formatters} = module.exports; /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ formatters.j = function (v) { try { return JSON.stringify(v); } catch (error) { return '[UnexpectedJSONParseError]: ' + error.message; } }; /***/ }), /***/ 40897: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. */ function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = __nccwpck_require__(70744); createDebug.destroy = destroy; Object.keys(env).forEach(key => { createDebug[key] = env[key]; }); /** * The currently active debug mode names, and names to skip. */ createDebug.names = []; createDebug.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ createDebug.formatters = {}; /** * Selects a color for a debug namespace * @param {String} namespace The namespace string for the debug instance to be colored * @return {Number|String} An ANSI color code for the given namespace * @api private */ function selectColor(namespace) { let hash = 0; for (let i = 0; i < namespace.length; i++) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } createDebug.selectColor = selectColor; /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { let prevTime; let enableOverride = null; let namespacesCache; let enabledCache; function debug(...args) { // Disabled? if (!debug.enabled) { return; } const self = debug; // Set `diff` timestamp const curr = Number(new Date()); const ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== 'string') { // Anything else let's inspect with %O args.unshift('%O'); } // Apply any `formatters` transformations let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { // If we encounter an escaped % then don't increase the array index if (match === '%%') { return '%'; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === 'function') { const val = args[index]; match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // Apply env-specific formatting (colors, etc.) createDebug.formatArgs.call(self, args); const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug.namespace = namespace; debug.useColors = createDebug.useColors(); debug.color = createDebug.selectColor(namespace); debug.extend = extend; debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. Object.defineProperty(debug, 'enabled', { enumerable: true, configurable: false, get: () => { if (enableOverride !== null) { return enableOverride; } if (namespacesCache !== createDebug.namespaces) { namespacesCache = createDebug.namespaces; enabledCache = createDebug.enabled(namespace); } return enabledCache; }, set: v => { enableOverride = v; } }); // Env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } return debug; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); newDebug.log = this.log; return newDebug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { createDebug.save(namespaces); createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; const split = (typeof namespaces === 'string' ? namespaces : '') .trim() .replace(' ', ',') .split(',') .filter(Boolean); for (const ns of split) { if (ns[0] === '-') { createDebug.skips.push(ns.slice(1)); } else { createDebug.names.push(ns); } } } /** * Checks if the given string matches a namespace template, honoring * asterisks as wildcards. * * @param {String} search * @param {String} template * @return {Boolean} */ function matchesTemplate(search, template) { let searchIndex = 0; let templateIndex = 0; let starIndex = -1; let matchIndex = 0; while (searchIndex < search.length) { if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) { // Match character or proceed with wildcard if (template[templateIndex] === '*') { starIndex = templateIndex; matchIndex = searchIndex; templateIndex++; // Skip the '*' } else { searchIndex++; templateIndex++; } } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition // Backtrack to the last '*' and try to match more characters templateIndex = starIndex + 1; matchIndex++; searchIndex = matchIndex; } else { return false; // No match } } // Handle trailing '*' in template while (templateIndex < template.length && template[templateIndex] === '*') { templateIndex++; } return templateIndex === template.length; } /** * Disable debug output. * * @return {String} namespaces * @api public */ function disable() { const namespaces = [ ...createDebug.names, ...createDebug.skips.map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { for (const skip of createDebug.skips) { if (matchesTemplate(name, skip)) { return false; } } for (const ns of createDebug.names) { if (matchesTemplate(name, ns)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } /** * XXX DO NOT USE. This is a temporary stub function. * XXX It WILL be removed in the next major release. */ function destroy() { console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } createDebug.enable(createDebug.load()); return createDebug; } module.exports = setup; /***/ }), /***/ 2830: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** * Detect Electron renderer / nwjs process, which is node, but we should * treat as a browser. */ if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { module.exports = __nccwpck_require__(6110); } else { module.exports = __nccwpck_require__(95108); } /***/ }), /***/ 95108: /***/ ((module, exports, __nccwpck_require__) => { /** * Module dependencies. */ const tty = __nccwpck_require__(52018); const util = __nccwpck_require__(39023); /** * This is the Node.js implementation of `debug()`. */ exports.init = init; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.destroy = util.deprecate( () => {}, 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' ); /** * Colors. */ exports.colors = [6, 2, 3, 4, 5, 1]; try { // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) // eslint-disable-next-line import/no-extraneous-dependencies const supportsColor = __nccwpck_require__(21450); if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (error) { // Swallow - we only care if `supports-color` is available; it doesn't have to be. } /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter(key => { return /^debug_/i.test(key); }).reduce((obj, key) => { // Camel-case const prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); // Coerce string value into JS value let val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) { val = true; } else if (/^(no|off|false|disabled)$/i.test(val)) { val = false; } else if (val === 'null') { val = null; } else { val = Number(val); } obj[prop] = val; return obj; }, {}); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); } /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs(args) { const {namespace: name, useColors} = this; if (useColors) { const c = this.color; const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); const prefix = ` ${colorCode};1m${name} \u001B[0m`; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); } else { args[0] = getDate() + name + ' ' + args[0]; } } function getDate() { if (exports.inspectOpts.hideDate) { return ''; } return new Date().toISOString() + ' '; } /** * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr. */ function log(...args) { return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n'); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { if (namespaces) { process.env.DEBUG = namespaces; } else { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { return process.env.DEBUG; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init(debug) { debug.inspectOpts = {}; const keys = Object.keys(exports.inspectOpts); for (let i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } } module.exports = __nccwpck_require__(40897)(exports); const {formatters} = module.exports; /** * Map %o to `util.inspect()`, all on a single line. */ formatters.o = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts) .split('\n') .map(str => str.trim()) .join(' '); }; /** * Map %O to `util.inspect()`, allowing multiple lines if needed. */ formatters.O = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts); }; /***/ }), /***/ 14150: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); class Deprecation extends Error { constructor(message) { super(message); // Maintains proper stack trace (only available on V8) /* istanbul ignore next */ if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } this.name = 'Deprecation'; } } exports.Deprecation = Deprecation; /***/ }), /***/ 75803: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.attributeNames = exports.elementNames = void 0; exports.elementNames = new Map([ "altGlyph", "altGlyphDef", "altGlyphItem", "animateColor", "animateMotion", "animateTransform", "clipPath", "feBlend", "feColorMatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap", "feDistantLight", "feDropShadow", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR", "feGaussianBlur", "feImage", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight", "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence", "foreignObject", "glyphRef", "linearGradient", "radialGradient", "textPath", ].map(function (val) { return [val.toLowerCase(), val]; })); exports.attributeNames = new Map([ "definitionURL", "attributeName", "attributeType", "baseFrequency", "baseProfile", "calcMode", "clipPathUnits", "diffuseConstant", "edgeMode", "filterUnits", "glyphRef", "gradientTransform", "gradientUnits", "kernelMatrix", "kernelUnitLength", "keyPoints", "keySplines", "keyTimes", "lengthAdjust", "limitingConeAngle", "markerHeight", "markerUnits", "markerWidth", "maskContentUnits", "maskUnits", "numOctaves", "pathLength", "patternContentUnits", "patternTransform", "patternUnits", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "preserveAspectRatio", "primitiveUnits", "refX", "refY", "repeatCount", "repeatDur", "requiredExtensions", "requiredFeatures", "specularConstant", "specularExponent", "spreadMethod", "startOffset", "stdDeviation", "stitchTiles", "surfaceScale", "systemLanguage", "tableValues", "targetX", "targetY", "textLength", "viewBox", "viewTarget", "xChannelSelector", "yChannelSelector", "zoomAndPan", ].map(function (val) { return [val.toLowerCase(), val]; })); /***/ }), /***/ 69943: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __assign = (this && this.__assign) || function () { __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; }; return __assign.apply(this, arguments); }; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (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; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.render = void 0; /* * Module dependencies */ var ElementType = __importStar(__nccwpck_require__(81108)); var entities_1 = __nccwpck_require__(8467); /** * Mixed-case SVG and MathML tags & attributes * recognized by the HTML parser. * * @see https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inforeign */ var foreignNames_js_1 = __nccwpck_require__(75803); var unencodedElements = new Set([ "style", "script", "xmp", "iframe", "noembed", "noframes", "plaintext", "noscript", ]); function replaceQuotes(value) { return value.replace(/"/g, """); } /** * Format attributes */ function formatAttributes(attributes, opts) { var _a; if (!attributes) return; var encode = ((_a = opts.encodeEntities) !== null && _a !== void 0 ? _a : opts.decodeEntities) === false ? replaceQuotes : opts.xmlMode || opts.encodeEntities !== "utf8" ? entities_1.encodeXML : entities_1.escapeAttribute; return Object.keys(attributes) .map(function (key) { var _a, _b; var value = (_a = attributes[key]) !== null && _a !== void 0 ? _a : ""; if (opts.xmlMode === "foreign") { /* Fix up mixed-case attribute names */ key = (_b = foreignNames_js_1.attributeNames.get(key)) !== null && _b !== void 0 ? _b : key; } if (!opts.emptyAttrs && !opts.xmlMode && value === "") { return key; } return "".concat(key, "=\"").concat(encode(value), "\""); }) .join(" "); } /** * Self-enclosing tags */ var singleTag = new Set([ "area", "base", "basefont", "br", "col", "command", "embed", "frame", "hr", "img", "input", "isindex", "keygen", "link", "meta", "param", "source", "track", "wbr", ]); /** * Renders a DOM node or an array of DOM nodes to a string. * * Can be thought of as the equivalent of the `outerHTML` of the passed node(s). * * @param node Node to be rendered. * @param options Changes serialization behavior */ function render(node, options) { if (options === void 0) { options = {}; } var nodes = "length" in node ? node : [node]; var output = ""; for (var i = 0; i < nodes.length; i++) { output += renderNode(nodes[i], options); } return output; } exports.render = render; exports["default"] = render; function renderNode(node, options) { switch (node.type) { case ElementType.Root: return render(node.children, options); // @ts-expect-error We don't use `Doctype` yet case ElementType.Doctype: case ElementType.Directive: return renderDirective(node); case ElementType.Comment: return renderComment(node); case ElementType.CDATA: return renderCdata(node); case ElementType.Script: case ElementType.Style: case ElementType.Tag: return renderTag(node, options); case ElementType.Text: return renderText(node, options); } } var foreignModeIntegrationPoints = new Set([ "mi", "mo", "mn", "ms", "mtext", "annotation-xml", "foreignObject", "desc", "title", ]); var foreignElements = new Set(["svg", "math"]); function renderTag(elem, opts) { var _a; // Handle SVG / MathML in HTML if (opts.xmlMode === "foreign") { /* Fix up mixed-case element names */ elem.name = (_a = foreignNames_js_1.elementNames.get(elem.name)) !== null && _a !== void 0 ? _a : elem.name; /* Exit foreign mode at integration points */ if (elem.parent && foreignModeIntegrationPoints.has(elem.parent.name)) { opts = __assign(__assign({}, opts), { xmlMode: false }); } } if (!opts.xmlMode && foreignElements.has(elem.name)) { opts = __assign(__assign({}, opts), { xmlMode: "foreign" }); } var tag = "<".concat(elem.name); var attribs = formatAttributes(elem.attribs, opts); if (attribs) { tag += " ".concat(attribs); } if (elem.children.length === 0 && (opts.xmlMode ? // In XML mode or foreign mode, and user hasn't explicitly turned off self-closing tags opts.selfClosingTags !== false : // User explicitly asked for self-closing tags, even in HTML mode opts.selfClosingTags && singleTag.has(elem.name))) { if (!opts.xmlMode) tag += " "; tag += "/>"; } else { tag += ">"; if (elem.children.length > 0) { tag += render(elem.children, opts); } if (opts.xmlMode || !singleTag.has(elem.name)) { tag += ""); } } return tag; } function renderDirective(elem) { return "<".concat(elem.data, ">"); } function renderText(elem, opts) { var _a; var data = elem.data || ""; // If entities weren't decoded, no need to encode them back if (((_a = opts.encodeEntities) !== null && _a !== void 0 ? _a : opts.decodeEntities) !== false && !(!opts.xmlMode && elem.parent && unencodedElements.has(elem.parent.name))) { data = opts.xmlMode || opts.encodeEntities !== "utf8" ? (0, entities_1.encodeXML)(data) : (0, entities_1.escapeText)(data); } return data; } function renderCdata(elem) { return ""); } function renderComment(elem) { return ""); } /***/ }), /***/ 81108: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Doctype = exports.CDATA = exports.Tag = exports.Style = exports.Script = exports.Comment = exports.Directive = exports.Text = exports.Root = exports.isTag = exports.ElementType = void 0; /** Types of elements found in htmlparser2's DOM */ var ElementType; (function (ElementType) { /** Type for the root element of a document */ ElementType["Root"] = "root"; /** Type for Text */ ElementType["Text"] = "text"; /** Type for */ ElementType["Directive"] = "directive"; /** Type for */ ElementType["Comment"] = "comment"; /** Type for `. this.sequenceIndex = Number(c === CharCodes.Lt); } } stateCDATASequence(c) { if (c === Sequences.Cdata[this.sequenceIndex]) { if (++this.sequenceIndex === Sequences.Cdata.length) { this.state = State.InCommentLike; this.currentSequence = Sequences.CdataEnd; this.sequenceIndex = 0; this.sectionStart = this.index + 1; } } else { this.sequenceIndex = 0; this.state = State.InDeclaration; this.stateInDeclaration(c); // Reconsume the character } } /** * When we wait for one specific character, we can speed things up * by skipping through the buffer until we find it. * * @returns Whether the character was found. */ fastForwardTo(c) { while (++this.index < this.buffer.length + this.offset) { if (this.buffer.charCodeAt(this.index - this.offset) === c) { return true; } } /* * We increment the index at the end of the `parse` loop, * so set it to `buffer.length - 1` here. * * TODO: Refactor `parse` to increment index before calling states. */ this.index = this.buffer.length + this.offset - 1; return false; } /** * Comments and CDATA end with `-->` and `]]>`. * * Their common qualities are: * - Their end sequences have a distinct character they start with. * - That character is then repeated, so we have to check multiple repeats. * - All characters but the start character of the sequence can be skipped. */ stateInCommentLike(c) { if (c === this.currentSequence[this.sequenceIndex]) { if (++this.sequenceIndex === this.currentSequence.length) { if (this.currentSequence === Sequences.CdataEnd) { this.cbs.oncdata(this.sectionStart, this.index, 2); } else { this.cbs.oncomment(this.sectionStart, this.index, 2); } this.sequenceIndex = 0; this.sectionStart = this.index + 1; this.state = State.Text; } } else if (this.sequenceIndex === 0) { // Fast-forward to the first character of the sequence if (this.fastForwardTo(this.currentSequence[0])) { this.sequenceIndex = 1; } } else if (c !== this.currentSequence[this.sequenceIndex - 1]) { // Allow long sequences, eg. --->, ]]]> this.sequenceIndex = 0; } } /** * HTML only allows ASCII alpha characters (a-z and A-Z) at the beginning of a tag name. * * XML allows a lot more characters here (@see https://www.w3.org/TR/REC-xml/#NT-NameStartChar). * We allow anything that wouldn't end the tag. */ isTagStartChar(c) { return this.xmlMode ? !isEndOfTagSection(c) : isASCIIAlpha(c); } startSpecial(sequence, offset) { this.isSpecial = true; this.currentSequence = sequence; this.sequenceIndex = offset; this.state = State.SpecialStartSequence; } stateBeforeTagName(c) { if (c === CharCodes.ExclamationMark) { this.state = State.BeforeDeclaration; this.sectionStart = this.index + 1; } else if (c === CharCodes.Questionmark) { this.state = State.InProcessingInstruction; this.sectionStart = this.index + 1; } else if (this.isTagStartChar(c)) { const lower = c | 0x20; this.sectionStart = this.index; if (this.xmlMode) { this.state = State.InTagName; } else if (lower === Sequences.ScriptEnd[2]) { this.state = State.BeforeSpecialS; } else if (lower === Sequences.TitleEnd[2] || lower === Sequences.XmpEnd[2]) { this.state = State.BeforeSpecialT; } else { this.state = State.InTagName; } } else if (c === CharCodes.Slash) { this.state = State.BeforeClosingTagName; } else { this.state = State.Text; this.stateText(c); } } stateInTagName(c) { if (isEndOfTagSection(c)) { this.cbs.onopentagname(this.sectionStart, this.index); this.sectionStart = -1; this.state = State.BeforeAttributeName; this.stateBeforeAttributeName(c); } } stateBeforeClosingTagName(c) { if (isWhitespace(c)) { // Ignore } else if (c === CharCodes.Gt) { this.state = State.Text; } else { this.state = this.isTagStartChar(c) ? State.InClosingTagName : State.InSpecialComment; this.sectionStart = this.index; } } stateInClosingTagName(c) { if (c === CharCodes.Gt || isWhitespace(c)) { this.cbs.onclosetag(this.sectionStart, this.index); this.sectionStart = -1; this.state = State.AfterClosingTagName; this.stateAfterClosingTagName(c); } } stateAfterClosingTagName(c) { // Skip everything until ">" if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) { this.state = State.Text; this.sectionStart = this.index + 1; } } stateBeforeAttributeName(c) { if (c === CharCodes.Gt) { this.cbs.onopentagend(this.index); if (this.isSpecial) { this.state = State.InSpecialTag; this.sequenceIndex = 0; } else { this.state = State.Text; } this.sectionStart = this.index + 1; } else if (c === CharCodes.Slash) { this.state = State.InSelfClosingTag; } else if (!isWhitespace(c)) { this.state = State.InAttributeName; this.sectionStart = this.index; } } stateInSelfClosingTag(c) { if (c === CharCodes.Gt) { this.cbs.onselfclosingtag(this.index); this.state = State.Text; this.sectionStart = this.index + 1; this.isSpecial = false; // Reset special state, in case of self-closing special tags } else if (!isWhitespace(c)) { this.state = State.BeforeAttributeName; this.stateBeforeAttributeName(c); } } stateInAttributeName(c) { if (c === CharCodes.Eq || isEndOfTagSection(c)) { this.cbs.onattribname(this.sectionStart, this.index); this.sectionStart = this.index; this.state = State.AfterAttributeName; this.stateAfterAttributeName(c); } } stateAfterAttributeName(c) { if (c === CharCodes.Eq) { this.state = State.BeforeAttributeValue; } else if (c === CharCodes.Slash || c === CharCodes.Gt) { this.cbs.onattribend(QuoteType.NoValue, this.sectionStart); this.sectionStart = -1; this.state = State.BeforeAttributeName; this.stateBeforeAttributeName(c); } else if (!isWhitespace(c)) { this.cbs.onattribend(QuoteType.NoValue, this.sectionStart); this.state = State.InAttributeName; this.sectionStart = this.index; } } stateBeforeAttributeValue(c) { if (c === CharCodes.DoubleQuote) { this.state = State.InAttributeValueDq; this.sectionStart = this.index + 1; } else if (c === CharCodes.SingleQuote) { this.state = State.InAttributeValueSq; this.sectionStart = this.index + 1; } else if (!isWhitespace(c)) { this.sectionStart = this.index; this.state = State.InAttributeValueNq; this.stateInAttributeValueNoQuotes(c); // Reconsume token } } handleInAttributeValue(c, quote) { if (c === quote || (!this.decodeEntities && this.fastForwardTo(quote))) { this.cbs.onattribdata(this.sectionStart, this.index); this.sectionStart = -1; this.cbs.onattribend(quote === CharCodes.DoubleQuote ? QuoteType.Double : QuoteType.Single, this.index + 1); this.state = State.BeforeAttributeName; } else if (this.decodeEntities && c === CharCodes.Amp) { this.startEntity(); } } stateInAttributeValueDoubleQuotes(c) { this.handleInAttributeValue(c, CharCodes.DoubleQuote); } stateInAttributeValueSingleQuotes(c) { this.handleInAttributeValue(c, CharCodes.SingleQuote); } stateInAttributeValueNoQuotes(c) { if (isWhitespace(c) || c === CharCodes.Gt) { this.cbs.onattribdata(this.sectionStart, this.index); this.sectionStart = -1; this.cbs.onattribend(QuoteType.Unquoted, this.index); this.state = State.BeforeAttributeName; this.stateBeforeAttributeName(c); } else if (this.decodeEntities && c === CharCodes.Amp) { this.startEntity(); } } stateBeforeDeclaration(c) { if (c === CharCodes.OpeningSquareBracket) { this.state = State.CDATASequence; this.sequenceIndex = 0; } else { this.state = c === CharCodes.Dash ? State.BeforeComment : State.InDeclaration; } } stateInDeclaration(c) { if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) { this.cbs.ondeclaration(this.sectionStart, this.index); this.state = State.Text; this.sectionStart = this.index + 1; } } stateInProcessingInstruction(c) { if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) { this.cbs.onprocessinginstruction(this.sectionStart, this.index); this.state = State.Text; this.sectionStart = this.index + 1; } } stateBeforeComment(c) { if (c === CharCodes.Dash) { this.state = State.InCommentLike; this.currentSequence = Sequences.CommentEnd; // Allow short comments (eg. ) this.sequenceIndex = 2; this.sectionStart = this.index + 1; } else { this.state = State.InDeclaration; } } stateInSpecialComment(c) { if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) { this.cbs.oncomment(this.sectionStart, this.index, 0); this.state = State.Text; this.sectionStart = this.index + 1; } } stateBeforeSpecialS(c) { const lower = c | 0x20; if (lower === Sequences.ScriptEnd[3]) { this.startSpecial(Sequences.ScriptEnd, 4); } else if (lower === Sequences.StyleEnd[3]) { this.startSpecial(Sequences.StyleEnd, 4); } else { this.state = State.InTagName; this.stateInTagName(c); // Consume the token again } } stateBeforeSpecialT(c) { const lower = c | 0x20; switch (lower) { case Sequences.TitleEnd[3]: { this.startSpecial(Sequences.TitleEnd, 4); break; } case Sequences.TextareaEnd[3]: { this.startSpecial(Sequences.TextareaEnd, 4); break; } case Sequences.XmpEnd[3]: { this.startSpecial(Sequences.XmpEnd, 4); break; } default: { this.state = State.InTagName; this.stateInTagName(c); // Consume the token again } } } startEntity() { this.baseState = this.state; this.state = State.InEntity; this.entityStart = this.index; this.entityDecoder.startEntity(this.xmlMode ? decode_1.DecodingMode.Strict : this.baseState === State.Text || this.baseState === State.InSpecialTag ? decode_1.DecodingMode.Legacy : decode_1.DecodingMode.Attribute); } stateInEntity() { const length = this.entityDecoder.write(this.buffer, this.index - this.offset); // If `length` is positive, we are done with the entity. if (length >= 0) { this.state = this.baseState; if (length === 0) { this.index = this.entityStart; } } else { // Mark buffer as consumed. this.index = this.offset + this.buffer.length - 1; } } /** * Remove data that has already been consumed from the buffer. */ cleanup() { // If we are inside of text or attributes, emit what we already have. if (this.running && this.sectionStart !== this.index) { if (this.state === State.Text || (this.state === State.InSpecialTag && this.sequenceIndex === 0)) { this.cbs.ontext(this.sectionStart, this.index); this.sectionStart = this.index; } else if (this.state === State.InAttributeValueDq || this.state === State.InAttributeValueSq || this.state === State.InAttributeValueNq) { this.cbs.onattribdata(this.sectionStart, this.index); this.sectionStart = this.index; } } } shouldContinue() { return this.index < this.buffer.length + this.offset && this.running; } /** * Iterates through the buffer, calling the function corresponding to the current state. * * States that are more likely to be hit are higher up, as a performance improvement. */ parse() { while (this.shouldContinue()) { const c = this.buffer.charCodeAt(this.index - this.offset); switch (this.state) { case State.Text: { this.stateText(c); break; } case State.SpecialStartSequence: { this.stateSpecialStartSequence(c); break; } case State.InSpecialTag: { this.stateInSpecialTag(c); break; } case State.CDATASequence: { this.stateCDATASequence(c); break; } case State.InAttributeValueDq: { this.stateInAttributeValueDoubleQuotes(c); break; } case State.InAttributeName: { this.stateInAttributeName(c); break; } case State.InCommentLike: { this.stateInCommentLike(c); break; } case State.InSpecialComment: { this.stateInSpecialComment(c); break; } case State.BeforeAttributeName: { this.stateBeforeAttributeName(c); break; } case State.InTagName: { this.stateInTagName(c); break; } case State.InClosingTagName: { this.stateInClosingTagName(c); break; } case State.BeforeTagName: { this.stateBeforeTagName(c); break; } case State.AfterAttributeName: { this.stateAfterAttributeName(c); break; } case State.InAttributeValueSq: { this.stateInAttributeValueSingleQuotes(c); break; } case State.BeforeAttributeValue: { this.stateBeforeAttributeValue(c); break; } case State.BeforeClosingTagName: { this.stateBeforeClosingTagName(c); break; } case State.AfterClosingTagName: { this.stateAfterClosingTagName(c); break; } case State.BeforeSpecialS: { this.stateBeforeSpecialS(c); break; } case State.BeforeSpecialT: { this.stateBeforeSpecialT(c); break; } case State.InAttributeValueNq: { this.stateInAttributeValueNoQuotes(c); break; } case State.InSelfClosingTag: { this.stateInSelfClosingTag(c); break; } case State.InDeclaration: { this.stateInDeclaration(c); break; } case State.BeforeDeclaration: { this.stateBeforeDeclaration(c); break; } case State.BeforeComment: { this.stateBeforeComment(c); break; } case State.InProcessingInstruction: { this.stateInProcessingInstruction(c); break; } case State.InEntity: { this.stateInEntity(); break; } } this.index++; } this.cleanup(); } finish() { if (this.state === State.InEntity) { this.entityDecoder.end(); this.state = this.baseState; } this.handleTrailingData(); this.cbs.onend(); } /** Handle any trailing data. */ handleTrailingData() { const endIndex = this.buffer.length + this.offset; // If there is no remaining data, we are done. if (this.sectionStart >= endIndex) { return; } if (this.state === State.InCommentLike) { if (this.currentSequence === Sequences.CdataEnd) { this.cbs.oncdata(this.sectionStart, endIndex, 0); } else { this.cbs.oncomment(this.sectionStart, endIndex, 0); } } else if (this.state === State.InTagName || this.state === State.BeforeAttributeName || this.state === State.BeforeAttributeValue || this.state === State.AfterAttributeName || this.state === State.InAttributeName || this.state === State.InAttributeValueSq || this.state === State.InAttributeValueDq || this.state === State.InAttributeValueNq || this.state === State.InClosingTagName) { /* * If we are currently in an opening or closing tag, us not calling the * respective callback signals that the tag should be ignored. */ } else { this.cbs.ontext(this.sectionStart, endIndex); } } emitCodePoint(cp, consumed) { if (this.baseState !== State.Text && this.baseState !== State.InSpecialTag) { if (this.sectionStart < this.entityStart) { this.cbs.onattribdata(this.sectionStart, this.entityStart); } this.sectionStart = this.entityStart + consumed; this.index = this.sectionStart - 1; this.cbs.onattribentity(cp); } else { if (this.sectionStart < this.entityStart) { this.cbs.ontext(this.sectionStart, this.entityStart); } this.sectionStart = this.entityStart + consumed; this.index = this.sectionStart - 1; this.cbs.ontextentity(cp, this.sectionStart); } } } exports["default"] = Tokenizer; //# sourceMappingURL=Tokenizer.js.map /***/ }), /***/ 93231: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DomUtils = exports.getFeed = exports.ElementType = exports.QuoteType = exports.Tokenizer = exports.DefaultHandler = exports.DomHandler = exports.Parser = void 0; exports.parseDocument = parseDocument; exports.parseDOM = parseDOM; exports.createDocumentStream = createDocumentStream; exports.createDomStream = createDomStream; exports.parseFeed = parseFeed; const Parser_js_1 = __nccwpck_require__(57136); var Parser_js_2 = __nccwpck_require__(57136); Object.defineProperty(exports, "Parser", ({ enumerable: true, get: function () { return Parser_js_2.Parser; } })); const domhandler_1 = __nccwpck_require__(57792); var domhandler_2 = __nccwpck_require__(57792); Object.defineProperty(exports, "DomHandler", ({ enumerable: true, get: function () { return domhandler_2.DomHandler; } })); // Old name for DomHandler Object.defineProperty(exports, "DefaultHandler", ({ enumerable: true, get: function () { return domhandler_2.DomHandler; } })); // Helper methods /** * Parses the data, returns the resulting document. * * @param data The data that should be parsed. * @param options Optional options for the parser and DOM handler. */ function parseDocument(data, options) { const handler = new domhandler_1.DomHandler(undefined, options); new Parser_js_1.Parser(handler, options).end(data); return handler.root; } /** * Parses data, returns an array of the root nodes. * * Note that the root nodes still have a `Document` node as their parent. * Use `parseDocument` to get the `Document` node instead. * * @param data The data that should be parsed. * @param options Optional options for the parser and DOM handler. * @deprecated Use `parseDocument` instead. */ function parseDOM(data, options) { return parseDocument(data, options).children; } /** * Creates a parser instance, with an attached DOM handler. * * @param callback A callback that will be called once parsing has been completed, with the resulting document. * @param options Optional options for the parser and DOM handler. * @param elementCallback An optional callback that will be called every time a tag has been completed inside of the DOM. */ function createDocumentStream(callback, options, elementCallback) { const handler = new domhandler_1.DomHandler((error) => callback(error, handler.root), options, elementCallback); return new Parser_js_1.Parser(handler, options); } /** * Creates a parser instance, with an attached DOM handler. * * @param callback A callback that will be called once parsing has been completed, with an array of root nodes. * @param options Optional options for the parser and DOM handler. * @param elementCallback An optional callback that will be called every time a tag has been completed inside of the DOM. * @deprecated Use `createDocumentStream` instead. */ function createDomStream(callback, options, elementCallback) { const handler = new domhandler_1.DomHandler(callback, options, elementCallback); return new Parser_js_1.Parser(handler, options); } var Tokenizer_js_1 = __nccwpck_require__(84170); Object.defineProperty(exports, "Tokenizer", ({ enumerable: true, get: function () { return __importDefault(Tokenizer_js_1).default; } })); Object.defineProperty(exports, "QuoteType", ({ enumerable: true, get: function () { return Tokenizer_js_1.QuoteType; } })); /* * All of the following exports exist for backwards-compatibility. * They should probably be removed eventually. */ exports.ElementType = __importStar(__nccwpck_require__(81108)); const domutils_1 = __nccwpck_require__(92357); var domutils_2 = __nccwpck_require__(92357); Object.defineProperty(exports, "getFeed", ({ enumerable: true, get: function () { return domutils_2.getFeed; } })); const parseFeedDefaultOptions = { xmlMode: true }; /** * Parse a feed. * * @param feed The feed that should be parsed, as a string. * @param options Optionally, options for parsing. When using this, you should set `xmlMode` to `true`. */ function parseFeed(feed, options = parseFeedDefaultOptions) { return (0, domutils_1.getFeed)(parseDOM(feed, options)); } exports.DomUtils = __importStar(__nccwpck_require__(92357)); //# sourceMappingURL=index.js.map /***/ }), /***/ 48344: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Adapted from https://github.com/mathiasbynens/he/blob/36afe179392226cf1b6ccdb16ebbb7a5a844d93a/src/he.js#L106-L134 var _a; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromCodePoint = void 0; exports.replaceCodePoint = replaceCodePoint; exports.decodeCodePoint = decodeCodePoint; const decodeMap = new Map([ [0, 65533], // C1 Unicode control character reference replacements [128, 8364], [130, 8218], [131, 402], [132, 8222], [133, 8230], [134, 8224], [135, 8225], [136, 710], [137, 8240], [138, 352], [139, 8249], [140, 338], [142, 381], [145, 8216], [146, 8217], [147, 8220], [148, 8221], [149, 8226], [150, 8211], [151, 8212], [152, 732], [153, 8482], [154, 353], [155, 8250], [156, 339], [158, 382], [159, 376], ]); /** * Polyfill for `String.fromCodePoint`. It is used to create a string from a Unicode code point. */ exports.fromCodePoint = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, n/no-unsupported-features/es-builtins (_a = String.fromCodePoint) !== null && _a !== void 0 ? _a : function (codePoint) { let output = ""; if (codePoint > 65535) { codePoint -= 65536; output += String.fromCharCode(((codePoint >>> 10) & 1023) | 55296); codePoint = 56320 | (codePoint & 1023); } output += String.fromCharCode(codePoint); return output; }; /** * Replace the given code point with a replacement character if it is a * surrogate or is outside the valid range. Otherwise return the code * point unchanged. */ function replaceCodePoint(codePoint) { var _a; if ((codePoint >= 55296 && codePoint <= 57343) || codePoint > 1114111) { return 65533; } return (_a = decodeMap.get(codePoint)) !== null && _a !== void 0 ? _a : codePoint; } /** * Replace the code point if relevant, then convert it to a string. * * @deprecated Use `fromCodePoint(replaceCodePoint(codePoint))` instead. * @param codePoint The code point to decode. * @returns The decoded code point. */ function decodeCodePoint(codePoint) { return (0, exports.fromCodePoint)(replaceCodePoint(codePoint)); } //# sourceMappingURL=decode-codepoint.js.map /***/ }), /***/ 92660: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromCodePoint = exports.replaceCodePoint = exports.decodeCodePoint = exports.xmlDecodeTree = exports.htmlDecodeTree = exports.EntityDecoder = exports.DecodingMode = exports.BinTrieFlags = void 0; exports.determineBranch = determineBranch; exports.decodeHTML = decodeHTML; exports.decodeHTMLAttribute = decodeHTMLAttribute; exports.decodeHTMLStrict = decodeHTMLStrict; exports.decodeXML = decodeXML; const decode_data_html_js_1 = __nccwpck_require__(2713); const decode_data_xml_js_1 = __nccwpck_require__(1735); const decode_codepoint_js_1 = __nccwpck_require__(48344); var CharCodes; (function (CharCodes) { CharCodes[CharCodes["NUM"] = 35] = "NUM"; CharCodes[CharCodes["SEMI"] = 59] = "SEMI"; CharCodes[CharCodes["EQUALS"] = 61] = "EQUALS"; CharCodes[CharCodes["ZERO"] = 48] = "ZERO"; CharCodes[CharCodes["NINE"] = 57] = "NINE"; CharCodes[CharCodes["LOWER_A"] = 97] = "LOWER_A"; CharCodes[CharCodes["LOWER_F"] = 102] = "LOWER_F"; CharCodes[CharCodes["LOWER_X"] = 120] = "LOWER_X"; CharCodes[CharCodes["LOWER_Z"] = 122] = "LOWER_Z"; CharCodes[CharCodes["UPPER_A"] = 65] = "UPPER_A"; CharCodes[CharCodes["UPPER_F"] = 70] = "UPPER_F"; CharCodes[CharCodes["UPPER_Z"] = 90] = "UPPER_Z"; })(CharCodes || (CharCodes = {})); /** Bit that needs to be set to convert an upper case ASCII character to lower case */ const TO_LOWER_BIT = 32; var BinTrieFlags; (function (BinTrieFlags) { BinTrieFlags[BinTrieFlags["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH"; BinTrieFlags[BinTrieFlags["BRANCH_LENGTH"] = 16256] = "BRANCH_LENGTH"; BinTrieFlags[BinTrieFlags["JUMP_TABLE"] = 127] = "JUMP_TABLE"; })(BinTrieFlags || (exports.BinTrieFlags = BinTrieFlags = {})); function isNumber(code) { return code >= CharCodes.ZERO && code <= CharCodes.NINE; } function isHexadecimalCharacter(code) { return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_F) || (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_F)); } function isAsciiAlphaNumeric(code) { return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_Z) || (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_Z) || isNumber(code)); } /** * Checks if the given character is a valid end character for an entity in an attribute. * * Attribute values that aren't terminated properly aren't parsed, and shouldn't lead to a parser error. * See the example in https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state */ function isEntityInAttributeInvalidEnd(code) { return code === CharCodes.EQUALS || isAsciiAlphaNumeric(code); } var EntityDecoderState; (function (EntityDecoderState) { EntityDecoderState[EntityDecoderState["EntityStart"] = 0] = "EntityStart"; EntityDecoderState[EntityDecoderState["NumericStart"] = 1] = "NumericStart"; EntityDecoderState[EntityDecoderState["NumericDecimal"] = 2] = "NumericDecimal"; EntityDecoderState[EntityDecoderState["NumericHex"] = 3] = "NumericHex"; EntityDecoderState[EntityDecoderState["NamedEntity"] = 4] = "NamedEntity"; })(EntityDecoderState || (EntityDecoderState = {})); var DecodingMode; (function (DecodingMode) { /** Entities in text nodes that can end with any character. */ DecodingMode[DecodingMode["Legacy"] = 0] = "Legacy"; /** Only allow entities terminated with a semicolon. */ DecodingMode[DecodingMode["Strict"] = 1] = "Strict"; /** Entities in attributes have limitations on ending characters. */ DecodingMode[DecodingMode["Attribute"] = 2] = "Attribute"; })(DecodingMode || (exports.DecodingMode = DecodingMode = {})); /** * Token decoder with support of writing partial entities. */ class EntityDecoder { constructor( /** The tree used to decode entities. */ decodeTree, /** * The function that is called when a codepoint is decoded. * * For multi-byte named entities, this will be called multiple times, * with the second codepoint, and the same `consumed` value. * * @param codepoint The decoded codepoint. * @param consumed The number of bytes consumed by the decoder. */ emitCodePoint, /** An object that is used to produce errors. */ errors) { this.decodeTree = decodeTree; this.emitCodePoint = emitCodePoint; this.errors = errors; /** The current state of the decoder. */ this.state = EntityDecoderState.EntityStart; /** Characters that were consumed while parsing an entity. */ this.consumed = 1; /** * The result of the entity. * * Either the result index of a numeric entity, or the codepoint of a * numeric entity. */ this.result = 0; /** The current index in the decode tree. */ this.treeIndex = 0; /** The number of characters that were consumed in excess. */ this.excess = 1; /** The mode in which the decoder is operating. */ this.decodeMode = DecodingMode.Strict; } /** Resets the instance to make it reusable. */ startEntity(decodeMode) { this.decodeMode = decodeMode; this.state = EntityDecoderState.EntityStart; this.result = 0; this.treeIndex = 0; this.excess = 1; this.consumed = 1; } /** * Write an entity to the decoder. This can be called multiple times with partial entities. * If the entity is incomplete, the decoder will return -1. * * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the * entity is incomplete, and resume when the next string is written. * * @param input The string containing the entity (or a continuation of the entity). * @param offset The offset at which the entity begins. Should be 0 if this is not the first call. * @returns The number of characters that were consumed, or -1 if the entity is incomplete. */ write(input, offset) { switch (this.state) { case EntityDecoderState.EntityStart: { if (input.charCodeAt(offset) === CharCodes.NUM) { this.state = EntityDecoderState.NumericStart; this.consumed += 1; return this.stateNumericStart(input, offset + 1); } this.state = EntityDecoderState.NamedEntity; return this.stateNamedEntity(input, offset); } case EntityDecoderState.NumericStart: { return this.stateNumericStart(input, offset); } case EntityDecoderState.NumericDecimal: { return this.stateNumericDecimal(input, offset); } case EntityDecoderState.NumericHex: { return this.stateNumericHex(input, offset); } case EntityDecoderState.NamedEntity: { return this.stateNamedEntity(input, offset); } } } /** * Switches between the numeric decimal and hexadecimal states. * * Equivalent to the `Numeric character reference state` in the HTML spec. * * @param input The string containing the entity (or a continuation of the entity). * @param offset The current offset. * @returns The number of characters that were consumed, or -1 if the entity is incomplete. */ stateNumericStart(input, offset) { if (offset >= input.length) { return -1; } if ((input.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) { this.state = EntityDecoderState.NumericHex; this.consumed += 1; return this.stateNumericHex(input, offset + 1); } this.state = EntityDecoderState.NumericDecimal; return this.stateNumericDecimal(input, offset); } addToNumericResult(input, start, end, base) { if (start !== end) { const digitCount = end - start; this.result = this.result * Math.pow(base, digitCount) + Number.parseInt(input.substr(start, digitCount), base); this.consumed += digitCount; } } /** * Parses a hexadecimal numeric entity. * * Equivalent to the `Hexademical character reference state` in the HTML spec. * * @param input The string containing the entity (or a continuation of the entity). * @param offset The current offset. * @returns The number of characters that were consumed, or -1 if the entity is incomplete. */ stateNumericHex(input, offset) { const startIndex = offset; while (offset < input.length) { const char = input.charCodeAt(offset); if (isNumber(char) || isHexadecimalCharacter(char)) { offset += 1; } else { this.addToNumericResult(input, startIndex, offset, 16); return this.emitNumericEntity(char, 3); } } this.addToNumericResult(input, startIndex, offset, 16); return -1; } /** * Parses a decimal numeric entity. * * Equivalent to the `Decimal character reference state` in the HTML spec. * * @param input The string containing the entity (or a continuation of the entity). * @param offset The current offset. * @returns The number of characters that were consumed, or -1 if the entity is incomplete. */ stateNumericDecimal(input, offset) { const startIndex = offset; while (offset < input.length) { const char = input.charCodeAt(offset); if (isNumber(char)) { offset += 1; } else { this.addToNumericResult(input, startIndex, offset, 10); return this.emitNumericEntity(char, 2); } } this.addToNumericResult(input, startIndex, offset, 10); return -1; } /** * Validate and emit a numeric entity. * * Implements the logic from the `Hexademical character reference start * state` and `Numeric character reference end state` in the HTML spec. * * @param lastCp The last code point of the entity. Used to see if the * entity was terminated with a semicolon. * @param expectedLength The minimum number of characters that should be * consumed. Used to validate that at least one digit * was consumed. * @returns The number of characters that were consumed. */ emitNumericEntity(lastCp, expectedLength) { var _a; // Ensure we consumed at least one digit. if (this.consumed <= expectedLength) { (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed); return 0; } // Figure out if this is a legit end of the entity if (lastCp === CharCodes.SEMI) { this.consumed += 1; } else if (this.decodeMode === DecodingMode.Strict) { return 0; } this.emitCodePoint((0, decode_codepoint_js_1.replaceCodePoint)(this.result), this.consumed); if (this.errors) { if (lastCp !== CharCodes.SEMI) { this.errors.missingSemicolonAfterCharacterReference(); } this.errors.validateNumericCharacterReference(this.result); } return this.consumed; } /** * Parses a named entity. * * Equivalent to the `Named character reference state` in the HTML spec. * * @param input The string containing the entity (or a continuation of the entity). * @param offset The current offset. * @returns The number of characters that were consumed, or -1 if the entity is incomplete. */ stateNamedEntity(input, offset) { const { decodeTree } = this; let current = decodeTree[this.treeIndex]; // The mask is the number of bytes of the value, including the current byte. let valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14; for (; offset < input.length; offset++, this.excess++) { const char = input.charCodeAt(offset); this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char); if (this.treeIndex < 0) { return this.result === 0 || // If we are parsing an attribute (this.decodeMode === DecodingMode.Attribute && // We shouldn't have consumed any characters after the entity, (valueLength === 0 || // And there should be no invalid characters. isEntityInAttributeInvalidEnd(char))) ? 0 : this.emitNotTerminatedNamedEntity(); } current = decodeTree[this.treeIndex]; valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14; // If the branch is a value, store it and continue if (valueLength !== 0) { // If the entity is terminated by a semicolon, we are done. if (char === CharCodes.SEMI) { return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess); } // If we encounter a non-terminated (legacy) entity while parsing strictly, then ignore it. if (this.decodeMode !== DecodingMode.Strict) { this.result = this.treeIndex; this.consumed += this.excess; this.excess = 0; } } } return -1; } /** * Emit a named entity that was not terminated with a semicolon. * * @returns The number of characters consumed. */ emitNotTerminatedNamedEntity() { var _a; const { result, decodeTree } = this; const valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14; this.emitNamedEntityData(result, valueLength, this.consumed); (_a = this.errors) === null || _a === void 0 ? void 0 : _a.missingSemicolonAfterCharacterReference(); return this.consumed; } /** * Emit a named entity. * * @param result The index of the entity in the decode tree. * @param valueLength The number of bytes in the entity. * @param consumed The number of characters consumed. * * @returns The number of characters consumed. */ emitNamedEntityData(result, valueLength, consumed) { const { decodeTree } = this; this.emitCodePoint(valueLength === 1 ? decodeTree[result] & ~BinTrieFlags.VALUE_LENGTH : decodeTree[result + 1], consumed); if (valueLength === 3) { // For multi-byte values, we need to emit the second byte. this.emitCodePoint(decodeTree[result + 2], consumed); } return consumed; } /** * Signal to the parser that the end of the input was reached. * * Remaining data will be emitted and relevant errors will be produced. * * @returns The number of characters consumed. */ end() { var _a; switch (this.state) { case EntityDecoderState.NamedEntity: { // Emit a named entity if we have one. return this.result !== 0 && (this.decodeMode !== DecodingMode.Attribute || this.result === this.treeIndex) ? this.emitNotTerminatedNamedEntity() : 0; } // Otherwise, emit a numeric entity if we have one. case EntityDecoderState.NumericDecimal: { return this.emitNumericEntity(0, 2); } case EntityDecoderState.NumericHex: { return this.emitNumericEntity(0, 3); } case EntityDecoderState.NumericStart: { (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed); return 0; } case EntityDecoderState.EntityStart: { // Return 0 if we have no entity. return 0; } } } } exports.EntityDecoder = EntityDecoder; /** * Creates a function that decodes entities in a string. * * @param decodeTree The decode tree. * @returns A function that decodes entities in a string. */ function getDecoder(decodeTree) { let returnValue = ""; const decoder = new EntityDecoder(decodeTree, (data) => (returnValue += (0, decode_codepoint_js_1.fromCodePoint)(data))); return function decodeWithTrie(input, decodeMode) { let lastIndex = 0; let offset = 0; while ((offset = input.indexOf("&", offset)) >= 0) { returnValue += input.slice(lastIndex, offset); decoder.startEntity(decodeMode); const length = decoder.write(input, // Skip the "&" offset + 1); if (length < 0) { lastIndex = offset + decoder.end(); break; } lastIndex = offset + length; // If `length` is 0, skip the current `&` and continue. offset = length === 0 ? lastIndex + 1 : lastIndex; } const result = returnValue + input.slice(lastIndex); // Make sure we don't keep a reference to the final string. returnValue = ""; return result; }; } /** * Determines the branch of the current node that is taken given the current * character. This function is used to traverse the trie. * * @param decodeTree The trie. * @param current The current node. * @param nodeIdx The index right after the current node and its value. * @param char The current character. * @returns The index of the next node, or -1 if no branch is taken. */ function determineBranch(decodeTree, current, nodeIndex, char) { const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7; const jumpOffset = current & BinTrieFlags.JUMP_TABLE; // Case 1: Single branch encoded in jump offset if (branchCount === 0) { return jumpOffset !== 0 && char === jumpOffset ? nodeIndex : -1; } // Case 2: Multiple branches encoded in jump table if (jumpOffset) { const value = char - jumpOffset; return value < 0 || value >= branchCount ? -1 : decodeTree[nodeIndex + value] - 1; } // Case 3: Multiple branches encoded in dictionary // Binary search for the character. let lo = nodeIndex; let hi = lo + branchCount - 1; while (lo <= hi) { const mid = (lo + hi) >>> 1; const midValue = decodeTree[mid]; if (midValue < char) { lo = mid + 1; } else if (midValue > char) { hi = mid - 1; } else { return decodeTree[mid + branchCount]; } } return -1; } const htmlDecoder = /* #__PURE__ */ getDecoder(decode_data_html_js_1.htmlDecodeTree); const xmlDecoder = /* #__PURE__ */ getDecoder(decode_data_xml_js_1.xmlDecodeTree); /** * Decodes an HTML string. * * @param htmlString The string to decode. * @param mode The decoding mode. * @returns The decoded string. */ function decodeHTML(htmlString, mode = DecodingMode.Legacy) { return htmlDecoder(htmlString, mode); } /** * Decodes an HTML string in an attribute. * * @param htmlAttribute The string to decode. * @returns The decoded string. */ function decodeHTMLAttribute(htmlAttribute) { return htmlDecoder(htmlAttribute, DecodingMode.Attribute); } /** * Decodes an HTML string, requiring all entities to be terminated by a semicolon. * * @param htmlString The string to decode. * @returns The decoded string. */ function decodeHTMLStrict(htmlString) { return htmlDecoder(htmlString, DecodingMode.Strict); } /** * Decodes an XML string, requiring all entities to be terminated by a semicolon. * * @param xmlString The string to decode. * @returns The decoded string. */ function decodeXML(xmlString) { return xmlDecoder(xmlString, DecodingMode.Strict); } // Re-export for use by eg. htmlparser2 var decode_data_html_js_2 = __nccwpck_require__(2713); Object.defineProperty(exports, "htmlDecodeTree", ({ enumerable: true, get: function () { return decode_data_html_js_2.htmlDecodeTree; } })); var decode_data_xml_js_2 = __nccwpck_require__(1735); Object.defineProperty(exports, "xmlDecodeTree", ({ enumerable: true, get: function () { return decode_data_xml_js_2.xmlDecodeTree; } })); var decode_codepoint_js_2 = __nccwpck_require__(48344); Object.defineProperty(exports, "decodeCodePoint", ({ enumerable: true, get: function () { return decode_codepoint_js_2.decodeCodePoint; } })); Object.defineProperty(exports, "replaceCodePoint", ({ enumerable: true, get: function () { return decode_codepoint_js_2.replaceCodePoint; } })); Object.defineProperty(exports, "fromCodePoint", ({ enumerable: true, get: function () { return decode_codepoint_js_2.fromCodePoint; } })); //# sourceMappingURL=decode.js.map /***/ }), /***/ 2713: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Generated using scripts/write-decode-map.ts Object.defineProperty(exports, "__esModule", ({ value: true })); exports.htmlDecodeTree = void 0; exports.htmlDecodeTree = new Uint16Array( // prettier-ignore /* #__PURE__ */ "\u1d41<\xd5\u0131\u028a\u049d\u057b\u05d0\u0675\u06de\u07a2\u07d6\u080f\u0a4a\u0a91\u0da1\u0e6d\u0f09\u0f26\u10ca\u1228\u12e1\u1415\u149d\u14c3\u14df\u1525\0\0\0\0\0\0\u156b\u16cd\u198d\u1c12\u1ddd\u1f7e\u2060\u21b0\u228d\u23c0\u23fb\u2442\u2824\u2912\u2d08\u2e48\u2fce\u3016\u32ba\u3639\u37ac\u38fe\u3a28\u3a71\u3ae0\u3b2e\u0800EMabcfglmnoprstu\\bfms\x7f\x84\x8b\x90\x95\x98\xa6\xb3\xb9\xc8\xcflig\u803b\xc6\u40c6P\u803b&\u4026cute\u803b\xc1\u40c1reve;\u4102\u0100iyx}rc\u803b\xc2\u40c2;\u4410r;\uc000\ud835\udd04rave\u803b\xc0\u40c0pha;\u4391acr;\u4100d;\u6a53\u0100gp\x9d\xa1on;\u4104f;\uc000\ud835\udd38plyFunction;\u6061ing\u803b\xc5\u40c5\u0100cs\xbe\xc3r;\uc000\ud835\udc9cign;\u6254ilde\u803b\xc3\u40c3ml\u803b\xc4\u40c4\u0400aceforsu\xe5\xfb\xfe\u0117\u011c\u0122\u0127\u012a\u0100cr\xea\xf2kslash;\u6216\u0176\xf6\xf8;\u6ae7ed;\u6306y;\u4411\u0180crt\u0105\u010b\u0114ause;\u6235noullis;\u612ca;\u4392r;\uc000\ud835\udd05pf;\uc000\ud835\udd39eve;\u42d8c\xf2\u0113mpeq;\u624e\u0700HOacdefhilorsu\u014d\u0151\u0156\u0180\u019e\u01a2\u01b5\u01b7\u01ba\u01dc\u0215\u0273\u0278\u027ecy;\u4427PY\u803b\xa9\u40a9\u0180cpy\u015d\u0162\u017aute;\u4106\u0100;i\u0167\u0168\u62d2talDifferentialD;\u6145leys;\u612d\u0200aeio\u0189\u018e\u0194\u0198ron;\u410cdil\u803b\xc7\u40c7rc;\u4108nint;\u6230ot;\u410a\u0100dn\u01a7\u01adilla;\u40b8terDot;\u40b7\xf2\u017fi;\u43a7rcle\u0200DMPT\u01c7\u01cb\u01d1\u01d6ot;\u6299inus;\u6296lus;\u6295imes;\u6297o\u0100cs\u01e2\u01f8kwiseContourIntegral;\u6232eCurly\u0100DQ\u0203\u020foubleQuote;\u601duote;\u6019\u0200lnpu\u021e\u0228\u0247\u0255on\u0100;e\u0225\u0226\u6237;\u6a74\u0180git\u022f\u0236\u023aruent;\u6261nt;\u622fourIntegral;\u622e\u0100fr\u024c\u024e;\u6102oduct;\u6210nterClockwiseContourIntegral;\u6233oss;\u6a2fcr;\uc000\ud835\udc9ep\u0100;C\u0284\u0285\u62d3ap;\u624d\u0580DJSZacefios\u02a0\u02ac\u02b0\u02b4\u02b8\u02cb\u02d7\u02e1\u02e6\u0333\u048d\u0100;o\u0179\u02a5trahd;\u6911cy;\u4402cy;\u4405cy;\u440f\u0180grs\u02bf\u02c4\u02c7ger;\u6021r;\u61a1hv;\u6ae4\u0100ay\u02d0\u02d5ron;\u410e;\u4414l\u0100;t\u02dd\u02de\u6207a;\u4394r;\uc000\ud835\udd07\u0100af\u02eb\u0327\u0100cm\u02f0\u0322ritical\u0200ADGT\u0300\u0306\u0316\u031ccute;\u40b4o\u0174\u030b\u030d;\u42d9bleAcute;\u42ddrave;\u4060ilde;\u42dcond;\u62c4ferentialD;\u6146\u0470\u033d\0\0\0\u0342\u0354\0\u0405f;\uc000\ud835\udd3b\u0180;DE\u0348\u0349\u034d\u40a8ot;\u60dcqual;\u6250ble\u0300CDLRUV\u0363\u0372\u0382\u03cf\u03e2\u03f8ontourIntegra\xec\u0239o\u0274\u0379\0\0\u037b\xbb\u0349nArrow;\u61d3\u0100eo\u0387\u03a4ft\u0180ART\u0390\u0396\u03a1rrow;\u61d0ightArrow;\u61d4e\xe5\u02cang\u0100LR\u03ab\u03c4eft\u0100AR\u03b3\u03b9rrow;\u67f8ightArrow;\u67faightArrow;\u67f9ight\u0100AT\u03d8\u03derrow;\u61d2ee;\u62a8p\u0241\u03e9\0\0\u03efrrow;\u61d1ownArrow;\u61d5erticalBar;\u6225n\u0300ABLRTa\u0412\u042a\u0430\u045e\u047f\u037crrow\u0180;BU\u041d\u041e\u0422\u6193ar;\u6913pArrow;\u61f5reve;\u4311eft\u02d2\u043a\0\u0446\0\u0450ightVector;\u6950eeVector;\u695eector\u0100;B\u0459\u045a\u61bdar;\u6956ight\u01d4\u0467\0\u0471eeVector;\u695fector\u0100;B\u047a\u047b\u61c1ar;\u6957ee\u0100;A\u0486\u0487\u62a4rrow;\u61a7\u0100ct\u0492\u0497r;\uc000\ud835\udc9frok;\u4110\u0800NTacdfglmopqstux\u04bd\u04c0\u04c4\u04cb\u04de\u04e2\u04e7\u04ee\u04f5\u0521\u052f\u0536\u0552\u055d\u0560\u0565G;\u414aH\u803b\xd0\u40d0cute\u803b\xc9\u40c9\u0180aiy\u04d2\u04d7\u04dcron;\u411arc\u803b\xca\u40ca;\u442dot;\u4116r;\uc000\ud835\udd08rave\u803b\xc8\u40c8ement;\u6208\u0100ap\u04fa\u04fecr;\u4112ty\u0253\u0506\0\0\u0512mallSquare;\u65fberySmallSquare;\u65ab\u0100gp\u0526\u052aon;\u4118f;\uc000\ud835\udd3csilon;\u4395u\u0100ai\u053c\u0549l\u0100;T\u0542\u0543\u6a75ilde;\u6242librium;\u61cc\u0100ci\u0557\u055ar;\u6130m;\u6a73a;\u4397ml\u803b\xcb\u40cb\u0100ip\u056a\u056fsts;\u6203onentialE;\u6147\u0280cfios\u0585\u0588\u058d\u05b2\u05ccy;\u4424r;\uc000\ud835\udd09lled\u0253\u0597\0\0\u05a3mallSquare;\u65fcerySmallSquare;\u65aa\u0370\u05ba\0\u05bf\0\0\u05c4f;\uc000\ud835\udd3dAll;\u6200riertrf;\u6131c\xf2\u05cb\u0600JTabcdfgorst\u05e8\u05ec\u05ef\u05fa\u0600\u0612\u0616\u061b\u061d\u0623\u066c\u0672cy;\u4403\u803b>\u403emma\u0100;d\u05f7\u05f8\u4393;\u43dcreve;\u411e\u0180eiy\u0607\u060c\u0610dil;\u4122rc;\u411c;\u4413ot;\u4120r;\uc000\ud835\udd0a;\u62d9pf;\uc000\ud835\udd3eeater\u0300EFGLST\u0635\u0644\u064e\u0656\u065b\u0666qual\u0100;L\u063e\u063f\u6265ess;\u62dbullEqual;\u6267reater;\u6aa2ess;\u6277lantEqual;\u6a7eilde;\u6273cr;\uc000\ud835\udca2;\u626b\u0400Aacfiosu\u0685\u068b\u0696\u069b\u069e\u06aa\u06be\u06caRDcy;\u442a\u0100ct\u0690\u0694ek;\u42c7;\u405eirc;\u4124r;\u610clbertSpace;\u610b\u01f0\u06af\0\u06b2f;\u610dizontalLine;\u6500\u0100ct\u06c3\u06c5\xf2\u06a9rok;\u4126mp\u0144\u06d0\u06d8ownHum\xf0\u012fqual;\u624f\u0700EJOacdfgmnostu\u06fa\u06fe\u0703\u0707\u070e\u071a\u071e\u0721\u0728\u0744\u0778\u078b\u078f\u0795cy;\u4415lig;\u4132cy;\u4401cute\u803b\xcd\u40cd\u0100iy\u0713\u0718rc\u803b\xce\u40ce;\u4418ot;\u4130r;\u6111rave\u803b\xcc\u40cc\u0180;ap\u0720\u072f\u073f\u0100cg\u0734\u0737r;\u412ainaryI;\u6148lie\xf3\u03dd\u01f4\u0749\0\u0762\u0100;e\u074d\u074e\u622c\u0100gr\u0753\u0758ral;\u622bsection;\u62c2isible\u0100CT\u076c\u0772omma;\u6063imes;\u6062\u0180gpt\u077f\u0783\u0788on;\u412ef;\uc000\ud835\udd40a;\u4399cr;\u6110ilde;\u4128\u01eb\u079a\0\u079ecy;\u4406l\u803b\xcf\u40cf\u0280cfosu\u07ac\u07b7\u07bc\u07c2\u07d0\u0100iy\u07b1\u07b5rc;\u4134;\u4419r;\uc000\ud835\udd0dpf;\uc000\ud835\udd41\u01e3\u07c7\0\u07ccr;\uc000\ud835\udca5rcy;\u4408kcy;\u4404\u0380HJacfos\u07e4\u07e8\u07ec\u07f1\u07fd\u0802\u0808cy;\u4425cy;\u440cppa;\u439a\u0100ey\u07f6\u07fbdil;\u4136;\u441ar;\uc000\ud835\udd0epf;\uc000\ud835\udd42cr;\uc000\ud835\udca6\u0580JTaceflmost\u0825\u0829\u082c\u0850\u0863\u09b3\u09b8\u09c7\u09cd\u0a37\u0a47cy;\u4409\u803b<\u403c\u0280cmnpr\u0837\u083c\u0841\u0844\u084dute;\u4139bda;\u439bg;\u67ealacetrf;\u6112r;\u619e\u0180aey\u0857\u085c\u0861ron;\u413ddil;\u413b;\u441b\u0100fs\u0868\u0970t\u0500ACDFRTUVar\u087e\u08a9\u08b1\u08e0\u08e6\u08fc\u092f\u095b\u0390\u096a\u0100nr\u0883\u088fgleBracket;\u67e8row\u0180;BR\u0899\u089a\u089e\u6190ar;\u61e4ightArrow;\u61c6eiling;\u6308o\u01f5\u08b7\0\u08c3bleBracket;\u67e6n\u01d4\u08c8\0\u08d2eeVector;\u6961ector\u0100;B\u08db\u08dc\u61c3ar;\u6959loor;\u630aight\u0100AV\u08ef\u08f5rrow;\u6194ector;\u694e\u0100er\u0901\u0917e\u0180;AV\u0909\u090a\u0910\u62a3rrow;\u61a4ector;\u695aiangle\u0180;BE\u0924\u0925\u0929\u62b2ar;\u69cfqual;\u62b4p\u0180DTV\u0937\u0942\u094cownVector;\u6951eeVector;\u6960ector\u0100;B\u0956\u0957\u61bfar;\u6958ector\u0100;B\u0965\u0966\u61bcar;\u6952ight\xe1\u039cs\u0300EFGLST\u097e\u098b\u0995\u099d\u09a2\u09adqualGreater;\u62daullEqual;\u6266reater;\u6276ess;\u6aa1lantEqual;\u6a7dilde;\u6272r;\uc000\ud835\udd0f\u0100;e\u09bd\u09be\u62d8ftarrow;\u61daidot;\u413f\u0180npw\u09d4\u0a16\u0a1bg\u0200LRlr\u09de\u09f7\u0a02\u0a10eft\u0100AR\u09e6\u09ecrrow;\u67f5ightArrow;\u67f7ightArrow;\u67f6eft\u0100ar\u03b3\u0a0aight\xe1\u03bfight\xe1\u03caf;\uc000\ud835\udd43er\u0100LR\u0a22\u0a2ceftArrow;\u6199ightArrow;\u6198\u0180cht\u0a3e\u0a40\u0a42\xf2\u084c;\u61b0rok;\u4141;\u626a\u0400acefiosu\u0a5a\u0a5d\u0a60\u0a77\u0a7c\u0a85\u0a8b\u0a8ep;\u6905y;\u441c\u0100dl\u0a65\u0a6fiumSpace;\u605flintrf;\u6133r;\uc000\ud835\udd10nusPlus;\u6213pf;\uc000\ud835\udd44c\xf2\u0a76;\u439c\u0480Jacefostu\u0aa3\u0aa7\u0aad\u0ac0\u0b14\u0b19\u0d91\u0d97\u0d9ecy;\u440acute;\u4143\u0180aey\u0ab4\u0ab9\u0aberon;\u4147dil;\u4145;\u441d\u0180gsw\u0ac7\u0af0\u0b0eative\u0180MTV\u0ad3\u0adf\u0ae8ediumSpace;\u600bhi\u0100cn\u0ae6\u0ad8\xeb\u0ad9eryThi\xee\u0ad9ted\u0100GL\u0af8\u0b06reaterGreate\xf2\u0673essLes\xf3\u0a48Line;\u400ar;\uc000\ud835\udd11\u0200Bnpt\u0b22\u0b28\u0b37\u0b3areak;\u6060BreakingSpace;\u40a0f;\u6115\u0680;CDEGHLNPRSTV\u0b55\u0b56\u0b6a\u0b7c\u0ba1\u0beb\u0c04\u0c5e\u0c84\u0ca6\u0cd8\u0d61\u0d85\u6aec\u0100ou\u0b5b\u0b64ngruent;\u6262pCap;\u626doubleVerticalBar;\u6226\u0180lqx\u0b83\u0b8a\u0b9bement;\u6209ual\u0100;T\u0b92\u0b93\u6260ilde;\uc000\u2242\u0338ists;\u6204reater\u0380;EFGLST\u0bb6\u0bb7\u0bbd\u0bc9\u0bd3\u0bd8\u0be5\u626fqual;\u6271ullEqual;\uc000\u2267\u0338reater;\uc000\u226b\u0338ess;\u6279lantEqual;\uc000\u2a7e\u0338ilde;\u6275ump\u0144\u0bf2\u0bfdownHump;\uc000\u224e\u0338qual;\uc000\u224f\u0338e\u0100fs\u0c0a\u0c27tTriangle\u0180;BE\u0c1a\u0c1b\u0c21\u62eaar;\uc000\u29cf\u0338qual;\u62ecs\u0300;EGLST\u0c35\u0c36\u0c3c\u0c44\u0c4b\u0c58\u626equal;\u6270reater;\u6278ess;\uc000\u226a\u0338lantEqual;\uc000\u2a7d\u0338ilde;\u6274ested\u0100GL\u0c68\u0c79reaterGreater;\uc000\u2aa2\u0338essLess;\uc000\u2aa1\u0338recedes\u0180;ES\u0c92\u0c93\u0c9b\u6280qual;\uc000\u2aaf\u0338lantEqual;\u62e0\u0100ei\u0cab\u0cb9verseElement;\u620cghtTriangle\u0180;BE\u0ccb\u0ccc\u0cd2\u62ebar;\uc000\u29d0\u0338qual;\u62ed\u0100qu\u0cdd\u0d0cuareSu\u0100bp\u0ce8\u0cf9set\u0100;E\u0cf0\u0cf3\uc000\u228f\u0338qual;\u62e2erset\u0100;E\u0d03\u0d06\uc000\u2290\u0338qual;\u62e3\u0180bcp\u0d13\u0d24\u0d4eset\u0100;E\u0d1b\u0d1e\uc000\u2282\u20d2qual;\u6288ceeds\u0200;EST\u0d32\u0d33\u0d3b\u0d46\u6281qual;\uc000\u2ab0\u0338lantEqual;\u62e1ilde;\uc000\u227f\u0338erset\u0100;E\u0d58\u0d5b\uc000\u2283\u20d2qual;\u6289ilde\u0200;EFT\u0d6e\u0d6f\u0d75\u0d7f\u6241qual;\u6244ullEqual;\u6247ilde;\u6249erticalBar;\u6224cr;\uc000\ud835\udca9ilde\u803b\xd1\u40d1;\u439d\u0700Eacdfgmoprstuv\u0dbd\u0dc2\u0dc9\u0dd5\u0ddb\u0de0\u0de7\u0dfc\u0e02\u0e20\u0e22\u0e32\u0e3f\u0e44lig;\u4152cute\u803b\xd3\u40d3\u0100iy\u0dce\u0dd3rc\u803b\xd4\u40d4;\u441eblac;\u4150r;\uc000\ud835\udd12rave\u803b\xd2\u40d2\u0180aei\u0dee\u0df2\u0df6cr;\u414cga;\u43a9cron;\u439fpf;\uc000\ud835\udd46enCurly\u0100DQ\u0e0e\u0e1aoubleQuote;\u601cuote;\u6018;\u6a54\u0100cl\u0e27\u0e2cr;\uc000\ud835\udcaaash\u803b\xd8\u40d8i\u016c\u0e37\u0e3cde\u803b\xd5\u40d5es;\u6a37ml\u803b\xd6\u40d6er\u0100BP\u0e4b\u0e60\u0100ar\u0e50\u0e53r;\u603eac\u0100ek\u0e5a\u0e5c;\u63deet;\u63b4arenthesis;\u63dc\u0480acfhilors\u0e7f\u0e87\u0e8a\u0e8f\u0e92\u0e94\u0e9d\u0eb0\u0efcrtialD;\u6202y;\u441fr;\uc000\ud835\udd13i;\u43a6;\u43a0usMinus;\u40b1\u0100ip\u0ea2\u0eadncareplan\xe5\u069df;\u6119\u0200;eio\u0eb9\u0eba\u0ee0\u0ee4\u6abbcedes\u0200;EST\u0ec8\u0ec9\u0ecf\u0eda\u627aqual;\u6aaflantEqual;\u627cilde;\u627eme;\u6033\u0100dp\u0ee9\u0eeeuct;\u620fortion\u0100;a\u0225\u0ef9l;\u621d\u0100ci\u0f01\u0f06r;\uc000\ud835\udcab;\u43a8\u0200Ufos\u0f11\u0f16\u0f1b\u0f1fOT\u803b\"\u4022r;\uc000\ud835\udd14pf;\u611acr;\uc000\ud835\udcac\u0600BEacefhiorsu\u0f3e\u0f43\u0f47\u0f60\u0f73\u0fa7\u0faa\u0fad\u1096\u10a9\u10b4\u10bearr;\u6910G\u803b\xae\u40ae\u0180cnr\u0f4e\u0f53\u0f56ute;\u4154g;\u67ebr\u0100;t\u0f5c\u0f5d\u61a0l;\u6916\u0180aey\u0f67\u0f6c\u0f71ron;\u4158dil;\u4156;\u4420\u0100;v\u0f78\u0f79\u611cerse\u0100EU\u0f82\u0f99\u0100lq\u0f87\u0f8eement;\u620builibrium;\u61cbpEquilibrium;\u696fr\xbb\u0f79o;\u43a1ght\u0400ACDFTUVa\u0fc1\u0feb\u0ff3\u1022\u1028\u105b\u1087\u03d8\u0100nr\u0fc6\u0fd2gleBracket;\u67e9row\u0180;BL\u0fdc\u0fdd\u0fe1\u6192ar;\u61e5eftArrow;\u61c4eiling;\u6309o\u01f5\u0ff9\0\u1005bleBracket;\u67e7n\u01d4\u100a\0\u1014eeVector;\u695dector\u0100;B\u101d\u101e\u61c2ar;\u6955loor;\u630b\u0100er\u102d\u1043e\u0180;AV\u1035\u1036\u103c\u62a2rrow;\u61a6ector;\u695biangle\u0180;BE\u1050\u1051\u1055\u62b3ar;\u69d0qual;\u62b5p\u0180DTV\u1063\u106e\u1078ownVector;\u694feeVector;\u695cector\u0100;B\u1082\u1083\u61bear;\u6954ector\u0100;B\u1091\u1092\u61c0ar;\u6953\u0100pu\u109b\u109ef;\u611dndImplies;\u6970ightarrow;\u61db\u0100ch\u10b9\u10bcr;\u611b;\u61b1leDelayed;\u69f4\u0680HOacfhimoqstu\u10e4\u10f1\u10f7\u10fd\u1119\u111e\u1151\u1156\u1161\u1167\u11b5\u11bb\u11bf\u0100Cc\u10e9\u10eeHcy;\u4429y;\u4428FTcy;\u442ccute;\u415a\u0280;aeiy\u1108\u1109\u110e\u1113\u1117\u6abcron;\u4160dil;\u415erc;\u415c;\u4421r;\uc000\ud835\udd16ort\u0200DLRU\u112a\u1134\u113e\u1149ownArrow\xbb\u041eeftArrow\xbb\u089aightArrow\xbb\u0fddpArrow;\u6191gma;\u43a3allCircle;\u6218pf;\uc000\ud835\udd4a\u0272\u116d\0\0\u1170t;\u621aare\u0200;ISU\u117b\u117c\u1189\u11af\u65a1ntersection;\u6293u\u0100bp\u118f\u119eset\u0100;E\u1197\u1198\u628fqual;\u6291erset\u0100;E\u11a8\u11a9\u6290qual;\u6292nion;\u6294cr;\uc000\ud835\udcaear;\u62c6\u0200bcmp\u11c8\u11db\u1209\u120b\u0100;s\u11cd\u11ce\u62d0et\u0100;E\u11cd\u11d5qual;\u6286\u0100ch\u11e0\u1205eeds\u0200;EST\u11ed\u11ee\u11f4\u11ff\u627bqual;\u6ab0lantEqual;\u627dilde;\u627fTh\xe1\u0f8c;\u6211\u0180;es\u1212\u1213\u1223\u62d1rset\u0100;E\u121c\u121d\u6283qual;\u6287et\xbb\u1213\u0580HRSacfhiors\u123e\u1244\u1249\u1255\u125e\u1271\u1276\u129f\u12c2\u12c8\u12d1ORN\u803b\xde\u40deADE;\u6122\u0100Hc\u124e\u1252cy;\u440by;\u4426\u0100bu\u125a\u125c;\u4009;\u43a4\u0180aey\u1265\u126a\u126fron;\u4164dil;\u4162;\u4422r;\uc000\ud835\udd17\u0100ei\u127b\u1289\u01f2\u1280\0\u1287efore;\u6234a;\u4398\u0100cn\u128e\u1298kSpace;\uc000\u205f\u200aSpace;\u6009lde\u0200;EFT\u12ab\u12ac\u12b2\u12bc\u623cqual;\u6243ullEqual;\u6245ilde;\u6248pf;\uc000\ud835\udd4bipleDot;\u60db\u0100ct\u12d6\u12dbr;\uc000\ud835\udcafrok;\u4166\u0ae1\u12f7\u130e\u131a\u1326\0\u132c\u1331\0\0\0\0\0\u1338\u133d\u1377\u1385\0\u13ff\u1404\u140a\u1410\u0100cr\u12fb\u1301ute\u803b\xda\u40dar\u0100;o\u1307\u1308\u619fcir;\u6949r\u01e3\u1313\0\u1316y;\u440eve;\u416c\u0100iy\u131e\u1323rc\u803b\xdb\u40db;\u4423blac;\u4170r;\uc000\ud835\udd18rave\u803b\xd9\u40d9acr;\u416a\u0100di\u1341\u1369er\u0100BP\u1348\u135d\u0100ar\u134d\u1350r;\u405fac\u0100ek\u1357\u1359;\u63dfet;\u63b5arenthesis;\u63ddon\u0100;P\u1370\u1371\u62c3lus;\u628e\u0100gp\u137b\u137fon;\u4172f;\uc000\ud835\udd4c\u0400ADETadps\u1395\u13ae\u13b8\u13c4\u03e8\u13d2\u13d7\u13f3rrow\u0180;BD\u1150\u13a0\u13a4ar;\u6912ownArrow;\u61c5ownArrow;\u6195quilibrium;\u696eee\u0100;A\u13cb\u13cc\u62a5rrow;\u61a5own\xe1\u03f3er\u0100LR\u13de\u13e8eftArrow;\u6196ightArrow;\u6197i\u0100;l\u13f9\u13fa\u43d2on;\u43a5ing;\u416ecr;\uc000\ud835\udcb0ilde;\u4168ml\u803b\xdc\u40dc\u0480Dbcdefosv\u1427\u142c\u1430\u1433\u143e\u1485\u148a\u1490\u1496ash;\u62abar;\u6aeby;\u4412ash\u0100;l\u143b\u143c\u62a9;\u6ae6\u0100er\u1443\u1445;\u62c1\u0180bty\u144c\u1450\u147aar;\u6016\u0100;i\u144f\u1455cal\u0200BLST\u1461\u1465\u146a\u1474ar;\u6223ine;\u407ceparator;\u6758ilde;\u6240ThinSpace;\u600ar;\uc000\ud835\udd19pf;\uc000\ud835\udd4dcr;\uc000\ud835\udcb1dash;\u62aa\u0280cefos\u14a7\u14ac\u14b1\u14b6\u14bcirc;\u4174dge;\u62c0r;\uc000\ud835\udd1apf;\uc000\ud835\udd4ecr;\uc000\ud835\udcb2\u0200fios\u14cb\u14d0\u14d2\u14d8r;\uc000\ud835\udd1b;\u439epf;\uc000\ud835\udd4fcr;\uc000\ud835\udcb3\u0480AIUacfosu\u14f1\u14f5\u14f9\u14fd\u1504\u150f\u1514\u151a\u1520cy;\u442fcy;\u4407cy;\u442ecute\u803b\xdd\u40dd\u0100iy\u1509\u150drc;\u4176;\u442br;\uc000\ud835\udd1cpf;\uc000\ud835\udd50cr;\uc000\ud835\udcb4ml;\u4178\u0400Hacdefos\u1535\u1539\u153f\u154b\u154f\u155d\u1560\u1564cy;\u4416cute;\u4179\u0100ay\u1544\u1549ron;\u417d;\u4417ot;\u417b\u01f2\u1554\0\u155boWidt\xe8\u0ad9a;\u4396r;\u6128pf;\u6124cr;\uc000\ud835\udcb5\u0be1\u1583\u158a\u1590\0\u15b0\u15b6\u15bf\0\0\0\0\u15c6\u15db\u15eb\u165f\u166d\0\u1695\u169b\u16b2\u16b9\0\u16becute\u803b\xe1\u40e1reve;\u4103\u0300;Ediuy\u159c\u159d\u15a1\u15a3\u15a8\u15ad\u623e;\uc000\u223e\u0333;\u623frc\u803b\xe2\u40e2te\u80bb\xb4\u0306;\u4430lig\u803b\xe6\u40e6\u0100;r\xb2\u15ba;\uc000\ud835\udd1erave\u803b\xe0\u40e0\u0100ep\u15ca\u15d6\u0100fp\u15cf\u15d4sym;\u6135\xe8\u15d3ha;\u43b1\u0100ap\u15dfc\u0100cl\u15e4\u15e7r;\u4101g;\u6a3f\u0264\u15f0\0\0\u160a\u0280;adsv\u15fa\u15fb\u15ff\u1601\u1607\u6227nd;\u6a55;\u6a5clope;\u6a58;\u6a5a\u0380;elmrsz\u1618\u1619\u161b\u161e\u163f\u164f\u1659\u6220;\u69a4e\xbb\u1619sd\u0100;a\u1625\u1626\u6221\u0461\u1630\u1632\u1634\u1636\u1638\u163a\u163c\u163e;\u69a8;\u69a9;\u69aa;\u69ab;\u69ac;\u69ad;\u69ae;\u69aft\u0100;v\u1645\u1646\u621fb\u0100;d\u164c\u164d\u62be;\u699d\u0100pt\u1654\u1657h;\u6222\xbb\xb9arr;\u637c\u0100gp\u1663\u1667on;\u4105f;\uc000\ud835\udd52\u0380;Eaeiop\u12c1\u167b\u167d\u1682\u1684\u1687\u168a;\u6a70cir;\u6a6f;\u624ad;\u624bs;\u4027rox\u0100;e\u12c1\u1692\xf1\u1683ing\u803b\xe5\u40e5\u0180cty\u16a1\u16a6\u16a8r;\uc000\ud835\udcb6;\u402amp\u0100;e\u12c1\u16af\xf1\u0288ilde\u803b\xe3\u40e3ml\u803b\xe4\u40e4\u0100ci\u16c2\u16c8onin\xf4\u0272nt;\u6a11\u0800Nabcdefiklnoprsu\u16ed\u16f1\u1730\u173c\u1743\u1748\u1778\u177d\u17e0\u17e6\u1839\u1850\u170d\u193d\u1948\u1970ot;\u6aed\u0100cr\u16f6\u171ek\u0200ceps\u1700\u1705\u170d\u1713ong;\u624cpsilon;\u43f6rime;\u6035im\u0100;e\u171a\u171b\u623dq;\u62cd\u0176\u1722\u1726ee;\u62bded\u0100;g\u172c\u172d\u6305e\xbb\u172drk\u0100;t\u135c\u1737brk;\u63b6\u0100oy\u1701\u1741;\u4431quo;\u601e\u0280cmprt\u1753\u175b\u1761\u1764\u1768aus\u0100;e\u010a\u0109ptyv;\u69b0s\xe9\u170cno\xf5\u0113\u0180ahw\u176f\u1771\u1773;\u43b2;\u6136een;\u626cr;\uc000\ud835\udd1fg\u0380costuvw\u178d\u179d\u17b3\u17c1\u17d5\u17db\u17de\u0180aiu\u1794\u1796\u179a\xf0\u0760rc;\u65efp\xbb\u1371\u0180dpt\u17a4\u17a8\u17adot;\u6a00lus;\u6a01imes;\u6a02\u0271\u17b9\0\0\u17becup;\u6a06ar;\u6605riangle\u0100du\u17cd\u17d2own;\u65bdp;\u65b3plus;\u6a04e\xe5\u1444\xe5\u14adarow;\u690d\u0180ako\u17ed\u1826\u1835\u0100cn\u17f2\u1823k\u0180lst\u17fa\u05ab\u1802ozenge;\u69ebriangle\u0200;dlr\u1812\u1813\u1818\u181d\u65b4own;\u65beeft;\u65c2ight;\u65b8k;\u6423\u01b1\u182b\0\u1833\u01b2\u182f\0\u1831;\u6592;\u65914;\u6593ck;\u6588\u0100eo\u183e\u184d\u0100;q\u1843\u1846\uc000=\u20e5uiv;\uc000\u2261\u20e5t;\u6310\u0200ptwx\u1859\u185e\u1867\u186cf;\uc000\ud835\udd53\u0100;t\u13cb\u1863om\xbb\u13cctie;\u62c8\u0600DHUVbdhmptuv\u1885\u1896\u18aa\u18bb\u18d7\u18db\u18ec\u18ff\u1905\u190a\u1910\u1921\u0200LRlr\u188e\u1890\u1892\u1894;\u6557;\u6554;\u6556;\u6553\u0280;DUdu\u18a1\u18a2\u18a4\u18a6\u18a8\u6550;\u6566;\u6569;\u6564;\u6567\u0200LRlr\u18b3\u18b5\u18b7\u18b9;\u655d;\u655a;\u655c;\u6559\u0380;HLRhlr\u18ca\u18cb\u18cd\u18cf\u18d1\u18d3\u18d5\u6551;\u656c;\u6563;\u6560;\u656b;\u6562;\u655fox;\u69c9\u0200LRlr\u18e4\u18e6\u18e8\u18ea;\u6555;\u6552;\u6510;\u650c\u0280;DUdu\u06bd\u18f7\u18f9\u18fb\u18fd;\u6565;\u6568;\u652c;\u6534inus;\u629flus;\u629eimes;\u62a0\u0200LRlr\u1919\u191b\u191d\u191f;\u655b;\u6558;\u6518;\u6514\u0380;HLRhlr\u1930\u1931\u1933\u1935\u1937\u1939\u193b\u6502;\u656a;\u6561;\u655e;\u653c;\u6524;\u651c\u0100ev\u0123\u1942bar\u803b\xa6\u40a6\u0200ceio\u1951\u1956\u195a\u1960r;\uc000\ud835\udcb7mi;\u604fm\u0100;e\u171a\u171cl\u0180;bh\u1968\u1969\u196b\u405c;\u69c5sub;\u67c8\u016c\u1974\u197el\u0100;e\u1979\u197a\u6022t\xbb\u197ap\u0180;Ee\u012f\u1985\u1987;\u6aae\u0100;q\u06dc\u06db\u0ce1\u19a7\0\u19e8\u1a11\u1a15\u1a32\0\u1a37\u1a50\0\0\u1ab4\0\0\u1ac1\0\0\u1b21\u1b2e\u1b4d\u1b52\0\u1bfd\0\u1c0c\u0180cpr\u19ad\u19b2\u19ddute;\u4107\u0300;abcds\u19bf\u19c0\u19c4\u19ca\u19d5\u19d9\u6229nd;\u6a44rcup;\u6a49\u0100au\u19cf\u19d2p;\u6a4bp;\u6a47ot;\u6a40;\uc000\u2229\ufe00\u0100eo\u19e2\u19e5t;\u6041\xee\u0693\u0200aeiu\u19f0\u19fb\u1a01\u1a05\u01f0\u19f5\0\u19f8s;\u6a4don;\u410ddil\u803b\xe7\u40e7rc;\u4109ps\u0100;s\u1a0c\u1a0d\u6a4cm;\u6a50ot;\u410b\u0180dmn\u1a1b\u1a20\u1a26il\u80bb\xb8\u01adptyv;\u69b2t\u8100\xa2;e\u1a2d\u1a2e\u40a2r\xe4\u01b2r;\uc000\ud835\udd20\u0180cei\u1a3d\u1a40\u1a4dy;\u4447ck\u0100;m\u1a47\u1a48\u6713ark\xbb\u1a48;\u43c7r\u0380;Ecefms\u1a5f\u1a60\u1a62\u1a6b\u1aa4\u1aaa\u1aae\u65cb;\u69c3\u0180;el\u1a69\u1a6a\u1a6d\u42c6q;\u6257e\u0261\u1a74\0\0\u1a88rrow\u0100lr\u1a7c\u1a81eft;\u61baight;\u61bb\u0280RSacd\u1a92\u1a94\u1a96\u1a9a\u1a9f\xbb\u0f47;\u64c8st;\u629birc;\u629aash;\u629dnint;\u6a10id;\u6aefcir;\u69c2ubs\u0100;u\u1abb\u1abc\u6663it\xbb\u1abc\u02ec\u1ac7\u1ad4\u1afa\0\u1b0aon\u0100;e\u1acd\u1ace\u403a\u0100;q\xc7\xc6\u026d\u1ad9\0\0\u1ae2a\u0100;t\u1ade\u1adf\u402c;\u4040\u0180;fl\u1ae8\u1ae9\u1aeb\u6201\xee\u1160e\u0100mx\u1af1\u1af6ent\xbb\u1ae9e\xf3\u024d\u01e7\u1afe\0\u1b07\u0100;d\u12bb\u1b02ot;\u6a6dn\xf4\u0246\u0180fry\u1b10\u1b14\u1b17;\uc000\ud835\udd54o\xe4\u0254\u8100\xa9;s\u0155\u1b1dr;\u6117\u0100ao\u1b25\u1b29rr;\u61b5ss;\u6717\u0100cu\u1b32\u1b37r;\uc000\ud835\udcb8\u0100bp\u1b3c\u1b44\u0100;e\u1b41\u1b42\u6acf;\u6ad1\u0100;e\u1b49\u1b4a\u6ad0;\u6ad2dot;\u62ef\u0380delprvw\u1b60\u1b6c\u1b77\u1b82\u1bac\u1bd4\u1bf9arr\u0100lr\u1b68\u1b6a;\u6938;\u6935\u0270\u1b72\0\0\u1b75r;\u62dec;\u62dfarr\u0100;p\u1b7f\u1b80\u61b6;\u693d\u0300;bcdos\u1b8f\u1b90\u1b96\u1ba1\u1ba5\u1ba8\u622arcap;\u6a48\u0100au\u1b9b\u1b9ep;\u6a46p;\u6a4aot;\u628dr;\u6a45;\uc000\u222a\ufe00\u0200alrv\u1bb5\u1bbf\u1bde\u1be3rr\u0100;m\u1bbc\u1bbd\u61b7;\u693cy\u0180evw\u1bc7\u1bd4\u1bd8q\u0270\u1bce\0\0\u1bd2re\xe3\u1b73u\xe3\u1b75ee;\u62ceedge;\u62cfen\u803b\xa4\u40a4earrow\u0100lr\u1bee\u1bf3eft\xbb\u1b80ight\xbb\u1bbde\xe4\u1bdd\u0100ci\u1c01\u1c07onin\xf4\u01f7nt;\u6231lcty;\u632d\u0980AHabcdefhijlorstuwz\u1c38\u1c3b\u1c3f\u1c5d\u1c69\u1c75\u1c8a\u1c9e\u1cac\u1cb7\u1cfb\u1cff\u1d0d\u1d7b\u1d91\u1dab\u1dbb\u1dc6\u1dcdr\xf2\u0381ar;\u6965\u0200glrs\u1c48\u1c4d\u1c52\u1c54ger;\u6020eth;\u6138\xf2\u1133h\u0100;v\u1c5a\u1c5b\u6010\xbb\u090a\u016b\u1c61\u1c67arow;\u690fa\xe3\u0315\u0100ay\u1c6e\u1c73ron;\u410f;\u4434\u0180;ao\u0332\u1c7c\u1c84\u0100gr\u02bf\u1c81r;\u61catseq;\u6a77\u0180glm\u1c91\u1c94\u1c98\u803b\xb0\u40b0ta;\u43b4ptyv;\u69b1\u0100ir\u1ca3\u1ca8sht;\u697f;\uc000\ud835\udd21ar\u0100lr\u1cb3\u1cb5\xbb\u08dc\xbb\u101e\u0280aegsv\u1cc2\u0378\u1cd6\u1cdc\u1ce0m\u0180;os\u0326\u1cca\u1cd4nd\u0100;s\u0326\u1cd1uit;\u6666amma;\u43ddin;\u62f2\u0180;io\u1ce7\u1ce8\u1cf8\u40f7de\u8100\xf7;o\u1ce7\u1cf0ntimes;\u62c7n\xf8\u1cf7cy;\u4452c\u026f\u1d06\0\0\u1d0arn;\u631eop;\u630d\u0280lptuw\u1d18\u1d1d\u1d22\u1d49\u1d55lar;\u4024f;\uc000\ud835\udd55\u0280;emps\u030b\u1d2d\u1d37\u1d3d\u1d42q\u0100;d\u0352\u1d33ot;\u6251inus;\u6238lus;\u6214quare;\u62a1blebarwedg\xe5\xfan\u0180adh\u112e\u1d5d\u1d67ownarrow\xf3\u1c83arpoon\u0100lr\u1d72\u1d76ef\xf4\u1cb4igh\xf4\u1cb6\u0162\u1d7f\u1d85karo\xf7\u0f42\u026f\u1d8a\0\0\u1d8ern;\u631fop;\u630c\u0180cot\u1d98\u1da3\u1da6\u0100ry\u1d9d\u1da1;\uc000\ud835\udcb9;\u4455l;\u69f6rok;\u4111\u0100dr\u1db0\u1db4ot;\u62f1i\u0100;f\u1dba\u1816\u65bf\u0100ah\u1dc0\u1dc3r\xf2\u0429a\xf2\u0fa6angle;\u69a6\u0100ci\u1dd2\u1dd5y;\u445fgrarr;\u67ff\u0900Dacdefglmnopqrstux\u1e01\u1e09\u1e19\u1e38\u0578\u1e3c\u1e49\u1e61\u1e7e\u1ea5\u1eaf\u1ebd\u1ee1\u1f2a\u1f37\u1f44\u1f4e\u1f5a\u0100Do\u1e06\u1d34o\xf4\u1c89\u0100cs\u1e0e\u1e14ute\u803b\xe9\u40e9ter;\u6a6e\u0200aioy\u1e22\u1e27\u1e31\u1e36ron;\u411br\u0100;c\u1e2d\u1e2e\u6256\u803b\xea\u40ealon;\u6255;\u444dot;\u4117\u0100Dr\u1e41\u1e45ot;\u6252;\uc000\ud835\udd22\u0180;rs\u1e50\u1e51\u1e57\u6a9aave\u803b\xe8\u40e8\u0100;d\u1e5c\u1e5d\u6a96ot;\u6a98\u0200;ils\u1e6a\u1e6b\u1e72\u1e74\u6a99nters;\u63e7;\u6113\u0100;d\u1e79\u1e7a\u6a95ot;\u6a97\u0180aps\u1e85\u1e89\u1e97cr;\u4113ty\u0180;sv\u1e92\u1e93\u1e95\u6205et\xbb\u1e93p\u01001;\u1e9d\u1ea4\u0133\u1ea1\u1ea3;\u6004;\u6005\u6003\u0100gs\u1eaa\u1eac;\u414bp;\u6002\u0100gp\u1eb4\u1eb8on;\u4119f;\uc000\ud835\udd56\u0180als\u1ec4\u1ece\u1ed2r\u0100;s\u1eca\u1ecb\u62d5l;\u69e3us;\u6a71i\u0180;lv\u1eda\u1edb\u1edf\u43b5on\xbb\u1edb;\u43f5\u0200csuv\u1eea\u1ef3\u1f0b\u1f23\u0100io\u1eef\u1e31rc\xbb\u1e2e\u0269\u1ef9\0\0\u1efb\xed\u0548ant\u0100gl\u1f02\u1f06tr\xbb\u1e5dess\xbb\u1e7a\u0180aei\u1f12\u1f16\u1f1als;\u403dst;\u625fv\u0100;D\u0235\u1f20D;\u6a78parsl;\u69e5\u0100Da\u1f2f\u1f33ot;\u6253rr;\u6971\u0180cdi\u1f3e\u1f41\u1ef8r;\u612fo\xf4\u0352\u0100ah\u1f49\u1f4b;\u43b7\u803b\xf0\u40f0\u0100mr\u1f53\u1f57l\u803b\xeb\u40ebo;\u60ac\u0180cip\u1f61\u1f64\u1f67l;\u4021s\xf4\u056e\u0100eo\u1f6c\u1f74ctatio\xee\u0559nential\xe5\u0579\u09e1\u1f92\0\u1f9e\0\u1fa1\u1fa7\0\0\u1fc6\u1fcc\0\u1fd3\0\u1fe6\u1fea\u2000\0\u2008\u205allingdotse\xf1\u1e44y;\u4444male;\u6640\u0180ilr\u1fad\u1fb3\u1fc1lig;\u8000\ufb03\u0269\u1fb9\0\0\u1fbdg;\u8000\ufb00ig;\u8000\ufb04;\uc000\ud835\udd23lig;\u8000\ufb01lig;\uc000fj\u0180alt\u1fd9\u1fdc\u1fe1t;\u666dig;\u8000\ufb02ns;\u65b1of;\u4192\u01f0\u1fee\0\u1ff3f;\uc000\ud835\udd57\u0100ak\u05bf\u1ff7\u0100;v\u1ffc\u1ffd\u62d4;\u6ad9artint;\u6a0d\u0100ao\u200c\u2055\u0100cs\u2011\u2052\u03b1\u201a\u2030\u2038\u2045\u2048\0\u2050\u03b2\u2022\u2025\u2027\u202a\u202c\0\u202e\u803b\xbd\u40bd;\u6153\u803b\xbc\u40bc;\u6155;\u6159;\u615b\u01b3\u2034\0\u2036;\u6154;\u6156\u02b4\u203e\u2041\0\0\u2043\u803b\xbe\u40be;\u6157;\u615c5;\u6158\u01b6\u204c\0\u204e;\u615a;\u615d8;\u615el;\u6044wn;\u6322cr;\uc000\ud835\udcbb\u0880Eabcdefgijlnorstv\u2082\u2089\u209f\u20a5\u20b0\u20b4\u20f0\u20f5\u20fa\u20ff\u2103\u2112\u2138\u0317\u213e\u2152\u219e\u0100;l\u064d\u2087;\u6a8c\u0180cmp\u2090\u2095\u209dute;\u41f5ma\u0100;d\u209c\u1cda\u43b3;\u6a86reve;\u411f\u0100iy\u20aa\u20aerc;\u411d;\u4433ot;\u4121\u0200;lqs\u063e\u0642\u20bd\u20c9\u0180;qs\u063e\u064c\u20c4lan\xf4\u0665\u0200;cdl\u0665\u20d2\u20d5\u20e5c;\u6aa9ot\u0100;o\u20dc\u20dd\u6a80\u0100;l\u20e2\u20e3\u6a82;\u6a84\u0100;e\u20ea\u20ed\uc000\u22db\ufe00s;\u6a94r;\uc000\ud835\udd24\u0100;g\u0673\u061bmel;\u6137cy;\u4453\u0200;Eaj\u065a\u210c\u210e\u2110;\u6a92;\u6aa5;\u6aa4\u0200Eaes\u211b\u211d\u2129\u2134;\u6269p\u0100;p\u2123\u2124\u6a8arox\xbb\u2124\u0100;q\u212e\u212f\u6a88\u0100;q\u212e\u211bim;\u62e7pf;\uc000\ud835\udd58\u0100ci\u2143\u2146r;\u610am\u0180;el\u066b\u214e\u2150;\u6a8e;\u6a90\u8300>;cdlqr\u05ee\u2160\u216a\u216e\u2173\u2179\u0100ci\u2165\u2167;\u6aa7r;\u6a7aot;\u62d7Par;\u6995uest;\u6a7c\u0280adels\u2184\u216a\u2190\u0656\u219b\u01f0\u2189\0\u218epro\xf8\u209er;\u6978q\u0100lq\u063f\u2196les\xf3\u2088i\xed\u066b\u0100en\u21a3\u21adrtneqq;\uc000\u2269\ufe00\xc5\u21aa\u0500Aabcefkosy\u21c4\u21c7\u21f1\u21f5\u21fa\u2218\u221d\u222f\u2268\u227dr\xf2\u03a0\u0200ilmr\u21d0\u21d4\u21d7\u21dbrs\xf0\u1484f\xbb\u2024il\xf4\u06a9\u0100dr\u21e0\u21e4cy;\u444a\u0180;cw\u08f4\u21eb\u21efir;\u6948;\u61adar;\u610firc;\u4125\u0180alr\u2201\u220e\u2213rts\u0100;u\u2209\u220a\u6665it\xbb\u220alip;\u6026con;\u62b9r;\uc000\ud835\udd25s\u0100ew\u2223\u2229arow;\u6925arow;\u6926\u0280amopr\u223a\u223e\u2243\u225e\u2263rr;\u61fftht;\u623bk\u0100lr\u2249\u2253eftarrow;\u61a9ightarrow;\u61aaf;\uc000\ud835\udd59bar;\u6015\u0180clt\u226f\u2274\u2278r;\uc000\ud835\udcbdas\xe8\u21f4rok;\u4127\u0100bp\u2282\u2287ull;\u6043hen\xbb\u1c5b\u0ae1\u22a3\0\u22aa\0\u22b8\u22c5\u22ce\0\u22d5\u22f3\0\0\u22f8\u2322\u2367\u2362\u237f\0\u2386\u23aa\u23b4cute\u803b\xed\u40ed\u0180;iy\u0771\u22b0\u22b5rc\u803b\xee\u40ee;\u4438\u0100cx\u22bc\u22bfy;\u4435cl\u803b\xa1\u40a1\u0100fr\u039f\u22c9;\uc000\ud835\udd26rave\u803b\xec\u40ec\u0200;ino\u073e\u22dd\u22e9\u22ee\u0100in\u22e2\u22e6nt;\u6a0ct;\u622dfin;\u69dcta;\u6129lig;\u4133\u0180aop\u22fe\u231a\u231d\u0180cgt\u2305\u2308\u2317r;\u412b\u0180elp\u071f\u230f\u2313in\xe5\u078ear\xf4\u0720h;\u4131f;\u62b7ed;\u41b5\u0280;cfot\u04f4\u232c\u2331\u233d\u2341are;\u6105in\u0100;t\u2338\u2339\u621eie;\u69dddo\xf4\u2319\u0280;celp\u0757\u234c\u2350\u235b\u2361al;\u62ba\u0100gr\u2355\u2359er\xf3\u1563\xe3\u234darhk;\u6a17rod;\u6a3c\u0200cgpt\u236f\u2372\u2376\u237by;\u4451on;\u412ff;\uc000\ud835\udd5aa;\u43b9uest\u803b\xbf\u40bf\u0100ci\u238a\u238fr;\uc000\ud835\udcben\u0280;Edsv\u04f4\u239b\u239d\u23a1\u04f3;\u62f9ot;\u62f5\u0100;v\u23a6\u23a7\u62f4;\u62f3\u0100;i\u0777\u23aelde;\u4129\u01eb\u23b8\0\u23bccy;\u4456l\u803b\xef\u40ef\u0300cfmosu\u23cc\u23d7\u23dc\u23e1\u23e7\u23f5\u0100iy\u23d1\u23d5rc;\u4135;\u4439r;\uc000\ud835\udd27ath;\u4237pf;\uc000\ud835\udd5b\u01e3\u23ec\0\u23f1r;\uc000\ud835\udcbfrcy;\u4458kcy;\u4454\u0400acfghjos\u240b\u2416\u2422\u2427\u242d\u2431\u2435\u243bppa\u0100;v\u2413\u2414\u43ba;\u43f0\u0100ey\u241b\u2420dil;\u4137;\u443ar;\uc000\ud835\udd28reen;\u4138cy;\u4445cy;\u445cpf;\uc000\ud835\udd5ccr;\uc000\ud835\udcc0\u0b80ABEHabcdefghjlmnoprstuv\u2470\u2481\u2486\u248d\u2491\u250e\u253d\u255a\u2580\u264e\u265e\u2665\u2679\u267d\u269a\u26b2\u26d8\u275d\u2768\u278b\u27c0\u2801\u2812\u0180art\u2477\u247a\u247cr\xf2\u09c6\xf2\u0395ail;\u691barr;\u690e\u0100;g\u0994\u248b;\u6a8bar;\u6962\u0963\u24a5\0\u24aa\0\u24b1\0\0\0\0\0\u24b5\u24ba\0\u24c6\u24c8\u24cd\0\u24f9ute;\u413amptyv;\u69b4ra\xee\u084cbda;\u43bbg\u0180;dl\u088e\u24c1\u24c3;\u6991\xe5\u088e;\u6a85uo\u803b\xab\u40abr\u0400;bfhlpst\u0899\u24de\u24e6\u24e9\u24eb\u24ee\u24f1\u24f5\u0100;f\u089d\u24e3s;\u691fs;\u691d\xeb\u2252p;\u61abl;\u6939im;\u6973l;\u61a2\u0180;ae\u24ff\u2500\u2504\u6aabil;\u6919\u0100;s\u2509\u250a\u6aad;\uc000\u2aad\ufe00\u0180abr\u2515\u2519\u251drr;\u690crk;\u6772\u0100ak\u2522\u252cc\u0100ek\u2528\u252a;\u407b;\u405b\u0100es\u2531\u2533;\u698bl\u0100du\u2539\u253b;\u698f;\u698d\u0200aeuy\u2546\u254b\u2556\u2558ron;\u413e\u0100di\u2550\u2554il;\u413c\xec\u08b0\xe2\u2529;\u443b\u0200cqrs\u2563\u2566\u256d\u257da;\u6936uo\u0100;r\u0e19\u1746\u0100du\u2572\u2577har;\u6967shar;\u694bh;\u61b2\u0280;fgqs\u258b\u258c\u0989\u25f3\u25ff\u6264t\u0280ahlrt\u2598\u25a4\u25b7\u25c2\u25e8rrow\u0100;t\u0899\u25a1a\xe9\u24f6arpoon\u0100du\u25af\u25b4own\xbb\u045ap\xbb\u0966eftarrows;\u61c7ight\u0180ahs\u25cd\u25d6\u25derrow\u0100;s\u08f4\u08a7arpoon\xf3\u0f98quigarro\xf7\u21f0hreetimes;\u62cb\u0180;qs\u258b\u0993\u25falan\xf4\u09ac\u0280;cdgs\u09ac\u260a\u260d\u261d\u2628c;\u6aa8ot\u0100;o\u2614\u2615\u6a7f\u0100;r\u261a\u261b\u6a81;\u6a83\u0100;e\u2622\u2625\uc000\u22da\ufe00s;\u6a93\u0280adegs\u2633\u2639\u263d\u2649\u264bppro\xf8\u24c6ot;\u62d6q\u0100gq\u2643\u2645\xf4\u0989gt\xf2\u248c\xf4\u099bi\xed\u09b2\u0180ilr\u2655\u08e1\u265asht;\u697c;\uc000\ud835\udd29\u0100;E\u099c\u2663;\u6a91\u0161\u2669\u2676r\u0100du\u25b2\u266e\u0100;l\u0965\u2673;\u696alk;\u6584cy;\u4459\u0280;acht\u0a48\u2688\u268b\u2691\u2696r\xf2\u25c1orne\xf2\u1d08ard;\u696bri;\u65fa\u0100io\u269f\u26a4dot;\u4140ust\u0100;a\u26ac\u26ad\u63b0che\xbb\u26ad\u0200Eaes\u26bb\u26bd\u26c9\u26d4;\u6268p\u0100;p\u26c3\u26c4\u6a89rox\xbb\u26c4\u0100;q\u26ce\u26cf\u6a87\u0100;q\u26ce\u26bbim;\u62e6\u0400abnoptwz\u26e9\u26f4\u26f7\u271a\u272f\u2741\u2747\u2750\u0100nr\u26ee\u26f1g;\u67ecr;\u61fdr\xeb\u08c1g\u0180lmr\u26ff\u270d\u2714eft\u0100ar\u09e6\u2707ight\xe1\u09f2apsto;\u67fcight\xe1\u09fdparrow\u0100lr\u2725\u2729ef\xf4\u24edight;\u61ac\u0180afl\u2736\u2739\u273dr;\u6985;\uc000\ud835\udd5dus;\u6a2dimes;\u6a34\u0161\u274b\u274fst;\u6217\xe1\u134e\u0180;ef\u2757\u2758\u1800\u65cange\xbb\u2758ar\u0100;l\u2764\u2765\u4028t;\u6993\u0280achmt\u2773\u2776\u277c\u2785\u2787r\xf2\u08a8orne\xf2\u1d8car\u0100;d\u0f98\u2783;\u696d;\u600eri;\u62bf\u0300achiqt\u2798\u279d\u0a40\u27a2\u27ae\u27bbquo;\u6039r;\uc000\ud835\udcc1m\u0180;eg\u09b2\u27aa\u27ac;\u6a8d;\u6a8f\u0100bu\u252a\u27b3o\u0100;r\u0e1f\u27b9;\u601arok;\u4142\u8400<;cdhilqr\u082b\u27d2\u2639\u27dc\u27e0\u27e5\u27ea\u27f0\u0100ci\u27d7\u27d9;\u6aa6r;\u6a79re\xe5\u25f2mes;\u62c9arr;\u6976uest;\u6a7b\u0100Pi\u27f5\u27f9ar;\u6996\u0180;ef\u2800\u092d\u181b\u65c3r\u0100du\u2807\u280dshar;\u694ahar;\u6966\u0100en\u2817\u2821rtneqq;\uc000\u2268\ufe00\xc5\u281e\u0700Dacdefhilnopsu\u2840\u2845\u2882\u288e\u2893\u28a0\u28a5\u28a8\u28da\u28e2\u28e4\u0a83\u28f3\u2902Dot;\u623a\u0200clpr\u284e\u2852\u2863\u287dr\u803b\xaf\u40af\u0100et\u2857\u2859;\u6642\u0100;e\u285e\u285f\u6720se\xbb\u285f\u0100;s\u103b\u2868to\u0200;dlu\u103b\u2873\u2877\u287bow\xee\u048cef\xf4\u090f\xf0\u13d1ker;\u65ae\u0100oy\u2887\u288cmma;\u6a29;\u443cash;\u6014asuredangle\xbb\u1626r;\uc000\ud835\udd2ao;\u6127\u0180cdn\u28af\u28b4\u28c9ro\u803b\xb5\u40b5\u0200;acd\u1464\u28bd\u28c0\u28c4s\xf4\u16a7ir;\u6af0ot\u80bb\xb7\u01b5us\u0180;bd\u28d2\u1903\u28d3\u6212\u0100;u\u1d3c\u28d8;\u6a2a\u0163\u28de\u28e1p;\u6adb\xf2\u2212\xf0\u0a81\u0100dp\u28e9\u28eeels;\u62a7f;\uc000\ud835\udd5e\u0100ct\u28f8\u28fdr;\uc000\ud835\udcc2pos\xbb\u159d\u0180;lm\u2909\u290a\u290d\u43bctimap;\u62b8\u0c00GLRVabcdefghijlmoprstuvw\u2942\u2953\u297e\u2989\u2998\u29da\u29e9\u2a15\u2a1a\u2a58\u2a5d\u2a83\u2a95\u2aa4\u2aa8\u2b04\u2b07\u2b44\u2b7f\u2bae\u2c34\u2c67\u2c7c\u2ce9\u0100gt\u2947\u294b;\uc000\u22d9\u0338\u0100;v\u2950\u0bcf\uc000\u226b\u20d2\u0180elt\u295a\u2972\u2976ft\u0100ar\u2961\u2967rrow;\u61cdightarrow;\u61ce;\uc000\u22d8\u0338\u0100;v\u297b\u0c47\uc000\u226a\u20d2ightarrow;\u61cf\u0100Dd\u298e\u2993ash;\u62afash;\u62ae\u0280bcnpt\u29a3\u29a7\u29ac\u29b1\u29ccla\xbb\u02deute;\u4144g;\uc000\u2220\u20d2\u0280;Eiop\u0d84\u29bc\u29c0\u29c5\u29c8;\uc000\u2a70\u0338d;\uc000\u224b\u0338s;\u4149ro\xf8\u0d84ur\u0100;a\u29d3\u29d4\u666el\u0100;s\u29d3\u0b38\u01f3\u29df\0\u29e3p\u80bb\xa0\u0b37mp\u0100;e\u0bf9\u0c00\u0280aeouy\u29f4\u29fe\u2a03\u2a10\u2a13\u01f0\u29f9\0\u29fb;\u6a43on;\u4148dil;\u4146ng\u0100;d\u0d7e\u2a0aot;\uc000\u2a6d\u0338p;\u6a42;\u443dash;\u6013\u0380;Aadqsx\u0b92\u2a29\u2a2d\u2a3b\u2a41\u2a45\u2a50rr;\u61d7r\u0100hr\u2a33\u2a36k;\u6924\u0100;o\u13f2\u13f0ot;\uc000\u2250\u0338ui\xf6\u0b63\u0100ei\u2a4a\u2a4ear;\u6928\xed\u0b98ist\u0100;s\u0ba0\u0b9fr;\uc000\ud835\udd2b\u0200Eest\u0bc5\u2a66\u2a79\u2a7c\u0180;qs\u0bbc\u2a6d\u0be1\u0180;qs\u0bbc\u0bc5\u2a74lan\xf4\u0be2i\xed\u0bea\u0100;r\u0bb6\u2a81\xbb\u0bb7\u0180Aap\u2a8a\u2a8d\u2a91r\xf2\u2971rr;\u61aear;\u6af2\u0180;sv\u0f8d\u2a9c\u0f8c\u0100;d\u2aa1\u2aa2\u62fc;\u62facy;\u445a\u0380AEadest\u2ab7\u2aba\u2abe\u2ac2\u2ac5\u2af6\u2af9r\xf2\u2966;\uc000\u2266\u0338rr;\u619ar;\u6025\u0200;fqs\u0c3b\u2ace\u2ae3\u2aeft\u0100ar\u2ad4\u2ad9rro\xf7\u2ac1ightarro\xf7\u2a90\u0180;qs\u0c3b\u2aba\u2aealan\xf4\u0c55\u0100;s\u0c55\u2af4\xbb\u0c36i\xed\u0c5d\u0100;r\u0c35\u2afei\u0100;e\u0c1a\u0c25i\xe4\u0d90\u0100pt\u2b0c\u2b11f;\uc000\ud835\udd5f\u8180\xac;in\u2b19\u2b1a\u2b36\u40acn\u0200;Edv\u0b89\u2b24\u2b28\u2b2e;\uc000\u22f9\u0338ot;\uc000\u22f5\u0338\u01e1\u0b89\u2b33\u2b35;\u62f7;\u62f6i\u0100;v\u0cb8\u2b3c\u01e1\u0cb8\u2b41\u2b43;\u62fe;\u62fd\u0180aor\u2b4b\u2b63\u2b69r\u0200;ast\u0b7b\u2b55\u2b5a\u2b5flle\xec\u0b7bl;\uc000\u2afd\u20e5;\uc000\u2202\u0338lint;\u6a14\u0180;ce\u0c92\u2b70\u2b73u\xe5\u0ca5\u0100;c\u0c98\u2b78\u0100;e\u0c92\u2b7d\xf1\u0c98\u0200Aait\u2b88\u2b8b\u2b9d\u2ba7r\xf2\u2988rr\u0180;cw\u2b94\u2b95\u2b99\u619b;\uc000\u2933\u0338;\uc000\u219d\u0338ghtarrow\xbb\u2b95ri\u0100;e\u0ccb\u0cd6\u0380chimpqu\u2bbd\u2bcd\u2bd9\u2b04\u0b78\u2be4\u2bef\u0200;cer\u0d32\u2bc6\u0d37\u2bc9u\xe5\u0d45;\uc000\ud835\udcc3ort\u026d\u2b05\0\0\u2bd6ar\xe1\u2b56m\u0100;e\u0d6e\u2bdf\u0100;q\u0d74\u0d73su\u0100bp\u2beb\u2bed\xe5\u0cf8\xe5\u0d0b\u0180bcp\u2bf6\u2c11\u2c19\u0200;Ees\u2bff\u2c00\u0d22\u2c04\u6284;\uc000\u2ac5\u0338et\u0100;e\u0d1b\u2c0bq\u0100;q\u0d23\u2c00c\u0100;e\u0d32\u2c17\xf1\u0d38\u0200;Ees\u2c22\u2c23\u0d5f\u2c27\u6285;\uc000\u2ac6\u0338et\u0100;e\u0d58\u2c2eq\u0100;q\u0d60\u2c23\u0200gilr\u2c3d\u2c3f\u2c45\u2c47\xec\u0bd7lde\u803b\xf1\u40f1\xe7\u0c43iangle\u0100lr\u2c52\u2c5ceft\u0100;e\u0c1a\u2c5a\xf1\u0c26ight\u0100;e\u0ccb\u2c65\xf1\u0cd7\u0100;m\u2c6c\u2c6d\u43bd\u0180;es\u2c74\u2c75\u2c79\u4023ro;\u6116p;\u6007\u0480DHadgilrs\u2c8f\u2c94\u2c99\u2c9e\u2ca3\u2cb0\u2cb6\u2cd3\u2ce3ash;\u62adarr;\u6904p;\uc000\u224d\u20d2ash;\u62ac\u0100et\u2ca8\u2cac;\uc000\u2265\u20d2;\uc000>\u20d2nfin;\u69de\u0180Aet\u2cbd\u2cc1\u2cc5rr;\u6902;\uc000\u2264\u20d2\u0100;r\u2cca\u2ccd\uc000<\u20d2ie;\uc000\u22b4\u20d2\u0100At\u2cd8\u2cdcrr;\u6903rie;\uc000\u22b5\u20d2im;\uc000\u223c\u20d2\u0180Aan\u2cf0\u2cf4\u2d02rr;\u61d6r\u0100hr\u2cfa\u2cfdk;\u6923\u0100;o\u13e7\u13e5ear;\u6927\u1253\u1a95\0\0\0\0\0\0\0\0\0\0\0\0\0\u2d2d\0\u2d38\u2d48\u2d60\u2d65\u2d72\u2d84\u1b07\0\0\u2d8d\u2dab\0\u2dc8\u2dce\0\u2ddc\u2e19\u2e2b\u2e3e\u2e43\u0100cs\u2d31\u1a97ute\u803b\xf3\u40f3\u0100iy\u2d3c\u2d45r\u0100;c\u1a9e\u2d42\u803b\xf4\u40f4;\u443e\u0280abios\u1aa0\u2d52\u2d57\u01c8\u2d5alac;\u4151v;\u6a38old;\u69bclig;\u4153\u0100cr\u2d69\u2d6dir;\u69bf;\uc000\ud835\udd2c\u036f\u2d79\0\0\u2d7c\0\u2d82n;\u42dbave\u803b\xf2\u40f2;\u69c1\u0100bm\u2d88\u0df4ar;\u69b5\u0200acit\u2d95\u2d98\u2da5\u2da8r\xf2\u1a80\u0100ir\u2d9d\u2da0r;\u69beoss;\u69bbn\xe5\u0e52;\u69c0\u0180aei\u2db1\u2db5\u2db9cr;\u414dga;\u43c9\u0180cdn\u2dc0\u2dc5\u01cdron;\u43bf;\u69b6pf;\uc000\ud835\udd60\u0180ael\u2dd4\u2dd7\u01d2r;\u69b7rp;\u69b9\u0380;adiosv\u2dea\u2deb\u2dee\u2e08\u2e0d\u2e10\u2e16\u6228r\xf2\u1a86\u0200;efm\u2df7\u2df8\u2e02\u2e05\u6a5dr\u0100;o\u2dfe\u2dff\u6134f\xbb\u2dff\u803b\xaa\u40aa\u803b\xba\u40bagof;\u62b6r;\u6a56lope;\u6a57;\u6a5b\u0180clo\u2e1f\u2e21\u2e27\xf2\u2e01ash\u803b\xf8\u40f8l;\u6298i\u016c\u2e2f\u2e34de\u803b\xf5\u40f5es\u0100;a\u01db\u2e3as;\u6a36ml\u803b\xf6\u40f6bar;\u633d\u0ae1\u2e5e\0\u2e7d\0\u2e80\u2e9d\0\u2ea2\u2eb9\0\0\u2ecb\u0e9c\0\u2f13\0\0\u2f2b\u2fbc\0\u2fc8r\u0200;ast\u0403\u2e67\u2e72\u0e85\u8100\xb6;l\u2e6d\u2e6e\u40b6le\xec\u0403\u0269\u2e78\0\0\u2e7bm;\u6af3;\u6afdy;\u443fr\u0280cimpt\u2e8b\u2e8f\u2e93\u1865\u2e97nt;\u4025od;\u402eil;\u6030enk;\u6031r;\uc000\ud835\udd2d\u0180imo\u2ea8\u2eb0\u2eb4\u0100;v\u2ead\u2eae\u43c6;\u43d5ma\xf4\u0a76ne;\u660e\u0180;tv\u2ebf\u2ec0\u2ec8\u43c0chfork\xbb\u1ffd;\u43d6\u0100au\u2ecf\u2edfn\u0100ck\u2ed5\u2eddk\u0100;h\u21f4\u2edb;\u610e\xf6\u21f4s\u0480;abcdemst\u2ef3\u2ef4\u1908\u2ef9\u2efd\u2f04\u2f06\u2f0a\u2f0e\u402bcir;\u6a23ir;\u6a22\u0100ou\u1d40\u2f02;\u6a25;\u6a72n\u80bb\xb1\u0e9dim;\u6a26wo;\u6a27\u0180ipu\u2f19\u2f20\u2f25ntint;\u6a15f;\uc000\ud835\udd61nd\u803b\xa3\u40a3\u0500;Eaceinosu\u0ec8\u2f3f\u2f41\u2f44\u2f47\u2f81\u2f89\u2f92\u2f7e\u2fb6;\u6ab3p;\u6ab7u\xe5\u0ed9\u0100;c\u0ece\u2f4c\u0300;acens\u0ec8\u2f59\u2f5f\u2f66\u2f68\u2f7eppro\xf8\u2f43urlye\xf1\u0ed9\xf1\u0ece\u0180aes\u2f6f\u2f76\u2f7approx;\u6ab9qq;\u6ab5im;\u62e8i\xed\u0edfme\u0100;s\u2f88\u0eae\u6032\u0180Eas\u2f78\u2f90\u2f7a\xf0\u2f75\u0180dfp\u0eec\u2f99\u2faf\u0180als\u2fa0\u2fa5\u2faalar;\u632eine;\u6312urf;\u6313\u0100;t\u0efb\u2fb4\xef\u0efbrel;\u62b0\u0100ci\u2fc0\u2fc5r;\uc000\ud835\udcc5;\u43c8ncsp;\u6008\u0300fiopsu\u2fda\u22e2\u2fdf\u2fe5\u2feb\u2ff1r;\uc000\ud835\udd2epf;\uc000\ud835\udd62rime;\u6057cr;\uc000\ud835\udcc6\u0180aeo\u2ff8\u3009\u3013t\u0100ei\u2ffe\u3005rnion\xf3\u06b0nt;\u6a16st\u0100;e\u3010\u3011\u403f\xf1\u1f19\xf4\u0f14\u0a80ABHabcdefhilmnoprstux\u3040\u3051\u3055\u3059\u30e0\u310e\u312b\u3147\u3162\u3172\u318e\u3206\u3215\u3224\u3229\u3258\u326e\u3272\u3290\u32b0\u32b7\u0180art\u3047\u304a\u304cr\xf2\u10b3\xf2\u03ddail;\u691car\xf2\u1c65ar;\u6964\u0380cdenqrt\u3068\u3075\u3078\u307f\u308f\u3094\u30cc\u0100eu\u306d\u3071;\uc000\u223d\u0331te;\u4155i\xe3\u116emptyv;\u69b3g\u0200;del\u0fd1\u3089\u308b\u308d;\u6992;\u69a5\xe5\u0fd1uo\u803b\xbb\u40bbr\u0580;abcfhlpstw\u0fdc\u30ac\u30af\u30b7\u30b9\u30bc\u30be\u30c0\u30c3\u30c7\u30cap;\u6975\u0100;f\u0fe0\u30b4s;\u6920;\u6933s;\u691e\xeb\u225d\xf0\u272el;\u6945im;\u6974l;\u61a3;\u619d\u0100ai\u30d1\u30d5il;\u691ao\u0100;n\u30db\u30dc\u6236al\xf3\u0f1e\u0180abr\u30e7\u30ea\u30eer\xf2\u17e5rk;\u6773\u0100ak\u30f3\u30fdc\u0100ek\u30f9\u30fb;\u407d;\u405d\u0100es\u3102\u3104;\u698cl\u0100du\u310a\u310c;\u698e;\u6990\u0200aeuy\u3117\u311c\u3127\u3129ron;\u4159\u0100di\u3121\u3125il;\u4157\xec\u0ff2\xe2\u30fa;\u4440\u0200clqs\u3134\u3137\u313d\u3144a;\u6937dhar;\u6969uo\u0100;r\u020e\u020dh;\u61b3\u0180acg\u314e\u315f\u0f44l\u0200;ips\u0f78\u3158\u315b\u109cn\xe5\u10bbar\xf4\u0fa9t;\u65ad\u0180ilr\u3169\u1023\u316esht;\u697d;\uc000\ud835\udd2f\u0100ao\u3177\u3186r\u0100du\u317d\u317f\xbb\u047b\u0100;l\u1091\u3184;\u696c\u0100;v\u318b\u318c\u43c1;\u43f1\u0180gns\u3195\u31f9\u31fcht\u0300ahlrst\u31a4\u31b0\u31c2\u31d8\u31e4\u31eerrow\u0100;t\u0fdc\u31ada\xe9\u30c8arpoon\u0100du\u31bb\u31bfow\xee\u317ep\xbb\u1092eft\u0100ah\u31ca\u31d0rrow\xf3\u0feaarpoon\xf3\u0551ightarrows;\u61c9quigarro\xf7\u30cbhreetimes;\u62ccg;\u42daingdotse\xf1\u1f32\u0180ahm\u320d\u3210\u3213r\xf2\u0feaa\xf2\u0551;\u600foust\u0100;a\u321e\u321f\u63b1che\xbb\u321fmid;\u6aee\u0200abpt\u3232\u323d\u3240\u3252\u0100nr\u3237\u323ag;\u67edr;\u61fer\xeb\u1003\u0180afl\u3247\u324a\u324er;\u6986;\uc000\ud835\udd63us;\u6a2eimes;\u6a35\u0100ap\u325d\u3267r\u0100;g\u3263\u3264\u4029t;\u6994olint;\u6a12ar\xf2\u31e3\u0200achq\u327b\u3280\u10bc\u3285quo;\u603ar;\uc000\ud835\udcc7\u0100bu\u30fb\u328ao\u0100;r\u0214\u0213\u0180hir\u3297\u329b\u32a0re\xe5\u31f8mes;\u62cai\u0200;efl\u32aa\u1059\u1821\u32ab\u65b9tri;\u69celuhar;\u6968;\u611e\u0d61\u32d5\u32db\u32df\u332c\u3338\u3371\0\u337a\u33a4\0\0\u33ec\u33f0\0\u3428\u3448\u345a\u34ad\u34b1\u34ca\u34f1\0\u3616\0\0\u3633cute;\u415bqu\xef\u27ba\u0500;Eaceinpsy\u11ed\u32f3\u32f5\u32ff\u3302\u330b\u330f\u331f\u3326\u3329;\u6ab4\u01f0\u32fa\0\u32fc;\u6ab8on;\u4161u\xe5\u11fe\u0100;d\u11f3\u3307il;\u415frc;\u415d\u0180Eas\u3316\u3318\u331b;\u6ab6p;\u6abaim;\u62e9olint;\u6a13i\xed\u1204;\u4441ot\u0180;be\u3334\u1d47\u3335\u62c5;\u6a66\u0380Aacmstx\u3346\u334a\u3357\u335b\u335e\u3363\u336drr;\u61d8r\u0100hr\u3350\u3352\xeb\u2228\u0100;o\u0a36\u0a34t\u803b\xa7\u40a7i;\u403bwar;\u6929m\u0100in\u3369\xf0nu\xf3\xf1t;\u6736r\u0100;o\u3376\u2055\uc000\ud835\udd30\u0200acoy\u3382\u3386\u3391\u33a0rp;\u666f\u0100hy\u338b\u338fcy;\u4449;\u4448rt\u026d\u3399\0\0\u339ci\xe4\u1464ara\xec\u2e6f\u803b\xad\u40ad\u0100gm\u33a8\u33b4ma\u0180;fv\u33b1\u33b2\u33b2\u43c3;\u43c2\u0400;deglnpr\u12ab\u33c5\u33c9\u33ce\u33d6\u33de\u33e1\u33e6ot;\u6a6a\u0100;q\u12b1\u12b0\u0100;E\u33d3\u33d4\u6a9e;\u6aa0\u0100;E\u33db\u33dc\u6a9d;\u6a9fe;\u6246lus;\u6a24arr;\u6972ar\xf2\u113d\u0200aeit\u33f8\u3408\u340f\u3417\u0100ls\u33fd\u3404lsetm\xe9\u336ahp;\u6a33parsl;\u69e4\u0100dl\u1463\u3414e;\u6323\u0100;e\u341c\u341d\u6aaa\u0100;s\u3422\u3423\u6aac;\uc000\u2aac\ufe00\u0180flp\u342e\u3433\u3442tcy;\u444c\u0100;b\u3438\u3439\u402f\u0100;a\u343e\u343f\u69c4r;\u633ff;\uc000\ud835\udd64a\u0100dr\u344d\u0402es\u0100;u\u3454\u3455\u6660it\xbb\u3455\u0180csu\u3460\u3479\u349f\u0100au\u3465\u346fp\u0100;s\u1188\u346b;\uc000\u2293\ufe00p\u0100;s\u11b4\u3475;\uc000\u2294\ufe00u\u0100bp\u347f\u348f\u0180;es\u1197\u119c\u3486et\u0100;e\u1197\u348d\xf1\u119d\u0180;es\u11a8\u11ad\u3496et\u0100;e\u11a8\u349d\xf1\u11ae\u0180;af\u117b\u34a6\u05b0r\u0165\u34ab\u05b1\xbb\u117car\xf2\u1148\u0200cemt\u34b9\u34be\u34c2\u34c5r;\uc000\ud835\udcc8tm\xee\xf1i\xec\u3415ar\xe6\u11be\u0100ar\u34ce\u34d5r\u0100;f\u34d4\u17bf\u6606\u0100an\u34da\u34edight\u0100ep\u34e3\u34eapsilo\xee\u1ee0h\xe9\u2eafs\xbb\u2852\u0280bcmnp\u34fb\u355e\u1209\u358b\u358e\u0480;Edemnprs\u350e\u350f\u3511\u3515\u351e\u3523\u352c\u3531\u3536\u6282;\u6ac5ot;\u6abd\u0100;d\u11da\u351aot;\u6ac3ult;\u6ac1\u0100Ee\u3528\u352a;\u6acb;\u628alus;\u6abfarr;\u6979\u0180eiu\u353d\u3552\u3555t\u0180;en\u350e\u3545\u354bq\u0100;q\u11da\u350feq\u0100;q\u352b\u3528m;\u6ac7\u0100bp\u355a\u355c;\u6ad5;\u6ad3c\u0300;acens\u11ed\u356c\u3572\u3579\u357b\u3326ppro\xf8\u32faurlye\xf1\u11fe\xf1\u11f3\u0180aes\u3582\u3588\u331bppro\xf8\u331aq\xf1\u3317g;\u666a\u0680123;Edehlmnps\u35a9\u35ac\u35af\u121c\u35b2\u35b4\u35c0\u35c9\u35d5\u35da\u35df\u35e8\u35ed\u803b\xb9\u40b9\u803b\xb2\u40b2\u803b\xb3\u40b3;\u6ac6\u0100os\u35b9\u35bct;\u6abeub;\u6ad8\u0100;d\u1222\u35c5ot;\u6ac4s\u0100ou\u35cf\u35d2l;\u67c9b;\u6ad7arr;\u697bult;\u6ac2\u0100Ee\u35e4\u35e6;\u6acc;\u628blus;\u6ac0\u0180eiu\u35f4\u3609\u360ct\u0180;en\u121c\u35fc\u3602q\u0100;q\u1222\u35b2eq\u0100;q\u35e7\u35e4m;\u6ac8\u0100bp\u3611\u3613;\u6ad4;\u6ad6\u0180Aan\u361c\u3620\u362drr;\u61d9r\u0100hr\u3626\u3628\xeb\u222e\u0100;o\u0a2b\u0a29war;\u692alig\u803b\xdf\u40df\u0be1\u3651\u365d\u3660\u12ce\u3673\u3679\0\u367e\u36c2\0\0\0\0\0\u36db\u3703\0\u3709\u376c\0\0\0\u3787\u0272\u3656\0\0\u365bget;\u6316;\u43c4r\xeb\u0e5f\u0180aey\u3666\u366b\u3670ron;\u4165dil;\u4163;\u4442lrec;\u6315r;\uc000\ud835\udd31\u0200eiko\u3686\u369d\u36b5\u36bc\u01f2\u368b\0\u3691e\u01004f\u1284\u1281a\u0180;sv\u3698\u3699\u369b\u43b8ym;\u43d1\u0100cn\u36a2\u36b2k\u0100as\u36a8\u36aeppro\xf8\u12c1im\xbb\u12acs\xf0\u129e\u0100as\u36ba\u36ae\xf0\u12c1rn\u803b\xfe\u40fe\u01ec\u031f\u36c6\u22e7es\u8180\xd7;bd\u36cf\u36d0\u36d8\u40d7\u0100;a\u190f\u36d5r;\u6a31;\u6a30\u0180eps\u36e1\u36e3\u3700\xe1\u2a4d\u0200;bcf\u0486\u36ec\u36f0\u36f4ot;\u6336ir;\u6af1\u0100;o\u36f9\u36fc\uc000\ud835\udd65rk;\u6ada\xe1\u3362rime;\u6034\u0180aip\u370f\u3712\u3764d\xe5\u1248\u0380adempst\u3721\u374d\u3740\u3751\u3757\u375c\u375fngle\u0280;dlqr\u3730\u3731\u3736\u3740\u3742\u65b5own\xbb\u1dbbeft\u0100;e\u2800\u373e\xf1\u092e;\u625cight\u0100;e\u32aa\u374b\xf1\u105aot;\u65ecinus;\u6a3alus;\u6a39b;\u69cdime;\u6a3bezium;\u63e2\u0180cht\u3772\u377d\u3781\u0100ry\u3777\u377b;\uc000\ud835\udcc9;\u4446cy;\u445brok;\u4167\u0100io\u378b\u378ex\xf4\u1777head\u0100lr\u3797\u37a0eftarro\xf7\u084fightarrow\xbb\u0f5d\u0900AHabcdfghlmoprstuw\u37d0\u37d3\u37d7\u37e4\u37f0\u37fc\u380e\u381c\u3823\u3834\u3851\u385d\u386b\u38a9\u38cc\u38d2\u38ea\u38f6r\xf2\u03edar;\u6963\u0100cr\u37dc\u37e2ute\u803b\xfa\u40fa\xf2\u1150r\u01e3\u37ea\0\u37edy;\u445eve;\u416d\u0100iy\u37f5\u37farc\u803b\xfb\u40fb;\u4443\u0180abh\u3803\u3806\u380br\xf2\u13adlac;\u4171a\xf2\u13c3\u0100ir\u3813\u3818sht;\u697e;\uc000\ud835\udd32rave\u803b\xf9\u40f9\u0161\u3827\u3831r\u0100lr\u382c\u382e\xbb\u0957\xbb\u1083lk;\u6580\u0100ct\u3839\u384d\u026f\u383f\0\0\u384arn\u0100;e\u3845\u3846\u631cr\xbb\u3846op;\u630fri;\u65f8\u0100al\u3856\u385acr;\u416b\u80bb\xa8\u0349\u0100gp\u3862\u3866on;\u4173f;\uc000\ud835\udd66\u0300adhlsu\u114b\u3878\u387d\u1372\u3891\u38a0own\xe1\u13b3arpoon\u0100lr\u3888\u388cef\xf4\u382digh\xf4\u382fi\u0180;hl\u3899\u389a\u389c\u43c5\xbb\u13faon\xbb\u389aparrows;\u61c8\u0180cit\u38b0\u38c4\u38c8\u026f\u38b6\0\0\u38c1rn\u0100;e\u38bc\u38bd\u631dr\xbb\u38bdop;\u630eng;\u416fri;\u65f9cr;\uc000\ud835\udcca\u0180dir\u38d9\u38dd\u38e2ot;\u62f0lde;\u4169i\u0100;f\u3730\u38e8\xbb\u1813\u0100am\u38ef\u38f2r\xf2\u38a8l\u803b\xfc\u40fcangle;\u69a7\u0780ABDacdeflnoprsz\u391c\u391f\u3929\u392d\u39b5\u39b8\u39bd\u39df\u39e4\u39e8\u39f3\u39f9\u39fd\u3a01\u3a20r\xf2\u03f7ar\u0100;v\u3926\u3927\u6ae8;\u6ae9as\xe8\u03e1\u0100nr\u3932\u3937grt;\u699c\u0380eknprst\u34e3\u3946\u394b\u3952\u395d\u3964\u3996app\xe1\u2415othin\xe7\u1e96\u0180hir\u34eb\u2ec8\u3959op\xf4\u2fb5\u0100;h\u13b7\u3962\xef\u318d\u0100iu\u3969\u396dgm\xe1\u33b3\u0100bp\u3972\u3984setneq\u0100;q\u397d\u3980\uc000\u228a\ufe00;\uc000\u2acb\ufe00setneq\u0100;q\u398f\u3992\uc000\u228b\ufe00;\uc000\u2acc\ufe00\u0100hr\u399b\u399fet\xe1\u369ciangle\u0100lr\u39aa\u39afeft\xbb\u0925ight\xbb\u1051y;\u4432ash\xbb\u1036\u0180elr\u39c4\u39d2\u39d7\u0180;be\u2dea\u39cb\u39cfar;\u62bbq;\u625alip;\u62ee\u0100bt\u39dc\u1468a\xf2\u1469r;\uc000\ud835\udd33tr\xe9\u39aesu\u0100bp\u39ef\u39f1\xbb\u0d1c\xbb\u0d59pf;\uc000\ud835\udd67ro\xf0\u0efbtr\xe9\u39b4\u0100cu\u3a06\u3a0br;\uc000\ud835\udccb\u0100bp\u3a10\u3a18n\u0100Ee\u3980\u3a16\xbb\u397en\u0100Ee\u3992\u3a1e\xbb\u3990igzag;\u699a\u0380cefoprs\u3a36\u3a3b\u3a56\u3a5b\u3a54\u3a61\u3a6airc;\u4175\u0100di\u3a40\u3a51\u0100bg\u3a45\u3a49ar;\u6a5fe\u0100;q\u15fa\u3a4f;\u6259erp;\u6118r;\uc000\ud835\udd34pf;\uc000\ud835\udd68\u0100;e\u1479\u3a66at\xe8\u1479cr;\uc000\ud835\udccc\u0ae3\u178e\u3a87\0\u3a8b\0\u3a90\u3a9b\0\0\u3a9d\u3aa8\u3aab\u3aaf\0\0\u3ac3\u3ace\0\u3ad8\u17dc\u17dftr\xe9\u17d1r;\uc000\ud835\udd35\u0100Aa\u3a94\u3a97r\xf2\u03c3r\xf2\u09f6;\u43be\u0100Aa\u3aa1\u3aa4r\xf2\u03b8r\xf2\u09eba\xf0\u2713is;\u62fb\u0180dpt\u17a4\u3ab5\u3abe\u0100fl\u3aba\u17a9;\uc000\ud835\udd69im\xe5\u17b2\u0100Aa\u3ac7\u3acar\xf2\u03cer\xf2\u0a01\u0100cq\u3ad2\u17b8r;\uc000\ud835\udccd\u0100pt\u17d6\u3adcr\xe9\u17d4\u0400acefiosu\u3af0\u3afd\u3b08\u3b0c\u3b11\u3b15\u3b1b\u3b21c\u0100uy\u3af6\u3afbte\u803b\xfd\u40fd;\u444f\u0100iy\u3b02\u3b06rc;\u4177;\u444bn\u803b\xa5\u40a5r;\uc000\ud835\udd36cy;\u4457pf;\uc000\ud835\udd6acr;\uc000\ud835\udcce\u0100cm\u3b26\u3b29y;\u444el\u803b\xff\u40ff\u0500acdefhiosw\u3b42\u3b48\u3b54\u3b58\u3b64\u3b69\u3b6d\u3b74\u3b7a\u3b80cute;\u417a\u0100ay\u3b4d\u3b52ron;\u417e;\u4437ot;\u417c\u0100et\u3b5d\u3b61tr\xe6\u155fa;\u43b6r;\uc000\ud835\udd37cy;\u4436grarr;\u61ddpf;\uc000\ud835\udd6bcr;\uc000\ud835\udccf\u0100jn\u3b85\u3b87;\u600dj;\u600c" .split("") .map((c) => c.charCodeAt(0))); //# sourceMappingURL=decode-data-html.js.map /***/ }), /***/ 1735: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Generated using scripts/write-decode-map.ts Object.defineProperty(exports, "__esModule", ({ value: true })); exports.xmlDecodeTree = void 0; exports.xmlDecodeTree = new Uint16Array( // prettier-ignore /* #__PURE__ */ "\u0200aglq\t\x15\x18\x1b\u026d\x0f\0\0\x12p;\u4026os;\u4027t;\u403et;\u403cuot;\u4022" .split("") .map((c) => c.charCodeAt(0))); //# sourceMappingURL=decode-data-xml.js.map /***/ }), /***/ 7501: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.adapter = void 0; exports.serializeDoctypeContent = serializeDoctypeContent; const parse5_1 = __nccwpck_require__(50069); const domhandler_1 = __nccwpck_require__(57792); function enquoteDoctypeId(id) { const quote = id.includes('"') ? "'" : '"'; return quote + id + quote; } /** @internal */ function serializeDoctypeContent(name, publicId, systemId) { let str = '!DOCTYPE '; if (name) { str += name; } if (publicId) { str += ` PUBLIC ${enquoteDoctypeId(publicId)}`; } else if (systemId) { str += ' SYSTEM'; } if (systemId) { str += ` ${enquoteDoctypeId(systemId)}`; } return str; } exports.adapter = { // Re-exports from domhandler isCommentNode: domhandler_1.isComment, isElementNode: domhandler_1.isTag, isTextNode: domhandler_1.isText, //Node construction createDocument() { const node = new domhandler_1.Document([]); node['x-mode'] = parse5_1.html.DOCUMENT_MODE.NO_QUIRKS; return node; }, createDocumentFragment() { return new domhandler_1.Document([]); }, createElement(tagName, namespaceURI, attrs) { const attribs = Object.create(null); const attribsNamespace = Object.create(null); const attribsPrefix = Object.create(null); for (let i = 0; i < attrs.length; i++) { const attrName = attrs[i].name; attribs[attrName] = attrs[i].value; attribsNamespace[attrName] = attrs[i].namespace; attribsPrefix[attrName] = attrs[i].prefix; } const node = new domhandler_1.Element(tagName, attribs, []); node.namespace = namespaceURI; node['x-attribsNamespace'] = attribsNamespace; node['x-attribsPrefix'] = attribsPrefix; return node; }, createCommentNode(data) { return new domhandler_1.Comment(data); }, createTextNode(value) { return new domhandler_1.Text(value); }, //Tree mutation appendChild(parentNode, newNode) { const prev = parentNode.children[parentNode.children.length - 1]; if (prev) { prev.next = newNode; newNode.prev = prev; } parentNode.children.push(newNode); newNode.parent = parentNode; }, insertBefore(parentNode, newNode, referenceNode) { const insertionIdx = parentNode.children.indexOf(referenceNode); const { prev } = referenceNode; if (prev) { prev.next = newNode; newNode.prev = prev; } referenceNode.prev = newNode; newNode.next = referenceNode; parentNode.children.splice(insertionIdx, 0, newNode); newNode.parent = parentNode; }, setTemplateContent(templateElement, contentElement) { exports.adapter.appendChild(templateElement, contentElement); }, getTemplateContent(templateElement) { return templateElement.children[0]; }, setDocumentType(document, name, publicId, systemId) { const data = serializeDoctypeContent(name, publicId, systemId); let doctypeNode = document.children.find((node) => (0, domhandler_1.isDirective)(node) && node.name === '!doctype'); if (doctypeNode) { doctypeNode.data = data !== null && data !== void 0 ? data : null; } else { doctypeNode = new domhandler_1.ProcessingInstruction('!doctype', data); exports.adapter.appendChild(document, doctypeNode); } doctypeNode['x-name'] = name; doctypeNode['x-publicId'] = publicId; doctypeNode['x-systemId'] = systemId; }, setDocumentMode(document, mode) { document['x-mode'] = mode; }, getDocumentMode(document) { return document['x-mode']; }, detachNode(node) { if (node.parent) { const idx = node.parent.children.indexOf(node); const { prev, next } = node; node.prev = null; node.next = null; if (prev) { prev.next = next; } if (next) { next.prev = prev; } node.parent.children.splice(idx, 1); node.parent = null; } }, insertText(parentNode, text) { const lastChild = parentNode.children[parentNode.children.length - 1]; if (lastChild && (0, domhandler_1.isText)(lastChild)) { lastChild.data += text; } else { exports.adapter.appendChild(parentNode, exports.adapter.createTextNode(text)); } }, insertTextBefore(parentNode, text, referenceNode) { const prevNode = parentNode.children[parentNode.children.indexOf(referenceNode) - 1]; if (prevNode && (0, domhandler_1.isText)(prevNode)) { prevNode.data += text; } else { exports.adapter.insertBefore(parentNode, exports.adapter.createTextNode(text), referenceNode); } }, adoptAttributes(recipient, attrs) { for (let i = 0; i < attrs.length; i++) { const attrName = attrs[i].name; if (recipient.attribs[attrName] === undefined) { recipient.attribs[attrName] = attrs[i].value; recipient['x-attribsNamespace'][attrName] = attrs[i].namespace; recipient['x-attribsPrefix'][attrName] = attrs[i].prefix; } } }, //Tree traversing getFirstChild(node) { return node.children[0]; }, getChildNodes(node) { return node.children; }, getParentNode(node) { return node.parent; }, getAttrList(element) { return element.attributes; }, //Node data getTagName(element) { return element.name; }, getNamespaceURI(element) { return element.namespace; }, getTextNodeContent(textNode) { return textNode.data; }, getCommentNodeContent(commentNode) { return commentNode.data; }, getDocumentTypeNodeName(doctypeNode) { var _a; return (_a = doctypeNode['x-name']) !== null && _a !== void 0 ? _a : ''; }, getDocumentTypeNodePublicId(doctypeNode) { var _a; return (_a = doctypeNode['x-publicId']) !== null && _a !== void 0 ? _a : ''; }, getDocumentTypeNodeSystemId(doctypeNode) { var _a; return (_a = doctypeNode['x-systemId']) !== null && _a !== void 0 ? _a : ''; }, //Node types isDocumentTypeNode(node) { return (0, domhandler_1.isDirective)(node) && node.name === '!doctype'; }, // Source code location setNodeSourceCodeLocation(node, location) { if (location) { node.startIndex = location.startOffset; node.endIndex = location.endOffset; } node.sourceCodeLocation = location; }, getNodeSourceCodeLocation(node) { return node.sourceCodeLocation; }, updateNodeSourceCodeLocation(node, endLocation) { if (endLocation.endOffset != null) node.endIndex = endLocation.endOffset; node.sourceCodeLocation = Object.assign(Object.assign({}, node.sourceCodeLocation), endLocation); }, }; /***/ }), /***/ 36920: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ParserStream = void 0; const node_stream_1 = __nccwpck_require__(57075); const parse5_1 = __nccwpck_require__(50069); /* eslint-disable unicorn/consistent-function-scoping -- The rule seems to be broken here. */ /** * Streaming HTML parser with scripting support. * A [writable stream](https://nodejs.org/api/stream.html#stream_class_stream_writable). * * @example * * ```js * const ParserStream = require('parse5-parser-stream'); * const http = require('http'); * const { finished } = require('node:stream'); * * // Fetch the page content and obtain it's node * http.get('http://inikulin.github.io/parse5/', res => { * const parser = new ParserStream(); * * finished(parser, () => { * console.log(parser.document.childNodes[1].childNodes[0].tagName); //> 'head' * }); * * res.pipe(parser); * }); * ``` * */ class ParserStream extends node_stream_1.Writable { static getFragmentStream(fragmentContext, options) { const parser = parse5_1.Parser.getFragmentParser(fragmentContext, options); const stream = new ParserStream(options, parser); return stream; } /** The resulting document node. */ get document() { return this.parser.document; } getFragment() { return this.parser.getFragment(); } /** * @param options Parsing options. */ constructor(options, parser = new parse5_1.Parser(options)) { super({ decodeStrings: false }); this.parser = parser; this.lastChunkWritten = false; this.writeCallback = undefined; this.pendingHtmlInsertions = []; const resume = () => { for (let i = this.pendingHtmlInsertions.length - 1; i >= 0; i--) { this.parser.tokenizer.insertHtmlAtCurrentPos(this.pendingHtmlInsertions[i]); } this.pendingHtmlInsertions.length = 0; //NOTE: keep parsing if we don't wait for the next input chunk this.parser.tokenizer.resume(this.writeCallback); }; const documentWrite = (html) => { if (!this.parser.stopped) { this.pendingHtmlInsertions.push(html); } }; const scriptHandler = (scriptElement) => { if (this.listenerCount('script') > 0) { this.parser.tokenizer.pause(); this.emit('script', scriptElement, documentWrite, resume); } }; this.parser.scriptHandler = scriptHandler; } //WritableStream implementation _write(chunk, _encoding, callback) { if (typeof chunk !== 'string') { throw new TypeError('Parser can work only with string streams.'); } this.writeCallback = callback; this.parser.tokenizer.write(chunk, this.lastChunkWritten, this.writeCallback); } // TODO [engine:node@>=16]: Due to issues with Node < 16, we are overriding `end` instead of `_final`. // eslint-disable-next-line @typescript-eslint/no-explicit-any end(chunk, encoding, callback) { this.lastChunkWritten = true; super.end(chunk || '', encoding, callback); } } exports.ParserStream = ParserStream; //# sourceMappingURL=index.js.map /***/ }), /***/ 32377: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isConforming = isConforming; exports.getDocumentMode = getDocumentMode; const html_js_1 = __nccwpck_require__(81510); //Const const VALID_DOCTYPE_NAME = 'html'; const VALID_SYSTEM_ID = 'about:legacy-compat'; const QUIRKS_MODE_SYSTEM_ID = 'http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd'; const QUIRKS_MODE_PUBLIC_ID_PREFIXES = [ '+//silmaril//dtd html pro v0r11 19970101//', '-//as//dtd html 3.0 aswedit + extensions//', '-//advasoft ltd//dtd html 3.0 aswedit + extensions//', '-//ietf//dtd html 2.0 level 1//', '-//ietf//dtd html 2.0 level 2//', '-//ietf//dtd html 2.0 strict level 1//', '-//ietf//dtd html 2.0 strict level 2//', '-//ietf//dtd html 2.0 strict//', '-//ietf//dtd html 2.0//', '-//ietf//dtd html 2.1e//', '-//ietf//dtd html 3.0//', '-//ietf//dtd html 3.2 final//', '-//ietf//dtd html 3.2//', '-//ietf//dtd html 3//', '-//ietf//dtd html level 0//', '-//ietf//dtd html level 1//', '-//ietf//dtd html level 2//', '-//ietf//dtd html level 3//', '-//ietf//dtd html strict level 0//', '-//ietf//dtd html strict level 1//', '-//ietf//dtd html strict level 2//', '-//ietf//dtd html strict level 3//', '-//ietf//dtd html strict//', '-//ietf//dtd html//', '-//metrius//dtd metrius presentational//', '-//microsoft//dtd internet explorer 2.0 html strict//', '-//microsoft//dtd internet explorer 2.0 html//', '-//microsoft//dtd internet explorer 2.0 tables//', '-//microsoft//dtd internet explorer 3.0 html strict//', '-//microsoft//dtd internet explorer 3.0 html//', '-//microsoft//dtd internet explorer 3.0 tables//', '-//netscape comm. corp.//dtd html//', '-//netscape comm. corp.//dtd strict html//', "-//o'reilly and associates//dtd html 2.0//", "-//o'reilly and associates//dtd html extended 1.0//", "-//o'reilly and associates//dtd html extended relaxed 1.0//", '-//sq//dtd html 2.0 hotmetal + extensions//', '-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//', '-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//', '-//spyglass//dtd html 2.0 extended//', '-//sun microsystems corp.//dtd hotjava html//', '-//sun microsystems corp.//dtd hotjava strict html//', '-//w3c//dtd html 3 1995-03-24//', '-//w3c//dtd html 3.2 draft//', '-//w3c//dtd html 3.2 final//', '-//w3c//dtd html 3.2//', '-//w3c//dtd html 3.2s draft//', '-//w3c//dtd html 4.0 frameset//', '-//w3c//dtd html 4.0 transitional//', '-//w3c//dtd html experimental 19960712//', '-//w3c//dtd html experimental 970421//', '-//w3c//dtd w3 html//', '-//w3o//dtd w3 html 3.0//', '-//webtechs//dtd mozilla html 2.0//', '-//webtechs//dtd mozilla html//', ]; const QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES = [ ...QUIRKS_MODE_PUBLIC_ID_PREFIXES, '-//w3c//dtd html 4.01 frameset//', '-//w3c//dtd html 4.01 transitional//', ]; const QUIRKS_MODE_PUBLIC_IDS = new Set([ '-//w3o//dtd w3 html strict 3.0//en//', '-/w3c/dtd html 4.0 transitional/en', 'html', ]); const LIMITED_QUIRKS_PUBLIC_ID_PREFIXES = ['-//w3c//dtd xhtml 1.0 frameset//', '-//w3c//dtd xhtml 1.0 transitional//']; const LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES = [ ...LIMITED_QUIRKS_PUBLIC_ID_PREFIXES, '-//w3c//dtd html 4.01 frameset//', '-//w3c//dtd html 4.01 transitional//', ]; //Utils function hasPrefix(publicId, prefixes) { return prefixes.some((prefix) => publicId.startsWith(prefix)); } //API function isConforming(token) { return (token.name === VALID_DOCTYPE_NAME && token.publicId === null && (token.systemId === null || token.systemId === VALID_SYSTEM_ID)); } function getDocumentMode(token) { if (token.name !== VALID_DOCTYPE_NAME) { return html_js_1.DOCUMENT_MODE.QUIRKS; } const { systemId } = token; if (systemId && systemId.toLowerCase() === QUIRKS_MODE_SYSTEM_ID) { return html_js_1.DOCUMENT_MODE.QUIRKS; } let { publicId } = token; if (publicId !== null) { publicId = publicId.toLowerCase(); if (QUIRKS_MODE_PUBLIC_IDS.has(publicId)) { return html_js_1.DOCUMENT_MODE.QUIRKS; } let prefixes = systemId === null ? QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES : QUIRKS_MODE_PUBLIC_ID_PREFIXES; if (hasPrefix(publicId, prefixes)) { return html_js_1.DOCUMENT_MODE.QUIRKS; } prefixes = systemId === null ? LIMITED_QUIRKS_PUBLIC_ID_PREFIXES : LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES; if (hasPrefix(publicId, prefixes)) { return html_js_1.DOCUMENT_MODE.LIMITED_QUIRKS; } } return html_js_1.DOCUMENT_MODE.NO_QUIRKS; } /***/ }), /***/ 69322: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ERR = void 0; var ERR; (function (ERR) { ERR["controlCharacterInInputStream"] = "control-character-in-input-stream"; ERR["noncharacterInInputStream"] = "noncharacter-in-input-stream"; ERR["surrogateInInputStream"] = "surrogate-in-input-stream"; ERR["nonVoidHtmlElementStartTagWithTrailingSolidus"] = "non-void-html-element-start-tag-with-trailing-solidus"; ERR["endTagWithAttributes"] = "end-tag-with-attributes"; ERR["endTagWithTrailingSolidus"] = "end-tag-with-trailing-solidus"; ERR["unexpectedSolidusInTag"] = "unexpected-solidus-in-tag"; ERR["unexpectedNullCharacter"] = "unexpected-null-character"; ERR["unexpectedQuestionMarkInsteadOfTagName"] = "unexpected-question-mark-instead-of-tag-name"; ERR["invalidFirstCharacterOfTagName"] = "invalid-first-character-of-tag-name"; ERR["unexpectedEqualsSignBeforeAttributeName"] = "unexpected-equals-sign-before-attribute-name"; ERR["missingEndTagName"] = "missing-end-tag-name"; ERR["unexpectedCharacterInAttributeName"] = "unexpected-character-in-attribute-name"; ERR["unknownNamedCharacterReference"] = "unknown-named-character-reference"; ERR["missingSemicolonAfterCharacterReference"] = "missing-semicolon-after-character-reference"; ERR["unexpectedCharacterAfterDoctypeSystemIdentifier"] = "unexpected-character-after-doctype-system-identifier"; ERR["unexpectedCharacterInUnquotedAttributeValue"] = "unexpected-character-in-unquoted-attribute-value"; ERR["eofBeforeTagName"] = "eof-before-tag-name"; ERR["eofInTag"] = "eof-in-tag"; ERR["missingAttributeValue"] = "missing-attribute-value"; ERR["missingWhitespaceBetweenAttributes"] = "missing-whitespace-between-attributes"; ERR["missingWhitespaceAfterDoctypePublicKeyword"] = "missing-whitespace-after-doctype-public-keyword"; ERR["missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers"] = "missing-whitespace-between-doctype-public-and-system-identifiers"; ERR["missingWhitespaceAfterDoctypeSystemKeyword"] = "missing-whitespace-after-doctype-system-keyword"; ERR["missingQuoteBeforeDoctypePublicIdentifier"] = "missing-quote-before-doctype-public-identifier"; ERR["missingQuoteBeforeDoctypeSystemIdentifier"] = "missing-quote-before-doctype-system-identifier"; ERR["missingDoctypePublicIdentifier"] = "missing-doctype-public-identifier"; ERR["missingDoctypeSystemIdentifier"] = "missing-doctype-system-identifier"; ERR["abruptDoctypePublicIdentifier"] = "abrupt-doctype-public-identifier"; ERR["abruptDoctypeSystemIdentifier"] = "abrupt-doctype-system-identifier"; ERR["cdataInHtmlContent"] = "cdata-in-html-content"; ERR["incorrectlyOpenedComment"] = "incorrectly-opened-comment"; ERR["eofInScriptHtmlCommentLikeText"] = "eof-in-script-html-comment-like-text"; ERR["eofInDoctype"] = "eof-in-doctype"; ERR["nestedComment"] = "nested-comment"; ERR["abruptClosingOfEmptyComment"] = "abrupt-closing-of-empty-comment"; ERR["eofInComment"] = "eof-in-comment"; ERR["incorrectlyClosedComment"] = "incorrectly-closed-comment"; ERR["eofInCdata"] = "eof-in-cdata"; ERR["absenceOfDigitsInNumericCharacterReference"] = "absence-of-digits-in-numeric-character-reference"; ERR["nullCharacterReference"] = "null-character-reference"; ERR["surrogateCharacterReference"] = "surrogate-character-reference"; ERR["characterReferenceOutsideUnicodeRange"] = "character-reference-outside-unicode-range"; ERR["controlCharacterReference"] = "control-character-reference"; ERR["noncharacterCharacterReference"] = "noncharacter-character-reference"; ERR["missingWhitespaceBeforeDoctypeName"] = "missing-whitespace-before-doctype-name"; ERR["missingDoctypeName"] = "missing-doctype-name"; ERR["invalidCharacterSequenceAfterDoctypeName"] = "invalid-character-sequence-after-doctype-name"; ERR["duplicateAttribute"] = "duplicate-attribute"; ERR["nonConformingDoctype"] = "non-conforming-doctype"; ERR["missingDoctype"] = "missing-doctype"; ERR["misplacedDoctype"] = "misplaced-doctype"; ERR["endTagWithoutMatchingOpenElement"] = "end-tag-without-matching-open-element"; ERR["closingOfElementWithOpenChildElements"] = "closing-of-element-with-open-child-elements"; ERR["disallowedContentInNoscriptInHead"] = "disallowed-content-in-noscript-in-head"; ERR["openElementsLeftAfterEof"] = "open-elements-left-after-eof"; ERR["abandonedHeadElementChild"] = "abandoned-head-element-child"; ERR["misplacedStartTagForHeadElement"] = "misplaced-start-tag-for-head-element"; ERR["nestedNoscriptInHead"] = "nested-noscript-in-head"; ERR["eofInElementThatCanContainOnlyText"] = "eof-in-element-that-can-contain-only-text"; })(ERR || (exports.ERR = ERR = {})); /***/ }), /***/ 79319: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SVG_TAG_NAMES_ADJUSTMENT_MAP = void 0; exports.causesExit = causesExit; exports.adjustTokenMathMLAttrs = adjustTokenMathMLAttrs; exports.adjustTokenSVGAttrs = adjustTokenSVGAttrs; exports.adjustTokenXMLAttrs = adjustTokenXMLAttrs; exports.adjustTokenSVGTagName = adjustTokenSVGTagName; exports.isIntegrationPoint = isIntegrationPoint; const html_js_1 = __nccwpck_require__(81510); //MIME types const MIME_TYPES = { TEXT_HTML: 'text/html', APPLICATION_XML: 'application/xhtml+xml', }; //Attributes const DEFINITION_URL_ATTR = 'definitionurl'; const ADJUSTED_DEFINITION_URL_ATTR = 'definitionURL'; const SVG_ATTRS_ADJUSTMENT_MAP = new Map([ 'attributeName', 'attributeType', 'baseFrequency', 'baseProfile', 'calcMode', 'clipPathUnits', 'diffuseConstant', 'edgeMode', 'filterUnits', 'glyphRef', 'gradientTransform', 'gradientUnits', 'kernelMatrix', 'kernelUnitLength', 'keyPoints', 'keySplines', 'keyTimes', 'lengthAdjust', 'limitingConeAngle', 'markerHeight', 'markerUnits', 'markerWidth', 'maskContentUnits', 'maskUnits', 'numOctaves', 'pathLength', 'patternContentUnits', 'patternTransform', 'patternUnits', 'pointsAtX', 'pointsAtY', 'pointsAtZ', 'preserveAlpha', 'preserveAspectRatio', 'primitiveUnits', 'refX', 'refY', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'specularConstant', 'specularExponent', 'spreadMethod', 'startOffset', 'stdDeviation', 'stitchTiles', 'surfaceScale', 'systemLanguage', 'tableValues', 'targetX', 'targetY', 'textLength', 'viewBox', 'viewTarget', 'xChannelSelector', 'yChannelSelector', 'zoomAndPan', ].map((attr) => [attr.toLowerCase(), attr])); const XML_ATTRS_ADJUSTMENT_MAP = new Map([ ['xlink:actuate', { prefix: 'xlink', name: 'actuate', namespace: html_js_1.NS.XLINK }], ['xlink:arcrole', { prefix: 'xlink', name: 'arcrole', namespace: html_js_1.NS.XLINK }], ['xlink:href', { prefix: 'xlink', name: 'href', namespace: html_js_1.NS.XLINK }], ['xlink:role', { prefix: 'xlink', name: 'role', namespace: html_js_1.NS.XLINK }], ['xlink:show', { prefix: 'xlink', name: 'show', namespace: html_js_1.NS.XLINK }], ['xlink:title', { prefix: 'xlink', name: 'title', namespace: html_js_1.NS.XLINK }], ['xlink:type', { prefix: 'xlink', name: 'type', namespace: html_js_1.NS.XLINK }], ['xml:lang', { prefix: 'xml', name: 'lang', namespace: html_js_1.NS.XML }], ['xml:space', { prefix: 'xml', name: 'space', namespace: html_js_1.NS.XML }], ['xmlns', { prefix: '', name: 'xmlns', namespace: html_js_1.NS.XMLNS }], ['xmlns:xlink', { prefix: 'xmlns', name: 'xlink', namespace: html_js_1.NS.XMLNS }], ]); //SVG tag names adjustment map exports.SVG_TAG_NAMES_ADJUSTMENT_MAP = new Map([ 'altGlyph', 'altGlyphDef', 'altGlyphItem', 'animateColor', 'animateMotion', 'animateTransform', 'clipPath', 'feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence', 'foreignObject', 'glyphRef', 'linearGradient', 'radialGradient', 'textPath', ].map((tn) => [tn.toLowerCase(), tn])); //Tags that causes exit from foreign content const EXITS_FOREIGN_CONTENT = new Set([ html_js_1.TAG_ID.B, html_js_1.TAG_ID.BIG, html_js_1.TAG_ID.BLOCKQUOTE, html_js_1.TAG_ID.BODY, html_js_1.TAG_ID.BR, html_js_1.TAG_ID.CENTER, html_js_1.TAG_ID.CODE, html_js_1.TAG_ID.DD, html_js_1.TAG_ID.DIV, html_js_1.TAG_ID.DL, html_js_1.TAG_ID.DT, html_js_1.TAG_ID.EM, html_js_1.TAG_ID.EMBED, html_js_1.TAG_ID.H1, html_js_1.TAG_ID.H2, html_js_1.TAG_ID.H3, html_js_1.TAG_ID.H4, html_js_1.TAG_ID.H5, html_js_1.TAG_ID.H6, html_js_1.TAG_ID.HEAD, html_js_1.TAG_ID.HR, html_js_1.TAG_ID.I, html_js_1.TAG_ID.IMG, html_js_1.TAG_ID.LI, html_js_1.TAG_ID.LISTING, html_js_1.TAG_ID.MENU, html_js_1.TAG_ID.META, html_js_1.TAG_ID.NOBR, html_js_1.TAG_ID.OL, html_js_1.TAG_ID.P, html_js_1.TAG_ID.PRE, html_js_1.TAG_ID.RUBY, html_js_1.TAG_ID.S, html_js_1.TAG_ID.SMALL, html_js_1.TAG_ID.SPAN, html_js_1.TAG_ID.STRONG, html_js_1.TAG_ID.STRIKE, html_js_1.TAG_ID.SUB, html_js_1.TAG_ID.SUP, html_js_1.TAG_ID.TABLE, html_js_1.TAG_ID.TT, html_js_1.TAG_ID.U, html_js_1.TAG_ID.UL, html_js_1.TAG_ID.VAR, ]); //Check exit from foreign content function causesExit(startTagToken) { const tn = startTagToken.tagID; const isFontWithAttrs = tn === html_js_1.TAG_ID.FONT && startTagToken.attrs.some(({ name }) => name === html_js_1.ATTRS.COLOR || name === html_js_1.ATTRS.SIZE || name === html_js_1.ATTRS.FACE); return isFontWithAttrs || EXITS_FOREIGN_CONTENT.has(tn); } //Token adjustments function adjustTokenMathMLAttrs(token) { for (let i = 0; i < token.attrs.length; i++) { if (token.attrs[i].name === DEFINITION_URL_ATTR) { token.attrs[i].name = ADJUSTED_DEFINITION_URL_ATTR; break; } } } function adjustTokenSVGAttrs(token) { for (let i = 0; i < token.attrs.length; i++) { const adjustedAttrName = SVG_ATTRS_ADJUSTMENT_MAP.get(token.attrs[i].name); if (adjustedAttrName != null) { token.attrs[i].name = adjustedAttrName; } } } function adjustTokenXMLAttrs(token) { for (let i = 0; i < token.attrs.length; i++) { const adjustedAttrEntry = XML_ATTRS_ADJUSTMENT_MAP.get(token.attrs[i].name); if (adjustedAttrEntry) { token.attrs[i].prefix = adjustedAttrEntry.prefix; token.attrs[i].name = adjustedAttrEntry.name; token.attrs[i].namespace = adjustedAttrEntry.namespace; } } } function adjustTokenSVGTagName(token) { const adjustedTagName = exports.SVG_TAG_NAMES_ADJUSTMENT_MAP.get(token.tagName); if (adjustedTagName != null) { token.tagName = adjustedTagName; token.tagID = (0, html_js_1.getTagID)(token.tagName); } } //Integration points function isMathMLTextIntegrationPoint(tn, ns) { return ns === html_js_1.NS.MATHML && (tn === html_js_1.TAG_ID.MI || tn === html_js_1.TAG_ID.MO || tn === html_js_1.TAG_ID.MN || tn === html_js_1.TAG_ID.MS || tn === html_js_1.TAG_ID.MTEXT); } function isHtmlIntegrationPoint(tn, ns, attrs) { if (ns === html_js_1.NS.MATHML && tn === html_js_1.TAG_ID.ANNOTATION_XML) { for (let i = 0; i < attrs.length; i++) { if (attrs[i].name === html_js_1.ATTRS.ENCODING) { const value = attrs[i].value.toLowerCase(); return value === MIME_TYPES.TEXT_HTML || value === MIME_TYPES.APPLICATION_XML; } } } return ns === html_js_1.NS.SVG && (tn === html_js_1.TAG_ID.FOREIGN_OBJECT || tn === html_js_1.TAG_ID.DESC || tn === html_js_1.TAG_ID.TITLE); } function isIntegrationPoint(tn, ns, attrs, foreignNS) { return (((!foreignNS || foreignNS === html_js_1.NS.HTML) && isHtmlIntegrationPoint(tn, ns, attrs)) || ((!foreignNS || foreignNS === html_js_1.NS.MATHML) && isMathMLTextIntegrationPoint(tn, ns))); } /***/ }), /***/ 81510: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NUMBERED_HEADERS = exports.SPECIAL_ELEMENTS = exports.TAG_ID = exports.TAG_NAMES = exports.DOCUMENT_MODE = exports.ATTRS = exports.NS = void 0; exports.getTagID = getTagID; exports.hasUnescapedText = hasUnescapedText; /** All valid namespaces in HTML. */ var NS; (function (NS) { NS["HTML"] = "http://www.w3.org/1999/xhtml"; NS["MATHML"] = "http://www.w3.org/1998/Math/MathML"; NS["SVG"] = "http://www.w3.org/2000/svg"; NS["XLINK"] = "http://www.w3.org/1999/xlink"; NS["XML"] = "http://www.w3.org/XML/1998/namespace"; NS["XMLNS"] = "http://www.w3.org/2000/xmlns/"; })(NS || (exports.NS = NS = {})); var ATTRS; (function (ATTRS) { ATTRS["TYPE"] = "type"; ATTRS["ACTION"] = "action"; ATTRS["ENCODING"] = "encoding"; ATTRS["PROMPT"] = "prompt"; ATTRS["NAME"] = "name"; ATTRS["COLOR"] = "color"; ATTRS["FACE"] = "face"; ATTRS["SIZE"] = "size"; })(ATTRS || (exports.ATTRS = ATTRS = {})); /** * The mode of the document. * * @see {@link https://dom.spec.whatwg.org/#concept-document-limited-quirks} */ var DOCUMENT_MODE; (function (DOCUMENT_MODE) { DOCUMENT_MODE["NO_QUIRKS"] = "no-quirks"; DOCUMENT_MODE["QUIRKS"] = "quirks"; DOCUMENT_MODE["LIMITED_QUIRKS"] = "limited-quirks"; })(DOCUMENT_MODE || (exports.DOCUMENT_MODE = DOCUMENT_MODE = {})); var TAG_NAMES; (function (TAG_NAMES) { TAG_NAMES["A"] = "a"; TAG_NAMES["ADDRESS"] = "address"; TAG_NAMES["ANNOTATION_XML"] = "annotation-xml"; TAG_NAMES["APPLET"] = "applet"; TAG_NAMES["AREA"] = "area"; TAG_NAMES["ARTICLE"] = "article"; TAG_NAMES["ASIDE"] = "aside"; TAG_NAMES["B"] = "b"; TAG_NAMES["BASE"] = "base"; TAG_NAMES["BASEFONT"] = "basefont"; TAG_NAMES["BGSOUND"] = "bgsound"; TAG_NAMES["BIG"] = "big"; TAG_NAMES["BLOCKQUOTE"] = "blockquote"; TAG_NAMES["BODY"] = "body"; TAG_NAMES["BR"] = "br"; TAG_NAMES["BUTTON"] = "button"; TAG_NAMES["CAPTION"] = "caption"; TAG_NAMES["CENTER"] = "center"; TAG_NAMES["CODE"] = "code"; TAG_NAMES["COL"] = "col"; TAG_NAMES["COLGROUP"] = "colgroup"; TAG_NAMES["DD"] = "dd"; TAG_NAMES["DESC"] = "desc"; TAG_NAMES["DETAILS"] = "details"; TAG_NAMES["DIALOG"] = "dialog"; TAG_NAMES["DIR"] = "dir"; TAG_NAMES["DIV"] = "div"; TAG_NAMES["DL"] = "dl"; TAG_NAMES["DT"] = "dt"; TAG_NAMES["EM"] = "em"; TAG_NAMES["EMBED"] = "embed"; TAG_NAMES["FIELDSET"] = "fieldset"; TAG_NAMES["FIGCAPTION"] = "figcaption"; TAG_NAMES["FIGURE"] = "figure"; TAG_NAMES["FONT"] = "font"; TAG_NAMES["FOOTER"] = "footer"; TAG_NAMES["FOREIGN_OBJECT"] = "foreignObject"; TAG_NAMES["FORM"] = "form"; TAG_NAMES["FRAME"] = "frame"; TAG_NAMES["FRAMESET"] = "frameset"; TAG_NAMES["H1"] = "h1"; TAG_NAMES["H2"] = "h2"; TAG_NAMES["H3"] = "h3"; TAG_NAMES["H4"] = "h4"; TAG_NAMES["H5"] = "h5"; TAG_NAMES["H6"] = "h6"; TAG_NAMES["HEAD"] = "head"; TAG_NAMES["HEADER"] = "header"; TAG_NAMES["HGROUP"] = "hgroup"; TAG_NAMES["HR"] = "hr"; TAG_NAMES["HTML"] = "html"; TAG_NAMES["I"] = "i"; TAG_NAMES["IMG"] = "img"; TAG_NAMES["IMAGE"] = "image"; TAG_NAMES["INPUT"] = "input"; TAG_NAMES["IFRAME"] = "iframe"; TAG_NAMES["KEYGEN"] = "keygen"; TAG_NAMES["LABEL"] = "label"; TAG_NAMES["LI"] = "li"; TAG_NAMES["LINK"] = "link"; TAG_NAMES["LISTING"] = "listing"; TAG_NAMES["MAIN"] = "main"; TAG_NAMES["MALIGNMARK"] = "malignmark"; TAG_NAMES["MARQUEE"] = "marquee"; TAG_NAMES["MATH"] = "math"; TAG_NAMES["MENU"] = "menu"; TAG_NAMES["META"] = "meta"; TAG_NAMES["MGLYPH"] = "mglyph"; TAG_NAMES["MI"] = "mi"; TAG_NAMES["MO"] = "mo"; TAG_NAMES["MN"] = "mn"; TAG_NAMES["MS"] = "ms"; TAG_NAMES["MTEXT"] = "mtext"; TAG_NAMES["NAV"] = "nav"; TAG_NAMES["NOBR"] = "nobr"; TAG_NAMES["NOFRAMES"] = "noframes"; TAG_NAMES["NOEMBED"] = "noembed"; TAG_NAMES["NOSCRIPT"] = "noscript"; TAG_NAMES["OBJECT"] = "object"; TAG_NAMES["OL"] = "ol"; TAG_NAMES["OPTGROUP"] = "optgroup"; TAG_NAMES["OPTION"] = "option"; TAG_NAMES["P"] = "p"; TAG_NAMES["PARAM"] = "param"; TAG_NAMES["PLAINTEXT"] = "plaintext"; TAG_NAMES["PRE"] = "pre"; TAG_NAMES["RB"] = "rb"; TAG_NAMES["RP"] = "rp"; TAG_NAMES["RT"] = "rt"; TAG_NAMES["RTC"] = "rtc"; TAG_NAMES["RUBY"] = "ruby"; TAG_NAMES["S"] = "s"; TAG_NAMES["SCRIPT"] = "script"; TAG_NAMES["SEARCH"] = "search"; TAG_NAMES["SECTION"] = "section"; TAG_NAMES["SELECT"] = "select"; TAG_NAMES["SOURCE"] = "source"; TAG_NAMES["SMALL"] = "small"; TAG_NAMES["SPAN"] = "span"; TAG_NAMES["STRIKE"] = "strike"; TAG_NAMES["STRONG"] = "strong"; TAG_NAMES["STYLE"] = "style"; TAG_NAMES["SUB"] = "sub"; TAG_NAMES["SUMMARY"] = "summary"; TAG_NAMES["SUP"] = "sup"; TAG_NAMES["TABLE"] = "table"; TAG_NAMES["TBODY"] = "tbody"; TAG_NAMES["TEMPLATE"] = "template"; TAG_NAMES["TEXTAREA"] = "textarea"; TAG_NAMES["TFOOT"] = "tfoot"; TAG_NAMES["TD"] = "td"; TAG_NAMES["TH"] = "th"; TAG_NAMES["THEAD"] = "thead"; TAG_NAMES["TITLE"] = "title"; TAG_NAMES["TR"] = "tr"; TAG_NAMES["TRACK"] = "track"; TAG_NAMES["TT"] = "tt"; TAG_NAMES["U"] = "u"; TAG_NAMES["UL"] = "ul"; TAG_NAMES["SVG"] = "svg"; TAG_NAMES["VAR"] = "var"; TAG_NAMES["WBR"] = "wbr"; TAG_NAMES["XMP"] = "xmp"; })(TAG_NAMES || (exports.TAG_NAMES = TAG_NAMES = {})); /** * Tag IDs are numeric IDs for known tag names. * * We use tag IDs to improve the performance of tag name comparisons. */ var TAG_ID; (function (TAG_ID) { TAG_ID[TAG_ID["UNKNOWN"] = 0] = "UNKNOWN"; TAG_ID[TAG_ID["A"] = 1] = "A"; TAG_ID[TAG_ID["ADDRESS"] = 2] = "ADDRESS"; TAG_ID[TAG_ID["ANNOTATION_XML"] = 3] = "ANNOTATION_XML"; TAG_ID[TAG_ID["APPLET"] = 4] = "APPLET"; TAG_ID[TAG_ID["AREA"] = 5] = "AREA"; TAG_ID[TAG_ID["ARTICLE"] = 6] = "ARTICLE"; TAG_ID[TAG_ID["ASIDE"] = 7] = "ASIDE"; TAG_ID[TAG_ID["B"] = 8] = "B"; TAG_ID[TAG_ID["BASE"] = 9] = "BASE"; TAG_ID[TAG_ID["BASEFONT"] = 10] = "BASEFONT"; TAG_ID[TAG_ID["BGSOUND"] = 11] = "BGSOUND"; TAG_ID[TAG_ID["BIG"] = 12] = "BIG"; TAG_ID[TAG_ID["BLOCKQUOTE"] = 13] = "BLOCKQUOTE"; TAG_ID[TAG_ID["BODY"] = 14] = "BODY"; TAG_ID[TAG_ID["BR"] = 15] = "BR"; TAG_ID[TAG_ID["BUTTON"] = 16] = "BUTTON"; TAG_ID[TAG_ID["CAPTION"] = 17] = "CAPTION"; TAG_ID[TAG_ID["CENTER"] = 18] = "CENTER"; TAG_ID[TAG_ID["CODE"] = 19] = "CODE"; TAG_ID[TAG_ID["COL"] = 20] = "COL"; TAG_ID[TAG_ID["COLGROUP"] = 21] = "COLGROUP"; TAG_ID[TAG_ID["DD"] = 22] = "DD"; TAG_ID[TAG_ID["DESC"] = 23] = "DESC"; TAG_ID[TAG_ID["DETAILS"] = 24] = "DETAILS"; TAG_ID[TAG_ID["DIALOG"] = 25] = "DIALOG"; TAG_ID[TAG_ID["DIR"] = 26] = "DIR"; TAG_ID[TAG_ID["DIV"] = 27] = "DIV"; TAG_ID[TAG_ID["DL"] = 28] = "DL"; TAG_ID[TAG_ID["DT"] = 29] = "DT"; TAG_ID[TAG_ID["EM"] = 30] = "EM"; TAG_ID[TAG_ID["EMBED"] = 31] = "EMBED"; TAG_ID[TAG_ID["FIELDSET"] = 32] = "FIELDSET"; TAG_ID[TAG_ID["FIGCAPTION"] = 33] = "FIGCAPTION"; TAG_ID[TAG_ID["FIGURE"] = 34] = "FIGURE"; TAG_ID[TAG_ID["FONT"] = 35] = "FONT"; TAG_ID[TAG_ID["FOOTER"] = 36] = "FOOTER"; TAG_ID[TAG_ID["FOREIGN_OBJECT"] = 37] = "FOREIGN_OBJECT"; TAG_ID[TAG_ID["FORM"] = 38] = "FORM"; TAG_ID[TAG_ID["FRAME"] = 39] = "FRAME"; TAG_ID[TAG_ID["FRAMESET"] = 40] = "FRAMESET"; TAG_ID[TAG_ID["H1"] = 41] = "H1"; TAG_ID[TAG_ID["H2"] = 42] = "H2"; TAG_ID[TAG_ID["H3"] = 43] = "H3"; TAG_ID[TAG_ID["H4"] = 44] = "H4"; TAG_ID[TAG_ID["H5"] = 45] = "H5"; TAG_ID[TAG_ID["H6"] = 46] = "H6"; TAG_ID[TAG_ID["HEAD"] = 47] = "HEAD"; TAG_ID[TAG_ID["HEADER"] = 48] = "HEADER"; TAG_ID[TAG_ID["HGROUP"] = 49] = "HGROUP"; TAG_ID[TAG_ID["HR"] = 50] = "HR"; TAG_ID[TAG_ID["HTML"] = 51] = "HTML"; TAG_ID[TAG_ID["I"] = 52] = "I"; TAG_ID[TAG_ID["IMG"] = 53] = "IMG"; TAG_ID[TAG_ID["IMAGE"] = 54] = "IMAGE"; TAG_ID[TAG_ID["INPUT"] = 55] = "INPUT"; TAG_ID[TAG_ID["IFRAME"] = 56] = "IFRAME"; TAG_ID[TAG_ID["KEYGEN"] = 57] = "KEYGEN"; TAG_ID[TAG_ID["LABEL"] = 58] = "LABEL"; TAG_ID[TAG_ID["LI"] = 59] = "LI"; TAG_ID[TAG_ID["LINK"] = 60] = "LINK"; TAG_ID[TAG_ID["LISTING"] = 61] = "LISTING"; TAG_ID[TAG_ID["MAIN"] = 62] = "MAIN"; TAG_ID[TAG_ID["MALIGNMARK"] = 63] = "MALIGNMARK"; TAG_ID[TAG_ID["MARQUEE"] = 64] = "MARQUEE"; TAG_ID[TAG_ID["MATH"] = 65] = "MATH"; TAG_ID[TAG_ID["MENU"] = 66] = "MENU"; TAG_ID[TAG_ID["META"] = 67] = "META"; TAG_ID[TAG_ID["MGLYPH"] = 68] = "MGLYPH"; TAG_ID[TAG_ID["MI"] = 69] = "MI"; TAG_ID[TAG_ID["MO"] = 70] = "MO"; TAG_ID[TAG_ID["MN"] = 71] = "MN"; TAG_ID[TAG_ID["MS"] = 72] = "MS"; TAG_ID[TAG_ID["MTEXT"] = 73] = "MTEXT"; TAG_ID[TAG_ID["NAV"] = 74] = "NAV"; TAG_ID[TAG_ID["NOBR"] = 75] = "NOBR"; TAG_ID[TAG_ID["NOFRAMES"] = 76] = "NOFRAMES"; TAG_ID[TAG_ID["NOEMBED"] = 77] = "NOEMBED"; TAG_ID[TAG_ID["NOSCRIPT"] = 78] = "NOSCRIPT"; TAG_ID[TAG_ID["OBJECT"] = 79] = "OBJECT"; TAG_ID[TAG_ID["OL"] = 80] = "OL"; TAG_ID[TAG_ID["OPTGROUP"] = 81] = "OPTGROUP"; TAG_ID[TAG_ID["OPTION"] = 82] = "OPTION"; TAG_ID[TAG_ID["P"] = 83] = "P"; TAG_ID[TAG_ID["PARAM"] = 84] = "PARAM"; TAG_ID[TAG_ID["PLAINTEXT"] = 85] = "PLAINTEXT"; TAG_ID[TAG_ID["PRE"] = 86] = "PRE"; TAG_ID[TAG_ID["RB"] = 87] = "RB"; TAG_ID[TAG_ID["RP"] = 88] = "RP"; TAG_ID[TAG_ID["RT"] = 89] = "RT"; TAG_ID[TAG_ID["RTC"] = 90] = "RTC"; TAG_ID[TAG_ID["RUBY"] = 91] = "RUBY"; TAG_ID[TAG_ID["S"] = 92] = "S"; TAG_ID[TAG_ID["SCRIPT"] = 93] = "SCRIPT"; TAG_ID[TAG_ID["SEARCH"] = 94] = "SEARCH"; TAG_ID[TAG_ID["SECTION"] = 95] = "SECTION"; TAG_ID[TAG_ID["SELECT"] = 96] = "SELECT"; TAG_ID[TAG_ID["SOURCE"] = 97] = "SOURCE"; TAG_ID[TAG_ID["SMALL"] = 98] = "SMALL"; TAG_ID[TAG_ID["SPAN"] = 99] = "SPAN"; TAG_ID[TAG_ID["STRIKE"] = 100] = "STRIKE"; TAG_ID[TAG_ID["STRONG"] = 101] = "STRONG"; TAG_ID[TAG_ID["STYLE"] = 102] = "STYLE"; TAG_ID[TAG_ID["SUB"] = 103] = "SUB"; TAG_ID[TAG_ID["SUMMARY"] = 104] = "SUMMARY"; TAG_ID[TAG_ID["SUP"] = 105] = "SUP"; TAG_ID[TAG_ID["TABLE"] = 106] = "TABLE"; TAG_ID[TAG_ID["TBODY"] = 107] = "TBODY"; TAG_ID[TAG_ID["TEMPLATE"] = 108] = "TEMPLATE"; TAG_ID[TAG_ID["TEXTAREA"] = 109] = "TEXTAREA"; TAG_ID[TAG_ID["TFOOT"] = 110] = "TFOOT"; TAG_ID[TAG_ID["TD"] = 111] = "TD"; TAG_ID[TAG_ID["TH"] = 112] = "TH"; TAG_ID[TAG_ID["THEAD"] = 113] = "THEAD"; TAG_ID[TAG_ID["TITLE"] = 114] = "TITLE"; TAG_ID[TAG_ID["TR"] = 115] = "TR"; TAG_ID[TAG_ID["TRACK"] = 116] = "TRACK"; TAG_ID[TAG_ID["TT"] = 117] = "TT"; TAG_ID[TAG_ID["U"] = 118] = "U"; TAG_ID[TAG_ID["UL"] = 119] = "UL"; TAG_ID[TAG_ID["SVG"] = 120] = "SVG"; TAG_ID[TAG_ID["VAR"] = 121] = "VAR"; TAG_ID[TAG_ID["WBR"] = 122] = "WBR"; TAG_ID[TAG_ID["XMP"] = 123] = "XMP"; })(TAG_ID || (exports.TAG_ID = TAG_ID = {})); const TAG_NAME_TO_ID = new Map([ [TAG_NAMES.A, TAG_ID.A], [TAG_NAMES.ADDRESS, TAG_ID.ADDRESS], [TAG_NAMES.ANNOTATION_XML, TAG_ID.ANNOTATION_XML], [TAG_NAMES.APPLET, TAG_ID.APPLET], [TAG_NAMES.AREA, TAG_ID.AREA], [TAG_NAMES.ARTICLE, TAG_ID.ARTICLE], [TAG_NAMES.ASIDE, TAG_ID.ASIDE], [TAG_NAMES.B, TAG_ID.B], [TAG_NAMES.BASE, TAG_ID.BASE], [TAG_NAMES.BASEFONT, TAG_ID.BASEFONT], [TAG_NAMES.BGSOUND, TAG_ID.BGSOUND], [TAG_NAMES.BIG, TAG_ID.BIG], [TAG_NAMES.BLOCKQUOTE, TAG_ID.BLOCKQUOTE], [TAG_NAMES.BODY, TAG_ID.BODY], [TAG_NAMES.BR, TAG_ID.BR], [TAG_NAMES.BUTTON, TAG_ID.BUTTON], [TAG_NAMES.CAPTION, TAG_ID.CAPTION], [TAG_NAMES.CENTER, TAG_ID.CENTER], [TAG_NAMES.CODE, TAG_ID.CODE], [TAG_NAMES.COL, TAG_ID.COL], [TAG_NAMES.COLGROUP, TAG_ID.COLGROUP], [TAG_NAMES.DD, TAG_ID.DD], [TAG_NAMES.DESC, TAG_ID.DESC], [TAG_NAMES.DETAILS, TAG_ID.DETAILS], [TAG_NAMES.DIALOG, TAG_ID.DIALOG], [TAG_NAMES.DIR, TAG_ID.DIR], [TAG_NAMES.DIV, TAG_ID.DIV], [TAG_NAMES.DL, TAG_ID.DL], [TAG_NAMES.DT, TAG_ID.DT], [TAG_NAMES.EM, TAG_ID.EM], [TAG_NAMES.EMBED, TAG_ID.EMBED], [TAG_NAMES.FIELDSET, TAG_ID.FIELDSET], [TAG_NAMES.FIGCAPTION, TAG_ID.FIGCAPTION], [TAG_NAMES.FIGURE, TAG_ID.FIGURE], [TAG_NAMES.FONT, TAG_ID.FONT], [TAG_NAMES.FOOTER, TAG_ID.FOOTER], [TAG_NAMES.FOREIGN_OBJECT, TAG_ID.FOREIGN_OBJECT], [TAG_NAMES.FORM, TAG_ID.FORM], [TAG_NAMES.FRAME, TAG_ID.FRAME], [TAG_NAMES.FRAMESET, TAG_ID.FRAMESET], [TAG_NAMES.H1, TAG_ID.H1], [TAG_NAMES.H2, TAG_ID.H2], [TAG_NAMES.H3, TAG_ID.H3], [TAG_NAMES.H4, TAG_ID.H4], [TAG_NAMES.H5, TAG_ID.H5], [TAG_NAMES.H6, TAG_ID.H6], [TAG_NAMES.HEAD, TAG_ID.HEAD], [TAG_NAMES.HEADER, TAG_ID.HEADER], [TAG_NAMES.HGROUP, TAG_ID.HGROUP], [TAG_NAMES.HR, TAG_ID.HR], [TAG_NAMES.HTML, TAG_ID.HTML], [TAG_NAMES.I, TAG_ID.I], [TAG_NAMES.IMG, TAG_ID.IMG], [TAG_NAMES.IMAGE, TAG_ID.IMAGE], [TAG_NAMES.INPUT, TAG_ID.INPUT], [TAG_NAMES.IFRAME, TAG_ID.IFRAME], [TAG_NAMES.KEYGEN, TAG_ID.KEYGEN], [TAG_NAMES.LABEL, TAG_ID.LABEL], [TAG_NAMES.LI, TAG_ID.LI], [TAG_NAMES.LINK, TAG_ID.LINK], [TAG_NAMES.LISTING, TAG_ID.LISTING], [TAG_NAMES.MAIN, TAG_ID.MAIN], [TAG_NAMES.MALIGNMARK, TAG_ID.MALIGNMARK], [TAG_NAMES.MARQUEE, TAG_ID.MARQUEE], [TAG_NAMES.MATH, TAG_ID.MATH], [TAG_NAMES.MENU, TAG_ID.MENU], [TAG_NAMES.META, TAG_ID.META], [TAG_NAMES.MGLYPH, TAG_ID.MGLYPH], [TAG_NAMES.MI, TAG_ID.MI], [TAG_NAMES.MO, TAG_ID.MO], [TAG_NAMES.MN, TAG_ID.MN], [TAG_NAMES.MS, TAG_ID.MS], [TAG_NAMES.MTEXT, TAG_ID.MTEXT], [TAG_NAMES.NAV, TAG_ID.NAV], [TAG_NAMES.NOBR, TAG_ID.NOBR], [TAG_NAMES.NOFRAMES, TAG_ID.NOFRAMES], [TAG_NAMES.NOEMBED, TAG_ID.NOEMBED], [TAG_NAMES.NOSCRIPT, TAG_ID.NOSCRIPT], [TAG_NAMES.OBJECT, TAG_ID.OBJECT], [TAG_NAMES.OL, TAG_ID.OL], [TAG_NAMES.OPTGROUP, TAG_ID.OPTGROUP], [TAG_NAMES.OPTION, TAG_ID.OPTION], [TAG_NAMES.P, TAG_ID.P], [TAG_NAMES.PARAM, TAG_ID.PARAM], [TAG_NAMES.PLAINTEXT, TAG_ID.PLAINTEXT], [TAG_NAMES.PRE, TAG_ID.PRE], [TAG_NAMES.RB, TAG_ID.RB], [TAG_NAMES.RP, TAG_ID.RP], [TAG_NAMES.RT, TAG_ID.RT], [TAG_NAMES.RTC, TAG_ID.RTC], [TAG_NAMES.RUBY, TAG_ID.RUBY], [TAG_NAMES.S, TAG_ID.S], [TAG_NAMES.SCRIPT, TAG_ID.SCRIPT], [TAG_NAMES.SEARCH, TAG_ID.SEARCH], [TAG_NAMES.SECTION, TAG_ID.SECTION], [TAG_NAMES.SELECT, TAG_ID.SELECT], [TAG_NAMES.SOURCE, TAG_ID.SOURCE], [TAG_NAMES.SMALL, TAG_ID.SMALL], [TAG_NAMES.SPAN, TAG_ID.SPAN], [TAG_NAMES.STRIKE, TAG_ID.STRIKE], [TAG_NAMES.STRONG, TAG_ID.STRONG], [TAG_NAMES.STYLE, TAG_ID.STYLE], [TAG_NAMES.SUB, TAG_ID.SUB], [TAG_NAMES.SUMMARY, TAG_ID.SUMMARY], [TAG_NAMES.SUP, TAG_ID.SUP], [TAG_NAMES.TABLE, TAG_ID.TABLE], [TAG_NAMES.TBODY, TAG_ID.TBODY], [TAG_NAMES.TEMPLATE, TAG_ID.TEMPLATE], [TAG_NAMES.TEXTAREA, TAG_ID.TEXTAREA], [TAG_NAMES.TFOOT, TAG_ID.TFOOT], [TAG_NAMES.TD, TAG_ID.TD], [TAG_NAMES.TH, TAG_ID.TH], [TAG_NAMES.THEAD, TAG_ID.THEAD], [TAG_NAMES.TITLE, TAG_ID.TITLE], [TAG_NAMES.TR, TAG_ID.TR], [TAG_NAMES.TRACK, TAG_ID.TRACK], [TAG_NAMES.TT, TAG_ID.TT], [TAG_NAMES.U, TAG_ID.U], [TAG_NAMES.UL, TAG_ID.UL], [TAG_NAMES.SVG, TAG_ID.SVG], [TAG_NAMES.VAR, TAG_ID.VAR], [TAG_NAMES.WBR, TAG_ID.WBR], [TAG_NAMES.XMP, TAG_ID.XMP], ]); function getTagID(tagName) { var _a; return (_a = TAG_NAME_TO_ID.get(tagName)) !== null && _a !== void 0 ? _a : TAG_ID.UNKNOWN; } const $ = TAG_ID; exports.SPECIAL_ELEMENTS = { [NS.HTML]: new Set([ $.ADDRESS, $.APPLET, $.AREA, $.ARTICLE, $.ASIDE, $.BASE, $.BASEFONT, $.BGSOUND, $.BLOCKQUOTE, $.BODY, $.BR, $.BUTTON, $.CAPTION, $.CENTER, $.COL, $.COLGROUP, $.DD, $.DETAILS, $.DIR, $.DIV, $.DL, $.DT, $.EMBED, $.FIELDSET, $.FIGCAPTION, $.FIGURE, $.FOOTER, $.FORM, $.FRAME, $.FRAMESET, $.H1, $.H2, $.H3, $.H4, $.H5, $.H6, $.HEAD, $.HEADER, $.HGROUP, $.HR, $.HTML, $.IFRAME, $.IMG, $.INPUT, $.LI, $.LINK, $.LISTING, $.MAIN, $.MARQUEE, $.MENU, $.META, $.NAV, $.NOEMBED, $.NOFRAMES, $.NOSCRIPT, $.OBJECT, $.OL, $.P, $.PARAM, $.PLAINTEXT, $.PRE, $.SCRIPT, $.SECTION, $.SELECT, $.SOURCE, $.STYLE, $.SUMMARY, $.TABLE, $.TBODY, $.TD, $.TEMPLATE, $.TEXTAREA, $.TFOOT, $.TH, $.THEAD, $.TITLE, $.TR, $.TRACK, $.UL, $.WBR, $.XMP, ]), [NS.MATHML]: new Set([$.MI, $.MO, $.MN, $.MS, $.MTEXT, $.ANNOTATION_XML]), [NS.SVG]: new Set([$.TITLE, $.FOREIGN_OBJECT, $.DESC]), [NS.XLINK]: new Set(), [NS.XML]: new Set(), [NS.XMLNS]: new Set(), }; exports.NUMBERED_HEADERS = new Set([$.H1, $.H2, $.H3, $.H4, $.H5, $.H6]); const UNESCAPED_TEXT = new Set([ TAG_NAMES.STYLE, TAG_NAMES.SCRIPT, TAG_NAMES.XMP, TAG_NAMES.IFRAME, TAG_NAMES.NOEMBED, TAG_NAMES.NOFRAMES, TAG_NAMES.PLAINTEXT, ]); function hasUnescapedText(tn, scriptingEnabled) { return UNESCAPED_TEXT.has(tn) || (scriptingEnabled && tn === TAG_NAMES.NOSCRIPT); } /***/ }), /***/ 30294: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TokenType = void 0; exports.getTokenAttr = getTokenAttr; var TokenType; (function (TokenType) { TokenType[TokenType["CHARACTER"] = 0] = "CHARACTER"; TokenType[TokenType["NULL_CHARACTER"] = 1] = "NULL_CHARACTER"; TokenType[TokenType["WHITESPACE_CHARACTER"] = 2] = "WHITESPACE_CHARACTER"; TokenType[TokenType["START_TAG"] = 3] = "START_TAG"; TokenType[TokenType["END_TAG"] = 4] = "END_TAG"; TokenType[TokenType["COMMENT"] = 5] = "COMMENT"; TokenType[TokenType["DOCTYPE"] = 6] = "DOCTYPE"; TokenType[TokenType["EOF"] = 7] = "EOF"; TokenType[TokenType["HIBERNATION"] = 8] = "HIBERNATION"; })(TokenType || (exports.TokenType = TokenType = {})); function getTokenAttr(token, attrName) { for (let i = token.attrs.length - 1; i >= 0; i--) { if (token.attrs[i].name === attrName) { return token.attrs[i].value; } } return null; } /***/ }), /***/ 73616: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SEQUENCES = exports.CODE_POINTS = exports.REPLACEMENT_CHARACTER = void 0; exports.isSurrogate = isSurrogate; exports.isSurrogatePair = isSurrogatePair; exports.getSurrogatePairCodePoint = getSurrogatePairCodePoint; exports.isControlCodePoint = isControlCodePoint; exports.isUndefinedCodePoint = isUndefinedCodePoint; const UNDEFINED_CODE_POINTS = new Set([ 65534, 65535, 131070, 131071, 196606, 196607, 262142, 262143, 327678, 327679, 393214, 393215, 458750, 458751, 524286, 524287, 589822, 589823, 655358, 655359, 720894, 720895, 786430, 786431, 851966, 851967, 917502, 917503, 983038, 983039, 1048574, 1048575, 1114110, 1114111, ]); exports.REPLACEMENT_CHARACTER = '\uFFFD'; var CODE_POINTS; (function (CODE_POINTS) { CODE_POINTS[CODE_POINTS["EOF"] = -1] = "EOF"; CODE_POINTS[CODE_POINTS["NULL"] = 0] = "NULL"; CODE_POINTS[CODE_POINTS["TABULATION"] = 9] = "TABULATION"; CODE_POINTS[CODE_POINTS["CARRIAGE_RETURN"] = 13] = "CARRIAGE_RETURN"; CODE_POINTS[CODE_POINTS["LINE_FEED"] = 10] = "LINE_FEED"; CODE_POINTS[CODE_POINTS["FORM_FEED"] = 12] = "FORM_FEED"; CODE_POINTS[CODE_POINTS["SPACE"] = 32] = "SPACE"; CODE_POINTS[CODE_POINTS["EXCLAMATION_MARK"] = 33] = "EXCLAMATION_MARK"; CODE_POINTS[CODE_POINTS["QUOTATION_MARK"] = 34] = "QUOTATION_MARK"; CODE_POINTS[CODE_POINTS["AMPERSAND"] = 38] = "AMPERSAND"; CODE_POINTS[CODE_POINTS["APOSTROPHE"] = 39] = "APOSTROPHE"; CODE_POINTS[CODE_POINTS["HYPHEN_MINUS"] = 45] = "HYPHEN_MINUS"; CODE_POINTS[CODE_POINTS["SOLIDUS"] = 47] = "SOLIDUS"; CODE_POINTS[CODE_POINTS["DIGIT_0"] = 48] = "DIGIT_0"; CODE_POINTS[CODE_POINTS["DIGIT_9"] = 57] = "DIGIT_9"; CODE_POINTS[CODE_POINTS["SEMICOLON"] = 59] = "SEMICOLON"; CODE_POINTS[CODE_POINTS["LESS_THAN_SIGN"] = 60] = "LESS_THAN_SIGN"; CODE_POINTS[CODE_POINTS["EQUALS_SIGN"] = 61] = "EQUALS_SIGN"; CODE_POINTS[CODE_POINTS["GREATER_THAN_SIGN"] = 62] = "GREATER_THAN_SIGN"; CODE_POINTS[CODE_POINTS["QUESTION_MARK"] = 63] = "QUESTION_MARK"; CODE_POINTS[CODE_POINTS["LATIN_CAPITAL_A"] = 65] = "LATIN_CAPITAL_A"; CODE_POINTS[CODE_POINTS["LATIN_CAPITAL_Z"] = 90] = "LATIN_CAPITAL_Z"; CODE_POINTS[CODE_POINTS["RIGHT_SQUARE_BRACKET"] = 93] = "RIGHT_SQUARE_BRACKET"; CODE_POINTS[CODE_POINTS["GRAVE_ACCENT"] = 96] = "GRAVE_ACCENT"; CODE_POINTS[CODE_POINTS["LATIN_SMALL_A"] = 97] = "LATIN_SMALL_A"; CODE_POINTS[CODE_POINTS["LATIN_SMALL_Z"] = 122] = "LATIN_SMALL_Z"; })(CODE_POINTS || (exports.CODE_POINTS = CODE_POINTS = {})); exports.SEQUENCES = { DASH_DASH: '--', CDATA_START: '[CDATA[', DOCTYPE: 'doctype', SCRIPT: 'script', PUBLIC: 'public', SYSTEM: 'system', }; //Surrogates function isSurrogate(cp) { return cp >= 55296 && cp <= 57343; } function isSurrogatePair(cp) { return cp >= 56320 && cp <= 57343; } function getSurrogatePairCodePoint(cp1, cp2) { return (cp1 - 55296) * 1024 + 9216 + cp2; } //NOTE: excluding NULL and ASCII whitespace function isControlCodePoint(cp) { return ((cp !== 0x20 && cp !== 0x0a && cp !== 0x0d && cp !== 0x09 && cp !== 0x0c && cp >= 0x01 && cp <= 0x1f) || (cp >= 0x7f && cp <= 0x9f)); } function isUndefinedCodePoint(cp) { return (cp >= 64976 && cp <= 65007) || UNDEFINED_CODE_POINTS.has(cp); } /***/ }), /***/ 50069: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TokenizerMode = exports.Tokenizer = exports.Token = exports.html = exports.foreignContent = exports.ErrorCodes = exports.serializeOuter = exports.serialize = exports.Parser = exports.defaultTreeAdapter = void 0; exports.parse = parse; exports.parseFragment = parseFragment; const index_js_1 = __nccwpck_require__(99945); var default_js_1 = __nccwpck_require__(24760); Object.defineProperty(exports, "defaultTreeAdapter", ({ enumerable: true, get: function () { return default_js_1.defaultTreeAdapter; } })); var index_js_2 = __nccwpck_require__(99945); Object.defineProperty(exports, "Parser", ({ enumerable: true, get: function () { return index_js_2.Parser; } })); var index_js_3 = __nccwpck_require__(47950); Object.defineProperty(exports, "serialize", ({ enumerable: true, get: function () { return index_js_3.serialize; } })); Object.defineProperty(exports, "serializeOuter", ({ enumerable: true, get: function () { return index_js_3.serializeOuter; } })); var error_codes_js_1 = __nccwpck_require__(69322); Object.defineProperty(exports, "ErrorCodes", ({ enumerable: true, get: function () { return error_codes_js_1.ERR; } })); /** @internal */ exports.foreignContent = __nccwpck_require__(79319); exports.html = __nccwpck_require__(81510); exports.Token = __nccwpck_require__(30294); /** @internal */ var index_js_4 = __nccwpck_require__(55007); Object.defineProperty(exports, "Tokenizer", ({ enumerable: true, get: function () { return index_js_4.Tokenizer; } })); Object.defineProperty(exports, "TokenizerMode", ({ enumerable: true, get: function () { return index_js_4.TokenizerMode; } })); // Shorthands /** * Parses an HTML string. * * @param html Input HTML string. * @param options Parsing options. * @returns Document * * @example * * ```js * const parse5 = require('parse5'); * * const document = parse5.parse('Hi there!'); * * console.log(document.childNodes[1].tagName); //> 'html' *``` */ function parse(html, options) { return index_js_1.Parser.parse(html, options); } function parseFragment(fragmentContext, html, options) { if (typeof fragmentContext === 'string') { options = html; html = fragmentContext; fragmentContext = null; } const parser = index_js_1.Parser.getFragmentParser(fragmentContext, options); parser.tokenizer.write(html, true); return parser.getFragment(); } /***/ }), /***/ 69048: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FormattingElementList = exports.EntryType = void 0; //Const const NOAH_ARK_CAPACITY = 3; var EntryType; (function (EntryType) { EntryType[EntryType["Marker"] = 0] = "Marker"; EntryType[EntryType["Element"] = 1] = "Element"; })(EntryType || (exports.EntryType = EntryType = {})); const MARKER = { type: EntryType.Marker }; //List of formatting elements class FormattingElementList { constructor(treeAdapter) { this.treeAdapter = treeAdapter; this.entries = []; this.bookmark = null; } //Noah Ark's condition //OPTIMIZATION: at first we try to find possible candidates for exclusion using //lightweight heuristics without thorough attributes check. _getNoahArkConditionCandidates(newElement, neAttrs) { const candidates = []; const neAttrsLength = neAttrs.length; const neTagName = this.treeAdapter.getTagName(newElement); const neNamespaceURI = this.treeAdapter.getNamespaceURI(newElement); for (let i = 0; i < this.entries.length; i++) { const entry = this.entries[i]; if (entry.type === EntryType.Marker) { break; } const { element } = entry; if (this.treeAdapter.getTagName(element) === neTagName && this.treeAdapter.getNamespaceURI(element) === neNamespaceURI) { const elementAttrs = this.treeAdapter.getAttrList(element); if (elementAttrs.length === neAttrsLength) { candidates.push({ idx: i, attrs: elementAttrs }); } } } return candidates; } _ensureNoahArkCondition(newElement) { if (this.entries.length < NOAH_ARK_CAPACITY) return; const neAttrs = this.treeAdapter.getAttrList(newElement); const candidates = this._getNoahArkConditionCandidates(newElement, neAttrs); if (candidates.length < NOAH_ARK_CAPACITY) return; //NOTE: build attrs map for the new element, so we can perform fast lookups const neAttrsMap = new Map(neAttrs.map((neAttr) => [neAttr.name, neAttr.value])); let validCandidates = 0; //NOTE: remove bottommost candidates, until Noah's Ark condition will not be met for (let i = 0; i < candidates.length; i++) { const candidate = candidates[i]; // We know that `candidate.attrs.length === neAttrs.length` if (candidate.attrs.every((cAttr) => neAttrsMap.get(cAttr.name) === cAttr.value)) { validCandidates += 1; if (validCandidates >= NOAH_ARK_CAPACITY) { this.entries.splice(candidate.idx, 1); } } } } //Mutations insertMarker() { this.entries.unshift(MARKER); } pushElement(element, token) { this._ensureNoahArkCondition(element); this.entries.unshift({ type: EntryType.Element, element, token, }); } insertElementAfterBookmark(element, token) { const bookmarkIdx = this.entries.indexOf(this.bookmark); this.entries.splice(bookmarkIdx, 0, { type: EntryType.Element, element, token, }); } removeEntry(entry) { const entryIndex = this.entries.indexOf(entry); if (entryIndex !== -1) { this.entries.splice(entryIndex, 1); } } /** * Clears the list of formatting elements up to the last marker. * * @see https://html.spec.whatwg.org/multipage/parsing.html#clear-the-list-of-active-formatting-elements-up-to-the-last-marker */ clearToLastMarker() { const markerIdx = this.entries.indexOf(MARKER); if (markerIdx === -1) { this.entries.length = 0; } else { this.entries.splice(0, markerIdx + 1); } } //Search getElementEntryInScopeWithTagName(tagName) { const entry = this.entries.find((entry) => entry.type === EntryType.Marker || this.treeAdapter.getTagName(entry.element) === tagName); return entry && entry.type === EntryType.Element ? entry : null; } getElementEntry(element) { return this.entries.find((entry) => entry.type === EntryType.Element && entry.element === element); } } exports.FormattingElementList = FormattingElementList; /***/ }), /***/ 99945: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Parser = void 0; const index_js_1 = __nccwpck_require__(55007); const open_element_stack_js_1 = __nccwpck_require__(54857); const formatting_element_list_js_1 = __nccwpck_require__(69048); const default_js_1 = __nccwpck_require__(24760); const doctype = __nccwpck_require__(32377); const foreignContent = __nccwpck_require__(79319); const error_codes_js_1 = __nccwpck_require__(69322); const unicode = __nccwpck_require__(73616); const html_js_1 = __nccwpck_require__(81510); const token_js_1 = __nccwpck_require__(30294); //Misc constants const HIDDEN_INPUT_TYPE = 'hidden'; //Adoption agency loops iteration count const AA_OUTER_LOOP_ITER = 8; const AA_INNER_LOOP_ITER = 3; //Insertion modes var InsertionMode; (function (InsertionMode) { InsertionMode[InsertionMode["INITIAL"] = 0] = "INITIAL"; InsertionMode[InsertionMode["BEFORE_HTML"] = 1] = "BEFORE_HTML"; InsertionMode[InsertionMode["BEFORE_HEAD"] = 2] = "BEFORE_HEAD"; InsertionMode[InsertionMode["IN_HEAD"] = 3] = "IN_HEAD"; InsertionMode[InsertionMode["IN_HEAD_NO_SCRIPT"] = 4] = "IN_HEAD_NO_SCRIPT"; InsertionMode[InsertionMode["AFTER_HEAD"] = 5] = "AFTER_HEAD"; InsertionMode[InsertionMode["IN_BODY"] = 6] = "IN_BODY"; InsertionMode[InsertionMode["TEXT"] = 7] = "TEXT"; InsertionMode[InsertionMode["IN_TABLE"] = 8] = "IN_TABLE"; InsertionMode[InsertionMode["IN_TABLE_TEXT"] = 9] = "IN_TABLE_TEXT"; InsertionMode[InsertionMode["IN_CAPTION"] = 10] = "IN_CAPTION"; InsertionMode[InsertionMode["IN_COLUMN_GROUP"] = 11] = "IN_COLUMN_GROUP"; InsertionMode[InsertionMode["IN_TABLE_BODY"] = 12] = "IN_TABLE_BODY"; InsertionMode[InsertionMode["IN_ROW"] = 13] = "IN_ROW"; InsertionMode[InsertionMode["IN_CELL"] = 14] = "IN_CELL"; InsertionMode[InsertionMode["IN_SELECT"] = 15] = "IN_SELECT"; InsertionMode[InsertionMode["IN_SELECT_IN_TABLE"] = 16] = "IN_SELECT_IN_TABLE"; InsertionMode[InsertionMode["IN_TEMPLATE"] = 17] = "IN_TEMPLATE"; InsertionMode[InsertionMode["AFTER_BODY"] = 18] = "AFTER_BODY"; InsertionMode[InsertionMode["IN_FRAMESET"] = 19] = "IN_FRAMESET"; InsertionMode[InsertionMode["AFTER_FRAMESET"] = 20] = "AFTER_FRAMESET"; InsertionMode[InsertionMode["AFTER_AFTER_BODY"] = 21] = "AFTER_AFTER_BODY"; InsertionMode[InsertionMode["AFTER_AFTER_FRAMESET"] = 22] = "AFTER_AFTER_FRAMESET"; })(InsertionMode || (InsertionMode = {})); const BASE_LOC = { startLine: -1, startCol: -1, startOffset: -1, endLine: -1, endCol: -1, endOffset: -1, }; const TABLE_STRUCTURE_TAGS = new Set([html_js_1.TAG_ID.TABLE, html_js_1.TAG_ID.TBODY, html_js_1.TAG_ID.TFOOT, html_js_1.TAG_ID.THEAD, html_js_1.TAG_ID.TR]); const defaultParserOptions = { scriptingEnabled: true, sourceCodeLocationInfo: false, treeAdapter: default_js_1.defaultTreeAdapter, onParseError: null, }; //Parser class Parser { constructor(options, document, /** @internal */ fragmentContext = null, /** @internal */ scriptHandler = null) { this.fragmentContext = fragmentContext; this.scriptHandler = scriptHandler; this.currentToken = null; this.stopped = false; /** @internal */ this.insertionMode = InsertionMode.INITIAL; /** @internal */ this.originalInsertionMode = InsertionMode.INITIAL; /** @internal */ this.headElement = null; /** @internal */ this.formElement = null; /** Indicates that the current node is not an element in the HTML namespace */ this.currentNotInHTML = false; /** * The template insertion mode stack is maintained from the left. * Ie. the topmost element will always have index 0. * * @internal */ this.tmplInsertionModeStack = []; /** @internal */ this.pendingCharacterTokens = []; /** @internal */ this.hasNonWhitespacePendingCharacterToken = false; /** @internal */ this.framesetOk = true; /** @internal */ this.skipNextNewLine = false; /** @internal */ this.fosterParentingEnabled = false; this.options = Object.assign(Object.assign({}, defaultParserOptions), options); this.treeAdapter = this.options.treeAdapter; this.onParseError = this.options.onParseError; // Always enable location info if we report parse errors. if (this.onParseError) { this.options.sourceCodeLocationInfo = true; } this.document = document !== null && document !== void 0 ? document : this.treeAdapter.createDocument(); this.tokenizer = new index_js_1.Tokenizer(this.options, this); this.activeFormattingElements = new formatting_element_list_js_1.FormattingElementList(this.treeAdapter); this.fragmentContextID = fragmentContext ? (0, html_js_1.getTagID)(this.treeAdapter.getTagName(fragmentContext)) : html_js_1.TAG_ID.UNKNOWN; this._setContextModes(fragmentContext !== null && fragmentContext !== void 0 ? fragmentContext : this.document, this.fragmentContextID); this.openElements = new open_element_stack_js_1.OpenElementStack(this.document, this.treeAdapter, this); } // API static parse(html, options) { const parser = new this(options); parser.tokenizer.write(html, true); return parser.document; } static getFragmentParser(fragmentContext, options) { const opts = Object.assign(Object.assign({}, defaultParserOptions), options); //NOTE: use a