' }
+ * @param url The optional url being authorized
*/
- 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);
- });
+ async getRequestHeaders(url) {
+ const headers = (await this.getRequestMetadataAsync(url)).headers;
+ return headers;
+ }
+ async getRequestMetadataAsync(
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ url) {
+ const thisCreds = this.credentials;
+ if (!thisCreds.access_token &&
+ !thisCreds.refresh_token &&
+ !this.apiKey &&
+ !this.refreshHandler) {
+ throw new Error('No access, refresh token, API key or refresh handler callback is set.');
+ }
+ if (thisCreds.access_token && !this.isTokenExpiring()) {
+ thisCreds.token_type = thisCreds.token_type || 'Bearer';
+ const headers = {
+ Authorization: thisCreds.token_type + ' ' + thisCreds.access_token,
+ };
+ return { headers: this.addSharedMetadataHeaders(headers) };
+ }
+ // If refreshHandler exists, call processAndValidateRefreshHandler().
+ if (this.refreshHandler) {
+ const refreshedAccessToken = await this.processAndValidateRefreshHandler();
+ if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) {
+ this.setCredentials(refreshedAccessToken);
+ const headers = {
+ Authorization: 'Bearer ' + this.credentials.access_token,
+ };
+ return { headers: this.addSharedMetadataHeaders(headers) };
+ }
+ }
+ if (this.apiKey) {
+ return { headers: { 'X-Goog-Api-Key': this.apiKey } };
+ }
+ let r = null;
+ let tokens = null;
+ try {
+ r = await this.refreshToken(thisCreds.refresh_token);
+ tokens = r.tokens;
+ }
+ catch (err) {
+ const e = err;
+ if (e.response &&
+ (e.response.status === 403 || e.response.status === 404)) {
+ e.message = `Could not refresh access token: ${e.message}`;
+ }
+ throw e;
+ }
+ const credentials = this.credentials;
+ credentials.token_type = credentials.token_type || 'Bearer';
+ tokens.refresh_token = credentials.refresh_token;
+ this.credentials = tokens;
+ const headers = {
+ Authorization: credentials.token_type + ' ' + tokens.access_token,
+ };
+ return { headers: this.addSharedMetadataHeaders(headers), res: r.res };
}
/**
+ * Generates an URL to revoke the given token.
+ * @param token The existing token to be revoked.
*
- * 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.
+ * @deprecated use instance method {@link OAuth2Client.getRevokeTokenURL}
+ */
+ static getRevokeTokenUrl(token) {
+ return new OAuth2Client().getRevokeTokenURL(token).toString();
+ }
+ /**
+ * Generates a URL to revoke the given token.
*
- * @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.
+ * @param token The existing token to be revoked.
*/
- 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}`);
+ getRevokeTokenURL(token) {
+ const url = new URL(this.endpoints.oauth2RevokeUrl);
+ url.searchParams.append('token', token);
+ return url;
+ }
+ revokeToken(token, callback) {
+ const opts = {
+ ...OAuth2Client.RETRY_CONFIG,
+ url: this.getRevokeTokenURL(token).toString(),
+ method: 'POST',
+ };
+ if (callback) {
+ this.transporter
+ .request(opts)
+ .then(r => callback(null, r), callback);
}
- 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}`);
+ else {
+ return this.transporter.request(opts);
}
- 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;
- }
- }
+ }
+ revokeCredentials(callback) {
+ if (callback) {
+ this.revokeCredentialsAsync().then(res => callback(null, res), callback);
}
- if (!options.blobHTTPHeaders) {
- options.blobHTTPHeaders = {};
+ else {
+ return this.revokeCredentialsAsync();
}
- if (!options.conditions) {
- options.conditions = {};
+ }
+ async revokeCredentialsAsync() {
+ const token = this.credentials.access_token;
+ this.credentials = {};
+ if (token) {
+ return this.revokeToken(token);
}
- return tracingClient.withSpan("BlockBlobClient-uploadSeekableInternal", options, async (updatedOptions) => {
- if (size <= maxSingleShotSize) {
- return assertResponse(await this.upload(bodyFactory(0, size), size, updatedOptions));
+ else {
+ throw new Error('No access token to revoke.');
+ }
+ }
+ request(opts, callback) {
+ if (callback) {
+ this.requestAsync(opts).then(r => callback(null, r), e => {
+ return callback(e, e.response);
+ });
+ }
+ else {
+ return this.requestAsync(opts);
+ }
+ }
+ async requestAsync(opts, reAuthRetried = false) {
+ let r2;
+ try {
+ const r = await this.getRequestMetadataAsync(opts.url);
+ opts.headers = opts.headers || {};
+ if (r.headers && r.headers['x-goog-user-project']) {
+ opts.headers['x-goog-user-project'] = r.headers['x-goog-user-project'];
}
- 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}`);
+ if (r.headers && r.headers.Authorization) {
+ opts.headers.Authorization = r.headers.Authorization;
}
- 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,
- });
+ if (this.apiKey) {
+ opts.headers['X-Goog-Api-Key'] = this.apiKey;
+ }
+ r2 = await this.transporter.request(opts);
+ }
+ catch (e) {
+ const res = e.response;
+ if (res) {
+ const statusCode = res.status;
+ // Retry the request for metadata if the following criteria are true:
+ // - We haven't already retried. It only makes sense to retry once.
+ // - The response was a 401 or a 403
+ // - The request didn't send a readableStream
+ // - An access_token and refresh_token were available, but either no
+ // expiry_date was available or the forceRefreshOnFailure flag is set.
+ // The absent expiry_date case can happen when developers stash the
+ // access_token and refresh_token for later use, but the access_token
+ // fails on the first try because it's expired. Some developers may
+ // choose to enable forceRefreshOnFailure to mitigate time-related
+ // errors.
+ // Or the following criteria are true:
+ // - We haven't already retried. It only makes sense to retry once.
+ // - The response was a 401 or a 403
+ // - The request didn't send a readableStream
+ // - No refresh_token was available
+ // - An access_token and a refreshHandler callback were available, but
+ // either no expiry_date was available or the forceRefreshOnFailure
+ // flag is set. The access_token fails on the first try because it's
+ // expired. Some developers may choose to enable forceRefreshOnFailure
+ // to mitigate time-related errors.
+ const mayRequireRefresh = this.credentials &&
+ this.credentials.access_token &&
+ this.credentials.refresh_token &&
+ (!this.credentials.expiry_date || this.forceRefreshOnFailure);
+ const mayRequireRefreshWithNoRefreshToken = this.credentials &&
+ this.credentials.access_token &&
+ !this.credentials.refresh_token &&
+ (!this.credentials.expiry_date || this.forceRefreshOnFailure) &&
+ this.refreshHandler;
+ const isReadableStream = res.config.data instanceof stream.Readable;
+ const isAuthErr = statusCode === 401 || statusCode === 403;
+ if (!reAuthRetried &&
+ isAuthErr &&
+ !isReadableStream &&
+ mayRequireRefresh) {
+ await this.refreshAccessTokenAsync();
+ return this.requestAsync(opts, true);
+ }
+ else if (!reAuthRetried &&
+ isAuthErr &&
+ !isReadableStream &&
+ mayRequireRefreshWithNoRefreshToken) {
+ const refreshedAccessToken = await this.processAndValidateRefreshHandler();
+ if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) {
+ this.setCredentials(refreshedAccessToken);
}
- });
+ return this.requestAsync(opts, true);
+ }
}
- await batch.do();
- return this.commitBlockList(blockList, updatedOptions);
- });
+ throw e;
+ }
+ return r2;
+ }
+ verifyIdToken(options, callback) {
+ // This function used to accept two arguments instead of an options object.
+ // Check the types to help users upgrade with less pain.
+ // This check can be removed after a 2.0 release.
+ if (callback && typeof callback !== 'function') {
+ throw new Error('This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.');
+ }
+ if (callback) {
+ this.verifyIdTokenAsync(options).then(r => callback(null, r), callback);
+ }
+ else {
+ return this.verifyIdTokenAsync(options);
+ }
+ }
+ async verifyIdTokenAsync(options) {
+ if (!options.idToken) {
+ throw new Error('The verifyIdToken method requires an ID Token');
+ }
+ const response = await this.getFederatedSignonCertsAsync();
+ const login = await this.verifySignedJwtWithCertsAsync(options.idToken, response.certs, options.audience, this.issuers, options.maxExpiry);
+ return login;
}
/**
- * 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.
+ * Obtains information about the provisioned access token. Especially useful
+ * if you want to check the scopes that were provisioned to a given token.
*
- * @param filePath - Full path of local file
- * @param options - Options to Upload to Block Blob operation.
- * @returns Response data for the Blob Upload operation.
+ * @param accessToken Required. The Access Token for which you want to get
+ * user info.
*/
- 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 }));
+ async getTokenInfo(accessToken) {
+ const { data } = await this.transporter.request({
+ ...OAuth2Client.RETRY_CONFIG,
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ Authorization: `Bearer ${accessToken}`,
+ },
+ url: this.endpoints.tokenInfoUrl.toString(),
});
+ const info = Object.assign({
+ expiry_date: new Date().getTime() + data.expires_in * 1000,
+ scopes: data.scope.split(' '),
+ }, data);
+ delete info.expires_in;
+ delete info.scope;
+ return info;
+ }
+ getFederatedSignonCerts(callback) {
+ if (callback) {
+ this.getFederatedSignonCertsAsync().then(r => callback(null, r.certs, r.res), callback);
+ }
+ else {
+ return this.getFederatedSignonCertsAsync();
+ }
+ }
+ async getFederatedSignonCertsAsync() {
+ const nowTime = new Date().getTime();
+ const format = (0, crypto_1.hasBrowserCrypto)()
+ ? CertificateFormat.JWK
+ : CertificateFormat.PEM;
+ if (this.certificateExpiry &&
+ nowTime < this.certificateExpiry.getTime() &&
+ this.certificateCacheFormat === format) {
+ return { certs: this.certificateCache, format };
+ }
+ let res;
+ let url;
+ switch (format) {
+ case CertificateFormat.PEM:
+ url = this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();
+ break;
+ case CertificateFormat.JWK:
+ url = this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();
+ break;
+ default:
+ throw new Error(`Unsupported certificate format ${format}`);
+ }
+ try {
+ res = await this.transporter.request({
+ ...OAuth2Client.RETRY_CONFIG,
+ url,
+ });
+ }
+ catch (e) {
+ if (e instanceof Error) {
+ e.message = `Failed to retrieve verification certificates: ${e.message}`;
+ }
+ throw e;
+ }
+ const cacheControl = res ? res.headers['cache-control'] : undefined;
+ let cacheAge = -1;
+ if (cacheControl) {
+ const pattern = new RegExp('max-age=([0-9]*)');
+ const regexResult = pattern.exec(cacheControl);
+ if (regexResult && regexResult.length === 2) {
+ // Cache results with max-age (in seconds)
+ cacheAge = Number(regexResult[1]) * 1000; // milliseconds
+ }
+ }
+ let certificates = {};
+ switch (format) {
+ case CertificateFormat.PEM:
+ certificates = res.data;
+ break;
+ case CertificateFormat.JWK:
+ for (const key of res.data.keys) {
+ certificates[key.kid] = key;
+ }
+ break;
+ default:
+ throw new Error(`Unsupported certificate format ${format}`);
+ }
+ const now = new Date();
+ this.certificateExpiry =
+ cacheAge === -1 ? null : new Date(now.getTime() + cacheAge);
+ this.certificateCache = certificates;
+ this.certificateCacheFormat = format;
+ return { certs: certificates, format, res };
+ }
+ getIapPublicKeys(callback) {
+ if (callback) {
+ this.getIapPublicKeysAsync().then(r => callback(null, r.pubkeys, r.res), callback);
+ }
+ else {
+ return this.getIapPublicKeysAsync();
+ }
+ }
+ async getIapPublicKeysAsync() {
+ let res;
+ const url = this.endpoints.oauth2IapPublicKeyUrl.toString();
+ try {
+ res = await this.transporter.request({
+ ...OAuth2Client.RETRY_CONFIG,
+ url,
+ });
+ }
+ catch (e) {
+ if (e instanceof Error) {
+ e.message = `Failed to retrieve verification certificates: ${e.message}`;
+ }
+ throw e;
+ }
+ return { pubkeys: res.data, res };
+ }
+ verifySignedJwtWithCerts() {
+ // To make the code compatible with browser SubtleCrypto we need to make
+ // this method async.
+ throw new Error('verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.');
}
/**
- * 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.
+ * Verify the id token is signed with the correct certificate
+ * and is from the correct audience.
+ * @param jwt The jwt to verify (The ID Token in this case).
+ * @param certs The array of certs to test the jwt against.
+ * @param requiredAudience The audience to test the jwt against.
+ * @param issuers The allowed issuers of the jwt (Optional).
+ * @param maxExpiry The max expiry the certificate can be (Optional).
+ * @return Returns a promise resolving to LoginTicket on verification.
*/
- async uploadStream(stream, bufferSize = DEFAULT_BLOCK_BUFFER_SIZE_BYTES, maxConcurrency = 5, options = {}) {
- if (!options.blobHTTPHeaders) {
- options.blobHTTPHeaders = {};
+ async verifySignedJwtWithCertsAsync(jwt, certs, requiredAudience, issuers, maxExpiry) {
+ const crypto = (0, crypto_1.createCrypto)();
+ if (!maxExpiry) {
+ maxExpiry = OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_;
+ }
+ const segments = jwt.split('.');
+ if (segments.length !== 3) {
+ throw new Error('Wrong number of segments in token: ' + jwt);
+ }
+ const signed = segments[0] + '.' + segments[1];
+ let signature = segments[2];
+ let envelope;
+ let payload;
+ try {
+ envelope = JSON.parse(crypto.decodeBase64StringUtf8(segments[0]));
+ }
+ catch (err) {
+ if (err instanceof Error) {
+ err.message = `Can't parse token envelope: ${segments[0]}': ${err.message}`;
+ }
+ throw err;
+ }
+ if (!envelope) {
+ throw new Error("Can't parse token envelope: " + segments[0]);
+ }
+ try {
+ payload = JSON.parse(crypto.decodeBase64StringUtf8(segments[1]));
+ }
+ catch (err) {
+ if (err instanceof Error) {
+ err.message = `Can't parse token payload '${segments[0]}`;
+ }
+ throw err;
}
- if (!options.conditions) {
- options.conditions = {};
+ if (!payload) {
+ throw new Error("Can't parse token payload: " + segments[1]);
+ }
+ if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) {
+ // If this is not present, then there's no reason to attempt verification
+ throw new Error('No pem found for envelope: ' + JSON.stringify(envelope));
+ }
+ const cert = certs[envelope.kid];
+ if (envelope.alg === 'ES256') {
+ signature = formatEcdsa.joseToDer(signature, 'ES256').toString('base64');
+ }
+ const verified = await crypto.verify(cert, signed, signature);
+ if (!verified) {
+ throw new Error('Invalid token signature: ' + jwt);
+ }
+ if (!payload.iat) {
+ throw new Error('No issue time in token: ' + JSON.stringify(payload));
+ }
+ if (!payload.exp) {
+ throw new Error('No expiration time in token: ' + JSON.stringify(payload));
+ }
+ const iat = Number(payload.iat);
+ if (isNaN(iat))
+ throw new Error('iat field using invalid format');
+ const exp = Number(payload.exp);
+ if (isNaN(exp))
+ throw new Error('exp field using invalid format');
+ const now = new Date().getTime() / 1000;
+ if (exp >= now + maxExpiry) {
+ throw new Error('Expiration time too far in future: ' + JSON.stringify(payload));
+ }
+ const earliest = iat - OAuth2Client.CLOCK_SKEW_SECS_;
+ const latest = exp + OAuth2Client.CLOCK_SKEW_SECS_;
+ if (now < earliest) {
+ throw new Error('Token used too early, ' +
+ now +
+ ' < ' +
+ earliest +
+ ': ' +
+ JSON.stringify(payload));
+ }
+ if (now > latest) {
+ throw new Error('Token used too late, ' +
+ now +
+ ' > ' +
+ latest +
+ ': ' +
+ JSON.stringify(payload));
+ }
+ if (issuers && issuers.indexOf(payload.iss) < 0) {
+ throw new Error('Invalid issuer, expected one of [' +
+ issuers +
+ '], but got ' +
+ payload.iss);
+ }
+ // Check the audience matches if we have one
+ if (typeof requiredAudience !== 'undefined' && requiredAudience !== null) {
+ const aud = payload.aud;
+ let audVerified = false;
+ // If the requiredAudience is an array, check if it contains token
+ // audience
+ if (requiredAudience.constructor === Array) {
+ audVerified = requiredAudience.indexOf(aud) > -1;
+ }
+ else {
+ audVerified = aud === requiredAudience;
+ }
+ if (!audVerified) {
+ throw new Error('Wrong recipient, payload audience != requiredAudience');
+ }
}
- 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 })));
- });
+ return new loginticket_1.LoginTicket(envelope, payload);
+ }
+ /**
+ * Returns a promise that resolves with AccessTokenResponse type if
+ * refreshHandler is defined.
+ * If not, nothing is returned.
+ */
+ async processAndValidateRefreshHandler() {
+ if (this.refreshHandler) {
+ const accessTokenResponse = await this.refreshHandler();
+ if (!accessTokenResponse.access_token) {
+ throw new Error('No access token is returned by the refreshHandler callback.');
+ }
+ return accessTokenResponse;
+ }
+ return;
+ }
+ /**
+ * Returns true if a token is expired or will expire within
+ * eagerRefreshThresholdMillismilliseconds.
+ * If there is no expiry time, assumes the token is not expired or expiring.
+ */
+ isTokenExpiring() {
+ const expiryDate = this.credentials.expiry_date;
+ return expiryDate
+ ? expiryDate <= new Date().getTime() + this.eagerRefreshThresholdMillis
+ : false;
}
}
+exports.OAuth2Client = OAuth2Client;
/**
- * PageBlobClient defines a set of operations applicable to page blobs.
+ * @deprecated use instance's {@link OAuth2Client.endpoints}
*/
-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;
+OAuth2Client.GOOGLE_TOKEN_INFO_URL = 'https://oauth2.googleapis.com/tokeninfo';
+/**
+ * Clock skew - five minutes in seconds
+ */
+OAuth2Client.CLOCK_SKEW_SECS_ = 300;
+/**
+ * The default max Token Lifetime is one day in seconds
+ */
+OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_ = 86400;
+
+
+/***/ }),
+
+/***/ 6653:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.OAuthClientAuthHandler = void 0;
+exports.getErrorFromOAuthErrorResponse = getErrorFromOAuthErrorResponse;
+const querystring = __nccwpck_require__(83480);
+const crypto_1 = __nccwpck_require__(88851);
+/** List of HTTP methods that accept request bodies. */
+const METHODS_SUPPORTING_REQUEST_BODY = ['PUT', 'POST', 'PATCH'];
+/**
+ * Abstract class for handling client authentication in OAuth-based
+ * operations.
+ * When request-body client authentication is used, only application/json and
+ * application/x-www-form-urlencoded content types for HTTP methods that support
+ * request bodies are supported.
+ */
+class OAuthClientAuthHandler {
+ /**
+ * Instantiates an OAuth client authentication handler.
+ * @param clientAuthentication The client auth credentials.
+ */
+ constructor(clientAuthentication) {
+ this.clientAuthentication = clientAuthentication;
+ this.crypto = (0, crypto_1.createCrypto)();
+ }
+ /**
+ * Applies client authentication on the OAuth request's headers or POST
+ * body but does not process the request.
+ * @param opts The GaxiosOptions whose headers or data are to be modified
+ * depending on the client authentication mechanism to be used.
+ * @param bearerToken The optional bearer token to use for authentication.
+ * When this is used, no client authentication credentials are needed.
+ */
+ applyClientAuthenticationOptions(opts, bearerToken) {
+ // Inject authenticated header.
+ this.injectAuthenticatedHeaders(opts, bearerToken);
+ // Inject authenticated request body.
+ if (!bearerToken) {
+ this.injectAuthenticatedRequestBody(opts);
}
- 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);
+ }
+ /**
+ * Applies client authentication on the request's header if either
+ * basic authentication or bearer token authentication is selected.
+ *
+ * @param opts The GaxiosOptions whose headers or data are to be modified
+ * depending on the client authentication mechanism to be used.
+ * @param bearerToken The optional bearer token to use for authentication.
+ * When this is used, no client authentication credentials are needed.
+ */
+ injectAuthenticatedHeaders(opts, bearerToken) {
+ var _a;
+ // Bearer token prioritized higher than basic Auth.
+ if (bearerToken) {
+ opts.headers = opts.headers || {};
+ Object.assign(opts.headers, {
+ Authorization: `Bearer ${bearerToken}}`,
+ });
}
- 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 (((_a = this.clientAuthentication) === null || _a === void 0 ? void 0 : _a.confidentialClientType) === 'basic') {
+ opts.headers = opts.headers || {};
+ const clientId = this.clientAuthentication.clientId;
+ const clientSecret = this.clientAuthentication.clientSecret || '';
+ const base64EncodedCreds = this.crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`);
+ Object.assign(opts.headers, {
+ Authorization: `Basic ${base64EncodedCreds}`,
+ });
}
- 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);
+ }
+ /**
+ * Applies client authentication on the request's body if request-body
+ * client authentication is selected.
+ *
+ * @param opts The GaxiosOptions whose headers or data are to be modified
+ * depending on the client authentication mechanism to be used.
+ */
+ injectAuthenticatedRequestBody(opts) {
+ var _a;
+ if (((_a = this.clientAuthentication) === null || _a === void 0 ? void 0 : _a.confidentialClientType) === 'request-body') {
+ const method = (opts.method || 'GET').toUpperCase();
+ // Inject authenticated request body.
+ if (METHODS_SUPPORTING_REQUEST_BODY.indexOf(method) !== -1) {
+ // Get content-type.
+ let contentType;
+ const headers = opts.headers || {};
+ for (const key in headers) {
+ if (key.toLowerCase() === 'content-type' && headers[key]) {
+ contentType = headers[key].toLowerCase();
+ break;
}
- pipeline = newPipeline(sharedKeyCredential, options);
+ }
+ if (contentType === 'application/x-www-form-urlencoded') {
+ opts.data = opts.data || '';
+ const data = querystring.parse(opts.data);
+ Object.assign(data, {
+ client_id: this.clientAuthentication.clientId,
+ client_secret: this.clientAuthentication.clientSecret || '',
+ });
+ opts.data = querystring.stringify(data);
+ }
+ else if (contentType === 'application/json') {
+ opts.data = opts.data || {};
+ Object.assign(opts.data, {
+ client_id: this.clientAuthentication.clientId,
+ client_secret: this.clientAuthentication.clientSecret || '',
+ });
}
else {
- throw new Error("Account connection string is only supported in Node.js environment");
+ throw new Error(`${contentType} content-types are not supported with ` +
+ `${this.clientAuthentication.confidentialClientType} ` +
+ 'client authentication');
}
}
- 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");
+ throw new Error(`${method} HTTP method does not support ` +
+ `${this.clientAuthentication.confidentialClientType} ` +
+ 'client authentication');
}
}
- 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.
+ * Retry config for Auth-related requests.
*
- * @param snapshot - The snapshot timestamp.
- * @returns A new PageBlobClient object identical to the source but with the specified snapshot timestamp.
+ * @remarks
+ *
+ * This is not a part of the default {@link AuthClient.transporter transporter/gaxios}
+ * config as some downstream APIs would prefer if customers explicitly enable retries,
+ * such as GCS.
*/
- withSnapshot(snapshot) {
- return new PageBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline);
+ static get RETRY_CONFIG() {
+ return {
+ retry: true,
+ retryConfig: {
+ httpMethodsToRetry: ['GET', 'PUT', 'POST', 'HEAD', 'OPTIONS', 'DELETE'],
+ },
+ };
+ }
+}
+exports.OAuthClientAuthHandler = OAuthClientAuthHandler;
+/**
+ * Converts an OAuth error response to a native JavaScript Error.
+ * @param resp The OAuth error response to convert to a native Error object.
+ * @param err The optional original error. If provided, the error properties
+ * will be copied to the new error.
+ * @return The converted native Error object.
+ */
+function getErrorFromOAuthErrorResponse(resp, err) {
+ // Error response.
+ const errorCode = resp.error;
+ const errorDescription = resp.error_description;
+ const errorUri = resp.error_uri;
+ let message = `Error code ${errorCode}`;
+ if (typeof errorDescription !== 'undefined') {
+ message += `: ${errorDescription}`;
+ }
+ if (typeof errorUri !== 'undefined') {
+ message += ` - ${errorUri}`;
}
+ const newError = new Error(message);
+ // Copy properties from original error to newly generated error.
+ if (err) {
+ const keys = Object.keys(err);
+ if (err.stack) {
+ // Copy error.stack if available.
+ keys.push('stack');
+ }
+ keys.forEach(key => {
+ // Do not overwrite the message field.
+ if (key !== 'message') {
+ Object.defineProperty(newError, key, {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ value: err[key],
+ writable: false,
+ enumerable: true,
+ });
+ }
+ });
+ }
+ return newError;
+}
+
+
+/***/ }),
+
+/***/ 62045:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// Copyright 2024 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.PassThroughClient = void 0;
+const authclient_1 = __nccwpck_require__(34810);
+/**
+ * An AuthClient without any Authentication information. Useful for:
+ * - Anonymous access
+ * - Local Emulators
+ * - Testing Environments
+ *
+ */
+class PassThroughClient extends authclient_1.AuthClient {
/**
- * Creates a page blob of the specified length. Call uploadPages to upload data
- * data to a page blob.
- * @see https://docs.microsoft.com/rest/api/storageservices/put-blob
+ * Creates a request without any authentication headers or checks.
*
- * @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.
+ * @remarks
+ *
+ * In testing environments it may be useful to change the provided
+ * {@link AuthClient.transporter} for any desired request overrides/handling.
+ *
+ * @param opts
+ * @returns The response of the request.
*/
- 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,
- }));
- });
+ async request(opts) {
+ return this.transporter.request(opts);
}
/**
- * Creates a page blob of the specified length. Call uploadPages to upload data
- * data to a page blob. If the blob with the same name already exists, the content
- * of the existing blob will remain unchanged.
- * @see https://docs.microsoft.com/rest/api/storageservices/put-blob
+ * A required method of the base class.
+ * Always will return an empty object.
*
- * @param size - size of the page blob.
- * @param options -
+ * @returns {}
*/
- 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;
- }
- });
+ async getAccessToken() {
+ return {};
}
/**
- * Writes 1 or more pages to the page blob. The start and end offsets must be a multiple of 512.
- * @see https://docs.microsoft.com/rest/api/storageservices/put-page
+ * A required method of the base class.
+ * Always will return an empty object.
*
- * @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.
+ * @returns {}
*/
- 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,
- }));
- });
+ async getRequestHeaders() {
+ return {};
+ }
+}
+exports.PassThroughClient = PassThroughClient;
+const a = new PassThroughClient();
+a.getAccessToken();
+
+
+/***/ }),
+
+/***/ 46077:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// Copyright 2022 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.PluggableAuthClient = exports.ExecutableError = void 0;
+const baseexternalclient_1 = __nccwpck_require__(142);
+const executable_response_1 = __nccwpck_require__(43247);
+const pluggable_auth_handler_1 = __nccwpck_require__(908);
+/**
+ * Error thrown from the executable run by PluggableAuthClient.
+ */
+class ExecutableError extends Error {
+ constructor(message, code) {
+ super(`The executable failed with exit code: ${code} and error message: ${message}.`);
+ this.code = code;
+ Object.setPrototypeOf(this, new.target.prototype);
}
+}
+exports.ExecutableError = ExecutableError;
+/**
+ * The default executable timeout when none is provided, in milliseconds.
+ */
+const DEFAULT_EXECUTABLE_TIMEOUT_MILLIS = 30 * 1000;
+/**
+ * The minimum allowed executable timeout in milliseconds.
+ */
+const MINIMUM_EXECUTABLE_TIMEOUT_MILLIS = 5 * 1000;
+/**
+ * The maximum allowed executable timeout in milliseconds.
+ */
+const MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS = 120 * 1000;
+/**
+ * The environment variable to check to see if executable can be run.
+ * Value must be set to '1' for the executable to run.
+ */
+const GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES = 'GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES';
+/**
+ * The maximum currently supported executable version.
+ */
+const MAXIMUM_EXECUTABLE_VERSION = 1;
+/**
+ * PluggableAuthClient enables the exchange of workload identity pool external credentials for
+ * Google access tokens by retrieving 3rd party tokens through a user supplied executable. These
+ * scripts/executables are completely independent of the Google Cloud Auth libraries. These
+ * credentials plug into ADC and will call the specified executable to retrieve the 3rd party token
+ * to be exchanged for a Google access token.
+ *
+ * To use these credentials, the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable
+ * must be set to '1'. This is for security reasons.
+ *
+ *
Both OIDC and SAML are supported. The executable must adhere to a specific response format
+ * defined below.
+ *
+ *
The executable must print out the 3rd party token to STDOUT in JSON format. When an
+ * output_file is specified in the credential configuration, the executable must also handle writing the
+ * JSON response to this file.
+ *
+ *
+ * OIDC response sample:
+ * {
+ * "version": 1,
+ * "success": true,
+ * "token_type": "urn:ietf:params:oauth:token-type:id_token",
+ * "id_token": "HEADER.PAYLOAD.SIGNATURE",
+ * "expiration_time": 1620433341
+ * }
+ *
+ * SAML2 response sample:
+ * {
+ * "version": 1,
+ * "success": true,
+ * "token_type": "urn:ietf:params:oauth:token-type:saml2",
+ * "saml_response": "...",
+ * "expiration_time": 1620433341
+ * }
+ *
+ * Error response sample:
+ * {
+ * "version": 1,
+ * "success": false,
+ * "code": "401",
+ * "message": "Error message."
+ * }
+ *
+ *
+ * The "expiration_time" field in the JSON response is only required for successful
+ * responses when an output file was specified in the credential configuration
+ *
+ *
The auth libraries will populate certain environment variables that will be accessible by the
+ * executable, such as: GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE, GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE,
+ * GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE, GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL, and
+ * GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE.
+ *
+ *
Please see this repositories README for a complete executable request/response specification.
+ */
+class PluggableAuthClient extends baseexternalclient_1.BaseExternalAccountClient {
/**
- * The Upload Pages operation writes a range of pages to a page blob where the
- * contents are read from a URL.
- * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-page-from-url
- *
- * @param 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 -
+ * Instantiates a PluggableAuthClient instance using the provided JSON
+ * object loaded from an external account credentials file.
+ * An error is thrown if the credential is not a valid pluggable auth credential.
+ * @param options The external account options object typically loaded from
+ * the external account JSON credential file.
+ * @param additionalOptions **DEPRECATED, all options are available in the
+ * `options` parameter.** Optional additional behavior customization options.
+ * These currently customize expiration threshold time and whether to retry
+ * on 401/403 API request errors.
*/
- 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,
- }));
+ constructor(options, additionalOptions) {
+ super(options, additionalOptions);
+ if (!options.credential_source.executable) {
+ throw new Error('No valid Pluggable Auth "credential_source" provided.');
+ }
+ this.command = options.credential_source.executable.command;
+ if (!this.command) {
+ throw new Error('No valid Pluggable Auth "credential_source" provided.');
+ }
+ // Check if the provided timeout exists and if it is valid.
+ if (options.credential_source.executable.timeout_millis === undefined) {
+ this.timeoutMillis = DEFAULT_EXECUTABLE_TIMEOUT_MILLIS;
+ }
+ else {
+ this.timeoutMillis = options.credential_source.executable.timeout_millis;
+ if (this.timeoutMillis < MINIMUM_EXECUTABLE_TIMEOUT_MILLIS ||
+ this.timeoutMillis > MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS) {
+ throw new Error(`Timeout must be between ${MINIMUM_EXECUTABLE_TIMEOUT_MILLIS} and ` +
+ `${MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS} milliseconds.`);
+ }
+ }
+ this.outputFile = options.credential_source.executable.output_file;
+ this.handler = new pluggable_auth_handler_1.PluggableAuthHandler({
+ command: this.command,
+ timeoutMillis: this.timeoutMillis,
+ outputFile: this.outputFile,
});
+ this.credentialSourceType = 'executable';
+ }
+ /**
+ * Triggered when an external subject token is needed to be exchanged for a
+ * GCP access token via GCP STS endpoint.
+ * This uses the `options.credential_source` object to figure out how
+ * to retrieve the token using the current environment. In this case,
+ * this calls a user provided executable which returns the subject token.
+ * The logic is summarized as:
+ * 1. Validated that the executable is allowed to run. The
+ * GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment must be set to
+ * 1 for security reasons.
+ * 2. If an output file is specified by the user, check the file location
+ * for a response. If the file exists and contains a valid response,
+ * return the subject token from the file.
+ * 3. Call the provided executable and return response.
+ * @return A promise that resolves with the external subject token.
+ */
+ async retrieveSubjectToken() {
+ // Check if the executable is allowed to run.
+ if (process.env[GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES] !== '1') {
+ throw new Error('Pluggable Auth executables need to be explicitly allowed to run by ' +
+ 'setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment ' +
+ 'Variable to 1.');
+ }
+ let executableResponse = undefined;
+ // Try to get cached executable response from output file.
+ if (this.outputFile) {
+ executableResponse = await this.handler.retrieveCachedResponse();
+ }
+ // If no response from output file, call the executable.
+ if (!executableResponse) {
+ // Set up environment map with required values for the executable.
+ const envMap = new Map();
+ envMap.set('GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE', this.audience);
+ envMap.set('GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE', this.subjectTokenType);
+ // Always set to 0 because interactive mode is not supported.
+ envMap.set('GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE', '0');
+ if (this.outputFile) {
+ envMap.set('GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE', this.outputFile);
+ }
+ const serviceAccountEmail = this.getServiceAccountEmail();
+ if (serviceAccountEmail) {
+ envMap.set('GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL', serviceAccountEmail);
+ }
+ executableResponse =
+ await this.handler.retrieveResponseFromExecutable(envMap);
+ }
+ if (executableResponse.version > MAXIMUM_EXECUTABLE_VERSION) {
+ throw new Error(`Version of executable is not currently supported, maximum supported version is ${MAXIMUM_EXECUTABLE_VERSION}.`);
+ }
+ // Check that response was successful.
+ if (!executableResponse.success) {
+ throw new ExecutableError(executableResponse.errorMessage, executableResponse.errorCode);
+ }
+ // Check that response contains expiration time if output file was specified.
+ if (this.outputFile) {
+ if (!executableResponse.expirationTime) {
+ throw new executable_response_1.InvalidExpirationTimeFieldError('The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.');
+ }
+ }
+ // Check that response is not expired.
+ if (executableResponse.isExpired()) {
+ throw new Error('Executable response is expired.');
+ }
+ // Return subject token from response.
+ return executableResponse.subjectToken;
+ }
+}
+exports.PluggableAuthClient = PluggableAuthClient;
+
+
+/***/ }),
+
+/***/ 908:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// Copyright 2022 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.PluggableAuthHandler = void 0;
+const pluggable_auth_client_1 = __nccwpck_require__(46077);
+const executable_response_1 = __nccwpck_require__(43247);
+const childProcess = __nccwpck_require__(35317);
+const fs = __nccwpck_require__(79896);
+/**
+ * A handler used to retrieve 3rd party token responses from user defined
+ * executables and cached file output for the PluggableAuthClient class.
+ */
+class PluggableAuthHandler {
+ /**
+ * Instantiates a PluggableAuthHandler instance using the provided
+ * PluggableAuthHandlerOptions object.
+ */
+ constructor(options) {
+ if (!options.command) {
+ throw new Error('No command provided.');
+ }
+ this.commandComponents = PluggableAuthHandler.parseCommand(options.command);
+ this.timeoutMillis = options.timeoutMillis;
+ if (!this.timeoutMillis) {
+ throw new Error('No timeoutMillis provided.');
+ }
+ this.outputFile = options.outputFile;
}
/**
- * Frees the specified pages from the page blob.
- * @see https://docs.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.
+ * Calls user provided executable to get a 3rd party subject token and
+ * returns the response.
+ * @param envMap a Map of additional Environment Variables required for
+ * the executable.
+ * @return A promise that resolves with the executable response.
*/
- 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,
- }));
+ retrieveResponseFromExecutable(envMap) {
+ return new Promise((resolve, reject) => {
+ // Spawn process to run executable using added environment variables.
+ const child = childProcess.spawn(this.commandComponents[0], this.commandComponents.slice(1), {
+ env: { ...process.env, ...Object.fromEntries(envMap) },
+ });
+ let output = '';
+ // Append stdout to output as executable runs.
+ child.stdout.on('data', (data) => {
+ output += data;
+ });
+ // Append stderr as executable runs.
+ child.stderr.on('data', (err) => {
+ output += err;
+ });
+ // Set up a timeout to end the child process and throw an error.
+ const timeout = setTimeout(() => {
+ // Kill child process and remove listeners so 'close' event doesn't get
+ // read after child process is killed.
+ child.removeAllListeners();
+ child.kill();
+ return reject(new Error('The executable failed to finish within the timeout specified.'));
+ }, this.timeoutMillis);
+ child.on('close', (code) => {
+ // Cancel timeout if executable closes before timeout is reached.
+ clearTimeout(timeout);
+ if (code === 0) {
+ // If the executable completed successfully, try to return the parsed response.
+ try {
+ const responseJson = JSON.parse(output);
+ const response = new executable_response_1.ExecutableResponse(responseJson);
+ return resolve(response);
+ }
+ catch (error) {
+ if (error instanceof executable_response_1.ExecutableResponseError) {
+ return reject(error);
+ }
+ return reject(new executable_response_1.ExecutableResponseError(`The executable returned an invalid response: ${output}`));
+ }
+ }
+ else {
+ return reject(new pluggable_auth_client_1.ExecutableError(output, code.toString()));
+ }
+ });
});
}
/**
- * Returns the list of valid page ranges for a page blob or snapshot of a page blob.
- * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges
- *
- * @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.
+ * Checks user provided output file for response from previous run of
+ * executable and return the response if it exists, is formatted correctly, and is not expired.
*/
- 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);
+ async retrieveCachedResponse() {
+ if (!this.outputFile || this.outputFile.length === 0) {
+ return undefined;
+ }
+ let filePath;
+ try {
+ filePath = await fs.promises.realpath(this.outputFile);
+ }
+ catch (_a) {
+ // If file path cannot be resolved, return undefined.
+ return undefined;
+ }
+ if (!(await fs.promises.lstat(filePath)).isFile()) {
+ // If path does not lead to file, return undefined.
+ return undefined;
+ }
+ const responseString = await fs.promises.readFile(filePath, {
+ encoding: 'utf8',
});
+ if (responseString === '') {
+ return undefined;
+ }
+ try {
+ const responseJson = JSON.parse(responseString);
+ const response = new executable_response_1.ExecutableResponse(responseJson);
+ // Check if response is successful and unexpired.
+ if (response.isValid()) {
+ return new executable_response_1.ExecutableResponse(responseJson);
+ }
+ return undefined;
+ }
+ catch (error) {
+ if (error instanceof executable_response_1.ExecutableResponseError) {
+ throw error;
+ }
+ throw new executable_response_1.ExecutableResponseError(`The output file contained an invalid response: ${responseString}`);
+ }
}
/**
- * 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://docs.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.
+ * Parses given command string into component array, splitting on spaces unless
+ * spaces are between quotation marks.
*/
- 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,
- }));
+ static parseCommand(command) {
+ // Split the command into components by splitting on spaces,
+ // unless spaces are contained in quotation marks.
+ const components = command.match(/(?:[^\s"]+|"[^"]*")+/g);
+ if (!components) {
+ throw new Error(`Provided command: "${command}" could not be parsed.`);
+ }
+ // Remove quotation marks from the beginning and end of each component if they are present.
+ for (let i = 0; i < components.length; i++) {
+ if (components[i][0] === '"' && components[i].slice(-1) === '"') {
+ components[i] = components[i].slice(1, -1);
+ }
+ }
+ return components;
+ }
+}
+exports.PluggableAuthHandler = PluggableAuthHandler;
+
+
+/***/ }),
+
+/***/ 99807:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// Copyright 2015 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.UserRefreshClient = exports.USER_REFRESH_ACCOUNT_TYPE = void 0;
+const oauth2client_1 = __nccwpck_require__(10091);
+const querystring_1 = __nccwpck_require__(83480);
+exports.USER_REFRESH_ACCOUNT_TYPE = 'authorized_user';
+class UserRefreshClient extends oauth2client_1.OAuth2Client {
+ constructor(optionsOrClientId, clientSecret, refreshToken, eagerRefreshThresholdMillis, forceRefreshOnFailure) {
+ const opts = optionsOrClientId && typeof optionsOrClientId === 'object'
+ ? optionsOrClientId
+ : {
+ clientId: optionsOrClientId,
+ clientSecret,
+ refreshToken,
+ eagerRefreshThresholdMillis,
+ forceRefreshOnFailure,
+ };
+ super(opts);
+ this._refreshToken = opts.refreshToken;
+ this.credentials.refresh_token = opts.refreshToken;
+ }
+ /**
+ * Refreshes the access token.
+ * @param refreshToken An ignored refreshToken..
+ * @param callback Optional callback.
+ */
+ async refreshTokenNoCache(
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ refreshToken) {
+ return super.refreshTokenNoCache(this._refreshToken);
+ }
+ async fetchIdToken(targetAudience) {
+ const res = await this.transporter.request({
+ ...UserRefreshClient.RETRY_CONFIG,
+ url: this.endpoints.oauth2TokenUrl,
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
+ method: 'POST',
+ data: (0, querystring_1.stringify)({
+ client_id: this._clientId,
+ client_secret: this._clientSecret,
+ grant_type: 'refresh_token',
+ refresh_token: this._refreshToken,
+ target_audience: targetAudience,
+ }),
});
+ return res.data.id_token;
}
/**
- * 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.
+ * Create a UserRefreshClient credentials instance using the given input
+ * options.
+ * @param json The input object.
*/
- 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);
- }
+ fromJSON(json) {
+ if (!json) {
+ throw new Error('Must pass in a JSON object containing the user refresh token');
+ }
+ if (json.type !== 'authorized_user') {
+ throw new Error('The incoming JSON object does not have the "authorized_user" type');
+ }
+ if (!json.client_id) {
+ throw new Error('The incoming JSON object does not contain a client_id field');
+ }
+ if (!json.client_secret) {
+ throw new Error('The incoming JSON object does not contain a client_secret field');
+ }
+ if (!json.refresh_token) {
+ throw new Error('The incoming JSON object does not contain a refresh_token field');
+ }
+ this._clientId = json.client_id;
+ this._clientSecret = json.client_secret;
+ this._refreshToken = json.refresh_token;
+ this.credentials.refresh_token = json.refresh_token;
+ this.quotaProjectId = json.quota_project_id;
+ this.universeDomain = json.universe_domain || this.universeDomain;
+ }
+ fromStream(inputStream, callback) {
+ if (callback) {
+ this.fromStreamAsync(inputStream).then(() => callback(), callback);
+ }
+ else {
+ return this.fromStreamAsync(inputStream);
+ }
+ }
+ async fromStreamAsync(inputStream) {
+ return new Promise((resolve, reject) => {
+ if (!inputStream) {
+ return reject(new Error('Must pass in a stream containing the user refresh token.'));
+ }
+ let s = '';
+ inputStream
+ .setEncoding('utf8')
+ .on('error', reject)
+ .on('data', chunk => (s += chunk))
+ .on('end', () => {
+ try {
+ const data = JSON.parse(s);
+ this.fromJSON(data);
+ return resolve();
+ }
+ catch (err) {
+ return reject(err);
+ }
+ });
});
}
/**
- * 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.
+ * Create a UserRefreshClient credentials instance using the given input
+ * options.
+ * @param json The input object.
*/
- 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; }
+ static fromJSON(json) {
+ const client = new UserRefreshClient();
+ client.fromJSON(json);
+ return client;
+ }
+}
+exports.UserRefreshClient = UserRefreshClient;
+
+
+/***/ }),
+
+/***/ 121:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.StsCredentials = void 0;
+const gaxios_1 = __nccwpck_require__(97003);
+const querystring = __nccwpck_require__(83480);
+const transporters_1 = __nccwpck_require__(67633);
+const oauth2common_1 = __nccwpck_require__(6653);
+/**
+ * Implements the OAuth 2.0 token exchange based on
+ * https://tools.ietf.org/html/rfc8693
+ */
+class StsCredentials extends oauth2common_1.OAuthClientAuthHandler {
+ /**
+ * Initializes an STS credentials instance.
+ * @param tokenExchangeEndpoint The token exchange endpoint.
+ * @param clientAuthentication The client authentication credentials if
+ * available.
+ */
+ constructor(tokenExchangeEndpoint, clientAuthentication) {
+ super(clientAuthentication);
+ this.tokenExchangeEndpoint = tokenExchangeEndpoint;
+ this.transporter = new transporters_1.DefaultTransporter();
+ }
+ /**
+ * Exchanges the provided token for another type of token based on the
+ * rfc8693 spec.
+ * @param stsCredentialsOptions The token exchange options used to populate
+ * the token exchange request.
+ * @param additionalHeaders Optional additional headers to pass along the
+ * request.
+ * @param options Optional additional GCP-specific non-spec defined options
+ * to send with the request.
+ * Example: `&options=${encodeUriComponent(JSON.stringified(options))}`
+ * @return A promise that resolves with the token exchange response containing
+ * the requested token and its expiration time.
+ */
+ async exchangeToken(stsCredentialsOptions, additionalHeaders,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ options) {
+ var _a, _b, _c;
+ const values = {
+ grant_type: stsCredentialsOptions.grantType,
+ resource: stsCredentialsOptions.resource,
+ audience: stsCredentialsOptions.audience,
+ scope: (_a = stsCredentialsOptions.scope) === null || _a === void 0 ? void 0 : _a.join(' '),
+ requested_token_type: stsCredentialsOptions.requestedTokenType,
+ subject_token: stsCredentialsOptions.subjectToken,
+ subject_token_type: stsCredentialsOptions.subjectTokenType,
+ actor_token: (_b = stsCredentialsOptions.actingParty) === null || _b === void 0 ? void 0 : _b.actorToken,
+ actor_token_type: (_c = stsCredentialsOptions.actingParty) === null || _c === void 0 ? void 0 : _c.actorTokenType,
+ // Non-standard GCP-specific options.
+ options: options && JSON.stringify(options),
+ };
+ // Remove undefined fields.
+ Object.keys(values).forEach(key => {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ if (typeof values[key] === 'undefined') {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ delete values[key];
}
});
+ const headers = {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ };
+ // Inject additional STS headers if available.
+ Object.assign(headers, additionalHeaders || {});
+ const opts = {
+ ...StsCredentials.RETRY_CONFIG,
+ url: this.tokenExchangeEndpoint.toString(),
+ method: 'POST',
+ headers,
+ data: querystring.stringify(values),
+ responseType: 'json',
+ };
+ // Apply OAuth client authentication.
+ this.applyClientAuthenticationOptions(opts);
+ try {
+ const response = await this.transporter.request(opts);
+ // Successful response.
+ const stsSuccessfulResponse = response.data;
+ stsSuccessfulResponse.res = response;
+ return stsSuccessfulResponse;
+ }
+ catch (error) {
+ // Translate error to OAuthError.
+ if (error instanceof gaxios_1.GaxiosError && error.response) {
+ throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data,
+ // Preserve other fields from the original error.
+ error);
+ }
+ // Request could fail before the server responds.
+ throw error;
+ }
}
+}
+exports.StsCredentials = StsCredentials;
+
+
+/***/ }),
+
+/***/ 24627:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// Copyright 2024 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.UrlSubjectTokenSupplier = void 0;
+/**
+ * Internal subject token supplier implementation used when a URL
+ * is configured in the credential configuration used to build an {@link IdentityPoolClient}
+ */
+class UrlSubjectTokenSupplier {
/**
- * Returns an async iterable iterator to list of page ranges for a page blob.
- * @see https://docs.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.
+ * Instantiates a URL subject token supplier.
+ * @param opts The URL subject token supplier options to build the supplier with.
*/
- 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));
- },
+ constructor(opts) {
+ this.url = opts.url;
+ this.formatType = opts.formatType;
+ this.subjectTokenFieldName = opts.subjectTokenFieldName;
+ this.headers = opts.headers;
+ this.additionalGaxiosOptions = opts.additionalGaxiosOptions;
+ }
+ /**
+ * Sends a GET request to the URL provided in the constructor and resolves
+ * with the returned external subject token.
+ * @param context {@link ExternalAccountSupplierContext} from the calling
+ * {@link IdentityPoolClient}, contains the requested audience and subject
+ * token type for the external account identity. Not used.
+ */
+ async getSubjectToken(context) {
+ const opts = {
+ ...this.additionalGaxiosOptions,
+ url: this.url,
+ method: 'GET',
+ headers: this.headers,
+ responseType: this.formatType,
+ };
+ let subjectToken;
+ if (this.formatType === 'text') {
+ const response = await context.transporter.request(opts);
+ subjectToken = response.data;
+ }
+ else if (this.formatType === 'json' && this.subjectTokenFieldName) {
+ const response = await context.transporter.request(opts);
+ subjectToken = response.data[this.subjectTokenFieldName];
+ }
+ if (!subjectToken) {
+ throw new Error('Unable to parse the subject_token from the credential_source URL');
+ }
+ return subjectToken;
+ }
+}
+exports.UrlSubjectTokenSupplier = UrlSubjectTokenSupplier;
+
+
+/***/ }),
+
+/***/ 93438:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// Copyright 2019 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+/* global window */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.BrowserCrypto = void 0;
+// This file implements crypto functions we need using in-browser
+// SubtleCrypto interface `window.crypto.subtle`.
+const base64js = __nccwpck_require__(38793);
+const crypto_1 = __nccwpck_require__(88851);
+class BrowserCrypto {
+ constructor() {
+ if (typeof window === 'undefined' ||
+ window.crypto === undefined ||
+ window.crypto.subtle === undefined) {
+ throw new Error("SubtleCrypto not found. Make sure it's an https:// website.");
+ }
+ }
+ async sha256DigestBase64(str) {
+ // SubtleCrypto digest() method is async, so we must make
+ // this method async as well.
+ // To calculate SHA256 digest using SubtleCrypto, we first
+ // need to convert an input string to an ArrayBuffer:
+ const inputBuffer = new TextEncoder().encode(str);
+ // Result is ArrayBuffer as well.
+ const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer);
+ return base64js.fromByteArray(new Uint8Array(outputBuffer));
+ }
+ randomBytesBase64(count) {
+ const array = new Uint8Array(count);
+ window.crypto.getRandomValues(array);
+ return base64js.fromByteArray(array);
+ }
+ static padBase64(base64) {
+ // base64js requires padding, so let's add some '='
+ while (base64.length % 4 !== 0) {
+ base64 += '=';
+ }
+ return base64;
+ }
+ async verify(pubkey, data, signature) {
+ const algo = {
+ name: 'RSASSA-PKCS1-v1_5',
+ hash: { name: 'SHA-256' },
};
+ const dataArray = new TextEncoder().encode(data);
+ const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature));
+ const cryptoKey = await window.crypto.subtle.importKey('jwk', pubkey, algo, true, ['verify']);
+ // SubtleCrypto's verify method is async so we must make
+ // this method async as well.
+ const result = await window.crypto.subtle.verify(algo, cryptoKey, signatureArray, dataArray);
+ return result;
+ }
+ async sign(privateKey, data) {
+ const algo = {
+ name: 'RSASSA-PKCS1-v1_5',
+ hash: { name: 'SHA-256' },
+ };
+ const dataArray = new TextEncoder().encode(data);
+ const cryptoKey = await window.crypto.subtle.importKey('jwk', privateKey, algo, true, ['sign']);
+ // SubtleCrypto's sign method is async so we must make
+ // this method async as well.
+ const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray);
+ return base64js.fromByteArray(new Uint8Array(result));
+ }
+ decodeBase64StringUtf8(base64) {
+ const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64));
+ const result = new TextDecoder().decode(uint8array);
+ return result;
+ }
+ encodeBase64StringUtf8(text) {
+ const uint8array = new TextEncoder().encode(text);
+ const result = base64js.fromByteArray(uint8array);
+ return result;
}
/**
- * Gets the collection of page ranges that differ between a specified snapshot and this page blob.
- * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges
- *
- * @param 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.
+ * Computes the SHA-256 hash of the provided string.
+ * @param str The plain text string to hash.
+ * @return A promise that resolves with the SHA-256 hash of the provided
+ * string in hexadecimal encoding.
*/
- 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);
- });
+ async sha256DigestHex(str) {
+ // SubtleCrypto digest() method is async, so we must make
+ // this method async as well.
+ // To calculate SHA256 digest using SubtleCrypto, we first
+ // need to convert an input string to an ArrayBuffer:
+ const inputBuffer = new TextEncoder().encode(str);
+ // Result is ArrayBuffer as well.
+ const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer);
+ return (0, crypto_1.fromArrayBufferToHex)(outputBuffer);
}
/**
- * 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://docs.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.
+ * Computes the HMAC hash of a message using the provided crypto key and the
+ * SHA-256 algorithm.
+ * @param key The secret crypto key in utf-8 or ArrayBuffer format.
+ * @param msg The plain text message.
+ * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer
+ * format.
*/
- 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,
- }));
- });
+ async signWithHmacSha256(key, msg) {
+ // Convert key, if provided in ArrayBuffer format, to string.
+ const rawKey = typeof key === 'string'
+ ? key
+ : String.fromCharCode(...new Uint16Array(key));
+ const enc = new TextEncoder();
+ const cryptoKey = await window.crypto.subtle.importKey('raw', enc.encode(rawKey), {
+ name: 'HMAC',
+ hash: {
+ name: 'SHA-256',
+ },
+ }, false, ['sign']);
+ return window.crypto.subtle.sign('HMAC', cryptoKey, enc.encode(msg));
+ }
+}
+exports.BrowserCrypto = BrowserCrypto;
+
+
+/***/ }),
+
+/***/ 88851:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// Copyright 2019 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+/* global window */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createCrypto = createCrypto;
+exports.hasBrowserCrypto = hasBrowserCrypto;
+exports.fromArrayBufferToHex = fromArrayBufferToHex;
+const crypto_1 = __nccwpck_require__(93438);
+const crypto_2 = __nccwpck_require__(27388);
+function createCrypto() {
+ if (hasBrowserCrypto()) {
+ return new crypto_1.BrowserCrypto();
+ }
+ return new crypto_2.NodeCrypto();
+}
+function hasBrowserCrypto() {
+ return (typeof window !== 'undefined' &&
+ typeof window.crypto !== 'undefined' &&
+ typeof window.crypto.subtle !== 'undefined');
+}
+/**
+ * Converts an ArrayBuffer to a hexadecimal string.
+ * @param arrayBuffer The ArrayBuffer to convert to hexadecimal string.
+ * @return The hexadecimal encoding of the ArrayBuffer.
+ */
+function fromArrayBufferToHex(arrayBuffer) {
+ // Convert buffer to byte array.
+ const byteArray = Array.from(new Uint8Array(arrayBuffer));
+ // Convert bytes to hex string.
+ return byteArray
+ .map(byte => {
+ return byte.toString(16).padStart(2, '0');
+ })
+ .join('');
+}
+
+
+/***/ }),
+
+/***/ 27388:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// Copyright 2019 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.NodeCrypto = void 0;
+const crypto = __nccwpck_require__(76982);
+class NodeCrypto {
+ async sha256DigestBase64(str) {
+ return crypto.createHash('sha256').update(str).digest('base64');
+ }
+ randomBytesBase64(count) {
+ return crypto.randomBytes(count).toString('base64');
+ }
+ async verify(pubkey, data, signature) {
+ const verifier = crypto.createVerify('RSA-SHA256');
+ verifier.update(data);
+ verifier.end();
+ return verifier.verify(pubkey, signature, 'base64');
+ }
+ async sign(privateKey, data) {
+ const signer = crypto.createSign('RSA-SHA256');
+ signer.update(data);
+ signer.end();
+ return signer.sign(privateKey, 'base64');
+ }
+ decodeBase64StringUtf8(base64) {
+ return Buffer.from(base64, 'base64').toString('utf-8');
+ }
+ encodeBase64StringUtf8(text) {
+ return Buffer.from(text, 'utf-8').toString('base64');
}
/**
- * 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.
+ * Computes the SHA-256 hash of the provided string.
+ * @param str The plain text string to hash.
+ * @return A promise that resolves with the SHA-256 hash of the provided
+ * string in hexadecimal encoding.
*/
- 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);
- }
- });
+ async sha256DigestHex(str) {
+ return crypto.createHash('sha256').update(str).digest('hex');
}
/**
- * 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.
+ * Computes the HMAC hash of a message using the provided crypto key and the
+ * SHA-256 algorithm.
+ * @param key The secret crypto key in utf-8 or ArrayBuffer format.
+ * @param msg The plain text message.
+ * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer
+ * format.
*/
- 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))));
- }
+ async signWithHmacSha256(key, msg) {
+ const cryptoKey = typeof key === 'string' ? key : toBuffer(key);
+ return toArrayBuffer(crypto.createHmac('sha256', cryptoKey).update(msg).digest());
+ }
+}
+exports.NodeCrypto = NodeCrypto;
+/**
+ * Converts a Node.js Buffer to an ArrayBuffer.
+ * https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer
+ * @param buffer The Buffer input to covert.
+ * @return The ArrayBuffer representation of the input.
+ */
+function toArrayBuffer(buffer) {
+ return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
+}
+/**
+ * Converts an ArrayBuffer to a Node.js Buffer.
+ * @param arrayBuffer The ArrayBuffer input to covert.
+ * @return The Buffer representation of the input.
+ */
+function toBuffer(arrayBuffer) {
+ return Buffer.from(arrayBuffer);
+}
+
+
+/***/ }),
+
+/***/ 492:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.GoogleAuth = exports.auth = exports.DefaultTransporter = exports.PassThroughClient = exports.ExecutableError = exports.PluggableAuthClient = exports.DownscopedClient = exports.BaseExternalAccountClient = exports.ExternalAccountClient = exports.IdentityPoolClient = exports.AwsRequestSigner = exports.AwsClient = exports.UserRefreshClient = exports.LoginTicket = exports.ClientAuthentication = exports.OAuth2Client = exports.CodeChallengeMethod = exports.Impersonated = exports.JWT = exports.JWTAccess = exports.IdTokenClient = exports.IAMAuth = exports.GCPEnv = exports.Compute = exports.DEFAULT_UNIVERSE = exports.AuthClient = exports.gaxios = exports.gcpMetadata = void 0;
+// Copyright 2017 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+const googleauth_1 = __nccwpck_require__(95934);
+Object.defineProperty(exports, "GoogleAuth", ({ enumerable: true, get: function () { return googleauth_1.GoogleAuth; } }));
+// Export common deps to ensure types/instances are the exact match. Useful
+// for consistently configuring the library across versions.
+exports.gcpMetadata = __nccwpck_require__(23046);
+exports.gaxios = __nccwpck_require__(97003);
+var authclient_1 = __nccwpck_require__(34810);
+Object.defineProperty(exports, "AuthClient", ({ enumerable: true, get: function () { return authclient_1.AuthClient; } }));
+Object.defineProperty(exports, "DEFAULT_UNIVERSE", ({ enumerable: true, get: function () { return authclient_1.DEFAULT_UNIVERSE; } }));
+var computeclient_1 = __nccwpck_require__(20977);
+Object.defineProperty(exports, "Compute", ({ enumerable: true, get: function () { return computeclient_1.Compute; } }));
+var envDetect_1 = __nccwpck_require__(60963);
+Object.defineProperty(exports, "GCPEnv", ({ enumerable: true, get: function () { return envDetect_1.GCPEnv; } }));
+var iam_1 = __nccwpck_require__(89390);
+Object.defineProperty(exports, "IAMAuth", ({ enumerable: true, get: function () { return iam_1.IAMAuth; } }));
+var idtokenclient_1 = __nccwpck_require__(12718);
+Object.defineProperty(exports, "IdTokenClient", ({ enumerable: true, get: function () { return idtokenclient_1.IdTokenClient; } }));
+var jwtaccess_1 = __nccwpck_require__(27060);
+Object.defineProperty(exports, "JWTAccess", ({ enumerable: true, get: function () { return jwtaccess_1.JWTAccess; } }));
+var jwtclient_1 = __nccwpck_require__(75277);
+Object.defineProperty(exports, "JWT", ({ enumerable: true, get: function () { return jwtclient_1.JWT; } }));
+var impersonated_1 = __nccwpck_require__(39964);
+Object.defineProperty(exports, "Impersonated", ({ enumerable: true, get: function () { return impersonated_1.Impersonated; } }));
+var oauth2client_1 = __nccwpck_require__(10091);
+Object.defineProperty(exports, "CodeChallengeMethod", ({ enumerable: true, get: function () { return oauth2client_1.CodeChallengeMethod; } }));
+Object.defineProperty(exports, "OAuth2Client", ({ enumerable: true, get: function () { return oauth2client_1.OAuth2Client; } }));
+Object.defineProperty(exports, "ClientAuthentication", ({ enumerable: true, get: function () { return oauth2client_1.ClientAuthentication; } }));
+var loginticket_1 = __nccwpck_require__(53882);
+Object.defineProperty(exports, "LoginTicket", ({ enumerable: true, get: function () { return loginticket_1.LoginTicket; } }));
+var refreshclient_1 = __nccwpck_require__(99807);
+Object.defineProperty(exports, "UserRefreshClient", ({ enumerable: true, get: function () { return refreshclient_1.UserRefreshClient; } }));
+var awsclient_1 = __nccwpck_require__(81261);
+Object.defineProperty(exports, "AwsClient", ({ enumerable: true, get: function () { return awsclient_1.AwsClient; } }));
+var awsrequestsigner_1 = __nccwpck_require__(27647);
+Object.defineProperty(exports, "AwsRequestSigner", ({ enumerable: true, get: function () { return awsrequestsigner_1.AwsRequestSigner; } }));
+var identitypoolclient_1 = __nccwpck_require__(29960);
+Object.defineProperty(exports, "IdentityPoolClient", ({ enumerable: true, get: function () { return identitypoolclient_1.IdentityPoolClient; } }));
+var externalclient_1 = __nccwpck_require__(88323);
+Object.defineProperty(exports, "ExternalAccountClient", ({ enumerable: true, get: function () { return externalclient_1.ExternalAccountClient; } }));
+var baseexternalclient_1 = __nccwpck_require__(142);
+Object.defineProperty(exports, "BaseExternalAccountClient", ({ enumerable: true, get: function () { return baseexternalclient_1.BaseExternalAccountClient; } }));
+var downscopedclient_1 = __nccwpck_require__(77556);
+Object.defineProperty(exports, "DownscopedClient", ({ enumerable: true, get: function () { return downscopedclient_1.DownscopedClient; } }));
+var pluggable_auth_client_1 = __nccwpck_require__(46077);
+Object.defineProperty(exports, "PluggableAuthClient", ({ enumerable: true, get: function () { return pluggable_auth_client_1.PluggableAuthClient; } }));
+Object.defineProperty(exports, "ExecutableError", ({ enumerable: true, get: function () { return pluggable_auth_client_1.ExecutableError; } }));
+var passthrough_1 = __nccwpck_require__(62045);
+Object.defineProperty(exports, "PassThroughClient", ({ enumerable: true, get: function () { return passthrough_1.PassThroughClient; } }));
+var transporters_1 = __nccwpck_require__(67633);
+Object.defineProperty(exports, "DefaultTransporter", ({ enumerable: true, get: function () { return transporters_1.DefaultTransporter; } }));
+const auth = new googleauth_1.GoogleAuth();
+exports.auth = auth;
+
+
+/***/ }),
+
+/***/ 78290:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// Copyright 2017 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.validate = validate;
+// Accepts an options object passed from the user to the API. In the
+// previous version of the API, it referred to a `Request` options object.
+// Now it refers to an Axiox Request Config object. This is here to help
+// ensure users don't pass invalid options when they upgrade from 0.x to 1.x.
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function validate(options) {
+ const vpairs = [
+ { invalid: 'uri', expected: 'url' },
+ { invalid: 'json', expected: 'data' },
+ { invalid: 'qs', expected: 'params' },
+ ];
+ for (const pair of vpairs) {
+ if (options[pair.invalid]) {
+ const e = `'${pair.invalid}' is not a valid configuration option. Please use '${pair.expected}' instead. This library is using Axios for requests. Please see https://github.com/axios/axios to learn more about the valid request options.`;
+ throw new Error(e);
+ }
+ }
+}
+
+
+/***/ }),
+
+/***/ 67633:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// Copyright 2019 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.DefaultTransporter = void 0;
+const gaxios_1 = __nccwpck_require__(97003);
+const options_1 = __nccwpck_require__(78290);
+// eslint-disable-next-line @typescript-eslint/no-var-requires
+const pkg = __nccwpck_require__(96066);
+const PRODUCT_NAME = 'google-api-nodejs-client';
+class DefaultTransporter {
+ constructor() {
+ /**
+ * A configurable, replacable `Gaxios` instance.
+ */
+ this.instance = new gaxios_1.Gaxios();
+ }
+ /**
+ * Configures request options before making a request.
+ * @param opts GaxiosOptions options.
+ * @return Configured options.
+ */
+ configure(opts = {}) {
+ opts.headers = opts.headers || {};
+ if (typeof window === 'undefined') {
+ // set transporter user agent if not in browser
+ const uaValue = opts.headers['User-Agent'];
+ if (!uaValue) {
+ opts.headers['User-Agent'] = DefaultTransporter.USER_AGENT;
}
- 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; }
+ else if (!uaValue.includes(`${PRODUCT_NAME}/`)) {
+ opts.headers['User-Agent'] =
+ `${uaValue} ${DefaultTransporter.USER_AGENT}`;
}
+ // track google-auth-library-nodejs version:
+ if (!opts.headers['x-goog-api-client']) {
+ const nodeVersion = process.version.replace(/^v/, '');
+ opts.headers['x-goog-api-client'] = `gl-node/${nodeVersion}`;
+ }
+ }
+ return opts;
+ }
+ /**
+ * Makes a request using Gaxios with given options.
+ * @param opts GaxiosOptions options.
+ * @param callback optional callback that contains GaxiosResponse object.
+ * @return GaxiosPromise, assuming no callback is passed.
+ */
+ request(opts) {
+ // ensure the user isn't passing in request-style options
+ opts = this.configure(opts);
+ (0, options_1.validate)(opts);
+ return this.instance.request(opts).catch(e => {
+ throw this.processError(e);
});
}
+ get defaults() {
+ return this.instance.defaults;
+ }
+ set defaults(opts) {
+ this.instance.defaults = opts;
+ }
/**
- * Returns an async iterable iterator to list of page ranges that differ between a specified snapshot and this page blob.
- * @see https://docs.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.
+ * Changes the error to include details from the body.
*/
- 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));
- },
- };
+ processError(e) {
+ const res = e.response;
+ const err = e;
+ const body = res ? res.data : null;
+ if (res && body && body.error && res.status !== 200) {
+ if (typeof body.error === 'string') {
+ err.message = body.error;
+ err.status = res.status;
+ }
+ else if (Array.isArray(body.error.errors)) {
+ err.message = body.error.errors
+ .map((err2) => err2.message)
+ .join('\n');
+ err.code = body.error.code;
+ err.errors = body.error.errors;
+ }
+ else {
+ err.message = body.error.message;
+ err.code = body.error.code;
+ }
+ }
+ else if (res && res.status >= 400) {
+ // Consider all 4xx and 5xx responses errors.
+ err.message = body;
+ err.status = res.status;
+ }
+ return err;
}
+}
+exports.DefaultTransporter = DefaultTransporter;
+/**
+ * Default user agent.
+ */
+DefaultTransporter.USER_AGENT = `${PRODUCT_NAME}/${pkg.version}`;
+
+
+/***/ }),
+
+/***/ 37870:
+/***/ (function(__unused_webpack_module, exports) {
+
+"use strict";
+
+// Copyright 2023 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
+};
+var _LRUCache_instances, _LRUCache_cache, _LRUCache_moveToEnd, _LRUCache_evict;
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.LRUCache = void 0;
+exports.snakeToCamel = snakeToCamel;
+exports.originalOrCamelOptions = originalOrCamelOptions;
+/**
+ * Returns the camel case of a provided string.
+ *
+ * @remarks
+ *
+ * Match any `_` and not `_` pair, then return the uppercase of the not `_`
+ * character.
+ *
+ * @internal
+ *
+ * @param str the string to convert
+ * @returns the camelCase'd string
+ */
+function snakeToCamel(str) {
+ return str.replace(/([_][^_])/g, match => match.slice(1).toUpperCase());
+}
+/**
+ * Get the value of `obj[key]` or `obj[camelCaseKey]`, with a preference
+ * for original, non-camelCase key.
+ *
+ * @param obj object to lookup a value in
+ * @returns a `get` function for getting `obj[key || snakeKey]`, if available
+ */
+function originalOrCamelOptions(obj) {
/**
- * Gets the collection of page ranges that differ between a specified snapshot and this page blob for managed disks.
- * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges
*
- * @param 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.
+ * @param key an index of object, preferably snake_case
+ * @returns the value `obj[key || snakeKey]`, if available
*/
- 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);
- });
+ function get(key) {
+ var _a;
+ const o = (obj || {});
+ return (_a = o[key]) !== null && _a !== void 0 ? _a : o[snakeToCamel(key)];
+ }
+ return { get };
+}
+/**
+ * A simple LRU cache utility.
+ * Not meant for external usage.
+ *
+ * @experimental
+ * @internal
+ */
+class LRUCache {
+ constructor(options) {
+ _LRUCache_instances.add(this);
+ /**
+ * Maps are in order. Thus, the older item is the first item.
+ *
+ * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map}
+ */
+ _LRUCache_cache.set(this, new Map());
+ this.capacity = options.capacity;
+ this.maxAge = options.maxAge;
}
/**
- * Resizes the page blob to the specified size (which must be a multiple of 512).
- * @see https://docs.microsoft.com/rest/api/storageservices/set-blob-properties
+ * Add an item to the cache.
*
- * @param size - Target size
- * @param options - Options to the Page Blob Resize operation.
- * @returns Response data for the Page Blob Resize operation.
+ * @param key the key to upsert
+ * @param value the value of the key
*/
- 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,
- }));
- });
+ set(key, value) {
+ __classPrivateFieldGet(this, _LRUCache_instances, "m", _LRUCache_moveToEnd).call(this, key, value);
+ __classPrivateFieldGet(this, _LRUCache_instances, "m", _LRUCache_evict).call(this);
}
/**
- * Sets a page blob's sequence number.
- * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties
+ * Get an item from the cache.
*
- * @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.
+ * @param key the key to retrieve
*/
- 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,
- }));
- });
+ get(key) {
+ const item = __classPrivateFieldGet(this, _LRUCache_cache, "f").get(key);
+ if (!item)
+ return;
+ __classPrivateFieldGet(this, _LRUCache_instances, "m", _LRUCache_moveToEnd).call(this, key, item.value);
+ __classPrivateFieldGet(this, _LRUCache_instances, "m", _LRUCache_evict).call(this);
+ return item.value;
}
+}
+exports.LRUCache = LRUCache;
+_LRUCache_cache = new WeakMap(), _LRUCache_instances = new WeakSet(), _LRUCache_moveToEnd = function _LRUCache_moveToEnd(key, value) {
+ __classPrivateFieldGet(this, _LRUCache_cache, "f").delete(key);
+ __classPrivateFieldGet(this, _LRUCache_cache, "f").set(key, {
+ value,
+ lastAccessed: Date.now(),
+ });
+}, _LRUCache_evict = function _LRUCache_evict() {
+ const cutoffDate = this.maxAge ? Date.now() - this.maxAge : 0;
/**
- * Begins an operation to start an incremental copy from one page blob's snapshot to this page blob.
- * The snapshot is copied such that only the differential changes between the previously
- * copied snapshot are transferred to the destination.
- * The copied snapshots are complete copies of the original snapshot and can be read or copied from as usual.
- * @see https://docs.microsoft.com/rest/api/storageservices/incremental-copy-blob
- * @see https://docs.microsoft.com/en-us/azure/virtual-machines/windows/incremental-snapshots
- *
- * @param 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.
+ * Because we know Maps are in order, this item is both the
+ * last item in the list (capacity) and oldest (maxAge).
*/
- 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,
- }));
- });
+ let oldestItem = __classPrivateFieldGet(this, _LRUCache_cache, "f").entries().next();
+ while (!oldestItem.done &&
+ (__classPrivateFieldGet(this, _LRUCache_cache, "f").size > this.capacity || // too many
+ oldestItem.value[1].lastAccessed < cutoffDate) // too old
+ ) {
+ __classPrivateFieldGet(this, _LRUCache_cache, "f").delete(oldestItem.value[0]);
+ oldestItem = __classPrivateFieldGet(this, _LRUCache_cache, "f").entries().next();
}
-}
+};
-// 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;
+/***/ }),
+
+/***/ 71628:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// Copyright 2024 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Colours = void 0;
/**
- * Util class for parsing batch response.
+ * Handles figuring out if we can use ANSI colours and handing out the escape codes.
+ *
+ * This is for package-internal use only, and may change at any time.
+ *
+ * @private
+ * @internal
*/
-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.");
+class Colours {
+ /**
+ * @param stream The stream (e.g. process.stderr)
+ * @returns true if the stream should have colourization enabled
+ */
+ static isEnabled(stream) {
+ return (stream.isTTY &&
+ (typeof stream.getColorDepth === 'function'
+ ? stream.getColorDepth() > 2
+ : true));
+ }
+ static refresh() {
+ Colours.enabled = Colours.isEnabled(process.stderr);
+ if (!this.enabled) {
+ Colours.reset = '';
+ Colours.bright = '';
+ Colours.dim = '';
+ Colours.red = '';
+ Colours.green = '';
+ Colours.yellow = '';
+ Colours.blue = '';
+ Colours.magenta = '';
+ Colours.cyan = '';
+ Colours.white = '';
+ Colours.grey = '';
}
- this.batchResponse = batchResponse;
- this.subRequests = subRequests;
- this.responseBatchBoundary = this.batchResponse.contentType.split("=")[1];
- this.perResponsePrefix = `--${this.responseBatchBoundary}${HTTP_LINE_ENDING}`;
- this.batchResponseEnding = `--${this.responseBatchBoundary}--`;
+ else {
+ Colours.reset = '\u001b[0m';
+ Colours.bright = '\u001b[1m';
+ Colours.dim = '\u001b[2m';
+ Colours.red = '\u001b[31m';
+ Colours.green = '\u001b[32m';
+ Colours.yellow = '\u001b[33m';
+ Colours.blue = '\u001b[34m';
+ Colours.magenta = '\u001b[35m';
+ Colours.cyan = '\u001b[36m';
+ Colours.white = '\u001b[37m';
+ Colours.grey = '\u001b[90m';
+ }
+ }
+}
+exports.Colours = Colours;
+Colours.enabled = false;
+Colours.reset = '';
+Colours.bright = '';
+Colours.dim = '';
+Colours.red = '';
+Colours.green = '';
+Colours.yellow = '';
+Colours.blue = '';
+Colours.magenta = '';
+Colours.cyan = '';
+Colours.white = '';
+Colours.grey = '';
+Colours.refresh();
+//# sourceMappingURL=colours.js.map
+
+/***/ }),
+
+/***/ 81577:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+"use strict";
+
+// Copyright 2024 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ 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]; } };
}
- // For example of response, please refer to https://docs.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.");
+ 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 }));
+__exportStar(__nccwpck_require__(74788), exports);
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 74788:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+"use strict";
+
+// Copyright 2021-2024 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ 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.env = exports.DebugLogBackendBase = exports.placeholder = exports.AdhocDebugLogger = exports.LogSeverity = void 0;
+exports.getNodeBackend = getNodeBackend;
+exports.getDebugBackend = getDebugBackend;
+exports.getStructuredBackend = getStructuredBackend;
+exports.setBackend = setBackend;
+exports.log = log;
+const node_events_1 = __nccwpck_require__(78474);
+const process = __importStar(__nccwpck_require__(1708));
+const util = __importStar(__nccwpck_require__(57975));
+const colours_1 = __nccwpck_require__(71628);
+// Some functions (as noted) are based on the Node standard library, from
+// the following file:
+//
+// https://github.com/nodejs/node/blob/main/lib/internal/util/debuglog.js
+/**
+ * This module defines an ad-hoc debug logger for Google Cloud Platform
+ * client libraries in Node. An ad-hoc debug logger is a tool which lets
+ * users use an external, unified interface (in this case, environment
+ * variables) to determine what logging they want to see at runtime. This
+ * isn't necessarily fed into the console, but is meant to be under the
+ * control of the user. The kind of logging that will be produced by this
+ * is more like "call retry happened", not "event you'd want to record
+ * in Cloud Logger".
+ *
+ * More for Googlers implementing libraries with it:
+ * go/cloud-client-logging-design
+ */
+/**
+ * Possible log levels. These are a subset of Cloud Observability levels.
+ * https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity
+ */
+var LogSeverity;
+(function (LogSeverity) {
+ LogSeverity["DEFAULT"] = "DEFAULT";
+ LogSeverity["DEBUG"] = "DEBUG";
+ LogSeverity["INFO"] = "INFO";
+ LogSeverity["WARNING"] = "WARNING";
+ LogSeverity["ERROR"] = "ERROR";
+})(LogSeverity || (exports.LogSeverity = LogSeverity = {}));
+/**
+ * Our logger instance. This actually contains the meat of dealing
+ * with log lines, including EventEmitter. This contains the function
+ * that will be passed back to users of the package.
+ */
+class AdhocDebugLogger extends node_events_1.EventEmitter {
+ /**
+ * @param upstream The backend will pass a function that will be
+ * called whenever our logger function is invoked.
+ */
+ constructor(namespace, upstream) {
+ super();
+ this.namespace = namespace;
+ this.upstream = upstream;
+ this.func = Object.assign(this.invoke.bind(this), {
+ // Also add an instance pointer back to us.
+ instance: this,
+ // And pull over the EventEmitter functionality.
+ on: (event, listener) => this.on(event, listener),
+ });
+ // Convenience methods for log levels.
+ this.func.debug = (...args) => this.invokeSeverity(LogSeverity.DEBUG, ...args);
+ this.func.info = (...args) => this.invokeSeverity(LogSeverity.INFO, ...args);
+ this.func.warn = (...args) => this.invokeSeverity(LogSeverity.WARNING, ...args);
+ this.func.error = (...args) => this.invokeSeverity(LogSeverity.ERROR, ...args);
+ this.func.sublog = (namespace) => log(namespace, this.func);
+ }
+ invoke(fields, ...args) {
+ // Push out any upstream logger first.
+ if (this.upstream) {
+ this.upstream(fields, ...args);
}
- 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++;
+ // Emit sink events.
+ this.emit('log', fields, args);
+ }
+ invokeSeverity(severity, ...args) {
+ this.invoke({ severity }, ...args);
+ }
+}
+exports.AdhocDebugLogger = AdhocDebugLogger;
+/**
+ * This can be used in place of a real logger while waiting for Promises or disabling logging.
+ */
+exports.placeholder = new AdhocDebugLogger('', () => { }).func;
+/**
+ * The base class for debug logging backends. It's possible to use this, but the
+ * same non-guarantees above still apply (unstable interface, etc).
+ *
+ * @private
+ * @internal
+ */
+class DebugLogBackendBase {
+ constructor() {
+ var _a;
+ this.cached = new Map();
+ this.filters = [];
+ this.filtersSet = false;
+ // Look for the Node config variable for what systems to enable. We'll store
+ // these for the log method below, which will call setFilters() once.
+ let nodeFlag = (_a = process.env[exports.env.nodeEnables]) !== null && _a !== void 0 ? _a : '*';
+ if (nodeFlag === 'all') {
+ nodeFlag = '*';
+ }
+ this.filters = nodeFlag.split(',');
+ }
+ log(namespace, fields, ...args) {
+ try {
+ if (!this.filtersSet) {
+ this.setFilters();
+ this.filtersSet = true;
}
- else {
- subResponsesSucceededCount++;
+ let logger = this.cached.get(namespace);
+ if (!logger) {
+ logger = this.makeLogger(namespace);
+ this.cached.set(namespace, logger);
}
+ logger(fields, ...args);
}
- return {
- subResponses: deserializedSubResponses,
- subResponsesSucceededCount: subResponsesSucceededCount,
- subResponsesFailedCount: subResponsesFailedCount,
+ catch (e) {
+ // Silently ignore all errors; we don't want them to interfere with
+ // the user's running app.
+ // e;
+ console.error(e);
+ }
+ }
+}
+exports.DebugLogBackendBase = DebugLogBackendBase;
+// The basic backend. This one definitely works, but it's less feature-filled.
+//
+// Rather than using util.debuglog, this implements the same basic logic directly.
+// The reason for this decision is that debuglog checks the value of the
+// NODE_DEBUG environment variable before any user code runs; we therefore
+// can't pipe our own enables into it (and util.debuglog will never print unless
+// the user duplicates it into NODE_DEBUG, which isn't reasonable).
+//
+class NodeBackend extends DebugLogBackendBase {
+ constructor() {
+ super(...arguments);
+ // Default to allowing all systems, since we gate earlier based on whether the
+ // variable is empty.
+ this.enabledRegexp = /.*/g;
+ }
+ isEnabled(namespace) {
+ return this.enabledRegexp.test(namespace);
+ }
+ makeLogger(namespace) {
+ if (!this.enabledRegexp.test(namespace)) {
+ return () => { };
+ }
+ return (fields, ...args) => {
+ var _a;
+ // TODO: `fields` needs to be turned into a string here, one way or another.
+ const nscolour = `${colours_1.Colours.green}${namespace}${colours_1.Colours.reset}`;
+ const pid = `${colours_1.Colours.yellow}${process.pid}${colours_1.Colours.reset}`;
+ let level;
+ switch (fields.severity) {
+ case LogSeverity.ERROR:
+ level = `${colours_1.Colours.red}${fields.severity}${colours_1.Colours.reset}`;
+ break;
+ case LogSeverity.INFO:
+ level = `${colours_1.Colours.magenta}${fields.severity}${colours_1.Colours.reset}`;
+ break;
+ case LogSeverity.WARNING:
+ level = `${colours_1.Colours.yellow}${fields.severity}${colours_1.Colours.reset}`;
+ break;
+ default:
+ level = (_a = fields.severity) !== null && _a !== void 0 ? _a : LogSeverity.DEFAULT;
+ break;
+ }
+ const msg = util.formatWithOptions({ colors: colours_1.Colours.enabled }, ...args);
+ const filteredFields = Object.assign({}, fields);
+ delete filteredFields.severity;
+ const fieldsJson = Object.getOwnPropertyNames(filteredFields).length
+ ? JSON.stringify(filteredFields)
+ : '';
+ const fieldsColour = fieldsJson
+ ? `${colours_1.Colours.grey}${fieldsJson}${colours_1.Colours.reset}`
+ : '';
+ console.error('%s [%s|%s] %s%s', pid, nscolour, level, msg, fieldsJson ? ` ${fieldsColour}` : '');
};
}
+ // Regexp patterns below are from here:
+ // https://github.com/nodejs/node/blob/c0aebed4b3395bd65d54b18d1fd00f071002ac20/lib/internal/util/debuglog.js#L36
+ setFilters() {
+ const totalFilters = this.filters.join(',');
+ const regexp = totalFilters
+ .replace(/[|\\{}()[\]^$+?.]/g, '\\$&')
+ .replace(/\*/g, '.*')
+ .replace(/,/g, '$|^');
+ this.enabledRegexp = new RegExp(`^${regexp}$`, 'i');
+ }
}
-
-// 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.
+ * @returns A backend based on Node util.debuglog; this is the default.
*/
-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();
- });
- }
- });
+function getNodeBackend() {
+ return new NodeBackend();
+}
+class DebugBackend extends DebugLogBackendBase {
+ constructor(pkg) {
+ super();
+ this.debugPkg = pkg;
+ }
+ makeLogger(namespace) {
+ const debugLogger = this.debugPkg(namespace);
+ return (fields, ...args) => {
+ // TODO: `fields` needs to be turned into a string here.
+ debugLogger(args[0], ...args.slice(1));
+ };
+ }
+ setFilters() {
+ var _a;
+ const existingFilters = (_a = process.env['NODE_DEBUG']) !== null && _a !== void 0 ? _a : '';
+ process.env['NODE_DEBUG'] = `${existingFilters}${existingFilters ? ',' : ''}${this.filters.join(',')}`;
+ }
+}
+/**
+ * Creates a "debug" package backend. The user must call require('debug') and pass
+ * the resulting object to this function.
+ *
+ * ```
+ * setBackend(getDebugBackend(require('debug')))
+ * ```
+ *
+ * https://www.npmjs.com/package/debug
+ *
+ * Note: Google does not explicitly endorse or recommend this package; it's just
+ * being provided as an option.
+ *
+ * @returns A backend based on the npm "debug" package.
+ */
+function getDebugBackend(debugPkg) {
+ return new DebugBackend(debugPkg);
+}
+/**
+ * This pretty much works like the Node logger, but it outputs structured
+ * logging JSON matching Google Cloud's ingestion specs. Rather than handling
+ * its own output, it wraps another backend. The passed backend must be a subclass
+ * of `DebugLogBackendBase` (any of the backends exposed by this package will work).
+ */
+class StructuredBackend extends DebugLogBackendBase {
+ constructor(upstream) {
+ var _a;
+ super();
+ this.upstream = (_a = upstream) !== null && _a !== void 0 ? _a : new NodeBackend();
+ }
+ makeLogger(namespace) {
+ const debugLogger = this.upstream.makeLogger(namespace);
+ return (fields, ...args) => {
+ var _a;
+ const severity = (_a = fields.severity) !== null && _a !== void 0 ? _a : LogSeverity.INFO;
+ const json = Object.assign({
+ severity,
+ message: util.format(...args),
+ }, fields);
+ const jsonString = JSON.stringify(json);
+ debugLogger(fields, jsonString);
+ };
+ }
+ setFilters() {
+ this.upstream.setFilters();
}
+}
+/**
+ * Creates a "structured logging" backend. This pretty much works like the
+ * Node logger, but it outputs structured logging JSON matching Google
+ * Cloud's ingestion specs instead of plain text.
+ *
+ * ```
+ * setBackend(getStructuredBackend())
+ * ```
+ *
+ * @param upstream If you want to use something besides the Node backend to
+ * write the actual log lines into, pass that here.
+ * @returns A backend based on Google Cloud structured logging.
+ */
+function getStructuredBackend(upstream) {
+ return new StructuredBackend(upstream);
+}
+/**
+ * The environment variables that we standardized on, for all ad-hoc logging.
+ */
+exports.env = {
/**
- * Unlock a key.
- *
- * @param key -
+ * Filter wildcards specific to the Node syntax, and similar to the built-in
+ * utils.debuglog() environment variable. If missing, disables logging.
*/
- static async unlock(key) {
- return new Promise((resolve) => {
- if (this.keys[key] === MutexLockStatus.LOCKED) {
- this.emitUnlockEvent(key);
+ nodeEnables: 'GOOGLE_SDK_NODE_LOGGING',
+};
+// Keep a copy of all namespaced loggers so users can reliably .on() them.
+// Note that these cached functions will need to deal with changes in the backend.
+const loggerCache = new Map();
+// Our current global backend. This might be:
+let cachedBackend = undefined;
+/**
+ * Set the backend to use for our log output.
+ * - A backend object
+ * - null to disable logging
+ * - undefined for "nothing yet", defaults to the Node backend
+ *
+ * @param backend Results from one of the get*Backend() functions.
+ */
+function setBackend(backend) {
+ cachedBackend = backend;
+ loggerCache.clear();
+}
+/**
+ * Creates a logging function. Multiple calls to this with the same namespace
+ * will produce the same logger, with the same event emitter hooks.
+ *
+ * Namespaces can be a simple string ("system" name), or a qualified string
+ * (system:subsystem), which can be used for filtering, or for "system:*".
+ *
+ * @param namespace The namespace, a descriptive text string.
+ * @returns A function you can call that works similar to console.log().
+ */
+function log(namespace, parent) {
+ // If the enable flag isn't set, do nothing.
+ const enablesFlag = process.env[exports.env.nodeEnables];
+ if (!enablesFlag) {
+ return exports.placeholder;
+ }
+ // This might happen mostly if the typings are dropped in a user's code,
+ // or if they're calling from JavaScript.
+ if (!namespace) {
+ return exports.placeholder;
+ }
+ // Handle sub-loggers.
+ if (parent) {
+ namespace = `${parent.instance.namespace}:${namespace}`;
+ }
+ // Reuse loggers so things like event sinks are persistent.
+ const existing = loggerCache.get(namespace);
+ if (existing) {
+ return existing.func;
+ }
+ // Do we have a backend yet?
+ if (cachedBackend === null) {
+ // Explicitly disabled.
+ return exports.placeholder;
+ }
+ else if (cachedBackend === undefined) {
+ // One hasn't been made yet, so default to Node.
+ cachedBackend = getNodeBackend();
+ }
+ // The logger is further wrapped so we can handle the backend changing out.
+ const logger = (() => {
+ let previousBackend = undefined;
+ const newLogger = new AdhocDebugLogger(namespace, (fields, ...args) => {
+ if (previousBackend !== cachedBackend) {
+ // Did the user pass a custom backend?
+ if (cachedBackend === null) {
+ // Explicitly disabled.
+ return;
+ }
+ else if (cachedBackend === undefined) {
+ // One hasn't been made yet, so default to Node.
+ cachedBackend = getNodeBackend();
+ }
+ previousBackend = cachedBackend;
}
- delete this.keys[key];
- resolve();
+ cachedBackend === null || cachedBackend === void 0 ? void 0 : cachedBackend.log(namespace, fields, ...args);
});
- }
- 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);
- });
- }
- }
+ return newLogger;
+ })();
+ loggerCache.set(namespace, logger);
+ return logger.func;
}
-Mutex.keys = {};
-Mutex.listeners = {};
+//# sourceMappingURL=logging-utils.js.map
+
+/***/ }),
+
+/***/ 1174:
+/***/ ((module) => {
+
+"use strict";
+
+
+/** @type {import('./gOPD')} */
+module.exports = Object.getOwnPropertyDescriptor;
+
+
+/***/ }),
+
+/***/ 33170:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+/** @type {import('.')} */
+var $gOPD = __nccwpck_require__(1174);
+
+if ($gOPD) {
+ try {
+ $gOPD([], 'length');
+ } catch (e) {
+ // IE 8 has a broken gOPD
+ $gOPD = null;
+ }
+}
+
+module.exports = $gOPD;
+
+
+/***/ }),
+
+/***/ 28568:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+"use strict";
-// 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.
+ * Copyright 2018 Google LLC
+ *
+ * Distributed under MIT license.
+ * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
-class BlobBatch {
- constructor() {
- this.batch = "batch";
- this.batchRequest = new InnerBatchRequest();
+var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
+};
+var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
+ if (kind === "m") throw new TypeError("Private method is not writable");
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
+};
+var _GoogleToken_instances, _GoogleToken_inFlightRequest, _GoogleToken_getTokenAsync, _GoogleToken_getTokenAsyncInner, _GoogleToken_ensureEmail, _GoogleToken_revokeTokenAsync, _GoogleToken_configure, _GoogleToken_requestToken;
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.GoogleToken = void 0;
+const fs = __nccwpck_require__(79896);
+const gaxios_1 = __nccwpck_require__(97003);
+const jws = __nccwpck_require__(33324);
+const path = __nccwpck_require__(16928);
+const util_1 = __nccwpck_require__(39023);
+const readFile = fs.readFile
+ ? (0, util_1.promisify)(fs.readFile)
+ : async () => {
+ // if running in the web-browser, fs.readFile may not have been shimmed.
+ throw new ErrorWithCode('use key rather than keyFile.', 'MISSING_CREDENTIALS');
+ };
+const GOOGLE_TOKEN_URL = 'https://www.googleapis.com/oauth2/v4/token';
+const GOOGLE_REVOKE_TOKEN_URL = 'https://accounts.google.com/o/oauth2/revoke?token=';
+class ErrorWithCode extends Error {
+ constructor(message, code) {
+ super(message);
+ this.code = code;
+ }
+}
+class GoogleToken {
+ get accessToken() {
+ return this.rawToken ? this.rawToken.access_token : undefined;
+ }
+ get idToken() {
+ return this.rawToken ? this.rawToken.id_token : undefined;
+ }
+ get tokenType() {
+ return this.rawToken ? this.rawToken.token_type : undefined;
+ }
+ get refreshToken() {
+ return this.rawToken ? this.rawToken.refresh_token : undefined;
}
/**
- * 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
+ * Create a GoogleToken.
+ *
+ * @param options Configuration object.
*/
- getMultiPartContentType() {
- return this.batchRequest.getMultipartContentType();
+ constructor(options) {
+ _GoogleToken_instances.add(this);
+ this.transporter = {
+ request: opts => (0, gaxios_1.request)(opts),
+ };
+ _GoogleToken_inFlightRequest.set(this, void 0);
+ __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_configure).call(this, options);
}
/**
- * Get assembled HTTP request body for sub requests.
- */
- getHttpRequestBody() {
- return this.batchRequest.getHttpRequestBody();
+ * Returns whether the token has expired.
+ *
+ * @return true if the token has expired, false otherwise.
+ */
+ hasExpired() {
+ const now = new Date().getTime();
+ if (this.rawToken && this.expiresAt) {
+ return now >= this.expiresAt;
+ }
+ else {
+ return true;
+ }
}
/**
- * Get sub requests that are added into the batch request.
+ * Returns whether the token will expire within eagerRefreshThresholdMillis
+ *
+ * @return true if the token will be expired within eagerRefreshThresholdMillis, false otherwise.
*/
- 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);
+ isTokenExpiring() {
+ var _a;
+ const now = new Date().getTime();
+ const eagerRefreshThresholdMillis = (_a = this.eagerRefreshThresholdMillis) !== null && _a !== void 0 ? _a : 0;
+ if (this.rawToken && this.expiresAt) {
+ return this.expiresAt <= now + eagerRefreshThresholdMillis;
}
- finally {
- await Mutex.unlock(this.batch);
+ else {
+ return true;
}
}
- setBatchType(batchType) {
- if (!this.batchType) {
- this.batchType = batchType;
+ getToken(callback, opts = {}) {
+ if (typeof callback === 'object') {
+ opts = callback;
+ callback = undefined;
}
- 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.`);
+ opts = Object.assign({
+ forceRefresh: false,
+ }, opts);
+ if (callback) {
+ const cb = callback;
+ __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsync).call(this, opts).then(t => cb(null, t), callback);
+ return;
}
+ return __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsync).call(this, opts);
}
- 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;
+ /**
+ * Given a keyFile, extract the key and client email if available
+ * @param keyFile Path to a json, pem, or p12 file that contains the key.
+ * @returns an object with privateKey and clientEmail properties
+ */
+ async getCredentials(keyFile) {
+ const ext = path.extname(keyFile);
+ switch (ext) {
+ case '.json': {
+ const key = await readFile(keyFile, 'utf8');
+ const body = JSON.parse(key);
+ const privateKey = body.private_key;
+ const clientEmail = body.client_email;
+ if (!privateKey || !clientEmail) {
+ throw new ErrorWithCode('private_key and client_email are required.', 'MISSING_CREDENTIALS');
+ }
+ return { privateKey, clientEmail };
+ }
+ case '.der':
+ case '.crt':
+ case '.pem': {
+ const privateKey = await readFile(keyFile, 'utf8');
+ return { privateKey };
+ }
+ case '.p12':
+ case '.pfx': {
+ throw new ErrorWithCode('*.p12 certificates are not supported after v6.1.2. ' +
+ 'Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.', 'UNKNOWN_CERTIFICATE_TYPE');
+ }
+ default:
+ throw new ErrorWithCode('Unknown certificate type. Type is determined based on file extension. ' +
+ 'Current supported extensions are *.json, and *.pem.', 'UNKNOWN_CERTIFICATE_TYPE');
}
- else {
- throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided.");
+ }
+ revokeToken(callback) {
+ if (callback) {
+ __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_revokeTokenAsync).call(this).then(() => callback(), callback);
+ return;
}
- if (!options) {
- options = {};
+ return __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_revokeTokenAsync).call(this);
+ }
+}
+exports.GoogleToken = GoogleToken;
+_GoogleToken_inFlightRequest = new WeakMap(), _GoogleToken_instances = new WeakSet(), _GoogleToken_getTokenAsync = async function _GoogleToken_getTokenAsync(opts) {
+ if (__classPrivateFieldGet(this, _GoogleToken_inFlightRequest, "f") && !opts.forceRefresh) {
+ return __classPrivateFieldGet(this, _GoogleToken_inFlightRequest, "f");
+ }
+ try {
+ return await (__classPrivateFieldSet(this, _GoogleToken_inFlightRequest, __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsyncInner).call(this, opts), "f"));
+ }
+ finally {
+ __classPrivateFieldSet(this, _GoogleToken_inFlightRequest, undefined, "f");
+ }
+}, _GoogleToken_getTokenAsyncInner = async function _GoogleToken_getTokenAsyncInner(opts) {
+ if (this.isTokenExpiring() === false && opts.forceRefresh === false) {
+ return Promise.resolve(this.rawToken);
+ }
+ if (!this.key && !this.keyFile) {
+ throw new Error('No key or keyFile set.');
+ }
+ if (!this.key && this.keyFile) {
+ const creds = await this.getCredentials(this.keyFile);
+ this.key = creds.privateKey;
+ this.iss = creds.clientEmail || this.iss;
+ if (!creds.clientEmail) {
+ __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_ensureEmail).call(this);
}
- 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);
- });
+ }
+ return __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_requestToken).call(this);
+}, _GoogleToken_ensureEmail = function _GoogleToken_ensureEmail() {
+ if (!this.iss) {
+ throw new ErrorWithCode('email is required.', 'MISSING_CREDENTIALS');
+ }
+}, _GoogleToken_revokeTokenAsync = async function _GoogleToken_revokeTokenAsync() {
+ if (!this.accessToken) {
+ throw new Error('No token to revoke.');
+ }
+ const url = GOOGLE_REVOKE_TOKEN_URL + this.accessToken;
+ await this.transporter.request({
+ url,
+ retry: true,
+ });
+ __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_configure).call(this, {
+ email: this.iss,
+ sub: this.sub,
+ key: this.key,
+ keyFile: this.keyFile,
+ scope: this.scope,
+ additionalClaims: this.additionalClaims,
+ });
+}, _GoogleToken_configure = function _GoogleToken_configure(options = {}) {
+ this.keyFile = options.keyFile;
+ this.key = options.key;
+ this.rawToken = undefined;
+ this.iss = options.email || options.iss;
+ this.sub = options.sub;
+ this.additionalClaims = options.additionalClaims;
+ if (typeof options.scope === 'object') {
+ this.scope = options.scope.join(' ');
+ }
+ else {
+ this.scope = options.scope;
+ }
+ this.eagerRefreshThresholdMillis = options.eagerRefreshThresholdMillis;
+ if (options.transporter) {
+ this.transporter = options.transporter;
+ }
+}, _GoogleToken_requestToken =
+/**
+ * Request the token from Google.
+ */
+async function _GoogleToken_requestToken() {
+ var _a, _b;
+ const iat = Math.floor(new Date().getTime() / 1000);
+ const additionalClaims = this.additionalClaims || {};
+ const payload = Object.assign({
+ iss: this.iss,
+ scope: this.scope,
+ aud: GOOGLE_TOKEN_URL,
+ exp: iat + 3600,
+ iat,
+ sub: this.sub,
+ }, additionalClaims);
+ const signedJWT = jws.sign({
+ header: { alg: 'RS256' },
+ payload,
+ secret: this.key,
+ });
+ try {
+ const r = await this.transporter.request({
+ method: 'POST',
+ url: GOOGLE_TOKEN_URL,
+ data: {
+ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
+ assertion: signedJWT,
+ },
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ responseType: 'json',
+ retryConfig: {
+ httpMethodsToRetry: ['POST'],
+ },
});
+ this.rawToken = r.data;
+ this.expiresAt =
+ r.data.expires_in === null || r.data.expires_in === undefined
+ ? undefined
+ : (iat + r.data.expires_in) * 1000;
+ return this.rawToken;
}
- 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 = {};
+ catch (e) {
+ this.rawToken = undefined;
+ this.tokenExpires = undefined;
+ const body = e.response && ((_a = e.response) === null || _a === void 0 ? void 0 : _a.data)
+ ? (_b = e.response) === null || _b === void 0 ? void 0 : _b.data
+ : {};
+ if (body.error) {
+ const desc = body.error_description
+ ? `: ${body.error_description}`
+ : '';
+ e.message = `${body.error}${desc}`;
}
- 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);
- });
- });
+ throw e;
}
-}
+};
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 23336:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var origSymbol = typeof Symbol !== 'undefined' && Symbol;
+var hasSymbolSham = __nccwpck_require__(61114);
+
+/** @type {import('.')} */
+module.exports = function hasNativeSymbols() {
+ if (typeof origSymbol !== 'function') { return false; }
+ if (typeof Symbol !== 'function') { return false; }
+ if (typeof origSymbol('foo') !== 'symbol') { return false; }
+ if (typeof Symbol('bar') !== 'symbol') { return false; }
+
+ return hasSymbolSham();
+};
+
+
+/***/ }),
+
+/***/ 61114:
+/***/ ((module) => {
+
+"use strict";
+
+
+/** @type {import('./shams')} */
+/* eslint complexity: [2, 18], max-statements: [2, 33] */
+module.exports = function hasSymbols() {
+ if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
+ if (typeof Symbol.iterator === 'symbol') { return true; }
+
+ /** @type {{ [k in symbol]?: unknown }} */
+ var obj = {};
+ var sym = Symbol('test');
+ var symObj = Object(sym);
+ if (typeof sym === 'string') { return false; }
+
+ if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
+ if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
+
+ // temp disabled per https://github.com/ljharb/object.assign/issues/17
+ // if (sym instanceof Symbol) { return false; }
+ // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
+ // if (!(symObj instanceof Symbol)) { return false; }
+
+ // if (typeof Symbol.prototype.toString !== 'function') { return false; }
+ // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
+
+ var symVal = 42;
+ obj[sym] = symVal;
+ for (var _ in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
+ if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
+
+ if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
+
+ var syms = Object.getOwnPropertySymbols(obj);
+ if (syms.length !== 1 || syms[0] !== sym) { return false; }
+
+ if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
+
+ if (typeof Object.getOwnPropertyDescriptor === 'function') {
+ // eslint-disable-next-line no-extra-parens
+ var descriptor = /** @type {PropertyDescriptor} */ (Object.getOwnPropertyDescriptor(obj, sym));
+ if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
+ }
+
+ return true;
+};
+
+
+/***/ }),
+
+/***/ 85479:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var hasSymbols = __nccwpck_require__(61114);
+
+/** @type {import('.')} */
+module.exports = function hasToStringTagShams() {
+ return hasSymbols() && !!Symbol.toStringTag;
+};
+
+
+/***/ }),
+
+/***/ 54076:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var call = Function.prototype.call;
+var $hasOwn = Object.prototype.hasOwnProperty;
+var bind = __nccwpck_require__(37564);
+
+/** @type {import('.')} */
+module.exports = bind.call(call, $hasOwn);
+
+
+/***/ }),
+
+/***/ 81970:
+/***/ (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.HttpProxyAgent = void 0;
+const net = __importStar(__nccwpck_require__(69278));
+const tls = __importStar(__nccwpck_require__(64756));
+const debug_1 = __importDefault(__nccwpck_require__(2830));
+const events_1 = __nccwpck_require__(24434);
+const agent_base_1 = __nccwpck_require__(98894);
+const url_1 = __nccwpck_require__(87016);
+const debug = (0, debug_1.default)('http-proxy-agent');
/**
- * Inner batch request class which is responsible for assembling and serializing sub requests.
- * See https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#request-body for how requests are assembled.
+ * The `HttpProxyAgent` implements an HTTP Agent subclass that connects
+ * to the specified "HTTP proxy server" in order to proxy HTTP requests.
*/
-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();
+class HttpProxyAgent extends agent_base_1.Agent {
+ constructor(proxy, opts) {
+ super(opts);
+ this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy;
+ this.proxyHeaders = opts?.headers ?? {};
+ debug('Creating new HttpProxyAgent instance: %o', this.proxy.href);
+ // Trim off the brackets from IPv6 addresses
+ const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, '');
+ const port = this.proxy.port
+ ? parseInt(this.proxy.port, 10)
+ : this.proxy.protocol === 'https:'
+ ? 443
+ : 80;
+ this.connectOpts = {
+ ...(opts ? omit(opts, 'headers') : null),
+ host,
+ port,
+ };
}
- /**
- * 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" });
+ addRequest(req, opts) {
+ req._header = null;
+ this.setRequestProps(req, opts);
+ // @ts-expect-error `addRequest()` isn't defined in `@types/node`
+ super.addRequest(req, opts);
+ }
+ setRequestProps(req, opts) {
+ const { proxy } = this;
+ const protocol = opts.secureEndpoint ? 'https:' : 'http:';
+ const hostname = req.getHeader('host') || 'localhost';
+ const base = `${protocol}//${hostname}`;
+ const url = new url_1.URL(req.path, base);
+ if (opts.port !== 80) {
+ url.port = String(opts.port);
}
- else if (credential instanceof StorageSharedKeyCredential) {
- corePipeline.addPolicy(storageSharedKeyCredentialPolicy({
- accountName: credential.accountName,
- accountKey: credential.accountKey,
- }), { phase: "Sign" });
+ // Change the `http.ClientRequest` instance's "path" field
+ // to the absolute path of the URL that will be requested.
+ req.path = String(url);
+ // Inject the `Proxy-Authorization` header if necessary.
+ const headers = typeof this.proxyHeaders === 'function'
+ ? this.proxyHeaders()
+ : { ...this.proxyHeaders };
+ if (proxy.username || proxy.password) {
+ const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
+ headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
}
- 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}`;
+ if (!headers['Proxy-Connection']) {
+ headers['Proxy-Connection'] = this.keepAlive
+ ? 'Keep-Alive'
+ : 'close';
+ }
+ for (const name of Object.keys(headers)) {
+ const value = headers[name];
+ if (value) {
+ req.setHeader(name, value);
+ }
}
- 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`);
+ async connect(req, opts) {
+ req._header = null;
+ if (!req.path.includes('://')) {
+ this.setRequestProps(req, opts);
}
- // 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}'`);
+ // At this point, the http ClientRequest's internal `_header` field
+ // might have already been set. If this is the case then we'll need
+ // to re-generate the string since we just changed the `req.path`.
+ let first;
+ let endOfHeaders;
+ debug('Regenerating stored HTTP header string for request');
+ req._implicitHeader();
+ if (req.outputData && req.outputData.length > 0) {
+ debug('Patching connection write() output buffer with updated header');
+ first = req.outputData[0].data;
+ endOfHeaders = first.indexOf('\r\n\r\n') + 4;
+ req.outputData[0].data =
+ req._header + first.substring(endOfHeaders);
+ debug('Output buffer: %o', req.outputData[0].data);
}
+ // Create a socket connection to the proxy server.
+ let socket;
+ if (this.proxy.protocol === 'https:') {
+ debug('Creating `tls.Socket`: %o', this.connectOpts);
+ socket = tls.connect(this.connectOpts);
+ }
+ else {
+ debug('Creating `net.Socket`: %o', this.connectOpts);
+ socket = net.connect(this.connectOpts);
+ }
+ // Wait for the socket's `connect` event, so that this `callback()`
+ // function throws instead of the `http` request machinery. This is
+ // important for i.e. `PacProxyAgent` which determines a failed proxy
+ // connection via the `callback()` function throwing.
+ await (0, events_1.once)(socket, 'connect');
+ return socket;
}
- 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);
- },
- };
+HttpProxyAgent.protocols = ['http', 'https'];
+exports.HttpProxyAgent = HttpProxyAgent;
+function omit(obj, ...keys) {
+ const ret = {};
+ let key;
+ for (key in obj) {
+ if (!keys.includes(key)) {
+ ret[key] = obj[key];
+ }
+ }
+ return ret;
}
+//# sourceMappingURL=index.js.map
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
+/***/ }),
+
+/***/ 3669:
+/***/ (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.HttpsProxyAgent = void 0;
+const net = __importStar(__nccwpck_require__(69278));
+const tls = __importStar(__nccwpck_require__(64756));
+const assert_1 = __importDefault(__nccwpck_require__(42613));
+const debug_1 = __importDefault(__nccwpck_require__(2830));
+const agent_base_1 = __nccwpck_require__(98894);
+const url_1 = __nccwpck_require__(87016);
+const parse_proxy_response_1 = __nccwpck_require__(37943);
+const debug = (0, debug_1.default)('https-proxy-agent');
+const setServernameFromNonIpHost = (options) => {
+ if (options.servername === undefined &&
+ options.host &&
+ !net.isIP(options.host)) {
+ return {
+ ...options,
+ servername: options.host,
+ };
+ }
+ return options;
+};
/**
- * A BlobBatchClient allows you to make batched requests to the Azure Storage Blob service.
+ * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to
+ * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests.
*
- * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch
+ * Outgoing HTTP requests are first tunneled through the proxy server using the
+ * `CONNECT` HTTP request method to establish a connection to the proxy server,
+ * and then the proxy server connects to the destination target and issues the
+ * HTTP request from the proxy server.
+ *
+ * `https:` requests have their socket connection upgraded to TLS once
+ * the connection to the proxy server has been established.
*/
-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;
+class HttpsProxyAgent extends agent_base_1.Agent {
+ constructor(proxy, opts) {
+ super(opts);
+ this.options = { path: undefined };
+ this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy;
+ this.proxyHeaders = opts?.headers ?? {};
+ debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href);
+ // Trim off the brackets from IPv6 addresses
+ const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, '');
+ const port = this.proxy.port
+ ? parseInt(this.proxy.port, 10)
+ : this.proxy.protocol === 'https:'
+ ? 443
+ : 80;
+ this.connectOpts = {
+ // Attempt to negotiate http/1.1 for proxy servers that support http/2
+ ALPNProtocols: ['http/1.1'],
+ ...(opts ? omit(opts, 'headers') : null),
+ host,
+ port,
+ };
+ }
+ /**
+ * Called when the node-core HTTP client library is creating a
+ * new HTTP request.
+ */
+ async connect(req, opts) {
+ const { proxy } = this;
+ if (!opts.host) {
+ throw new TypeError('No "host" provided');
}
- else if (!credentialOrPipeline) {
- // no credential provided
- pipeline = newPipeline(new AnonymousCredential(), options);
+ // Create a socket connection to the proxy server.
+ let socket;
+ if (proxy.protocol === 'https:') {
+ debug('Creating `tls.Socket`: %o', this.connectOpts);
+ socket = tls.connect(setServernameFromNonIpHost(this.connectOpts));
}
else {
- pipeline = newPipeline(credentialOrPipeline, options);
+ debug('Creating `net.Socket`: %o', this.connectOpts);
+ socket = net.connect(this.connectOpts);
}
- const storageClientContext = new StorageContextClient(url, getCoreClientOptions(pipeline));
- const path = getURLPath(url);
- if (path && path !== "/") {
- // Container scoped.
- this.serviceOrContainerContext = storageClientContext.container;
+ const headers = typeof this.proxyHeaders === 'function'
+ ? this.proxyHeaders()
+ : { ...this.proxyHeaders };
+ const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
+ let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`;
+ // Inject the `Proxy-Authorization` header if necessary.
+ if (proxy.username || proxy.password) {
+ const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
+ headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
}
- else {
- this.serviceOrContainerContext = storageClientContext.service;
+ headers.Host = `${host}:${opts.port}`;
+ if (!headers['Proxy-Connection']) {
+ headers['Proxy-Connection'] = this.keepAlive
+ ? 'Keep-Alive'
+ : 'close';
}
- }
- /**
- * 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);
- }
+ for (const name of Object.keys(headers)) {
+ payload += `${name}: ${headers[name]}\r\n`;
}
- 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);
+ const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket);
+ socket.write(`${payload}\r\n`);
+ const { connect, buffered } = await proxyResponsePromise;
+ req.emit('proxyConnect', connect);
+ this.emit('proxyConnect', connect, req);
+ if (connect.statusCode === 200) {
+ req.once('socket', resume);
+ if (opts.secureEndpoint) {
+ // The proxy is connecting to a TLS server, so upgrade
+ // this socket connection to a TLS connection.
+ debug('Upgrading socket connection to TLS');
+ return tls.connect({
+ ...omit(setServernameFromNonIpHost(opts), 'host', 'path', 'port'),
+ socket,
+ });
}
+ return socket;
}
- return this.submitBatch(batch);
+ // Some other status code that's not 200... need to re-play the HTTP
+ // header "data" events onto the socket once the HTTP machinery is
+ // attached so that the node core `http` can parse and handle the
+ // error status code.
+ // Close the original socket, and a new "fake" socket is returned
+ // instead, so that the proxy doesn't get the HTTP request
+ // written to it (which may contain `Authorization` headers or other
+ // sensitive data).
+ //
+ // See: https://hackerone.com/reports/541502
+ socket.destroy();
+ const fakeSocket = new net.Socket({ writable: false });
+ fakeSocket.readable = true;
+ // Need to wait for the "socket" event to re-play the "data" events.
+ req.once('socket', (s) => {
+ debug('Replaying proxy buffer for failed request');
+ (0, assert_1.default)(s.listenerCount('data') > 0);
+ // Replay the "buffered" Buffer onto the fake `socket`, since at
+ // this point the HTTP module machinery has been hooked up for
+ // the user.
+ s.push(buffered);
+ s.push(null);
+ });
+ return fakeSocket;
}
- /**
- * 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://docs.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.");
+}
+HttpsProxyAgent.protocols = ['http', 'https'];
+exports.HttpsProxyAgent = HttpsProxyAgent;
+function resume(socket) {
+ socket.resume();
+}
+function omit(obj, ...keys) {
+ const ret = {};
+ let key;
+ for (key in obj) {
+ if (!keys.includes(key)) {
+ ret[key] = obj[key];
}
- 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;
- });
}
+ return ret;
}
+//# sourceMappingURL=index.js.map
-/**
- * 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;
+/***/ }),
+
+/***/ 37943:
+/***/ (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.parseProxyResponse = void 0;
+const debug_1 = __importDefault(__nccwpck_require__(2830));
+const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response');
+function parseProxyResponse(socket) {
+ return new Promise((resolve, reject) => {
+ // we need to buffer any HTTP traffic that happens with the proxy before we get
+ // the CONNECT response, so that if the response is anything other than an "200"
+ // response code, then we can re-play the "data" events on the socket once the
+ // HTTP parser is hooked up...
+ let buffersLength = 0;
+ const buffers = [];
+ function read() {
+ const b = socket.read();
+ if (b)
+ ondata(b);
+ else
+ socket.once('readable', read);
}
- 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);
+ function cleanup() {
+ socket.removeListener('end', onend);
+ socket.removeListener('error', onerror);
+ socket.removeListener('readable', read);
}
- 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);
+ function onend() {
+ cleanup();
+ debug('onend');
+ reject(new Error('Proxy connection ended before receiving CONNECT response'));
}
- 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);
+ function onerror(err) {
+ cleanup();
+ debug('onerror %o', err);
+ reject(err);
+ }
+ function ondata(b) {
+ buffers.push(b);
+ buffersLength += b.length;
+ const buffered = Buffer.concat(buffers, buffersLength);
+ const endOfHeaders = buffered.indexOf('\r\n\r\n');
+ if (endOfHeaders === -1) {
+ // keep buffering
+ debug('have not received end of HTTP headers yet...');
+ read();
+ return;
+ }
+ const headerParts = buffered
+ .slice(0, endOfHeaders)
+ .toString('ascii')
+ .split('\r\n');
+ const firstLine = headerParts.shift();
+ if (!firstLine) {
+ socket.destroy();
+ return reject(new Error('No header received from proxy CONNECT response'));
+ }
+ const firstLineParts = firstLine.split(' ');
+ const statusCode = +firstLineParts[1];
+ const statusText = firstLineParts.slice(2).join(' ');
+ const headers = {};
+ for (const header of headerParts) {
+ if (!header)
+ continue;
+ const firstColon = header.indexOf(':');
+ if (firstColon === -1) {
+ socket.destroy();
+ return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`));
+ }
+ const key = header.slice(0, firstColon).toLowerCase();
+ const value = header.slice(firstColon + 1).trimStart();
+ const current = headers[key];
+ if (typeof current === 'string') {
+ headers[key] = [current, value];
+ }
+ else if (Array.isArray(current)) {
+ current.push(value);
}
else {
- throw new Error("Account connection string is only supported in Node.js environment");
+ headers[key] = value;
}
}
- 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");
- }
+ debug('got proxy server response: %o %o', firstLine, headers);
+ cleanup();
+ resolve({
+ connect: {
+ statusCode,
+ statusText,
+ headers,
+ },
+ buffered,
+ });
}
- else {
- throw new Error("Expecting non-empty strings for containerName parameter");
+ socket.on('error', onerror);
+ socket.on('end', onend);
+ read();
+ });
+}
+exports.parseProxyResponse = parseProxyResponse;
+//# sourceMappingURL=parse-proxy-response.js.map
+
+/***/ }),
+
+/***/ 39598:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+try {
+ var util = __nccwpck_require__(39023);
+ /* istanbul ignore next */
+ if (typeof util.inherits !== 'function') throw '';
+ module.exports = util.inherits;
+} catch (e) {
+ /* istanbul ignore next */
+ module.exports = __nccwpck_require__(26589);
+}
+
+
+/***/ }),
+
+/***/ 26589:
+/***/ ((module) => {
+
+if (typeof Object.create === 'function') {
+ // implementation from standard node.js 'util' module
+ module.exports = function inherits(ctor, superCtor) {
+ if (superCtor) {
+ ctor.super_ = superCtor
+ ctor.prototype = Object.create(superCtor.prototype, {
+ constructor: {
+ value: ctor,
+ enumerable: false,
+ writable: true,
+ configurable: true
}
- 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://docs.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));
- });
+ };
+} else {
+ // old school shim for old browsers
+ module.exports = function inherits(ctor, superCtor) {
+ if (superCtor) {
+ ctor.super_ = superCtor
+ var TempCtor = function () {}
+ TempCtor.prototype = superCtor.prototype
+ ctor.prototype = new TempCtor()
+ ctor.prototype.constructor = ctor
}
- /**
- * Creates a new container under the specified account. If the container with
- * the same name already exists, it is not changed.
- * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container
- * 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;
- }
- }
- });
+ }
+}
+
+
+/***/ }),
+
+/***/ 96543:
+/***/ ((module) => {
+
+"use strict";
+
+
+const isStream = stream =>
+ stream !== null &&
+ typeof stream === 'object' &&
+ typeof stream.pipe === 'function';
+
+isStream.writable = stream =>
+ isStream(stream) &&
+ stream.writable !== false &&
+ typeof stream._write === 'function' &&
+ typeof stream._writableState === 'object';
+
+isStream.readable = stream =>
+ isStream(stream) &&
+ stream.readable !== false &&
+ typeof stream._read === 'function' &&
+ typeof stream._readableState === 'object';
+
+isStream.duplex = stream =>
+ isStream.writable(stream) &&
+ isStream.readable(stream);
+
+isStream.transform = stream =>
+ isStream.duplex(stream) &&
+ typeof stream._transform === 'function';
+
+module.exports = isStream;
+
+
+/***/ }),
+
+/***/ 14826:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+var json_stringify = (__nccwpck_require__(93651).stringify);
+var json_parse = __nccwpck_require__(3197);
+
+module.exports = function(options) {
+ return {
+ parse: json_parse(options),
+ stringify: json_stringify
}
- /**
- * 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;
+};
+//create the default method members with no options applied for backwards compatibility
+module.exports.parse = json_parse();
+module.exports.stringify = json_stringify;
+
+
+/***/ }),
+
+/***/ 3197:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+var BigNumber = null;
+
+// regexpxs extracted from
+// (c) BSD-3-Clause
+// https://github.com/fastify/secure-json-parse/graphs/contributors and https://github.com/hapijs/bourne/graphs/contributors
+
+const suspectProtoRx = /(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/;
+const suspectConstructorRx = /(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/;
+
+/*
+ json_parse.js
+ 2012-06-20
+
+ Public Domain.
+
+ NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+
+ This file creates a json_parse function.
+ During create you can (optionally) specify some behavioural switches
+
+ require('json-bigint')(options)
+
+ The optional options parameter holds switches that drive certain
+ aspects of the parsing process:
+ * options.strict = true will warn about duplicate-key usage in the json.
+ The default (strict = false) will silently ignore those and overwrite
+ values for keys that are in duplicate use.
+
+ The resulting function follows this signature:
+ json_parse(text, reviver)
+ This method parses a JSON text to produce an object or array.
+ It can throw a SyntaxError exception.
+
+ The optional reviver parameter is a function that can filter and
+ transform the results. It receives each of the keys and values,
+ and its return value is used instead of the original value.
+ If it returns what it received, then the structure is not modified.
+ If it returns undefined then the member is deleted.
+
+ Example:
+
+ // Parse the text. Values that look like ISO date strings will
+ // be converted to Date objects.
+
+ myData = json_parse(text, function (key, value) {
+ var a;
+ if (typeof value === 'string') {
+ a =
+/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
+ if (a) {
+ return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+ +a[5], +a[6]));
+ }
}
- 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);
+ return value;
+ });
+
+ This is a reference implementation. You are free to copy, modify, or
+ redistribute.
+
+ This code should be minified before deployment.
+ See http://javascript.crockford.com/jsmin.html
+
+ USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
+ NOT CONTROL.
+*/
+
+/*members "", "\"", "\/", "\\", at, b, call, charAt, f, fromCharCode,
+ hasOwnProperty, message, n, name, prototype, push, r, t, text
+*/
+
+var json_parse = function (options) {
+ 'use strict';
+
+ // This is a function that can parse a JSON text, producing a JavaScript
+ // data structure. It is a simple, recursive descent parser. It does not use
+ // eval or regular expressions, so it can be used as a model for implementing
+ // a JSON parser in other languages.
+
+ // We are defining the function inside of another function to avoid creating
+ // global variables.
+
+ // Default options one can override by passing options to the parse()
+ var _options = {
+ strict: false, // not being strict means do not generate syntax errors for "duplicate key"
+ storeAsString: false, // toggles whether the values should be stored as BigNumber (default) or a string
+ alwaysParseAsBig: false, // toggles whether all numbers should be Big
+ useNativeBigInt: false, // toggles whether to use native BigInt instead of bignumber.js
+ protoAction: 'error',
+ constructorAction: 'error',
+ };
+
+ // If there are options, then use them to override the default _options
+ if (options !== undefined && options !== null) {
+ if (options.strict === true) {
+ _options.strict = true;
}
- /**
- * Creates an {@link AppendBlobClient}
- *
- * @param blobName - An append blob name
- */
- getAppendBlobClient(blobName) {
- return new AppendBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline);
+ if (options.storeAsString === true) {
+ _options.storeAsString = true;
}
- /**
- * 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);
+ _options.alwaysParseAsBig =
+ options.alwaysParseAsBig === true ? options.alwaysParseAsBig : false;
+ _options.useNativeBigInt =
+ options.useNativeBigInt === true ? options.useNativeBigInt : false;
+
+ if (typeof options.constructorAction !== 'undefined') {
+ if (
+ options.constructorAction === 'error' ||
+ options.constructorAction === 'ignore' ||
+ options.constructorAction === 'preserve'
+ ) {
+ _options.constructorAction = options.constructorAction;
+ } else {
+ throw new Error(
+ `Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${options.constructorAction}`
+ );
+ }
}
- /**
- * Creates a {@link PageBlobClient}
- *
- * @param blobName - A page blob name
- */
- getPageBlobClient(blobName) {
- return new PageBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline);
+
+ if (typeof options.protoAction !== 'undefined') {
+ if (
+ options.protoAction === 'error' ||
+ options.protoAction === 'ignore' ||
+ options.protoAction === 'preserve'
+ ) {
+ _options.protoAction = options.protoAction;
+ } else {
+ throw new Error(
+ `Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${options.protoAction}`
+ );
+ }
}
- /**
- * Returns all user-defined metadata and system properties for the specified
- * container. The data returned does not include the container's list of blobs.
- * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-properties
- *
- * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if
- * they originally contained uppercase characters. This differs from the metadata keys returned by
- * the `listContainers` method of {@link BlobServiceClient} using the `includeMetadata` option, which
- * will retain their original casing.
- *
- * @param options - Options to Container Get Properties operation.
- */
- async getProperties(options = {}) {
- if (!options.conditions) {
- options.conditions = {};
+ }
+
+ var at, // The index of the current character
+ ch, // The current character
+ escapee = {
+ '"': '"',
+ '\\': '\\',
+ '/': '/',
+ b: '\b',
+ f: '\f',
+ n: '\n',
+ r: '\r',
+ t: '\t',
+ },
+ text,
+ error = function (m) {
+ // Call error when something is wrong.
+
+ throw {
+ name: 'SyntaxError',
+ message: m,
+ at: at,
+ text: text,
+ };
+ },
+ next = function (c) {
+ // If a c parameter is provided, verify that it matches the current character.
+
+ if (c && c !== ch) {
+ error("Expected '" + c + "' instead of '" + ch + "'");
+ }
+
+ // Get the next character. When there are no more characters,
+ // return the empty string.
+
+ ch = text.charAt(at);
+ at += 1;
+ return ch;
+ },
+ number = function () {
+ // Parse a number value.
+
+ var number,
+ string = '';
+
+ if (ch === '-') {
+ string = '-';
+ next('-');
+ }
+ while (ch >= '0' && ch <= '9') {
+ string += ch;
+ next();
+ }
+ if (ch === '.') {
+ string += '.';
+ while (next() && ch >= '0' && ch <= '9') {
+ string += ch;
}
- 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://docs.microsoft.com/en-us/rest/api/storageservices/delete-container
- *
- * @param options - Options to Container Delete operation.
- */
- async delete(options = {}) {
- if (!options.conditions) {
- options.conditions = {};
+ }
+ if (ch === 'e' || ch === 'E') {
+ string += ch;
+ next();
+ if (ch === '-' || ch === '+') {
+ string += ch;
+ next();
}
- 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://docs.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 });
+ while (ch >= '0' && ch <= '9') {
+ string += ch;
+ next();
+ }
+ }
+ number = +string;
+ if (!isFinite(number)) {
+ error('Bad number');
+ } else {
+ if (BigNumber == null) BigNumber = __nccwpck_require__(51259);
+ //if (number > 9007199254740992 || number < -9007199254740992)
+ // Bignumber has stricter check: everything with length > 15 digits disallowed
+ if (string.length > 15)
+ return _options.storeAsString
+ ? string
+ : _options.useNativeBigInt
+ ? BigInt(string)
+ : new BigNumber(string);
+ else
+ return !_options.alwaysParseAsBig
+ ? number
+ : _options.useNativeBigInt
+ ? BigInt(number)
+ : new BigNumber(number);
+ }
+ },
+ string = function () {
+ // Parse a string value.
+
+ var hex,
+ i,
+ string = '',
+ uffff;
+
+ // When parsing for string values, we must look for " and \ characters.
+
+ if (ch === '"') {
+ var startAt = at;
+ while (next()) {
+ if (ch === '"') {
+ if (at - 1 > startAt) string += text.substring(startAt, at - 1);
+ next();
+ return string;
+ }
+ if (ch === '\\') {
+ if (at - 1 > startAt) string += text.substring(startAt, at - 1);
+ next();
+ if (ch === 'u') {
+ uffff = 0;
+ for (i = 0; i < 4; i += 1) {
+ hex = parseInt(next(), 16);
+ if (!isFinite(hex)) {
+ break;
}
- throw e;
+ uffff = uffff * 16 + hex;
+ }
+ string += String.fromCharCode(uffff);
+ } else if (typeof escapee[ch] === 'string') {
+ string += escapee[ch];
+ } else {
+ break;
}
- });
- }
- /**
- * Sets one or more user-defined name-value pairs for the specified container.
- *
- * If no option provided, or no metadata defined in the parameter, the container
- * metadata will be removed.
- *
- * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-metadata
- *
- * @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 = {};
+ startAt = at;
+ }
}
- if (options.conditions.ifUnmodifiedSince) {
- throw new RangeError("the IfUnmodifiedSince must have their default values because they are ignored by the blob service");
+ }
+ error('Bad string');
+ },
+ white = function () {
+ // Skip whitespace.
+
+ while (ch && ch <= ' ') {
+ next();
+ }
+ },
+ word = function () {
+ // true, false, or null.
+
+ switch (ch) {
+ case 't':
+ next('t');
+ next('r');
+ next('u');
+ next('e');
+ return true;
+ case 'f':
+ next('f');
+ next('a');
+ next('l');
+ next('s');
+ next('e');
+ return false;
+ case 'n':
+ next('n');
+ next('u');
+ next('l');
+ next('l');
+ return null;
+ }
+ error("Unexpected '" + ch + "'");
+ },
+ value, // Place holder for the value function.
+ array = function () {
+ // Parse an array value.
+
+ var array = [];
+
+ if (ch === '[') {
+ next('[');
+ white();
+ if (ch === ']') {
+ next(']');
+ return array; // empty array
+ }
+ while (ch) {
+ array.push(value());
+ white();
+ if (ch === ']') {
+ next(']');
+ return array;
+ }
+ next(',');
+ white();
}
- 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://docs.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 = {};
+ }
+ error('Bad array');
+ },
+ object = function () {
+ // Parse an object value.
+
+ var key,
+ object = Object.create(null);
+
+ if (ch === '{') {
+ next('{');
+ white();
+ if (ch === '}') {
+ next('}');
+ return object; // empty object
+ }
+ while (ch) {
+ key = string();
+ white();
+ next(':');
+ if (
+ _options.strict === true &&
+ Object.hasOwnProperty.call(object, key)
+ ) {
+ error('Duplicate key "' + key + '"');
+ }
+
+ if (suspectProtoRx.test(key) === true) {
+ if (_options.protoAction === 'error') {
+ error('Object contains forbidden prototype property');
+ } else if (_options.protoAction === 'ignore') {
+ value();
+ } else {
+ object[key] = value();
+ }
+ } else if (suspectConstructorRx.test(key) === true) {
+ if (_options.constructorAction === 'error') {
+ error('Object contains forbidden constructor property');
+ } else if (_options.constructorAction === 'ignore') {
+ value();
+ } else {
+ object[key] = value();
+ }
+ } else {
+ object[key] = value();
+ }
+
+ white();
+ if (ch === '}') {
+ next('}');
+ return object;
+ }
+ next(',');
+ white();
}
- 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);
+ }
+ error('Bad object');
+ };
+
+ value = function () {
+ // Parse a JSON value. It could be an object, an array, a string, a number,
+ // or a word.
+
+ white();
+ switch (ch) {
+ case '{':
+ return object();
+ case '[':
+ return array();
+ case '"':
+ return string();
+ case '-':
+ return number();
+ default:
+ return ch >= '0' && ch <= '9' ? number() : word();
+ }
+ };
+
+ // Return the json_parse function. It will have access to all of the above
+ // functions and variables.
+
+ return function (source, reviver) {
+ var result;
+
+ text = source + '';
+ at = 0;
+ ch = ' ';
+ result = value();
+ white();
+ if (ch) {
+ error('Syntax error');
+ }
+
+ // If there is a reviver function, we recursively walk the new structure,
+ // passing each name/value pair to the reviver function for possible
+ // transformation, starting with a temporary root object that holds the result
+ // in an empty key. If there is not a reviver function, we simply return the
+ // result.
+
+ return typeof reviver === 'function'
+ ? (function walk(holder, key) {
+ var k,
+ v,
+ value = holder[key];
+ if (value && typeof value === 'object') {
+ Object.keys(value).forEach(function (k) {
+ v = walk(value, k);
+ if (v !== undefined) {
+ value[k] = v;
+ } else {
+ delete value[k];
+ }
+ });
+ }
+ return reviver.call(holder, key, value);
+ })({ '': result }, '')
+ : result;
+ };
+};
+
+module.exports = json_parse;
+
+
+/***/ }),
+
+/***/ 93651:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+var BigNumber = __nccwpck_require__(51259);
+
+/*
+ json2.js
+ 2013-05-26
+
+ Public Domain.
+
+ NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+
+ See http://www.JSON.org/js.html
+
+
+ This code should be minified before deployment.
+ See http://javascript.crockford.com/jsmin.html
+
+ USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
+ NOT CONTROL.
+
+
+ This file creates a global JSON object containing two methods: stringify
+ and parse.
+
+ JSON.stringify(value, replacer, space)
+ value any JavaScript value, usually an object or array.
+
+ replacer an optional parameter that determines how object
+ values are stringified for objects. It can be a
+ function or an array of strings.
+
+ space an optional parameter that specifies the indentation
+ of nested structures. If it is omitted, the text will
+ be packed without extra whitespace. If it is a number,
+ it will specify the number of spaces to indent at each
+ level. If it is a string (such as '\t' or ' '),
+ it contains the characters used to indent at each level.
+
+ This method produces a JSON text from a JavaScript value.
+
+ When an object value is found, if the object contains a toJSON
+ method, its toJSON method will be called and the result will be
+ stringified. A toJSON method does not serialize: it returns the
+ value represented by the name/value pair that should be serialized,
+ or undefined if nothing should be serialized. The toJSON method
+ will be passed the key associated with the value, and this will be
+ bound to the value
+
+ For example, this would serialize Dates as ISO strings.
+
+ Date.prototype.toJSON = function (key) {
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
}
- if (identifier.accessPolicy.startsOn) {
- accessPolicy.startsOn = new Date(identifier.accessPolicy.startsOn);
+
+ return this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z';
+ };
+
+ You can provide an optional replacer method. It will be passed the
+ key and value of each member, with this bound to the containing
+ object. The value that is returned from your method will be
+ serialized. If your method returns undefined, then the member will
+ be excluded from the serialization.
+
+ If the replacer parameter is an array of strings, then it will be
+ used to select the members to be serialized. It filters the results
+ such that only members with keys listed in the replacer array are
+ stringified.
+
+ Values that do not have JSON representations, such as undefined or
+ functions, will not be serialized. Such values in objects will be
+ dropped; in arrays they will be replaced with null. You can use
+ a replacer function to replace those with JSON values.
+ JSON.stringify(undefined) returns undefined.
+
+ The optional space parameter produces a stringification of the
+ value that is filled with line breaks and indentation to make it
+ easier to read.
+
+ If the space parameter is a non-empty string, then that string will
+ be used for indentation. If the space parameter is a number, then
+ the indentation will be that many spaces.
+
+ Example:
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}]);
+ // text is '["e",{"pluribus":"unum"}]'
+
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
+ // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
+
+ text = JSON.stringify([new Date()], function (key, value) {
+ return this[key] instanceof Date ?
+ 'Date(' + this[key] + ')' : value;
+ });
+ // text is '["Date(---current time---)"]'
+
+
+ JSON.parse(text, reviver)
+ This method parses a JSON text to produce an object or array.
+ It can throw a SyntaxError exception.
+
+ The optional reviver parameter is a function that can filter and
+ transform the results. It receives each of the keys and values,
+ and its return value is used instead of the original value.
+ If it returns what it received, then the structure is not modified.
+ If it returns undefined then the member is deleted.
+
+ Example:
+
+ // Parse the text. Values that look like ISO date strings will
+ // be converted to Date objects.
+
+ myData = JSON.parse(text, function (key, value) {
+ var a;
+ if (typeof value === 'string') {
+ a =
+/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
+ if (a) {
+ return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+ +a[5], +a[6]));
}
}
- 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://docs.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);
+ return value;
+ });
+
+ myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
+ var d;
+ if (typeof value === 'string' &&
+ value.slice(0, 5) === 'Date(' &&
+ value.slice(-1) === ')') {
+ d = new Date(value.slice(5, -1));
+ if (d) {
+ return d;
+ }
+ }
+ return value;
+ });
+
+
+ This is a reference implementation. You are free to copy, modify, or
+ redistribute.
+*/
+
+/*jslint evil: true, regexp: true */
+
+/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
+ call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
+ getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
+ lastIndex, length, parse, prototype, push, replace, slice, stringify,
+ test, toJSON, toString, valueOf
+*/
+
+
+// Create a JSON object only if one does not already exist. We create the
+// methods in a closure to avoid creating global variables.
+
+var JSON = module.exports;
+
+(function () {
+ 'use strict';
+
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
}
- /**
- * Creates a new block blob, or updates the content of an existing block blob.
- *
- * Updating an existing block blob overwrites any existing metadata on the blob.
- * Partial updates are not supported; the content of the existing blob is
- * overwritten with the new content. To perform a partial update of a block blob's,
- * use {@link BlockBlobClient.stageBlock} and {@link BlockBlobClient.commitBlockList}.
- *
- * This is a non-parallel uploading method, please use {@link BlockBlobClient.uploadFile},
- * {@link BlockBlobClient.uploadStream} or {@link BlockBlobClient.uploadBrowserData} for better
- * performance with concurrency uploading.
- *
- * @see https://docs.microsoft.com/rest/api/storageservices/put-blob
- *
- * @param 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,
- };
- });
+
+ var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ gap,
+ indent,
+ meta = { // table of character substitutions
+ '\b': '\\b',
+ '\t': '\\t',
+ '\n': '\\n',
+ '\f': '\\f',
+ '\r': '\\r',
+ '"' : '\\"',
+ '\\': '\\\\'
+ },
+ rep;
+
+
+ function quote(string) {
+
+// If the string contains no control characters, no quote characters, and no
+// backslash characters, then we can safely slap some quotes around it.
+// Otherwise we must also replace the offending characters with safe escape
+// sequences.
+
+ escapable.lastIndex = 0;
+ return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
+ var c = meta[a];
+ return typeof c === 'string'
+ ? c
+ : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ }) + '"' : '"' + string + '"';
}
- /**
- * Marks the specified blob or snapshot for deletion. The blob is later deleted
- * during garbage collection. Note that in order to delete a blob, you must delete
- * all of its snapshots. You can delete both at the same time with the Delete
- * Blob operation.
- * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob
- *
- * @param 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);
+
+
+ function str(key, holder) {
+
+// Produce a string from holder[key].
+
+ var i, // The loop counter.
+ k, // The member key.
+ v, // The member value.
+ length,
+ mind = gap,
+ partial,
+ value = holder[key],
+ isBigNumber = value != null && (value instanceof BigNumber || BigNumber.isBigNumber(value));
+
+// If the value has a toJSON method, call it to obtain a replacement value.
+
+ if (value && typeof value === 'object' &&
+ typeof value.toJSON === 'function') {
+ value = value.toJSON(key);
+ }
+
+// If we were called with a replacer function, then call the replacer to
+// obtain a replacement value.
+
+ if (typeof rep === 'function') {
+ value = rep.call(holder, key, value);
+ }
+
+// What happens next depends on the value's type.
+
+ switch (typeof value) {
+ case 'string':
+ if (isBigNumber) {
+ return value;
+ } else {
+ return quote(value);
}
- 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://docs.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://docs.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);
+
+ case 'number':
+
+// JSON numbers must be finite. Encode non-finite numbers as null.
+
+ return isFinite(value) ? String(value) : 'null';
+
+ case 'boolean':
+ case 'null':
+ case 'bigint':
+
+// If the value is a boolean or null, convert it to a string. Note:
+// typeof null does not produce 'null'. The case is included here in
+// the remote chance that this gets fixed someday.
+
+ return String(value);
+
+// If the type is 'object', we might be dealing with an object or an array or
+// null.
+
+ case 'object':
+
+// Due to a specification blunder in ECMAScript, typeof null is 'object',
+// so watch out for that case.
+
+ if (!value) {
+ return 'null';
+ }
+
+// Make an array to hold the partial results of stringifying this object value.
+
+ gap += indent;
+ partial = [];
+
+// Is the value an array?
+
+ if (Object.prototype.toString.apply(value) === '[object Array]') {
+
+// The value is an array. Stringify every element. Use null as a placeholder
+// for non-JSON values.
+
+ length = value.length;
+ for (i = 0; i < length; i += 1) {
+ partial[i] = str(i, value) || 'null';
+ }
+
+// Join all of the elements together, separated with commas, and wrap them in
+// brackets.
+
+ v = partial.length === 0
+ ? '[]'
+ : gap
+ ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
+ : '[' + partial.join(',') + ']';
+ gap = mind;
+ return v;
}
- });
- }
- /**
- * 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)));
+
+// If the replacer is an array, use it to select the members to be stringified.
+
+ if (rep && typeof rep === 'object') {
+ length = rep.length;
+ for (i = 0; i < length; i += 1) {
+ if (typeof rep[i] === 'string') {
+ k = rep[i];
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
}
+ } else {
+
+// Otherwise, iterate through all of the keys in the object.
+
+ Object.keys(value).forEach(function(k) {
+ var v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ });
}
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
- finally {
- try {
- if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e));
+
+// Join all of the member texts together, separated with commas,
+// and wrap them in braces.
+
+ v = partial.length === 0
+ ? '{}'
+ : gap
+ ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
+ : '{' + partial.join(',') + '}';
+ gap = mind;
+ return v;
+ }
+ }
+
+// If the JSON object does not yet have a stringify method, give it one.
+
+ if (typeof JSON.stringify !== 'function') {
+ JSON.stringify = function (value, replacer, space) {
+
+// The stringify method takes a value and an optional replacer, and an optional
+// space parameter, and returns a JSON text. The replacer can be a function
+// that can replace values, or an array of strings that will select the keys.
+// A default replacer method can be provided. Use of the space parameter can
+// produce text that is more easily readable.
+
+ var i;
+ gap = '';
+ indent = '';
+
+// If the space parameter is a number, make an indent string containing that
+// many spaces.
+
+ if (typeof space === 'number') {
+ for (i = 0; i < space; i += 1) {
+ indent += ' ';
}
- finally { if (e_1) throw e_1.error; }
+
+// If the space parameter is a string, it will be used as the indent string.
+
+ } else if (typeof space === 'string') {
+ indent = space;
}
- });
+
+// If there is a replacer, it must be a function or an array.
+// Otherwise, throw an error.
+
+ rep = replacer;
+ if (replacer && typeof replacer !== 'function' &&
+ (typeof replacer !== 'object' ||
+ typeof replacer.length !== 'number')) {
+ throw new Error('JSON.stringify');
+ }
+
+// Make a fake root object containing our value under the key of ''.
+// Return the result of stringifying the value.
+
+ return str('', {'': value});
+ };
}
- /**
- * 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;
+}());
+
+
+/***/ }),
+
+/***/ 38622:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+var Buffer = (__nccwpck_require__(93058).Buffer);
+var crypto = __nccwpck_require__(76982);
+var formatEcdsa = __nccwpck_require__(325);
+var util = __nccwpck_require__(39023);
+
+var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".'
+var MSG_INVALID_SECRET = 'secret must be a string or buffer';
+var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer';
+var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object';
+
+var supportsKeyObjects = typeof crypto.createPublicKey === 'function';
+if (supportsKeyObjects) {
+ MSG_INVALID_VERIFIER_KEY += ' or a KeyObject';
+ MSG_INVALID_SECRET += 'or a KeyObject';
+}
+
+function checkIsPublicKey(key) {
+ if (Buffer.isBuffer(key)) {
+ return;
+ }
+
+ if (typeof key === 'string') {
+ return;
+ }
+
+ if (!supportsKeyObjects) {
+ throw typeError(MSG_INVALID_VERIFIER_KEY);
+ }
+
+ if (typeof key !== 'object') {
+ throw typeError(MSG_INVALID_VERIFIER_KEY);
+ }
+
+ if (typeof key.type !== 'string') {
+ throw typeError(MSG_INVALID_VERIFIER_KEY);
+ }
+
+ if (typeof key.asymmetricKeyType !== 'string') {
+ throw typeError(MSG_INVALID_VERIFIER_KEY);
+ }
+
+ if (typeof key.export !== 'function') {
+ throw typeError(MSG_INVALID_VERIFIER_KEY);
+ }
+};
+
+function checkIsPrivateKey(key) {
+ if (Buffer.isBuffer(key)) {
+ return;
+ }
+
+ if (typeof key === 'string') {
+ return;
+ }
+
+ if (typeof key === 'object') {
+ return;
+ }
+
+ throw typeError(MSG_INVALID_SIGNER_KEY);
+};
+
+function checkIsSecretKey(key) {
+ if (Buffer.isBuffer(key)) {
+ return;
+ }
+
+ if (typeof key === 'string') {
+ return key;
+ }
+
+ if (!supportsKeyObjects) {
+ throw typeError(MSG_INVALID_SECRET);
+ }
+
+ if (typeof key !== 'object') {
+ throw typeError(MSG_INVALID_SECRET);
+ }
+
+ if (key.type !== 'secret') {
+ throw typeError(MSG_INVALID_SECRET);
+ }
+
+ if (typeof key.export !== 'function') {
+ throw typeError(MSG_INVALID_SECRET);
+ }
+}
+
+function fromBase64(base64) {
+ return base64
+ .replace(/=/g, '')
+ .replace(/\+/g, '-')
+ .replace(/\//g, '_');
+}
+
+function toBase64(base64url) {
+ base64url = base64url.toString();
+
+ var padding = 4 - base64url.length % 4;
+ if (padding !== 4) {
+ for (var i = 0; i < padding; ++i) {
+ base64url += '=';
+ }
+ }
+
+ return base64url
+ .replace(/\-/g, '+')
+ .replace(/_/g, '/');
+}
+
+function typeError(template) {
+ var args = [].slice.call(arguments, 1);
+ var errMsg = util.format.bind(util, template).apply(null, args);
+ return new TypeError(errMsg);
+}
+
+function bufferOrString(obj) {
+ return Buffer.isBuffer(obj) || typeof obj === 'string';
+}
+
+function normalizeInput(thing) {
+ if (!bufferOrString(thing))
+ thing = JSON.stringify(thing);
+ return thing;
+}
+
+function createHmacSigner(bits) {
+ return function sign(thing, secret) {
+ checkIsSecretKey(secret);
+ thing = normalizeInput(thing);
+ var hmac = crypto.createHmac('sha' + bits, secret);
+ var sig = (hmac.update(thing), hmac.digest('base64'))
+ return fromBase64(sig);
+ }
+}
+
+var bufferEqual;
+var timingSafeEqual = 'timingSafeEqual' in crypto ? function timingSafeEqual(a, b) {
+ if (a.byteLength !== b.byteLength) {
+ return false;
+ }
+
+ return crypto.timingSafeEqual(a, b)
+} : function timingSafeEqual(a, b) {
+ if (!bufferEqual) {
+ bufferEqual = __nccwpck_require__(39732);
+ }
+
+ return bufferEqual(a, b)
+}
+
+function createHmacVerifier(bits) {
+ return function verify(thing, signature, secret) {
+ var computedSig = createHmacSigner(bits)(thing, secret);
+ return timingSafeEqual(Buffer.from(signature), Buffer.from(computedSig));
+ }
+}
+
+function createKeySigner(bits) {
+ return function sign(thing, privateKey) {
+ checkIsPrivateKey(privateKey);
+ thing = normalizeInput(thing);
+ // Even though we are specifying "RSA" here, this works with ECDSA
+ // keys as well.
+ var signer = crypto.createSign('RSA-SHA' + bits);
+ var sig = (signer.update(thing), signer.sign(privateKey, 'base64'));
+ return fromBase64(sig);
+ }
+}
+
+function createKeyVerifier(bits) {
+ return function verify(thing, signature, publicKey) {
+ checkIsPublicKey(publicKey);
+ thing = normalizeInput(thing);
+ signature = toBase64(signature);
+ var verifier = crypto.createVerify('RSA-SHA' + bits);
+ verifier.update(thing);
+ return verifier.verify(publicKey, signature, 'base64');
+ }
+}
+
+function createPSSKeySigner(bits) {
+ return function sign(thing, privateKey) {
+ checkIsPrivateKey(privateKey);
+ thing = normalizeInput(thing);
+ var signer = crypto.createSign('RSA-SHA' + bits);
+ var sig = (signer.update(thing), signer.sign({
+ key: privateKey,
+ padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
+ saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST
+ }, 'base64'));
+ return fromBase64(sig);
+ }
+}
+
+function createPSSKeyVerifier(bits) {
+ return function verify(thing, signature, publicKey) {
+ checkIsPublicKey(publicKey);
+ thing = normalizeInput(thing);
+ signature = toBase64(signature);
+ var verifier = crypto.createVerify('RSA-SHA' + bits);
+ verifier.update(thing);
+ return verifier.verify({
+ key: publicKey,
+ padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
+ saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST
+ }, signature, 'base64');
+ }
+}
+
+function createECDSASigner(bits) {
+ var inner = createKeySigner(bits);
+ return function sign() {
+ var signature = inner.apply(null, arguments);
+ signature = formatEcdsa.derToJose(signature, 'ES' + bits);
+ return signature;
+ };
+}
+
+function createECDSAVerifer(bits) {
+ var inner = createKeyVerifier(bits);
+ return function verify(thing, signature, publicKey) {
+ signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64');
+ var result = inner(thing, signature, publicKey);
+ return result;
+ };
+}
+
+function createNoneSigner() {
+ return function sign() {
+ return '';
+ }
+}
+
+function createNoneVerifier() {
+ return function verify(thing, signature) {
+ return signature === '';
+ }
+}
+
+module.exports = function jwa(algorithm) {
+ var signerFactories = {
+ hs: createHmacSigner,
+ rs: createKeySigner,
+ ps: createPSSKeySigner,
+ es: createECDSASigner,
+ none: createNoneSigner,
+ }
+ var verifierFactories = {
+ hs: createHmacVerifier,
+ rs: createKeyVerifier,
+ ps: createPSSKeyVerifier,
+ es: createECDSAVerifer,
+ none: createNoneVerifier,
+ }
+ var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);
+ if (!match)
+ throw typeError(MSG_INVALID_ALGORITHM, algorithm);
+ var algo = (match[1] || match[3]).toLowerCase();
+ var bits = match[2];
+
+ return {
+ sign: signerFactories[algo](bits),
+ verify: verifierFactories[algo](bits),
+ }
+};
+
+
+/***/ }),
+
+/***/ 33324:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+/*global exports*/
+var SignStream = __nccwpck_require__(78600);
+var VerifyStream = __nccwpck_require__(4368);
+
+var ALGORITHMS = [
+ 'HS256', 'HS384', 'HS512',
+ 'RS256', 'RS384', 'RS512',
+ 'PS256', 'PS384', 'PS512',
+ 'ES256', 'ES384', 'ES512'
+];
+
+exports.ALGORITHMS = ALGORITHMS;
+exports.sign = SignStream.sign;
+exports.verify = VerifyStream.verify;
+exports.decode = VerifyStream.decode;
+exports.isValid = VerifyStream.isValid;
+exports.createSign = function createSign(opts) {
+ return new SignStream(opts);
+};
+exports.createVerify = function createVerify(opts) {
+ return new VerifyStream(opts);
+};
+
+
+/***/ }),
+
+/***/ 41831:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+/*global module, process*/
+var Buffer = (__nccwpck_require__(93058).Buffer);
+var Stream = __nccwpck_require__(2203);
+var util = __nccwpck_require__(39023);
+
+function DataStream(data) {
+ this.buffer = null;
+ this.writable = true;
+ this.readable = true;
+
+ // No input
+ if (!data) {
+ this.buffer = Buffer.alloc(0);
+ return this;
+ }
+
+ // Stream
+ if (typeof data.pipe === 'function') {
+ this.buffer = Buffer.alloc(0);
+ data.pipe(this);
+ return this;
+ }
+
+ // Buffer or String
+ // or Object (assumedly a passworded key)
+ if (data.length || typeof data === 'object') {
+ this.buffer = data;
+ this.writable = false;
+ process.nextTick(function () {
+ this.emit('end', data);
+ this.readable = false;
+ this.emit('close');
+ }.bind(this));
+ return this;
+ }
+
+ throw new TypeError('Unexpected data type ('+ typeof data + ')');
+}
+util.inherits(DataStream, Stream);
+
+DataStream.prototype.write = function write(data) {
+ this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]);
+ this.emit('data', data);
+};
+
+DataStream.prototype.end = function end(data) {
+ if (data)
+ this.write(data);
+ this.emit('end', data);
+ this.emit('close');
+ this.writable = false;
+ this.readable = false;
+};
+
+module.exports = DataStream;
+
+
+/***/ }),
+
+/***/ 78600:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+/*global module*/
+var Buffer = (__nccwpck_require__(93058).Buffer);
+var DataStream = __nccwpck_require__(41831);
+var jwa = __nccwpck_require__(38622);
+var Stream = __nccwpck_require__(2203);
+var toString = __nccwpck_require__(95126);
+var util = __nccwpck_require__(39023);
+
+function base64url(string, encoding) {
+ return Buffer
+ .from(string, encoding)
+ .toString('base64')
+ .replace(/=/g, '')
+ .replace(/\+/g, '-')
+ .replace(/\//g, '_');
+}
+
+function jwsSecuredInput(header, payload, encoding) {
+ encoding = encoding || 'utf8';
+ var encodedHeader = base64url(toString(header), 'binary');
+ var encodedPayload = base64url(toString(payload), encoding);
+ return util.format('%s.%s', encodedHeader, encodedPayload);
+}
+
+function jwsSign(opts) {
+ var header = opts.header;
+ var payload = opts.payload;
+ var secretOrKey = opts.secret || opts.privateKey;
+ var encoding = opts.encoding;
+ var algo = jwa(header.alg);
+ var securedInput = jwsSecuredInput(header, payload, encoding);
+ var signature = algo.sign(securedInput, secretOrKey);
+ return util.format('%s.%s', securedInput, signature);
+}
+
+function SignStream(opts) {
+ var secret = opts.secret||opts.privateKey||opts.key;
+ var secretStream = new DataStream(secret);
+ this.readable = true;
+ this.header = opts.header;
+ this.encoding = opts.encoding;
+ this.secret = this.privateKey = this.key = secretStream;
+ this.payload = new DataStream(opts.payload);
+ this.secret.once('close', function () {
+ if (!this.payload.writable && this.readable)
+ this.sign();
+ }.bind(this));
+
+ this.payload.once('close', function () {
+ if (!this.secret.writable && this.readable)
+ this.sign();
+ }.bind(this));
+}
+util.inherits(SignStream, Stream);
+
+SignStream.prototype.sign = function sign() {
+ try {
+ var signature = jwsSign({
+ header: this.header,
+ payload: this.payload.buffer,
+ secret: this.secret.buffer,
+ encoding: this.encoding
+ });
+ this.emit('done', signature);
+ this.emit('data', signature);
+ this.emit('end');
+ this.readable = false;
+ return signature;
+ } catch (e) {
+ this.readable = false;
+ this.emit('error', e);
+ this.emit('close');
+ }
+};
+
+SignStream.sign = jwsSign;
+
+module.exports = SignStream;
+
+
+/***/ }),
+
+/***/ 95126:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+/*global module*/
+var Buffer = (__nccwpck_require__(20181).Buffer);
+
+module.exports = function toString(obj) {
+ if (typeof obj === 'string')
+ return obj;
+ if (typeof obj === 'number' || Buffer.isBuffer(obj))
+ return obj.toString();
+ return JSON.stringify(obj);
+};
+
+
+/***/ }),
+
+/***/ 4368:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+/*global module*/
+var Buffer = (__nccwpck_require__(93058).Buffer);
+var DataStream = __nccwpck_require__(41831);
+var jwa = __nccwpck_require__(38622);
+var Stream = __nccwpck_require__(2203);
+var toString = __nccwpck_require__(95126);
+var util = __nccwpck_require__(39023);
+var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;
+
+function isObject(thing) {
+ return Object.prototype.toString.call(thing) === '[object Object]';
+}
+
+function safeJsonParse(thing) {
+ if (isObject(thing))
+ return thing;
+ try { return JSON.parse(thing); }
+ catch (e) { return undefined; }
+}
+
+function headerFromJWS(jwsSig) {
+ var encodedHeader = jwsSig.split('.', 1)[0];
+ return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary'));
+}
+
+function securedInputFromJWS(jwsSig) {
+ return jwsSig.split('.', 2).join('.');
+}
+
+function signatureFromJWS(jwsSig) {
+ return jwsSig.split('.')[2];
+}
+
+function payloadFromJWS(jwsSig, encoding) {
+ encoding = encoding || 'utf8';
+ var payload = jwsSig.split('.')[1];
+ return Buffer.from(payload, 'base64').toString(encoding);
+}
+
+function isValidJws(string) {
+ return JWS_REGEX.test(string) && !!headerFromJWS(string);
+}
+
+function jwsVerify(jwsSig, algorithm, secretOrKey) {
+ if (!algorithm) {
+ var err = new Error("Missing algorithm parameter for jws.verify");
+ err.code = "MISSING_ALGORITHM";
+ throw err;
+ }
+ jwsSig = toString(jwsSig);
+ var signature = signatureFromJWS(jwsSig);
+ var securedInput = securedInputFromJWS(jwsSig);
+ var algo = jwa(algorithm);
+ return algo.verify(securedInput, signature, secretOrKey);
+}
+
+function jwsDecode(jwsSig, opts) {
+ opts = opts || {};
+ jwsSig = toString(jwsSig);
+
+ if (!isValidJws(jwsSig))
+ return null;
+
+ var header = headerFromJWS(jwsSig);
+
+ if (!header)
+ return null;
+
+ var payload = payloadFromJWS(jwsSig);
+ if (header.typ === 'JWT' || opts.json)
+ payload = JSON.parse(payload, opts.encoding);
+
+ return {
+ header: header,
+ payload: payload,
+ signature: signatureFromJWS(jwsSig)
+ };
+}
+
+function VerifyStream(opts) {
+ opts = opts || {};
+ var secretOrKey = opts.secret||opts.publicKey||opts.key;
+ var secretStream = new DataStream(secretOrKey);
+ this.readable = true;
+ this.algorithm = opts.algorithm;
+ this.encoding = opts.encoding;
+ this.secret = this.publicKey = this.key = secretStream;
+ this.signature = new DataStream(opts.signature);
+ this.secret.once('close', function () {
+ if (!this.signature.writable && this.readable)
+ this.verify();
+ }.bind(this));
+
+ this.signature.once('close', function () {
+ if (!this.secret.writable && this.readable)
+ this.verify();
+ }.bind(this));
+}
+util.inherits(VerifyStream, Stream);
+VerifyStream.prototype.verify = function verify() {
+ try {
+ var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer);
+ var obj = jwsDecode(this.signature.buffer, this.encoding);
+ this.emit('done', valid, obj);
+ this.emit('data', valid);
+ this.emit('end');
+ this.readable = false;
+ return valid;
+ } catch (e) {
+ this.readable = false;
+ this.emit('error', e);
+ this.emit('close');
+ }
+};
+
+VerifyStream.decode = jwsDecode;
+VerifyStream.isValid = isValidJws;
+VerifyStream.verify = jwsVerify;
+
+module.exports = VerifyStream;
+
+
+/***/ }),
+
+/***/ 55641:
+/***/ ((module) => {
+
+"use strict";
+
+
+/** @type {import('./abs')} */
+module.exports = Math.abs;
+
+
+/***/ }),
+
+/***/ 96171:
+/***/ ((module) => {
+
+"use strict";
+
+
+/** @type {import('./floor')} */
+module.exports = Math.floor;
+
+
+/***/ }),
+
+/***/ 77044:
+/***/ ((module) => {
+
+"use strict";
+
+
+/** @type {import('./isNaN')} */
+module.exports = Number.isNaN || function isNaN(a) {
+ return a !== a;
+};
+
+
+/***/ }),
+
+/***/ 57147:
+/***/ ((module) => {
+
+"use strict";
+
+
+/** @type {import('./max')} */
+module.exports = Math.max;
+
+
+/***/ }),
+
+/***/ 41017:
+/***/ ((module) => {
+
+"use strict";
+
+
+/** @type {import('./min')} */
+module.exports = Math.min;
+
+
+/***/ }),
+
+/***/ 56947:
+/***/ ((module) => {
+
+"use strict";
+
+
+/** @type {import('./pow')} */
+module.exports = Math.pow;
+
+
+/***/ }),
+
+/***/ 42621:
+/***/ ((module) => {
+
+"use strict";
+
+
+/** @type {import('./round')} */
+module.exports = Math.round;
+
+
+/***/ }),
+
+/***/ 30156:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var $isNaN = __nccwpck_require__(77044);
+
+/** @type {import('./sign')} */
+module.exports = function sign(number) {
+ if ($isNaN(number) || number === 0) {
+ return number;
+ }
+ return number < 0 ? -1 : +1;
+};
+
+
+/***/ }),
+
+/***/ 99829:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+/*!
+ * mime-db
+ * Copyright(c) 2014 Jonathan Ong
+ * Copyright(c) 2015-2022 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+/**
+ * Module exports.
+ */
+
+module.exports = __nccwpck_require__(81813)
+
+
+/***/ }),
+
+/***/ 14096:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+/*!
+ * mime-types
+ * Copyright(c) 2014 Jonathan Ong
+ * Copyright(c) 2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+
+
+/**
+ * Module dependencies.
+ * @private
+ */
+
+var db = __nccwpck_require__(99829)
+var extname = (__nccwpck_require__(16928).extname)
+
+/**
+ * Module variables.
+ * @private
+ */
+
+var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/
+var TEXT_TYPE_REGEXP = /^text\//i
+
+/**
+ * Module exports.
+ * @public
+ */
+
+exports.charset = charset
+exports.charsets = { lookup: charset }
+exports.contentType = contentType
+exports.extension = extension
+exports.extensions = Object.create(null)
+exports.lookup = lookup
+exports.types = Object.create(null)
+
+// Populate the extensions/types maps
+populateMaps(exports.extensions, exports.types)
+
+/**
+ * Get the default charset for a MIME type.
+ *
+ * @param {string} type
+ * @return {boolean|string}
+ */
+
+function charset (type) {
+ if (!type || typeof type !== 'string') {
+ return false
+ }
+
+ // TODO: use media-typer
+ var match = EXTRACT_TYPE_REGEXP.exec(type)
+ var mime = match && db[match[1].toLowerCase()]
+
+ if (mime && mime.charset) {
+ return mime.charset
+ }
+
+ // default text/* to utf-8
+ if (match && TEXT_TYPE_REGEXP.test(match[1])) {
+ return 'UTF-8'
+ }
+
+ return false
+}
+
+/**
+ * Create a full Content-Type header given a MIME type or extension.
+ *
+ * @param {string} str
+ * @return {boolean|string}
+ */
+
+function contentType (str) {
+ // TODO: should this even be in this module?
+ if (!str || typeof str !== 'string') {
+ return false
+ }
+
+ var mime = str.indexOf('/') === -1
+ ? exports.lookup(str)
+ : str
+
+ if (!mime) {
+ return false
+ }
+
+ // TODO: use content-type or other module
+ if (mime.indexOf('charset') === -1) {
+ var charset = exports.charset(mime)
+ if (charset) mime += '; charset=' + charset.toLowerCase()
+ }
+
+ return mime
+}
+
+/**
+ * Get the default extension for a MIME type.
+ *
+ * @param {string} type
+ * @return {boolean|string}
+ */
+
+function extension (type) {
+ if (!type || typeof type !== 'string') {
+ return false
+ }
+
+ // TODO: use media-typer
+ var match = EXTRACT_TYPE_REGEXP.exec(type)
+
+ // get extensions
+ var exts = match && exports.extensions[match[1].toLowerCase()]
+
+ if (!exts || !exts.length) {
+ return false
+ }
+
+ return exts[0]
+}
+
+/**
+ * Lookup the MIME type for a file path/extension.
+ *
+ * @param {string} path
+ * @return {boolean|string}
+ */
+
+function lookup (path) {
+ if (!path || typeof path !== 'string') {
+ return false
+ }
+
+ // get the extension ("ext" or ".ext" or full path)
+ var extension = extname('x.' + path)
+ .toLowerCase()
+ .substr(1)
+
+ if (!extension) {
+ return false
+ }
+
+ return exports.types[extension] || false
+}
+
+/**
+ * Populate the extensions and types maps.
+ * @private
+ */
+
+function populateMaps (extensions, types) {
+ // source preference (least -> most)
+ var preference = ['nginx', 'apache', undefined, 'iana']
+
+ Object.keys(db).forEach(function forEachMimeType (type) {
+ var mime = db[type]
+ var exts = mime.extensions
+
+ if (!exts || !exts.length) {
+ return
+ }
+
+ // mime -> extensions
+ extensions[type] = exts
+
+ // extension -> mime
+ for (var i = 0; i < exts.length; i++) {
+ var extension = exts[i]
+
+ if (types[extension]) {
+ var from = preference.indexOf(db[types[extension]].source)
+ var to = preference.indexOf(mime.source)
+
+ if (types[extension] !== 'application/octet-stream' &&
+ (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) {
+ // skip the remapping
+ continue
}
- 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));
- },
- };
+ }
+
+ // set the extension -> mime
+ types[extension] = type
}
- /**
- * 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);
- }
- });
+ })
+}
+
+
+/***/ }),
+
+/***/ 14402:
+/***/ ((module) => {
+
+"use strict";
+
+
+/**
+ * @param typeMap [Object] Map of MIME type -> Array[extensions]
+ * @param ...
+ */
+function Mime() {
+ this._types = Object.create(null);
+ this._extensions = Object.create(null);
+
+ for (let i = 0; i < arguments.length; i++) {
+ this.define(arguments[i]);
+ }
+
+ this.define = this.define.bind(this);
+ this.getType = this.getType.bind(this);
+ this.getExtension = this.getExtension.bind(this);
+}
+
+/**
+ * Define mimetype -> extension mappings. Each key is a mime-type that maps
+ * to an array of extensions associated with the type. The first extension is
+ * used as the default extension for the type.
+ *
+ * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
+ *
+ * If a type declares an extension that has already been defined, an error will
+ * be thrown. To suppress this error and force the extension to be associated
+ * with the new type, pass `force`=true. Alternatively, you may prefix the
+ * extension with "*" to map the type to extension, without mapping the
+ * extension to the type.
+ *
+ * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']});
+ *
+ *
+ * @param map (Object) type definitions
+ * @param force (Boolean) if true, force overriding of existing definitions
+ */
+Mime.prototype.define = function(typeMap, force) {
+ for (let type in typeMap) {
+ let extensions = typeMap[type].map(function(t) {
+ return t.toLowerCase();
+ });
+ type = type.toLowerCase();
+
+ for (let i = 0; i < extensions.length; i++) {
+ const ext = extensions[i];
+
+ // '*' prefix = not the preferred type for this extension. So fixup the
+ // extension, and skip it.
+ if (ext[0] === '*') {
+ continue;
+ }
+
+ if (!force && (ext in this._types)) {
+ throw new Error(
+ 'Attempt to change mapping for "' + ext +
+ '" extension from "' + this._types[ext] + '" to "' + type +
+ '". Pass `force=true` to allow this, otherwise remove "' + ext +
+ '" from the list of extensions for "' + type + '".'
+ );
+ }
+
+ this._types[ext] = type;
}
- /**
- * 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; }
- }
- });
+
+ // Use first extension as default
+ if (force || !this._extensions[type]) {
+ const ext = extensions[0];
+ this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1);
+ }
+ }
+};
+
+/**
+ * Lookup a mime type based on extension
+ */
+Mime.prototype.getType = function(path) {
+ path = String(path);
+ let last = path.replace(/^.*[/\\]/, '').toLowerCase();
+ let ext = last.replace(/^.*\./, '').toLowerCase();
+
+ let hasPath = last.length < path.length;
+ let hasDot = ext.length < last.length - 1;
+
+ return (hasDot || !hasPath) && this._types[ext] || null;
+};
+
+/**
+ * Return file extension associated with a mime type
+ */
+Mime.prototype.getExtension = function(type) {
+ type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;
+ return type && this._extensions[type.toLowerCase()] || null;
+};
+
+module.exports = Mime;
+
+
+/***/ }),
+
+/***/ 94900:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+let Mime = __nccwpck_require__(14402);
+module.exports = new Mime(__nccwpck_require__(83725), __nccwpck_require__(68548));
+
+
+/***/ }),
+
+/***/ 68548:
+/***/ ((module) => {
+
+module.exports = {"application/prs.cww":["cww"],"application/vnd.1000minds.decision-model+xml":["1km"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.keynote":["key"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.balsamiq.bmml+xml":["bmml"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.citationstyles.style+xml":["csl"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dbf":["dbf"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mapbox-vector-tile":["mvt"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["*stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.ac+xml":["*ac"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openblox.game+xml":["obgx"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openstreetmap.data+xml":["osm"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.rar":["rar"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.software602.filler.form+xml":["fo"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.syncml.dmddf+xml":["ddf"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["*dmg"],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":["*bdoc"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["*deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["*iso"],"application/x-iwork-keynote-sffkey":["*key"],"application/x-iwork-numbers-sffnumbers":["*numbers"],"application/x-iwork-pages-sffpages":["*pages"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-keepass2":["kdbx"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":["*exe"],"application/x-msdownload":["*exe","*dll","com","bat","*msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["*wmf","*wmz","*emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":["*prc","*pdb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["*rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["*obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["*xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["*m4a"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":["*ra"],"audio/x-wav":["*wav"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/prs.btif":["btif"],"image/prs.pti":["pti"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.airzip.accelerator.azv":["azv"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["*sub"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.microsoft.icon":["ico"],"image/vnd.ms-dds":["dds"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.pco.b16":["b16"],"image/vnd.tencent.tap":["tap"],"image/vnd.valve.source.texture":["vtf"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/vnd.zbrush.pcx":["pcx"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["*ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":["*bmp"],"image/x-pcx":["*pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/vnd.wfa.wsc":["wsc"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.opengex":["ogex"],"model/vnd.parasolid.transmit.binary":["x_b"],"model/vnd.parasolid.transmit.text":["x_t"],"model/vnd.sap.vds":["vds"],"model/vnd.usdz+zip":["usdz"],"model/vnd.valve.source.compiled-map":["bsp"],"model/vnd.vtu":["vtu"],"text/prs.lines.tag":["dsc"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":["*org"],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]};
+
+/***/ }),
+
+/***/ 83725:
+/***/ ((module) => {
+
+module.exports = {"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["es","ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]};
+
+/***/ }),
+
+/***/ 43772:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+module.exports = minimatch
+minimatch.Minimatch = Minimatch
+
+var path = (function () { try { return __nccwpck_require__(16928) } catch (e) {}}()) || {
+ sep: '/'
+}
+minimatch.sep = path.sep
+
+var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
+var expand = __nccwpck_require__(94691)
+
+var plTypes = {
+ '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
+ '?': { open: '(?:', close: ')?' },
+ '+': { open: '(?:', close: ')+' },
+ '*': { open: '(?:', close: ')*' },
+ '@': { open: '(?:', close: ')' }
+}
+
+// any single thing other than /
+// don't need to escape / when using new RegExp()
+var qmark = '[^/]'
+
+// * => any number of characters
+var star = qmark + '*?'
+
+// ** when dots are allowed. Anything goes, except .. and .
+// not (^ or / followed by one or two dots followed by $ or /),
+// followed by anything, any number of times.
+var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
+
+// not a ^ or / followed by a dot,
+// followed by anything, any number of times.
+var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
+
+// characters that need to be escaped in RegExp.
+var reSpecials = charSet('().*{}+?[]^$\\!')
+
+// "abc" -> { a:true, b:true, c:true }
+function charSet (s) {
+ return s.split('').reduce(function (set, c) {
+ set[c] = true
+ return set
+ }, {})
+}
+
+// normalizes slashes.
+var slashSplit = /\/+/
+
+minimatch.filter = filter
+function filter (pattern, options) {
+ options = options || {}
+ return function (p, i, list) {
+ return minimatch(p, pattern, options)
+ }
+}
+
+function ext (a, b) {
+ b = b || {}
+ var t = {}
+ Object.keys(a).forEach(function (k) {
+ t[k] = a[k]
+ })
+ Object.keys(b).forEach(function (k) {
+ t[k] = b[k]
+ })
+ return t
+}
+
+minimatch.defaults = function (def) {
+ if (!def || typeof def !== 'object' || !Object.keys(def).length) {
+ return minimatch
+ }
+
+ var orig = minimatch
+
+ var m = function minimatch (p, pattern, options) {
+ return orig(p, pattern, ext(def, options))
+ }
+
+ m.Minimatch = function Minimatch (pattern, options) {
+ return new orig.Minimatch(pattern, ext(def, options))
+ }
+ m.Minimatch.defaults = function defaults (options) {
+ return orig.defaults(ext(def, options)).Minimatch
+ }
+
+ m.filter = function filter (pattern, options) {
+ return orig.filter(pattern, ext(def, options))
+ }
+
+ m.defaults = function defaults (options) {
+ return orig.defaults(ext(def, options))
+ }
+
+ m.makeRe = function makeRe (pattern, options) {
+ return orig.makeRe(pattern, ext(def, options))
+ }
+
+ m.braceExpand = function braceExpand (pattern, options) {
+ return orig.braceExpand(pattern, ext(def, options))
+ }
+
+ m.match = function (list, pattern, options) {
+ return orig.match(list, pattern, ext(def, options))
+ }
+
+ return m
+}
+
+Minimatch.defaults = function (def) {
+ return minimatch.defaults(def).Minimatch
+}
+
+function minimatch (p, pattern, options) {
+ assertValidPattern(pattern)
+
+ if (!options) options = {}
+
+ // shortcut: comments match nothing.
+ if (!options.nocomment && pattern.charAt(0) === '#') {
+ return false
+ }
+
+ return new Minimatch(pattern, options).match(p)
+}
+
+function Minimatch (pattern, options) {
+ if (!(this instanceof Minimatch)) {
+ return new Minimatch(pattern, options)
+ }
+
+ assertValidPattern(pattern)
+
+ if (!options) options = {}
+
+ pattern = pattern.trim()
+
+ // windows support: need to use /, not \
+ if (!options.allowWindowsEscape && path.sep !== '/') {
+ pattern = pattern.split(path.sep).join('/')
+ }
+
+ this.options = options
+ this.set = []
+ this.pattern = pattern
+ this.regexp = null
+ this.negate = false
+ this.comment = false
+ this.empty = false
+ this.partial = !!options.partial
+
+ // make the set of regexps etc.
+ this.make()
+}
+
+Minimatch.prototype.debug = function () {}
+
+Minimatch.prototype.make = make
+function make () {
+ var pattern = this.pattern
+ var options = this.options
+
+ // empty patterns and comments match nothing.
+ if (!options.nocomment && pattern.charAt(0) === '#') {
+ this.comment = true
+ return
+ }
+ if (!pattern) {
+ this.empty = true
+ return
+ }
+
+ // step 1: figure out negation, etc.
+ this.parseNegate()
+
+ // step 2: expand braces
+ var set = this.globSet = this.braceExpand()
+
+ if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) }
+
+ this.debug(this.pattern, set)
+
+ // step 3: now we have a set, so turn each one into a series of path-portion
+ // matching patterns.
+ // These will be regexps, except in the case of "**", which is
+ // set to the GLOBSTAR object for globstar behavior,
+ // and will not contain any / characters
+ set = this.globParts = set.map(function (s) {
+ return s.split(slashSplit)
+ })
+
+ this.debug(this.pattern, set)
+
+ // glob --> regexps
+ set = set.map(function (s, si, set) {
+ return s.map(this.parse, this)
+ }, this)
+
+ this.debug(this.pattern, set)
+
+ // filter out everything that didn't compile properly.
+ set = set.filter(function (s) {
+ return s.indexOf(false) === -1
+ })
+
+ this.debug(this.pattern, set)
+
+ this.set = set
+}
+
+Minimatch.prototype.parseNegate = parseNegate
+function parseNegate () {
+ var pattern = this.pattern
+ var negate = false
+ var options = this.options
+ var negateOffset = 0
+
+ if (options.nonegate) return
+
+ for (var i = 0, l = pattern.length
+ ; i < l && pattern.charAt(i) === '!'
+ ; i++) {
+ negate = !negate
+ negateOffset++
+ }
+
+ if (negateOffset) this.pattern = pattern.substr(negateOffset)
+ this.negate = negate
+}
+
+// Brace expansion:
+// a{b,c}d -> abd acd
+// a{b,}c -> abc ac
+// a{0..3}d -> a0d a1d a2d a3d
+// a{b,c{d,e}f}g -> abg acdfg acefg
+// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
+//
+// Invalid sets are not expanded.
+// a{2..}b -> a{2..}b
+// a{b}c -> a{b}c
+minimatch.braceExpand = function (pattern, options) {
+ return braceExpand(pattern, options)
+}
+
+Minimatch.prototype.braceExpand = braceExpand
+
+function braceExpand (pattern, options) {
+ if (!options) {
+ if (this instanceof Minimatch) {
+ options = this.options
+ } else {
+ options = {}
+ }
+ }
+
+ pattern = typeof pattern === 'undefined'
+ ? this.pattern : pattern
+
+ assertValidPattern(pattern)
+
+ // Thanks to Yeting Li for
+ // improving this regexp to avoid a ReDOS vulnerability.
+ if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
+ // shortcut. no need to expand.
+ return [pattern]
+ }
+
+ return expand(pattern)
+}
+
+var MAX_PATTERN_LENGTH = 1024 * 64
+var assertValidPattern = function (pattern) {
+ if (typeof pattern !== 'string') {
+ throw new TypeError('invalid pattern')
+ }
+
+ if (pattern.length > MAX_PATTERN_LENGTH) {
+ throw new TypeError('pattern is too long')
+ }
+}
+
+// parse a component of the expanded set.
+// At this point, no pattern may contain "/" in it
+// so we're going to return a 2d array, where each entry is the full
+// pattern, split on '/', and then turned into a regular expression.
+// A regexp is made at the end which joins each array with an
+// escaped /, and another full one which joins each regexp with |.
+//
+// Following the lead of Bash 4.1, note that "**" only has special meaning
+// when it is the *only* thing in a path portion. Otherwise, any series
+// of * is equivalent to a single *. Globstar behavior is enabled by
+// default, and can be disabled by setting options.noglobstar.
+Minimatch.prototype.parse = parse
+var SUBPARSE = {}
+function parse (pattern, isSub) {
+ assertValidPattern(pattern)
+
+ var options = this.options
+
+ // shortcuts
+ if (pattern === '**') {
+ if (!options.noglobstar)
+ return GLOBSTAR
+ else
+ pattern = '*'
+ }
+ if (pattern === '') return ''
+
+ var re = ''
+ var hasMagic = !!options.nocase
+ var escaping = false
+ // ? => one single character
+ var patternListStack = []
+ var negativeLists = []
+ var stateChar
+ var inClass = false
+ var reClassStart = -1
+ var classStart = -1
+ // . and .. never match anything that doesn't start with .,
+ // even when options.dot is set.
+ var patternStart = pattern.charAt(0) === '.' ? '' // anything
+ // not (start or / followed by . or .. followed by / or end)
+ : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
+ : '(?!\\.)'
+ var self = this
+
+ function clearStateChar () {
+ if (stateChar) {
+ // we had some state-tracking character
+ // that wasn't consumed by this pass.
+ switch (stateChar) {
+ case '*':
+ re += star
+ hasMagic = true
+ break
+ case '?':
+ re += qmark
+ hasMagic = true
+ break
+ default:
+ re += '\\' + stateChar
+ break
+ }
+ self.debug('clearStateChar %j %j', stateChar, re)
+ stateChar = false
}
- /**
- * 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");
+ }
+
+ for (var i = 0, len = pattern.length, c
+ ; (i < len) && (c = pattern.charAt(i))
+ ; i++) {
+ this.debug('%s\t%s %s %j', pattern, i, re, c)
+
+ // skip over any that are escaped.
+ if (escaping && reSpecials[c]) {
+ re += '\\' + c
+ escaping = false
+ continue
+ }
+
+ switch (c) {
+ /* istanbul ignore next */
+ case '/': {
+ // completely not allowed, even escaped.
+ // Should already be path-split by now.
+ return false
+ }
+
+ case '\\':
+ clearStateChar()
+ escaping = true
+ continue
+
+ // the various stateChar values
+ // for the "extglob" stuff.
+ case '?':
+ case '*':
+ case '+':
+ case '@':
+ case '!':
+ this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
+
+ // all of those are literals inside a class, except that
+ // the glob [!a] means [^a] in regexp
+ if (inClass) {
+ this.debug(' in class')
+ if (c === '!' && i === classStart + 1) c = '^'
+ re += c
+ continue
}
- if (options.includeVersions) {
- include.push("versions");
+
+ // if we already have a stateChar, then it means
+ // that there was something like ** or +? in there.
+ // Handle the stateChar, then proceed with this one.
+ self.debug('call clearStateChar %j', stateChar)
+ clearStateChar()
+ stateChar = c
+ // if extglob is disabled, then +(asdf|foo) isn't a thing.
+ // just clear the statechar *now*, rather than even diving into
+ // the patternList stuff.
+ if (options.noext) clearStateChar()
+ continue
+
+ case '(':
+ if (inClass) {
+ re += '('
+ continue
}
- if (options.includeUncommitedBlobs) {
- include.push("uncommittedblobs");
+
+ if (!stateChar) {
+ re += '\\('
+ continue
}
- if (options.includeTags) {
- include.push("tags");
+
+ patternListStack.push({
+ type: stateChar,
+ start: i - 1,
+ reStart: re.length,
+ open: plTypes[stateChar].open,
+ close: plTypes[stateChar].close
+ })
+ // negation is (?:(?!js)[^/]*)
+ re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
+ this.debug('plType %j %j', stateChar, re)
+ stateChar = false
+ continue
+
+ case ')':
+ if (inClass || !patternListStack.length) {
+ re += '\\)'
+ continue
}
- if (options.includeDeletedWithVersions) {
- include.push("deletedwithversions");
+
+ clearStateChar()
+ hasMagic = true
+ var pl = patternListStack.pop()
+ // negation is (?:(?!js)[^/]*)
+ // The others are (?:)
+ re += pl.close
+ if (pl.type === '!') {
+ negativeLists.push(pl)
}
- if (options.includeImmutabilityPolicy) {
- include.push("immutabilitypolicy");
+ pl.reEnd = re.length
+ continue
+
+ case '|':
+ if (inClass || !patternListStack.length || escaping) {
+ re += '\\|'
+ escaping = false
+ continue
}
- if (options.includeLegalHold) {
- include.push("legalhold");
+
+ clearStateChar()
+ re += '|'
+ continue
+
+ // these are mostly the same in regexp and glob
+ case '[':
+ // swallow any state-tracking char before the [
+ clearStateChar()
+
+ if (inClass) {
+ re += '\\' + c
+ continue
}
- if (options.prefix === "") {
- options.prefix = undefined;
+
+ inClass = true
+ classStart = i
+ reClassStart = re.length
+ re += c
+ continue
+
+ case ']':
+ // a right bracket shall lose its special
+ // meaning and represent itself in
+ // a bracket expression if it occurs
+ // first in the list. -- POSIX.2 2.8.3.2
+ if (i === classStart + 1 || !inClass) {
+ re += '\\' + c
+ escaping = false
+ continue
}
- 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://docs.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;
+
+ // handle the case where we left a class open.
+ // "[z-a]" is valid, equivalent to "\[z-a\]"
+ // split where the last [ was, make sure we don't have
+ // an invalid re. if so, re-walk the contents of the
+ // would-be class to re-translate any characters that
+ // were passed through as-is
+ // TODO: It would probably be faster to determine this
+ // without a try/catch and a new RegExp, but it's tricky
+ // to do safely. For now, this is safe and works.
+ var cs = pattern.substring(classStart + 1, i)
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;
+ RegExp('[' + cs + ']')
+ } catch (er) {
+ // not a valid class!
+ var sp = this.parse(cs, SUBPARSE)
+ re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
+ hasMagic = hasMagic || sp[1]
+ inClass = false
+ continue
}
- catch (error) {
- throw new Error("Unable to extract containerName with provided information.");
+
+ // finish up the class.
+ hasMagic = true
+ inClass = false
+ re += c
+ continue
+
+ default:
+ // swallow any state char that wasn't consumed
+ clearStateChar()
+
+ if (escaping) {
+ // no need
+ escaping = false
+ } else if (reSpecials[c]
+ && !(c === '^' && inClass)) {
+ re += '\\'
}
+
+ re += c
+
+ } // switch
+ } // for
+
+ // handle the case where we left a class open.
+ // "[abc" is valid, equivalent to "\[abc"
+ if (inClass) {
+ // split where the last [ was, and escape it
+ // this is a huge pita. We now have to re-walk
+ // the contents of the would-be class to re-translate
+ // any characters that were passed through as-is
+ cs = pattern.substr(classStart + 1)
+ sp = this.parse(cs, SUBPARSE)
+ re = re.substr(0, reClassStart) + '\\[' + sp[0]
+ hasMagic = hasMagic || sp[1]
+ }
+
+ // handle the case where we had a +( thing at the *end*
+ // of the pattern.
+ // each pattern list stack adds 3 chars, and we need to go through
+ // and escape any | chars that were passed through as-is for the regexp.
+ // Go through and escape them, taking care not to double-escape any
+ // | chars that were already escaped.
+ for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
+ var tail = re.slice(pl.reStart + pl.open.length)
+ this.debug('setting tail', re, pl)
+ // maybe some even number of \, then maybe 1 \, followed by a |
+ tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
+ if (!$2) {
+ // the | isn't already escaped, so escape it.
+ $2 = '\\'
+ }
+
+ // need to escape all those slashes *again*, without escaping the
+ // one that we need for escaping the | character. As it works out,
+ // escaping an even number of slashes can be done by simply repeating
+ // it exactly after itself. That's why this trick works.
+ //
+ // I am sorry that you have to see this.
+ return $1 + $1 + $2 + '|'
+ })
+
+ this.debug('tail=%j\n %s', tail, tail, pl, re)
+ var t = pl.type === '*' ? star
+ : pl.type === '?' ? qmark
+ : '\\' + pl.type
+
+ hasMagic = true
+ re = re.slice(0, pl.reStart) + t + '\\(' + tail
+ }
+
+ // handle trailing things that only matter at the very end.
+ clearStateChar()
+ if (escaping) {
+ // trailing \\
+ re += '\\\\'
+ }
+
+ // only need to apply the nodot start if the re starts with
+ // something that could conceivably capture a dot
+ var addPatternStart = false
+ switch (re.charAt(0)) {
+ case '[': case '.': case '(': addPatternStart = true
+ }
+
+ // Hack to work around lack of negative lookbehind in JS
+ // A pattern like: *.!(x).!(y|z) needs to ensure that a name
+ // like 'a.xyz.yz' doesn't match. So, the first negative
+ // lookahead, has to look ALL the way ahead, to the end of
+ // the pattern.
+ for (var n = negativeLists.length - 1; n > -1; n--) {
+ var nl = negativeLists[n]
+
+ var nlBefore = re.slice(0, nl.reStart)
+ var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
+ var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
+ var nlAfter = re.slice(nl.reEnd)
+
+ nlLast += nlAfter
+
+ // Handle nested stuff like *(*.js|!(*.json)), where open parens
+ // mean that we should *not* include the ) in the bit that is considered
+ // "after" the negated section.
+ var openParensBefore = nlBefore.split('(').length - 1
+ var cleanAfter = nlAfter
+ for (i = 0; i < openParensBefore; i++) {
+ cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
}
- /**
- * 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://docs.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));
- });
+ nlAfter = cleanAfter
+
+ var dollar = ''
+ if (nlAfter === '' && isSub !== SUBPARSE) {
+ dollar = '$'
}
- /**
- * 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://docs.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;
+ var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
+ re = newRe
+ }
+
+ // if the re is not "" at this point, then we need to make sure
+ // it doesn't match against an empty path part.
+ // Otherwise a/* will match a/, which it should not.
+ if (re !== '' && hasMagic) {
+ re = '(?=.)' + re
+ }
+
+ if (addPatternStart) {
+ re = patternStart + re
+ }
+
+ // parsing just a piece of a larger pattern.
+ if (isSub === SUBPARSE) {
+ return [re, hasMagic]
+ }
+
+ // skip the regexp for non-magical patterns
+ // unescape anything in it, though, so that it'll be
+ // an exact match against a file etc.
+ if (!hasMagic) {
+ return globUnescape(pattern)
+ }
+
+ var flags = options.nocase ? 'i' : ''
+ try {
+ var regExp = new RegExp('^' + re + '$', flags)
+ } catch (er) /* istanbul ignore next - should be impossible */ {
+ // If it was an invalid regular expression, then it can't match
+ // anything. This trick looks for a character after the end of
+ // the string, which is of course impossible, except in multi-line
+ // mode, but it's not a /m regex.
+ return new RegExp('$.')
+ }
+
+ regExp._glob = pattern
+ regExp._src = re
+
+ return regExp
+}
+
+minimatch.makeRe = function (pattern, options) {
+ return new Minimatch(pattern, options || {}).makeRe()
+}
+
+Minimatch.prototype.makeRe = makeRe
+function makeRe () {
+ if (this.regexp || this.regexp === false) return this.regexp
+
+ // at this point, this.set is a 2d array of partial
+ // pattern strings, or "**".
+ //
+ // It's better to use .match(). This function shouldn't
+ // be used, really, but it's pretty convenient sometimes,
+ // when you just want to work with a regex.
+ var set = this.set
+
+ if (!set.length) {
+ this.regexp = false
+ return this.regexp
+ }
+ var options = this.options
+
+ var twoStar = options.noglobstar ? star
+ : options.dot ? twoStarDot
+ : twoStarNoDot
+ var flags = options.nocase ? 'i' : ''
+
+ var re = set.map(function (pattern) {
+ return pattern.map(function (p) {
+ return (p === GLOBSTAR) ? twoStar
+ : (typeof p === 'string') ? regExpEscape(p)
+ : p._src
+ }).join('\\\/')
+ }).join('|')
+
+ // must match entire pattern
+ // ending in a * or ** will make it less strict.
+ re = '^(?:' + re + ')$'
+
+ // can match anything, as long as it's not this.
+ if (this.negate) re = '^(?!' + re + ').*$'
+
+ try {
+ this.regexp = new RegExp(re, flags)
+ } catch (ex) /* istanbul ignore next - should be impossible */ {
+ this.regexp = false
+ }
+ return this.regexp
+}
+
+minimatch.match = function (list, pattern, options) {
+ options = options || {}
+ var mm = new Minimatch(pattern, options)
+ list = list.filter(function (f) {
+ return mm.match(f)
+ })
+ if (mm.options.nonull && !list.length) {
+ list.push(pattern)
+ }
+ return list
+}
+
+Minimatch.prototype.match = function match (f, partial) {
+ if (typeof partial === 'undefined') partial = this.partial
+ this.debug('match', f, this.pattern)
+ // short-circuit in the case of busted things.
+ // comments, etc.
+ if (this.comment) return false
+ if (this.empty) return f === ''
+
+ if (f === '/' && partial) return true
+
+ var options = this.options
+
+ // windows: need to use /, not \
+ if (path.sep !== '/') {
+ f = f.split(path.sep).join('/')
+ }
+
+ // treat the test path as a set of pathparts.
+ f = f.split(slashSplit)
+ this.debug(this.pattern, 'split', f)
+
+ // just ONE of the pattern sets in this.set needs to match
+ // in order for it to be valid. If negating, then just one
+ // match means that we have failed.
+ // Either way, return on the first hit.
+
+ var set = this.set
+ this.debug(this.pattern, 'set', set)
+
+ // Find the basename of the path by looking for the last non-empty segment
+ var filename
+ var i
+ for (i = f.length - 1; i >= 0; i--) {
+ filename = f[i]
+ if (filename) break
+ }
+
+ for (i = 0; i < set.length; i++) {
+ var pattern = set[i]
+ var file = f
+ if (options.matchBase && pattern.length === 1) {
+ file = [filename]
}
- /**
- * 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://docs.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));
- });
+ var hit = this.matchOne(file, pattern, partial)
+ if (hit) {
+ if (options.flipNegate) return true
+ return !this.negate
}
- /**
- * 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://docs.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;
+ }
+
+ // didn't get any hits. this is success if it's a negative
+ // pattern, failure otherwise.
+ if (options.flipNegate) return false
+ return this.negate
+}
+
+// set partial to true to test if, for example,
+// "/a/b" matches the start of "/*/b/*/d"
+// Partial means, if you run out of file before you run
+// out of pattern, then that's fine, as long as all
+// the parts match.
+Minimatch.prototype.matchOne = function (file, pattern, partial) {
+ var options = this.options
+
+ this.debug('matchOne',
+ { 'this': this, file: file, pattern: pattern })
+
+ this.debug('matchOne', file.length, pattern.length)
+
+ for (var fi = 0,
+ pi = 0,
+ fl = file.length,
+ pl = pattern.length
+ ; (fi < fl) && (pi < pl)
+ ; fi++, pi++) {
+ this.debug('matchOne loop')
+ var p = pattern[pi]
+ var f = file[fi]
+
+ this.debug(pattern, p, f)
+
+ // should be impossible.
+ // some invalid regexp stuff in the set.
+ /* istanbul ignore if */
+ if (p === false) return false
+
+ if (p === GLOBSTAR) {
+ this.debug('GLOBSTAR', [pattern, p, f])
+
+ // "**"
+ // a/**/b/**/c would match the following:
+ // a/b/x/y/z/c
+ // a/x/y/z/b/c
+ // a/b/x/b/x/c
+ // a/b/c
+ // To do this, take the rest of the pattern after
+ // the **, and see if it would match the file remainder.
+ // If so, return success.
+ // If not, the ** "swallows" a segment, and try again.
+ // This is recursively awful.
+ //
+ // a/**/b/**/c matching a/b/x/y/z/c
+ // - a matches a
+ // - doublestar
+ // - matchOne(b/x/y/z/c, b/**/c)
+ // - b matches b
+ // - doublestar
+ // - matchOne(x/y/z/c, c) -> no
+ // - matchOne(y/z/c, c) -> no
+ // - matchOne(z/c, c) -> no
+ // - matchOne(c, c) yes, hit
+ var fr = fi
+ var pr = pi + 1
+ if (pr === pl) {
+ this.debug('** at the end')
+ // a ** at the end will just swallow the rest.
+ // We have found a match.
+ // however, it will not swallow /.x, unless
+ // options.dot is set.
+ // . and .. are *never* matched by **, for explosively
+ // exponential reasons.
+ for (; fi < fl; fi++) {
+ if (file[fi] === '.' || file[fi] === '..' ||
+ (!options.dot && file[fi].charAt(0) === '.')) return false
+ }
+ return true
+ }
+
+ // ok, let's see if we can swallow whatever we can.
+ while (fr < fl) {
+ var swallowee = file[fr]
+
+ this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
+
+ // XXX remove this slice. Just pass the start index.
+ if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
+ this.debug('globstar found match!', fr, fl, swallowee)
+ // found a match.
+ return true
+ } else {
+ // can't swallow "." or ".." ever.
+ // can only swallow ".foo" when explicitly asked.
+ if (swallowee === '.' || swallowee === '..' ||
+ (!options.dot && swallowee.charAt(0) === '.')) {
+ this.debug('dot detected!', file, fr, pattern, pr)
+ break
+ }
+
+ // ** swallows a segment, and continue.
+ this.debug('globstar swallow a segment, and continue')
+ fr++
+ }
+ }
+
+ // no match was found.
+ // However, in partial mode, we can't say this is necessarily over.
+ // If there's more *pattern* left, then
+ /* istanbul ignore if */
+ if (partial) {
+ // ran out of file
+ this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
+ if (fr === fl) return true
+ }
+ return false
}
- /**
- * Creates a BlobBatchClient object to conduct batch operations.
- *
- * @see https://docs.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);
+
+ // something other than **
+ // non-magic patterns just have to match exactly
+ // patterns with magic have been turned into regexps.
+ var hit
+ if (typeof p === 'string') {
+ hit = f === p
+ this.debug('string match', p, f, hit)
+ } else {
+ hit = f.match(p)
+ this.debug('pattern match', p, f, hit)
}
+
+ if (!hit) return false
+ }
+
+ // Note: ending in / means that we'll get a final ""
+ // at the end of the pattern. This can only match a
+ // corresponding "" at the end of the file.
+ // If the file ends in /, then it can only match a
+ // a pattern that ends in /, unless the pattern just
+ // doesn't have any more for it. But, a/b/ should *not*
+ // match "a/b/*", even though "" matches against the
+ // [^/]*? pattern, except in partial mode, where it might
+ // simply not be reached yet.
+ // However, a/b/ should still satisfy a/*
+
+ // now either we fell off the end of the pattern, or we're done.
+ if (fi === fl && pi === pl) {
+ // ran out of pattern and filename at the same time.
+ // an exact hit!
+ return true
+ } else if (fi === fl) {
+ // ran out of file, but still had pattern left.
+ // this is ok if we're doing the match as part of
+ // a glob fs traversal.
+ return partial
+ } else /* istanbul ignore else */ if (pi === pl) {
+ // ran out of pattern, still have file left.
+ // this is only acceptable if we're on the very last
+ // empty segment of a file with a trailing slash.
+ // a/* should match a/b/
+ return (fi === fl - 1) && (file[fi] === '')
+ }
+
+ // should be unreachable.
+ /* istanbul ignore next */
+ throw new Error('wtf?')
+}
+
+// replace stuff like \* with *
+function globUnescape (s) {
+ return s.replace(/\\(.)/g, '$1')
+}
+
+function regExpEscape (s) {
+ return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
+}
+
+
+/***/ }),
+
+/***/ 70744:
+/***/ ((module) => {
+
+/**
+ * Helpers.
+ */
+
+var s = 1000;
+var m = s * 60;
+var h = m * 60;
+var d = h * 24;
+var w = d * 7;
+var y = d * 365.25;
+
+/**
+ * Parse or format the given `val`.
+ *
+ * Options:
+ *
+ * - `long` verbose formatting [false]
+ *
+ * @param {String|Number} val
+ * @param {Object} [options]
+ * @throws {Error} throw an error if val is not a non-empty string or a number
+ * @return {String|Number}
+ * @api public
+ */
+
+module.exports = function (val, options) {
+ options = options || {};
+ var type = typeof val;
+ if (type === 'string' && val.length > 0) {
+ return parse(val);
+ } else if (type === 'number' && isFinite(val)) {
+ return options.long ? fmtLong(val) : fmtShort(val);
+ }
+ throw new Error(
+ 'val is not a non-empty string or a valid number. val=' +
+ JSON.stringify(val)
+ );
+};
+
+/**
+ * Parse the given `str` and return milliseconds.
+ *
+ * @param {String} str
+ * @return {Number}
+ * @api private
+ */
+
+function parse(str) {
+ str = String(str);
+ if (str.length > 100) {
+ return;
+ }
+ var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
+ str
+ );
+ if (!match) {
+ return;
+ }
+ var n = parseFloat(match[1]);
+ var type = (match[2] || 'ms').toLowerCase();
+ switch (type) {
+ case 'years':
+ case 'year':
+ case 'yrs':
+ case 'yr':
+ case 'y':
+ return n * y;
+ case 'weeks':
+ case 'week':
+ case 'w':
+ return n * w;
+ case 'days':
+ case 'day':
+ case 'd':
+ return n * d;
+ case 'hours':
+ case 'hour':
+ case 'hrs':
+ case 'hr':
+ case 'h':
+ return n * h;
+ case 'minutes':
+ case 'minute':
+ case 'mins':
+ case 'min':
+ case 'm':
+ return n * m;
+ case 'seconds':
+ case 'second':
+ case 'secs':
+ case 'sec':
+ case 's':
+ return n * s;
+ case 'milliseconds':
+ case 'millisecond':
+ case 'msecs':
+ case 'msec':
+ case 'ms':
+ return n;
+ default:
+ return undefined;
+ }
+}
+
+/**
+ * Short format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+function fmtShort(ms) {
+ var msAbs = Math.abs(ms);
+ if (msAbs >= d) {
+ return Math.round(ms / d) + 'd';
+ }
+ if (msAbs >= h) {
+ return Math.round(ms / h) + 'h';
+ }
+ if (msAbs >= m) {
+ return Math.round(ms / m) + 'm';
+ }
+ if (msAbs >= s) {
+ return Math.round(ms / s) + 's';
+ }
+ return ms + 'ms';
+}
+
+/**
+ * Long format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+function fmtLong(ms) {
+ var msAbs = Math.abs(ms);
+ if (msAbs >= d) {
+ return plural(ms, msAbs, d, 'day');
+ }
+ if (msAbs >= h) {
+ return plural(ms, msAbs, h, 'hour');
+ }
+ if (msAbs >= m) {
+ return plural(ms, msAbs, m, 'minute');
+ }
+ if (msAbs >= s) {
+ return plural(ms, msAbs, s, 'second');
+ }
+ return ms + ' ms';
+}
+
+/**
+ * Pluralization helper.
+ */
+
+function plural(ms, msAbs, n, name) {
+ var isPlural = msAbs >= n * 1.5;
+ return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
+}
+
+
+/***/ }),
+
+/***/ 26705:
+/***/ ((module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var Stream = _interopDefault(__nccwpck_require__(2203));
+var http = _interopDefault(__nccwpck_require__(58611));
+var Url = _interopDefault(__nccwpck_require__(87016));
+var whatwgUrl = _interopDefault(__nccwpck_require__(62686));
+var https = _interopDefault(__nccwpck_require__(65692));
+var zlib = _interopDefault(__nccwpck_require__(43106));
+
+// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
+
+// fix for "Readable" isn't a named export issue
+const Readable = Stream.Readable;
+
+const BUFFER = Symbol('buffer');
+const TYPE = Symbol('type');
+
+class Blob {
+ constructor() {
+ this[TYPE] = '';
+
+ const blobParts = arguments[0];
+ const options = arguments[1];
+
+ const buffers = [];
+ let size = 0;
+
+ if (blobParts) {
+ const a = blobParts;
+ const length = Number(a.length);
+ for (let i = 0; i < length; i++) {
+ const element = a[i];
+ let buffer;
+ if (element instanceof Buffer) {
+ buffer = element;
+ } else if (ArrayBuffer.isView(element)) {
+ buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
+ } else if (element instanceof ArrayBuffer) {
+ buffer = Buffer.from(element);
+ } else if (element instanceof Blob) {
+ buffer = element[BUFFER];
+ } else {
+ buffer = Buffer.from(typeof element === 'string' ? element : String(element));
+ }
+ size += buffer.length;
+ buffers.push(buffer);
+ }
+ }
+
+ this[BUFFER] = Buffer.concat(buffers);
+
+ let type = options && options.type !== undefined && String(options.type).toLowerCase();
+ if (type && !/[^\u0020-\u007E]/.test(type)) {
+ this[TYPE] = type;
+ }
+ }
+ get size() {
+ return this[BUFFER].length;
+ }
+ get type() {
+ return this[TYPE];
+ }
+ text() {
+ return Promise.resolve(this[BUFFER].toString());
+ }
+ arrayBuffer() {
+ const buf = this[BUFFER];
+ const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
+ return Promise.resolve(ab);
+ }
+ stream() {
+ const readable = new Readable();
+ readable._read = function () {};
+ readable.push(this[BUFFER]);
+ readable.push(null);
+ return readable;
+ }
+ toString() {
+ return '[object Blob]';
+ }
+ slice() {
+ const size = this.size;
+
+ const start = arguments[0];
+ const end = arguments[1];
+ let relativeStart, relativeEnd;
+ if (start === undefined) {
+ relativeStart = 0;
+ } else if (start < 0) {
+ relativeStart = Math.max(size + start, 0);
+ } else {
+ relativeStart = Math.min(start, size);
+ }
+ if (end === undefined) {
+ relativeEnd = size;
+ } else if (end < 0) {
+ relativeEnd = Math.max(size + end, 0);
+ } else {
+ relativeEnd = Math.min(end, size);
+ }
+ const span = Math.max(relativeEnd - relativeStart, 0);
+
+ const buffer = this[BUFFER];
+ const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
+ const blob = new Blob([], { type: arguments[2] });
+ blob[BUFFER] = slicedBuffer;
+ return blob;
+ }
+}
+
+Object.defineProperties(Blob.prototype, {
+ size: { enumerable: true },
+ type: { enumerable: true },
+ slice: { enumerable: true }
+});
+
+Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
+ value: 'Blob',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
+
+/**
+ * fetch-error.js
+ *
+ * FetchError interface for operational errors
+ */
+
+/**
+ * Create FetchError instance
+ *
+ * @param String message Error message for human
+ * @param String type Error type for machine
+ * @param String systemError For Node.js system error
+ * @return FetchError
+ */
+function FetchError(message, type, systemError) {
+ Error.call(this, message);
+
+ this.message = message;
+ this.type = type;
+
+ // when err.type is `system`, err.code contains system error code
+ if (systemError) {
+ this.code = this.errno = systemError.code;
+ }
+
+ // hide custom error implementation details from end-users
+ Error.captureStackTrace(this, this.constructor);
+}
+
+FetchError.prototype = Object.create(Error.prototype);
+FetchError.prototype.constructor = FetchError;
+FetchError.prototype.name = 'FetchError';
+
+let convert;
+try {
+ convert = (__nccwpck_require__(42078).convert);
+} catch (e) {}
+
+const INTERNALS = Symbol('Body internals');
+
+// fix an issue where "PassThrough" isn't a named export for node <10
+const PassThrough = Stream.PassThrough;
+
+/**
+ * Body mixin
+ *
+ * Ref: https://fetch.spec.whatwg.org/#body
+ *
+ * @param Stream body Readable stream
+ * @param Object opts Response options
+ * @return Void
+ */
+function Body(body) {
+ var _this = this;
+
+ var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
+ _ref$size = _ref.size;
+
+ let size = _ref$size === undefined ? 0 : _ref$size;
+ var _ref$timeout = _ref.timeout;
+ let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
+
+ if (body == null) {
+ // body is undefined or null
+ body = null;
+ } else if (isURLSearchParams(body)) {
+ // body is a URLSearchParams
+ body = Buffer.from(body.toString());
+ } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
+ // body is ArrayBuffer
+ body = Buffer.from(body);
+ } else if (ArrayBuffer.isView(body)) {
+ // body is ArrayBufferView
+ body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
+ } else if (body instanceof Stream) ; else {
+ // none of the above
+ // coerce to string then buffer
+ body = Buffer.from(String(body));
+ }
+ this[INTERNALS] = {
+ body,
+ disturbed: false,
+ error: null
+ };
+ this.size = size;
+ this.timeout = timeout;
+
+ if (body instanceof Stream) {
+ body.on('error', function (err) {
+ const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);
+ _this[INTERNALS].error = error;
+ });
+ }
+}
+
+Body.prototype = {
+ get body() {
+ return this[INTERNALS].body;
+ },
+
+ get bodyUsed() {
+ return this[INTERNALS].disturbed;
+ },
+
+ /**
+ * Decode response as ArrayBuffer
+ *
+ * @return Promise
+ */
+ arrayBuffer() {
+ return consumeBody.call(this).then(function (buf) {
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
+ });
+ },
+
+ /**
+ * Return raw response as Blob
+ *
+ * @return Promise
+ */
+ blob() {
+ let ct = this.headers && this.headers.get('content-type') || '';
+ return consumeBody.call(this).then(function (buf) {
+ return Object.assign(
+ // Prevent copying
+ new Blob([], {
+ type: ct.toLowerCase()
+ }), {
+ [BUFFER]: buf
+ });
+ });
+ },
+
+ /**
+ * Decode response as json
+ *
+ * @return Promise
+ */
+ json() {
+ var _this2 = this;
+
+ return consumeBody.call(this).then(function (buffer) {
+ try {
+ return JSON.parse(buffer.toString());
+ } catch (err) {
+ return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
+ }
+ });
+ },
+
+ /**
+ * Decode response as text
+ *
+ * @return Promise
+ */
+ text() {
+ return consumeBody.call(this).then(function (buffer) {
+ return buffer.toString();
+ });
+ },
+
+ /**
+ * Decode response as buffer (non-spec api)
+ *
+ * @return Promise
+ */
+ buffer() {
+ return consumeBody.call(this);
+ },
+
+ /**
+ * Decode response as text, while automatically detecting the encoding and
+ * trying to decode to UTF-8 (non-spec api)
+ *
+ * @return Promise
+ */
+ textConverted() {
+ var _this3 = this;
+
+ return consumeBody.call(this).then(function (buffer) {
+ return convertBody(buffer, _this3.headers);
+ });
+ }
+};
+
+// In browsers, all properties are enumerable.
+Object.defineProperties(Body.prototype, {
+ body: { enumerable: true },
+ bodyUsed: { enumerable: true },
+ arrayBuffer: { enumerable: true },
+ blob: { enumerable: true },
+ json: { enumerable: true },
+ text: { enumerable: true }
+});
+
+Body.mixIn = function (proto) {
+ for (const name of Object.getOwnPropertyNames(Body.prototype)) {
+ // istanbul ignore else: future proof
+ if (!(name in proto)) {
+ const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
+ Object.defineProperty(proto, name, desc);
+ }
+ }
+};
+
+/**
+ * Consume and convert an entire Body to a Buffer.
+ *
+ * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
+ *
+ * @return Promise
+ */
+function consumeBody() {
+ var _this4 = this;
+
+ if (this[INTERNALS].disturbed) {
+ return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
+ }
+
+ this[INTERNALS].disturbed = true;
+
+ if (this[INTERNALS].error) {
+ return Body.Promise.reject(this[INTERNALS].error);
+ }
+
+ let body = this.body;
+
+ // body is null
+ if (body === null) {
+ return Body.Promise.resolve(Buffer.alloc(0));
+ }
+
+ // body is blob
+ if (isBlob(body)) {
+ body = body.stream();
+ }
+
+ // body is buffer
+ if (Buffer.isBuffer(body)) {
+ return Body.Promise.resolve(body);
+ }
+
+ // istanbul ignore if: should never happen
+ if (!(body instanceof Stream)) {
+ return Body.Promise.resolve(Buffer.alloc(0));
+ }
+
+ // body is stream
+ // get ready to actually consume the body
+ let accum = [];
+ let accumBytes = 0;
+ let abort = false;
+
+ return new Body.Promise(function (resolve, reject) {
+ let resTimeout;
+
+ // allow timeout on slow response body
+ if (_this4.timeout) {
+ resTimeout = setTimeout(function () {
+ abort = true;
+ reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
+ }, _this4.timeout);
+ }
+
+ // handle stream errors
+ body.on('error', function (err) {
+ if (err.name === 'AbortError') {
+ // if the request was aborted, reject with this Error
+ abort = true;
+ reject(err);
+ } else {
+ // other errors, such as incorrect content-encoding
+ reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
+ }
+ });
+
+ body.on('data', function (chunk) {
+ if (abort || chunk === null) {
+ return;
+ }
+
+ if (_this4.size && accumBytes + chunk.length > _this4.size) {
+ abort = true;
+ reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
+ return;
+ }
+
+ accumBytes += chunk.length;
+ accum.push(chunk);
+ });
+
+ body.on('end', function () {
+ if (abort) {
+ return;
+ }
+
+ clearTimeout(resTimeout);
+
+ try {
+ resolve(Buffer.concat(accum, accumBytes));
+ } catch (err) {
+ // handle streams that have accumulated too much data (issue #414)
+ reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
+ }
+ });
+ });
+}
+
+/**
+ * Detect buffer encoding and convert to target encoding
+ * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
+ *
+ * @param Buffer buffer Incoming buffer
+ * @param String encoding Target encoding
+ * @return String
+ */
+function convertBody(buffer, headers) {
+ if (typeof convert !== 'function') {
+ throw new Error('The package `encoding` must be installed to use the textConverted() function');
+ }
+
+ const ct = headers.get('content-type');
+ let charset = 'utf-8';
+ let res, str;
+
+ // header
+ if (ct) {
+ res = /charset=([^;]*)/i.exec(ct);
+ }
+
+ // no charset in content type, peek at response body for at most 1024 bytes
+ str = buffer.slice(0, 1024).toString();
+
+ // html5
+ if (!res && str) {
+ res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined;
+
+ this[MAP] = Object.create(null);
+
+ if (init instanceof Headers) {
+ const rawHeaders = init.raw();
+ const headerNames = Object.keys(rawHeaders);
+
+ for (const headerName of headerNames) {
+ for (const value of rawHeaders[headerName]) {
+ this.append(headerName, value);
+ }
+ }
+
+ return;
+ }
+
+ // We don't worry about converting prop to ByteString here as append()
+ // will handle it.
+ if (init == null) ; else if (typeof init === 'object') {
+ const method = init[Symbol.iterator];
+ if (method != null) {
+ if (typeof method !== 'function') {
+ throw new TypeError('Header pairs must be iterable');
+ }
+
+ // sequence>
+ // Note: per spec we have to first exhaust the lists then process them
+ const pairs = [];
+ for (const pair of init) {
+ if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {
+ throw new TypeError('Each header pair must be iterable');
+ }
+ pairs.push(Array.from(pair));
+ }
+
+ for (const pair of pairs) {
+ if (pair.length !== 2) {
+ throw new TypeError('Each header pair must be a name/value tuple');
+ }
+ this.append(pair[0], pair[1]);
+ }
+ } else {
+ // record
+ for (const key of Object.keys(init)) {
+ const value = init[key];
+ this.append(key, value);
+ }
+ }
+ } else {
+ throw new TypeError('Provided initializer must be an object');
+ }
+ }
+
+ /**
+ * Return combined header value given name
+ *
+ * @param String name Header name
+ * @return Mixed
+ */
+ get(name) {
+ name = `${name}`;
+ validateName(name);
+ const key = find(this[MAP], name);
+ if (key === undefined) {
+ return null;
+ }
+
+ return this[MAP][key].join(', ');
+ }
+
+ /**
+ * Iterate over all headers
+ *
+ * @param Function callback Executed for each item with parameters (value, name, thisArg)
+ * @param Boolean thisArg `this` context for callback function
+ * @return Void
+ */
+ forEach(callback) {
+ let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
+
+ let pairs = getHeaders(this);
+ let i = 0;
+ while (i < pairs.length) {
+ var _pairs$i = pairs[i];
+ const name = _pairs$i[0],
+ value = _pairs$i[1];
+
+ callback.call(thisArg, value, name, this);
+ pairs = getHeaders(this);
+ i++;
+ }
+ }
+
+ /**
+ * Overwrite header values given name
+ *
+ * @param String name Header name
+ * @param String value Header value
+ * @return Void
+ */
+ set(name, value) {
+ name = `${name}`;
+ value = `${value}`;
+ validateName(name);
+ validateValue(value);
+ const key = find(this[MAP], name);
+ this[MAP][key !== undefined ? key : name] = [value];
+ }
+
+ /**
+ * Append a value onto existing header
+ *
+ * @param String name Header name
+ * @param String value Header value
+ * @return Void
+ */
+ append(name, value) {
+ name = `${name}`;
+ value = `${value}`;
+ validateName(name);
+ validateValue(value);
+ const key = find(this[MAP], name);
+ if (key !== undefined) {
+ this[MAP][key].push(value);
+ } else {
+ this[MAP][name] = [value];
+ }
+ }
+
+ /**
+ * Check for header name existence
+ *
+ * @param String name Header name
+ * @return Boolean
+ */
+ has(name) {
+ name = `${name}`;
+ validateName(name);
+ return find(this[MAP], name) !== undefined;
+ }
+
+ /**
+ * Delete all header values given name
+ *
+ * @param String name Header name
+ * @return Void
+ */
+ delete(name) {
+ name = `${name}`;
+ validateName(name);
+ const key = find(this[MAP], name);
+ if (key !== undefined) {
+ delete this[MAP][key];
+ }
+ }
+
+ /**
+ * Return raw headers (non-spec api)
+ *
+ * @return Object
+ */
+ raw() {
+ return this[MAP];
+ }
+
+ /**
+ * Get an iterator on keys.
+ *
+ * @return Iterator
+ */
+ keys() {
+ return createHeadersIterator(this, 'key');
+ }
+
+ /**
+ * Get an iterator on values.
+ *
+ * @return Iterator
+ */
+ values() {
+ return createHeadersIterator(this, 'value');
+ }
+
+ /**
+ * Get an iterator on entries.
+ *
+ * This is the default iterator of the Headers object.
+ *
+ * @return Iterator
+ */
+ [Symbol.iterator]() {
+ return createHeadersIterator(this, 'key+value');
+ }
+}
+Headers.prototype.entries = Headers.prototype[Symbol.iterator];
+
+Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
+ value: 'Headers',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
+
+Object.defineProperties(Headers.prototype, {
+ get: { enumerable: true },
+ forEach: { enumerable: true },
+ set: { enumerable: true },
+ append: { enumerable: true },
+ has: { enumerable: true },
+ delete: { enumerable: true },
+ keys: { enumerable: true },
+ values: { enumerable: true },
+ entries: { enumerable: true }
+});
+
+function getHeaders(headers) {
+ let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';
+
+ const keys = Object.keys(headers[MAP]).sort();
+ return keys.map(kind === 'key' ? function (k) {
+ return k.toLowerCase();
+ } : kind === 'value' ? function (k) {
+ return headers[MAP][k].join(', ');
+ } : function (k) {
+ return [k.toLowerCase(), headers[MAP][k].join(', ')];
+ });
+}
+
+const INTERNAL = Symbol('internal');
+
+function createHeadersIterator(target, kind) {
+ const iterator = Object.create(HeadersIteratorPrototype);
+ iterator[INTERNAL] = {
+ target,
+ kind,
+ index: 0
+ };
+ return iterator;
+}
+
+const HeadersIteratorPrototype = Object.setPrototypeOf({
+ next() {
+ // istanbul ignore if
+ if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
+ throw new TypeError('Value of `this` is not a HeadersIterator');
+ }
+
+ var _INTERNAL = this[INTERNAL];
+ const target = _INTERNAL.target,
+ kind = _INTERNAL.kind,
+ index = _INTERNAL.index;
+
+ const values = getHeaders(target, kind);
+ const len = values.length;
+ if (index >= len) {
+ return {
+ value: undefined,
+ done: true
+ };
+ }
+
+ this[INTERNAL].index = index + 1;
+
+ return {
+ value: values[index],
+ done: false
+ };
+ }
+}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
+
+Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
+ value: 'HeadersIterator',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
+
+/**
+ * Export the Headers object in a form that Node.js can consume.
+ *
+ * @param Headers headers
+ * @return Object
+ */
+function exportNodeCompatibleHeaders(headers) {
+ const obj = Object.assign({ __proto__: null }, headers[MAP]);
+
+ // http.request() only supports string as Host header. This hack makes
+ // specifying custom Host header possible.
+ const hostHeaderKey = find(headers[MAP], 'Host');
+ if (hostHeaderKey !== undefined) {
+ obj[hostHeaderKey] = obj[hostHeaderKey][0];
+ }
+
+ return obj;
}
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
/**
- * ONLY AVAILABLE IN NODE.JS RUNTIME.
+ * Create a Headers object from an object of headers, ignoring those that do
+ * not conform to HTTP grammar productions.
*
- * 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.
+ * @param Object obj Object of headers
+ * @return Headers
+ */
+function createHeadersLenient(obj) {
+ const headers = new Headers();
+ for (const name of Object.keys(obj)) {
+ if (invalidTokenRegex.test(name)) {
+ continue;
+ }
+ if (Array.isArray(obj[name])) {
+ for (const val of obj[name]) {
+ if (invalidHeaderCharRegex.test(val)) {
+ continue;
+ }
+ if (headers[MAP][name] === undefined) {
+ headers[MAP][name] = [val];
+ } else {
+ headers[MAP][name].push(val);
+ }
+ }
+ } else if (!invalidHeaderCharRegex.test(obj[name])) {
+ headers[MAP][name] = [obj[name]];
+ }
+ }
+ return headers;
+}
+
+const INTERNALS$1 = Symbol('Response internals');
+
+// fix an issue where "STATUS_CODES" aren't a named export for node <10
+const STATUS_CODES = http.STATUS_CODES;
+
+/**
+ * Response class
+ *
+ * @param Stream body Readable stream
+ * @param Object opts Response options
+ * @return Void
*/
-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://docs.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://docs.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("");
- }
+class Response {
+ constructor() {
+ let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
+ let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+
+ Body.call(this, body, opts);
+
+ const status = opts.status || 200;
+ const headers = new Headers(opts.headers);
+
+ if (body != null && !headers.has('Content-Type')) {
+ const contentType = extractContentType(body);
+ if (contentType) {
+ headers.append('Content-Type', contentType);
+ }
+ }
+
+ this[INTERNALS$1] = {
+ url: opts.url,
+ status,
+ statusText: opts.statusText || STATUS_CODES[status],
+ headers,
+ counter: opts.counter
+ };
+ }
+
+ get url() {
+ return this[INTERNALS$1].url || '';
+ }
+
+ get status() {
+ return this[INTERNALS$1].status;
+ }
+
+ /**
+ * Convenience property representing if the request ended normally
+ */
+ get ok() {
+ return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
+ }
+
+ get redirected() {
+ return this[INTERNALS$1].counter > 0;
+ }
+
+ get statusText() {
+ return this[INTERNALS$1].statusText;
+ }
+
+ get headers() {
+ return this[INTERNALS$1].headers;
+ }
+
+ /**
+ * Clone this response
+ *
+ * @return Response
+ */
+ clone() {
+ return new Response(clone(this), {
+ url: this.url,
+ status: this.status,
+ statusText: this.statusText,
+ headers: this.headers,
+ ok: this.ok,
+ redirected: this.redirected
+ });
+ }
+}
+
+Body.mixIn(Response.prototype);
+
+Object.defineProperties(Response.prototype, {
+ url: { enumerable: true },
+ status: { enumerable: true },
+ ok: { enumerable: true },
+ redirected: { enumerable: true },
+ statusText: { enumerable: true },
+ headers: { enumerable: true },
+ clone: { enumerable: true }
+});
+
+Object.defineProperty(Response.prototype, Symbol.toStringTag, {
+ value: 'Response',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
+
+const INTERNALS$2 = Symbol('Request internals');
+const URL = Url.URL || whatwgUrl.URL;
+
+// fix an issue where "format", "parse" aren't a named export for node <10
+const parse_url = Url.parse;
+const format_url = Url.format;
+
+/**
+ * Wrapper around `new URL` to handle arbitrary URLs
+ *
+ * @param {string} urlStr
+ * @return {void}
+ */
+function parseURL(urlStr) {
+ /*
+ Check whether the URL is absolute or not
+ Scheme: https://tools.ietf.org/html/rfc3986#section-3.1
+ Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3
+ */
+ if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) {
+ urlStr = new URL(urlStr).toString();
+ }
+
+ // Fallback to old implementation for arbitrary URLs
+ return parse_url(urlStr);
+}
+
+const streamDestructionSupported = 'destroy' in Stream.Readable.prototype;
+
+/**
+ * Check if a value is an instance of Request.
+ *
+ * @param Mixed input
+ * @return Boolean
+ */
+function isRequest(input) {
+ return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';
+}
+
+function isAbortSignal(signal) {
+ const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);
+ return !!(proto && proto.constructor.name === 'AbortSignal');
+}
+
+/**
+ * Request class
+ *
+ * @param Mixed input Url or Request instance
+ * @param Object init Custom options
+ * @return Void
+ */
+class Request {
+ constructor(input) {
+ let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+
+ let parsedURL;
+
+ // normalize input
+ if (!isRequest(input)) {
+ if (input && input.href) {
+ // in order to support Node.js' Url objects; though WHATWG's URL objects
+ // will fall into this branch also (since their `toString()` will return
+ // `href` property anyway)
+ parsedURL = parseURL(input.href);
+ } else {
+ // coerce input to a string before attempting to parse
+ parsedURL = parseURL(`${input}`);
+ }
+ input = {};
+ } else {
+ parsedURL = parseURL(input.url);
+ }
+
+ let method = init.method || input.method || 'GET';
+ method = method.toUpperCase();
+
+ if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
+ throw new TypeError('Request with GET/HEAD method cannot have body');
+ }
+
+ let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
+
+ Body.call(this, inputBody, {
+ timeout: init.timeout || input.timeout || 0,
+ size: init.size || input.size || 0
+ });
+
+ const headers = new Headers(init.headers || input.headers || {});
+
+ if (inputBody != null && !headers.has('Content-Type')) {
+ const contentType = extractContentType(inputBody);
+ if (contentType) {
+ headers.append('Content-Type', contentType);
+ }
+ }
+
+ let signal = isRequest(input) ? input.signal : null;
+ if ('signal' in init) signal = init.signal;
+
+ if (signal != null && !isAbortSignal(signal)) {
+ throw new TypeError('Expected signal to be an instanceof AbortSignal');
+ }
+
+ this[INTERNALS$2] = {
+ method,
+ redirect: init.redirect || input.redirect || 'follow',
+ headers,
+ parsedURL,
+ signal
+ };
+
+ // node-fetch-only options
+ this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
+ this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
+ this.counter = init.counter || input.counter || 0;
+ this.agent = init.agent || input.agent;
+ }
+
+ get method() {
+ return this[INTERNALS$2].method;
+ }
+
+ get url() {
+ return format_url(this[INTERNALS$2].parsedURL);
+ }
+
+ get headers() {
+ return this[INTERNALS$2].headers;
+ }
+
+ get redirect() {
+ return this[INTERNALS$2].redirect;
+ }
+
+ get signal() {
+ return this[INTERNALS$2].signal;
+ }
+
+ /**
+ * Clone this request
+ *
+ * @return Request
+ */
+ clone() {
+ return new Request(this);
+ }
+}
+
+Body.mixIn(Request.prototype);
+
+Object.defineProperty(Request.prototype, Symbol.toStringTag, {
+ value: 'Request',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
+
+Object.defineProperties(Request.prototype, {
+ method: { enumerable: true },
+ url: { enumerable: true },
+ headers: { enumerable: true },
+ redirect: { enumerable: true },
+ clone: { enumerable: true },
+ signal: { enumerable: true }
+});
+
+/**
+ * Convert a Request to Node.js http request options.
+ *
+ * @param Request A Request instance
+ * @return Object The options object to be passed to http.request
+ */
+function getNodeRequestOptions(request) {
+ const parsedURL = request[INTERNALS$2].parsedURL;
+ const headers = new Headers(request[INTERNALS$2].headers);
+
+ // fetch step 1.3
+ if (!headers.has('Accept')) {
+ headers.set('Accept', '*/*');
+ }
+
+ // Basic fetch
+ if (!parsedURL.protocol || !parsedURL.hostname) {
+ throw new TypeError('Only absolute URLs are supported');
+ }
+
+ if (!/^https?:$/.test(parsedURL.protocol)) {
+ throw new TypeError('Only HTTP(S) protocols are supported');
+ }
+
+ if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {
+ throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');
+ }
+
+ // HTTP-network-or-cache fetch steps 2.4-2.7
+ let contentLengthValue = null;
+ if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
+ contentLengthValue = '0';
+ }
+ if (request.body != null) {
+ const totalBytes = getTotalBytes(request);
+ if (typeof totalBytes === 'number') {
+ contentLengthValue = String(totalBytes);
+ }
+ }
+ if (contentLengthValue) {
+ headers.set('Content-Length', contentLengthValue);
+ }
+
+ // HTTP-network-or-cache fetch step 2.11
+ if (!headers.has('User-Agent')) {
+ headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
+ }
+
+ // HTTP-network-or-cache fetch step 2.15
+ if (request.compress && !headers.has('Accept-Encoding')) {
+ headers.set('Accept-Encoding', 'gzip,deflate');
+ }
+
+ let agent = request.agent;
+ if (typeof agent === 'function') {
+ agent = agent(parsedURL);
+ }
+
+ // HTTP-network fetch step 4.2
+ // chunked encoding is handled by Node.js
+
+ return Object.assign({}, parsedURL, {
+ method: request.method,
+ headers: exportNodeCompatibleHeaders(headers),
+ agent
+ });
+}
+
+/**
+ * abort-error.js
+ *
+ * AbortError interface for cancelled requests
+ */
+
+/**
+ * Create AbortError instance
+ *
+ * @param String message Error message for human
+ * @return AbortError
+ */
+function AbortError(message) {
+ Error.call(this, message);
+
+ this.type = 'aborted';
+ this.message = message;
+
+ // hide custom error implementation details from end-users
+ Error.captureStackTrace(this, this.constructor);
+}
+
+AbortError.prototype = Object.create(Error.prototype);
+AbortError.prototype.constructor = AbortError;
+AbortError.prototype.name = 'AbortError';
+
+const URL$1 = Url.URL || whatwgUrl.URL;
+
+// fix an issue where "PassThrough", "resolve" aren't a named export for node <10
+const PassThrough$1 = Stream.PassThrough;
+
+const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) {
+ const orig = new URL$1(original).hostname;
+ const dest = new URL$1(destination).hostname;
+
+ return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest);
+};
+
+/**
+ * isSameProtocol reports whether the two provided URLs use the same protocol.
+ *
+ * Both domains must already be in canonical form.
+ * @param {string|URL} original
+ * @param {string|URL} destination
+ */
+const isSameProtocol = function isSameProtocol(destination, original) {
+ const orig = new URL$1(original).protocol;
+ const dest = new URL$1(destination).protocol;
+
+ return orig === dest;
+};
+
+/**
+ * Fetch function
+ *
+ * @param Mixed url Absolute url or Request instance
+ * @param Object opts Fetch options
+ * @return Promise
+ */
+function fetch(url, opts) {
+
+ // allow custom promise
+ if (!fetch.Promise) {
+ throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
+ }
+
+ Body.Promise = fetch.Promise;
+
+ // wrap http.request into fetch
+ return new fetch.Promise(function (resolve, reject) {
+ // build request object
+ const request = new Request(url, opts);
+ const options = getNodeRequestOptions(request);
+
+ const send = (options.protocol === 'https:' ? https : http).request;
+ const signal = request.signal;
+
+ let response = null;
+
+ const abort = function abort() {
+ let error = new AbortError('The user aborted a request.');
+ reject(error);
+ if (request.body && request.body instanceof Stream.Readable) {
+ destroyStream(request.body, error);
+ }
+ if (!response || !response.body) return;
+ response.body.emit('error', error);
+ };
+
+ if (signal && signal.aborted) {
+ abort();
+ return;
+ }
+
+ const abortAndFinalize = function abortAndFinalize() {
+ abort();
+ finalize();
+ };
+
+ // send request
+ const req = send(options);
+ let reqTimeout;
+
+ if (signal) {
+ signal.addEventListener('abort', abortAndFinalize);
+ }
+
+ function finalize() {
+ req.abort();
+ if (signal) signal.removeEventListener('abort', abortAndFinalize);
+ clearTimeout(reqTimeout);
+ }
+
+ if (request.timeout) {
+ req.once('socket', function (socket) {
+ reqTimeout = setTimeout(function () {
+ reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
+ finalize();
+ }, request.timeout);
+ });
+ }
+
+ req.on('error', function (err) {
+ reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
+
+ if (response && response.body) {
+ destroyStream(response.body, err);
+ }
+
+ finalize();
+ });
+
+ fixResponseChunkedTransferBadEnding(req, function (err) {
+ if (signal && signal.aborted) {
+ return;
+ }
+
+ if (response && response.body) {
+ destroyStream(response.body, err);
+ }
+ });
+
+ /* c8 ignore next 18 */
+ if (parseInt(process.version.substring(1)) < 14) {
+ // Before Node.js 14, pipeline() does not fully support async iterators and does not always
+ // properly handle when the socket close/end events are out of order.
+ req.on('socket', function (s) {
+ s.addListener('close', function (hadError) {
+ // if a data listener is still present we didn't end cleanly
+ const hasDataListener = s.listenerCount('data') > 0;
+
+ // if end happened before close but the socket didn't emit an error, do it now
+ if (response && hasDataListener && !hadError && !(signal && signal.aborted)) {
+ const err = new Error('Premature close');
+ err.code = 'ERR_STREAM_PREMATURE_CLOSE';
+ response.body.emit('error', err);
+ }
+ });
+ });
+ }
+
+ req.on('response', function (res) {
+ clearTimeout(reqTimeout);
+
+ const headers = createHeadersLenient(res.headers);
+
+ // HTTP fetch step 5
+ if (fetch.isRedirect(res.statusCode)) {
+ // HTTP fetch step 5.2
+ const location = headers.get('Location');
+
+ // HTTP fetch step 5.3
+ let locationURL = null;
+ try {
+ locationURL = location === null ? null : new URL$1(location, request.url).toString();
+ } catch (err) {
+ // error here can only be invalid URL in Location: header
+ // do not throw when options.redirect == manual
+ // let the user extract the errorneous redirect URL
+ if (request.redirect !== 'manual') {
+ reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));
+ finalize();
+ return;
+ }
+ }
+
+ // HTTP fetch step 5.5
+ switch (request.redirect) {
+ case 'error':
+ reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));
+ finalize();
+ return;
+ case 'manual':
+ // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
+ if (locationURL !== null) {
+ // handle corrupted header
+ try {
+ headers.set('Location', locationURL);
+ } catch (err) {
+ // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request
+ reject(err);
+ }
+ }
+ break;
+ case 'follow':
+ // HTTP-redirect fetch step 2
+ if (locationURL === null) {
+ break;
+ }
+
+ // HTTP-redirect fetch step 5
+ if (request.counter >= request.follow) {
+ reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
+ finalize();
+ return;
+ }
+
+ // HTTP-redirect fetch step 6 (counter increment)
+ // Create a new Request object.
+ const requestOpts = {
+ headers: new Headers(request.headers),
+ follow: request.follow,
+ counter: request.counter + 1,
+ agent: request.agent,
+ compress: request.compress,
+ method: request.method,
+ body: request.body,
+ signal: request.signal,
+ timeout: request.timeout,
+ size: request.size
+ };
+
+ if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) {
+ for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) {
+ requestOpts.headers.delete(name);
+ }
+ }
+
+ // HTTP-redirect fetch step 9
+ if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
+ reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
+ finalize();
+ return;
+ }
+
+ // HTTP-redirect fetch step 11
+ if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
+ requestOpts.method = 'GET';
+ requestOpts.body = undefined;
+ requestOpts.headers.delete('content-length');
+ }
+
+ // HTTP-redirect fetch step 15
+ resolve(fetch(new Request(locationURL, requestOpts)));
+ finalize();
+ return;
+ }
+ }
+
+ // prepare response
+ res.once('end', function () {
+ if (signal) signal.removeEventListener('abort', abortAndFinalize);
+ });
+ let body = res.pipe(new PassThrough$1());
+
+ const response_options = {
+ url: request.url,
+ status: res.statusCode,
+ statusText: res.statusMessage,
+ headers: headers,
+ size: request.size,
+ timeout: request.timeout,
+ counter: request.counter
+ };
+
+ // HTTP-network fetch step 12.1.1.3
+ const codings = headers.get('Content-Encoding');
+
+ // HTTP-network fetch step 12.1.1.4: handle content codings
+
+ // in following scenarios we ignore compression support
+ // 1. compression support is disabled
+ // 2. HEAD request
+ // 3. no Content-Encoding header
+ // 4. no content response (204)
+ // 5. content not modified response (304)
+ if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
+ response = new Response(body, response_options);
+ resolve(response);
+ return;
+ }
+
+ // For Node v6+
+ // 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.
+ const zlibOptions = {
+ flush: zlib.Z_SYNC_FLUSH,
+ finishFlush: zlib.Z_SYNC_FLUSH
+ };
+
+ // for gzip
+ if (codings == 'gzip' || codings == 'x-gzip') {
+ body = body.pipe(zlib.createGunzip(zlibOptions));
+ response = new Response(body, response_options);
+ resolve(response);
+ return;
+ }
+
+ // for deflate
+ if (codings == 'deflate' || codings == 'x-deflate') {
+ // handle the infamous raw deflate response from old servers
+ // a hack for old IIS and Apache servers
+ const raw = res.pipe(new PassThrough$1());
+ raw.once('data', function (chunk) {
+ // see http://stackoverflow.com/questions/37519828
+ if ((chunk[0] & 0x0F) === 0x08) {
+ body = body.pipe(zlib.createInflate());
+ } else {
+ body = body.pipe(zlib.createInflateRaw());
+ }
+ response = new Response(body, response_options);
+ resolve(response);
+ });
+ raw.on('end', function () {
+ // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted.
+ if (!response) {
+ response = new Response(body, response_options);
+ resolve(response);
+ }
+ });
+ return;
+ }
+
+ // for br
+ if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {
+ body = body.pipe(zlib.createBrotliDecompress());
+ response = new Response(body, response_options);
+ resolve(response);
+ return;
+ }
+
+ // otherwise, use response as-is
+ response = new Response(body, response_options);
+ resolve(response);
+ });
+
+ writeToStream(req, request);
+ });
+}
+function fixResponseChunkedTransferBadEnding(request, errorCallback) {
+ let socket;
+
+ request.on('socket', function (s) {
+ socket = s;
+ });
+
+ request.on('response', function (response) {
+ const headers = response.headers;
+
+ if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) {
+ response.once('close', function (hadError) {
+ // tests for socket presence, as in some situations the
+ // the 'socket' event is not triggered for the request
+ // (happens in deno), avoids `TypeError`
+ // if a data listener is still present we didn't end cleanly
+ const hasDataListener = socket && socket.listenerCount('data') > 0;
+
+ if (hasDataListener && !hadError) {
+ const err = new Error('Premature close');
+ err.code = 'ERR_STREAM_PREMATURE_CLOSE';
+ errorCallback(err);
+ }
+ });
+ }
+ });
}
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
+function destroyStream(stream, err) {
+ if (stream.destroy) {
+ stream.destroy(err);
+ } else {
+ // node < 8
+ stream.emit('error', err);
+ stream.end();
+ }
+}
+
+/**
+ * Redirect code matching
+ *
+ * @param Number code Status code
+ * @return Boolean
+ */
+fetch.isRedirect = function (code) {
+ return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
+};
+
+// expose Promise
+fetch.Promise = global.Promise;
+
+module.exports = exports = fetch;
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports["default"] = exports;
+exports.Headers = Headers;
+exports.Request = Request;
+exports.Response = Response;
+exports.FetchError = FetchError;
+exports.AbortError = AbortError;
+
+
+/***/ }),
+
+/***/ 55560:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+var wrappy = __nccwpck_require__(58264)
+module.exports = wrappy(once)
+module.exports.strict = wrappy(onceStrict)
+
+once.proto = once(function () {
+ Object.defineProperty(Function.prototype, 'once', {
+ value: function () {
+ return once(this)
+ },
+ configurable: true
+ })
+
+ Object.defineProperty(Function.prototype, 'onceStrict', {
+ value: function () {
+ return onceStrict(this)
+ },
+ configurable: true
+ })
+})
+
+function once (fn) {
+ var f = function () {
+ if (f.called) return f.value
+ f.called = true
+ return f.value = fn.apply(this, arguments)
+ }
+ f.called = false
+ return f
+}
+
+function onceStrict (fn) {
+ var f = function () {
+ if (f.called)
+ throw new Error(f.onceError)
+ f.called = true
+ return f.value = fn.apply(this, arguments)
+ }
+ var name = fn.name || 'Function wrapped with `once`'
+ f.onceError = name + " shouldn't be called more than once"
+ f.called = false
+ return f
+}
+
+
+/***/ }),
+
+/***/ 58890:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+const Queue = __nccwpck_require__(30538);
+
+const pLimit = concurrency => {
+ if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {
+ throw new TypeError('Expected `concurrency` to be a number from 1 and up');
+ }
+
+ const queue = new Queue();
+ let activeCount = 0;
+
+ const next = () => {
+ activeCount--;
+
+ if (queue.size > 0) {
+ queue.dequeue()();
+ }
+ };
+
+ const run = async (fn, resolve, ...args) => {
+ activeCount++;
+
+ const result = (async () => fn(...args))();
+
+ resolve(result);
+
+ try {
+ await result;
+ } catch {}
+
+ next();
+ };
+
+ const enqueue = (fn, resolve, ...args) => {
+ queue.enqueue(run.bind(null, fn, resolve, ...args));
+
+ (async () => {
+ // This function needs to wait until the next microtask before comparing
+ // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously
+ // when the run function is dequeued and called. The comparison in the if-statement
+ // needs to happen asynchronously as well to get an up-to-date value for `activeCount`.
+ await Promise.resolve();
+
+ if (activeCount < concurrency && queue.size > 0) {
+ queue.dequeue()();
+ }
+ })();
+ };
+
+ const generator = (fn, ...args) => new Promise(resolve => {
+ enqueue(fn, resolve, ...args);
+ });
+
+ Object.defineProperties(generator, {
+ activeCount: {
+ get: () => activeCount
+ },
+ pendingCount: {
+ get: () => queue.size
+ },
+ clearQueue: {
+ value: () => {
+ queue.clear();
+ }
+ }
+ });
+
+ return generator;
+};
+
+module.exports = pLimit;
+
+
+/***/ }),
+
+/***/ 77777:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var parseUrl = (__nccwpck_require__(87016).parse);
+
+var DEFAULT_PORTS = {
+ ftp: 21,
+ gopher: 70,
+ http: 80,
+ https: 443,
+ ws: 80,
+ wss: 443,
+};
+
+var stringEndsWith = String.prototype.endsWith || function(s) {
+ return s.length <= this.length &&
+ this.indexOf(s, this.length - s.length) !== -1;
+};
+
/**
- * 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.
+ * @param {string|object} url - The URL, or the result from url.parse.
+ * @return {string} The URL of the proxy that should handle the request to the
+ * given URL. If no proxy is set, this will be an empty string.
*/
-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://docs.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("");
- }
+function getProxyForUrl(url) {
+ var parsedUrl = typeof url === 'string' ? parseUrl(url) : url || {};
+ var proto = parsedUrl.protocol;
+ var hostname = parsedUrl.host;
+ var port = parsedUrl.port;
+ if (typeof hostname !== 'string' || !hostname || typeof proto !== 'string') {
+ return ''; // Don't proxy URLs without a valid scheme or host.
+ }
+
+ proto = proto.split(':', 1)[0];
+ // 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*$/, '');
+ port = parseInt(port) || DEFAULT_PORTS[proto] || 0;
+ if (!shouldProxy(hostname, port)) {
+ return ''; // Don't proxy URLs that match NO_PROXY.
+ }
+
+ var proxy =
+ getEnv('npm_config_' + proto + '_proxy') ||
+ getEnv(proto + '_proxy') ||
+ getEnv('npm_config_proxy') ||
+ getEnv('all_proxy');
+ if (proxy && proxy.indexOf('://') === -1) {
+ // Missing scheme in proxy, default to the requested URL's scheme.
+ proxy = proto + '://' + proxy;
+ }
+ return proxy;
}
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
/**
- * ONLY AVAILABLE IN NODE.JS RUNTIME.
+ * Determines whether a given URL should be proxied.
*
- * 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.
+ * @param {string} hostname - The host name of the URL.
+ * @param {number} port - The effective port of the URL.
+ * @returns {boolean} Whether the given URL should be proxied.
+ * @private
*/
-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;
+function shouldProxy(hostname, port) {
+ var NO_PROXY =
+ (getEnv('npm_config_no_proxy') || getEnv('no_proxy')).toLowerCase();
+ if (!NO_PROXY) {
+ return true; // Always proxy if NO_PROXY is not set.
+ }
+ if (NO_PROXY === '*') {
+ return false; // Never proxy if wildcard is set.
+ }
+
+ return NO_PROXY.split(/[,\s]/).every(function(proxy) {
+ if (!proxy) {
+ return true; // Skip zero-length hosts.
}
- /**
- * 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;
+ var parsedProxy = proxy.match(/^(.+):(\d+)$/);
+ var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy;
+ var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0;
+ if (parsedProxyPort && parsedProxyPort !== port) {
+ return true; // Skip if ports don't match.
}
- /**
- * 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("");
+
+ if (!/^[.*]/.test(parsedProxyHostname)) {
+ // No wildcards, so stop proxying if there is an exact match.
+ return hostname !== parsedProxyHostname;
+ }
+
+ if (parsedProxyHostname.charAt(0) === '*') {
+ // Remove leading wildcard.
+ parsedProxyHostname = parsedProxyHostname.slice(1);
}
+ // Stop proxying if the hostname ends with the no_proxy host.
+ return !stringEndsWith.call(hostname, parsedProxyHostname);
+ });
}
-// 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.
+ * Get the value for an environment variable.
*
- * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas
- *
- * @param accountSASSignatureValues -
- * @param sharedKeyCredential -
+ * @param {string} key - The name of the environment variable.
+ * @return {string} The value of the environment variable.
+ * @private
*/
-function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) {
- return generateAccountSASQueryParametersInternal(accountSASSignatureValues, sharedKeyCredential)
- .sasQueryParameters;
+function getEnv(key) {
+ return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || '';
}
-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.");
+
+exports.getProxyForUrl = getProxyForUrl;
+
+
+/***/ }),
+
+/***/ 25500:
+/***/ ((module) => {
+
+"use strict";
+
+
+const codes = {};
+
+function createErrorType(code, message, Base) {
+ if (!Base) {
+ Base = Error
+ }
+
+ function getMessage (arg1, arg2, arg3) {
+ if (typeof message === 'string') {
+ return message
+ } else {
+ return message(arg1, arg2, arg3)
}
- if (accountSASSignatureValues.permissions &&
- accountSASSignatureValues.permissions.permanentDelete &&
- version < "2019-10-10") {
- throw RangeError("'version' must be >= '2019-10-10' when provided 'y' permission.");
+ }
+
+ class NodeError extends Base {
+ constructor (arg1, arg2, arg3) {
+ super(getMessage(arg1, arg2, arg3));
}
- if (accountSASSignatureValues.permissions &&
- accountSASSignatureValues.permissions.tag &&
- version < "2019-12-12") {
- throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission.");
+ }
+
+ NodeError.prototype.name = Base.name;
+ NodeError.prototype.code = code;
+
+ codes[code] = NodeError;
+}
+
+// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
+function oneOf(expected, thing) {
+ if (Array.isArray(expected)) {
+ const len = expected.length;
+ expected = expected.map((i) => String(i));
+ if (len > 2) {
+ return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` +
+ expected[len - 1];
+ } else if (len === 2) {
+ return `one of ${thing} ${expected[0]} or ${expected[1]}`;
+ } else {
+ return `of ${thing} ${expected[0]}`;
}
- if (accountSASSignatureValues.permissions &&
- accountSASSignatureValues.permissions.filter &&
- version < "2019-12-12") {
- throw RangeError("'version' must be >= '2019-12-12' when provided 'f' permission.");
+ } else {
+ return `of ${thing} ${String(expected)}`;
+ }
+}
+
+// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
+function startsWith(str, search, pos) {
+ return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
+}
+
+// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
+function endsWith(str, search, this_len) {
+ if (this_len === undefined || this_len > str.length) {
+ this_len = str.length;
+ }
+ return str.substring(this_len - search.length, this_len) === search;
+}
+
+// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
+function includes(str, search, start) {
+ if (typeof start !== 'number') {
+ start = 0;
+ }
+
+ if (start + search.length > str.length) {
+ return false;
+ } else {
+ return str.indexOf(search, start) !== -1;
+ }
+}
+
+createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
+ return 'The value "' + value + '" is invalid for option "' + name + '"'
+}, TypeError);
+createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
+ // determiner: 'must be' or 'must not be'
+ let determiner;
+ if (typeof expected === 'string' && startsWith(expected, 'not ')) {
+ determiner = 'must not be';
+ expected = expected.replace(/^not /, '');
+ } else {
+ determiner = 'must be';
+ }
+
+ let msg;
+ if (endsWith(name, ' argument')) {
+ // For cases like 'first argument'
+ msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;
+ } else {
+ const type = includes(name, '.') ? 'property' : 'argument';
+ msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`;
+ }
+
+ msg += `. Received type ${typeof actual}`;
+ return msg;
+}, TypeError);
+createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
+createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
+ return 'The ' + name + ' method is not implemented'
+});
+createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
+createErrorType('ERR_STREAM_DESTROYED', function (name) {
+ return 'Cannot call ' + name + ' after a stream was destroyed';
+});
+createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
+createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
+createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
+createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
+createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
+ return 'Unknown encoding: ' + arg
+}, TypeError);
+createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
+
+module.exports.F = codes;
+
+
+/***/ }),
+
+/***/ 82063:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// 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.
+
+// a duplex stream is just a stream that is both readable and writable.
+// Since JS doesn't have multiple prototypal inheritance, this class
+// prototypally inherits from Readable, and then parasitically from
+// Writable.
+
+
+
+/**/
+var objectKeys = Object.keys || function (obj) {
+ var keys = [];
+ for (var key in obj) keys.push(key);
+ return keys;
+};
+/**/
+
+module.exports = Duplex;
+var Readable = __nccwpck_require__(86893);
+var Writable = __nccwpck_require__(38797);
+__nccwpck_require__(39598)(Duplex, Readable);
+{
+ // Allow the keys array to be GC'ed.
+ var keys = objectKeys(Writable.prototype);
+ for (var v = 0; v < keys.length; v++) {
+ var method = keys[v];
+ if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
+ }
+}
+function Duplex(options) {
+ if (!(this instanceof Duplex)) return new Duplex(options);
+ Readable.call(this, options);
+ Writable.call(this, options);
+ this.allowHalfOpen = true;
+ if (options) {
+ if (options.readable === false) this.readable = false;
+ if (options.writable === false) this.writable = false;
+ if (options.allowHalfOpen === false) {
+ this.allowHalfOpen = false;
+ this.once('end', onend);
+ }
+ }
+}
+Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._writableState.highWaterMark;
+ }
+});
+Object.defineProperty(Duplex.prototype, 'writableBuffer', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._writableState && this._writableState.getBuffer();
+ }
+});
+Object.defineProperty(Duplex.prototype, 'writableLength', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._writableState.length;
+ }
+});
+
+// the no-half-open enforcer
+function onend() {
+ // If the writable side ended, then we're ok.
+ if (this._writableState.ended) return;
+
+ // no more data can be written.
+ // But allow more writes to happen in this tick.
+ process.nextTick(onEndNT, this);
+}
+function onEndNT(self) {
+ self.end();
+}
+Object.defineProperty(Duplex.prototype, 'destroyed', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ if (this._readableState === undefined || this._writableState === undefined) {
+ return false;
}
- if (accountSASSignatureValues.encryptionScope && version < "2020-12-06") {
- throw RangeError("'version' must be >= '2020-12-06' when provided 'encryptionScope' in SAS.");
+ return this._readableState.destroyed && this._writableState.destroyed;
+ },
+ set: function set(value) {
+ // we ignore the value if the stream
+ // has not been initialized yet
+ if (this._readableState === undefined || this._writableState === undefined) {
+ return;
}
- 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");
+
+ // backward compatibility, the user is explicitly
+ // managing destroyed
+ this._readableState.destroyed = value;
+ this._writableState.destroyed = value;
+ }
+});
+
+/***/ }),
+
+/***/ 35283:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// 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.
+
+// a passthrough stream.
+// basically just the most minimal sort of Transform stream.
+// Every written chunk gets output as-is.
+
+
+
+module.exports = PassThrough;
+var Transform = __nccwpck_require__(12337);
+__nccwpck_require__(39598)(PassThrough, Transform);
+function PassThrough(options) {
+ if (!(this instanceof PassThrough)) return new PassThrough(options);
+ Transform.call(this, options);
+}
+PassThrough.prototype._transform = function (chunk, encoding, cb) {
+ cb(null, chunk);
+};
+
+/***/ }),
+
+/***/ 86893:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// 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.
+
+
+
+module.exports = Readable;
+
+/**/
+var Duplex;
+/**/
+
+Readable.ReadableState = ReadableState;
+
+/**/
+var EE = (__nccwpck_require__(24434).EventEmitter);
+var EElistenerCount = function EElistenerCount(emitter, type) {
+ return emitter.listeners(type).length;
+};
+/**/
+
+/**/
+var Stream = __nccwpck_require__(63283);
+/**/
+
+var Buffer = (__nccwpck_require__(20181).Buffer);
+var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
+function _uint8ArrayToBuffer(chunk) {
+ return Buffer.from(chunk);
+}
+function _isUint8Array(obj) {
+ return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
+}
+
+/**/
+var debugUtil = __nccwpck_require__(39023);
+var debug;
+if (debugUtil && debugUtil.debuglog) {
+ debug = debugUtil.debuglog('stream');
+} else {
+ debug = function debug() {};
+}
+/**/
+
+var BufferList = __nccwpck_require__(77336);
+var destroyImpl = __nccwpck_require__(65089);
+var _require = __nccwpck_require__(54874),
+ getHighWaterMark = _require.getHighWaterMark;
+var _require$codes = (__nccwpck_require__(25500)/* .codes */ .F),
+ ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
+ ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
+ ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
+ ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;
+
+// Lazy loaded to improve the startup performance.
+var StringDecoder;
+var createReadableStreamAsyncIterator;
+var from;
+__nccwpck_require__(39598)(Readable, Stream);
+var errorOrDestroy = destroyImpl.errorOrDestroy;
+var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
+function prependListener(emitter, event, fn) {
+ // Sadly this is not cacheable as some libraries bundle their own
+ // event emitter implementation with them.
+ if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
+
+ // This is a hack to make sure that our error handler is attached before any
+ // userland ones. NEVER DO THIS. This is here only because this code needs
+ // to continue to work with older versions of Node.js that do not include
+ // the prependListener() method. The goal is to eventually remove this hack.
+ if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
+}
+function ReadableState(options, stream, isDuplex) {
+ Duplex = Duplex || __nccwpck_require__(82063);
+ options = options || {};
+
+ // Duplex streams are both readable and writable, but share
+ // the same options object.
+ // However, some cases require setting options to different
+ // values for the readable and the writable sides of the duplex stream.
+ // These options can be provided separately as readableXXX and writableXXX.
+ if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;
+
+ // object stream flag. Used to make read(n) ignore n and to
+ // make all the buffer merging and length checks go away
+ this.objectMode = !!options.objectMode;
+ if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
+
+ // the point at which it stops calling _read() to fill the buffer
+ // Note: 0 is a valid value, means "don't call _read preemptively ever"
+ this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex);
+
+ // A linked list is used to store data chunks instead of an array because the
+ // linked list can remove elements from the beginning faster than
+ // array.shift()
+ this.buffer = new BufferList();
+ this.length = 0;
+ this.pipes = null;
+ this.pipesCount = 0;
+ this.flowing = null;
+ this.ended = false;
+ this.endEmitted = false;
+ this.reading = false;
+
+ // a flag to be able to tell if the event 'readable'/'data' is emitted
+ // immediately, or on a later tick. We set this to true at first, because
+ // any actions that shouldn't happen until "later" should generally also
+ // not happen before the first read call.
+ this.sync = true;
+
+ // whenever we return null, then we set a flag to say
+ // that we're awaiting a 'readable' event emission.
+ this.needReadable = false;
+ this.emittedReadable = false;
+ this.readableListening = false;
+ this.resumeScheduled = false;
+ this.paused = true;
+
+ // Should close be emitted on destroy. Defaults to true.
+ this.emitClose = options.emitClose !== false;
+
+ // Should .destroy() be called after 'end' (and potentially 'finish')
+ this.autoDestroy = !!options.autoDestroy;
+
+ // has it been destroyed
+ this.destroyed = false;
+
+ // Crypto is kind of old and crusty. Historically, its default string
+ // encoding is 'binary' so we have to make this configurable.
+ // Everything else in the universe uses 'utf8', though.
+ this.defaultEncoding = options.defaultEncoding || 'utf8';
+
+ // the number of writers that are awaiting a drain event in .pipe()s
+ this.awaitDrain = 0;
+
+ // if true, a maybeReadMore has been scheduled
+ this.readingMore = false;
+ this.decoder = null;
+ this.encoding = null;
+ if (options.encoding) {
+ if (!StringDecoder) StringDecoder = (__nccwpck_require__(80634)/* .StringDecoder */ .I);
+ this.decoder = new StringDecoder(options.encoding);
+ this.encoding = options.encoding;
+ }
+}
+function Readable(options) {
+ Duplex = Duplex || __nccwpck_require__(82063);
+ if (!(this instanceof Readable)) return new Readable(options);
+
+ // Checking for a Stream.Duplex instance is faster here instead of inside
+ // the ReadableState constructor, at least with V8 6.5
+ var isDuplex = this instanceof Duplex;
+ this._readableState = new ReadableState(options, this, isDuplex);
+
+ // legacy
+ this.readable = true;
+ if (options) {
+ if (typeof options.read === 'function') this._read = options.read;
+ if (typeof options.destroy === 'function') this._destroy = options.destroy;
+ }
+ Stream.call(this);
+}
+Object.defineProperty(Readable.prototype, 'destroyed', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ if (this._readableState === undefined) {
+ return false;
}
- 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");
+ return this._readableState.destroyed;
+ },
+ set: function set(value) {
+ // we ignore the value if the stream
+ // has not been initialized yet
+ if (!this._readableState) {
+ return;
}
- 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");
- }
+ // backward compatibility, the user is explicitly
+ // managing destroyed
+ this._readableState.destroyed = value;
+ }
+});
+Readable.prototype.destroy = destroyImpl.destroy;
+Readable.prototype._undestroy = destroyImpl.undestroy;
+Readable.prototype._destroy = function (err, cb) {
+ cb(err);
+};
+
+// Manually shove something into the read() buffer.
+// This returns true if the highWaterMark has not been hit yet,
+// similar to how Writable.write() returns true if you should
+// write() some more.
+Readable.prototype.push = function (chunk, encoding) {
+ var state = this._readableState;
+ var skipChunkCheck;
+ if (!state.objectMode) {
+ if (typeof chunk === 'string') {
+ encoding = encoding || state.defaultEncoding;
+ if (encoding !== state.encoding) {
+ chunk = Buffer.from(chunk, encoding);
+ encoding = '';
+ }
+ skipChunkCheck = true;
}
- 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);
+ } else {
+ skipChunkCheck = true;
+ }
+ return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
+};
+
+// Unshift should *always* be something directly out of read()
+Readable.prototype.unshift = function (chunk) {
+ return readableAddChunk(this, chunk, null, true, false);
+};
+function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
+ debug('readableAddChunk', chunk);
+ var state = stream._readableState;
+ if (chunk === null) {
+ state.reading = false;
+ onEofChunk(stream, state);
+ } else {
+ var er;
+ if (!skipChunkCheck) er = chunkInvalid(state, chunk);
+ if (er) {
+ errorOrDestroy(stream, er);
+ } else if (state.objectMode || chunk && chunk.length > 0) {
+ if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
+ chunk = _uint8ArrayToBuffer(chunk);
+ }
+ if (addToFront) {
+ if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
+ } else if (state.ended) {
+ errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
+ } else if (state.destroyed) {
+ return false;
+ } else {
+ state.reading = false;
+ if (state.decoder && !encoding) {
+ chunk = state.decoder.write(chunk);
+ if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
+ } else {
+ addChunk(stream, state, chunk, false);
}
- super(url, pipeline);
- this.serviceContext = this.storageClientContext.service;
+ }
+ } else if (!addToFront) {
+ state.reading = false;
+ maybeReadMore(stream, state);
}
- /**
- * 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);
+ }
+
+ // We can push more data if we are below the highWaterMark.
+ // Also, if we have no data yet, we can stand some more bytes.
+ // This is to work around cases where hwm=0, such as the repl.
+ return !state.ended && (state.length < state.highWaterMark || state.length === 0);
+}
+function addChunk(stream, state, chunk, addToFront) {
+ if (state.flowing && state.length === 0 && !state.sync) {
+ state.awaitDrain = 0;
+ stream.emit('data', chunk);
+ } else {
+ // update the buffer info.
+ state.length += state.objectMode ? 1 : chunk.length;
+ if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
+ if (state.needReadable) emitReadable(stream);
+ }
+ maybeReadMore(stream, state);
+}
+function chunkInvalid(state, chunk) {
+ var er;
+ if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
+ er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
+ }
+ return er;
+}
+Readable.prototype.isPaused = function () {
+ return this._readableState.flowing === false;
+};
+
+// backwards compatibility.
+Readable.prototype.setEncoding = function (enc) {
+ if (!StringDecoder) StringDecoder = (__nccwpck_require__(80634)/* .StringDecoder */ .I);
+ var decoder = new StringDecoder(enc);
+ this._readableState.decoder = decoder;
+ // If setEncoding(null), decoder.encoding equals utf8
+ this._readableState.encoding = this._readableState.decoder.encoding;
+
+ // Iterate over current buffer to convert already stored Buffers:
+ var p = this._readableState.buffer.head;
+ var content = '';
+ while (p !== null) {
+ content += decoder.write(p.data);
+ p = p.next;
+ }
+ this._readableState.buffer.clear();
+ if (content !== '') this._readableState.buffer.push(content);
+ this._readableState.length = content.length;
+ return this;
+};
+
+// Don't raise the hwm > 1GB
+var MAX_HWM = 0x40000000;
+function computeNewHighWaterMark(n) {
+ if (n >= MAX_HWM) {
+ // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
+ n = MAX_HWM;
+ } else {
+ // Get the next highest power of 2 to prevent increasing hwm excessively in
+ // tiny amounts
+ n--;
+ n |= n >>> 1;
+ n |= n >>> 2;
+ n |= n >>> 4;
+ n |= n >>> 8;
+ n |= n >>> 16;
+ n++;
+ }
+ return n;
+}
+
+// This function is designed to be inlinable, so please take care when making
+// changes to the function body.
+function howMuchToRead(n, state) {
+ if (n <= 0 || state.length === 0 && state.ended) return 0;
+ if (state.objectMode) return 1;
+ if (n !== n) {
+ // Only flow one buffer at a time
+ if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
+ }
+ // If we're asking for more than the current hwm, then raise the hwm.
+ if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
+ if (n <= state.length) return n;
+ // Don't have enough
+ if (!state.ended) {
+ state.needReadable = true;
+ return 0;
+ }
+ return state.length;
+}
+
+// you can override either this method, or the async _read(n) below.
+Readable.prototype.read = function (n) {
+ debug('read', n);
+ n = parseInt(n, 10);
+ var state = this._readableState;
+ var nOrig = n;
+ if (n !== 0) state.emittedReadable = false;
+
+ // if we're doing read(0) to trigger a readable event, but we
+ // already have a bunch of data in the buffer, then just trigger
+ // the 'readable' event and move on.
+ if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
+ debug('read: emitReadable', state.length, state.ended);
+ if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
+ return null;
+ }
+ n = howMuchToRead(n, state);
+
+ // if we've ended, and we're now clear, then finish it up.
+ if (n === 0 && state.ended) {
+ if (state.length === 0) endReadable(this);
+ return null;
+ }
+
+ // All the actual chunk generation logic needs to be
+ // *below* the call to _read. The reason is that in certain
+ // synthetic stream cases, such as passthrough streams, _read
+ // may be a completely synchronous operation which may change
+ // the state of the read buffer, providing enough data when
+ // before there was *not* enough.
+ //
+ // So, the steps are:
+ // 1. Figure out what the state of things will be after we do
+ // a read from the buffer.
+ //
+ // 2. If that resulting state will trigger a _read, then call _read.
+ // Note that this may be asynchronous, or synchronous. Yes, it is
+ // deeply ugly to write APIs this way, but that still doesn't mean
+ // that the Readable class should behave improperly, as streams are
+ // designed to be sync/async agnostic.
+ // Take note if the _read call is sync or async (ie, if the read call
+ // has returned yet), so that we know whether or not it's safe to emit
+ // 'readable' etc.
+ //
+ // 3. Actually pull the requested chunks out of the buffer and return.
+
+ // if we need a readable event, then we need to do some reading.
+ var doRead = state.needReadable;
+ debug('need readable', doRead);
+
+ // if we currently have less than the highWaterMark, then also read some
+ if (state.length === 0 || state.length - n < state.highWaterMark) {
+ doRead = true;
+ debug('length less than watermark', doRead);
+ }
+
+ // however, if we've ended, then there's no point, and if we're already
+ // reading, then it's unnecessary.
+ if (state.ended || state.reading) {
+ doRead = false;
+ debug('reading or ended', doRead);
+ } else if (doRead) {
+ debug('do read');
+ state.reading = true;
+ state.sync = true;
+ // if the length is currently zero, then we *need* a readable event.
+ if (state.length === 0) state.needReadable = true;
+ // call internal read method
+ this._read(state.highWaterMark);
+ state.sync = false;
+ // If _read pushed data synchronously, then `reading` will be false,
+ // and we need to re-evaluate how much data we can return to the user.
+ if (!state.reading) n = howMuchToRead(nOrig, state);
+ }
+ var ret;
+ if (n > 0) ret = fromList(n, state);else ret = null;
+ if (ret === null) {
+ state.needReadable = state.length <= state.highWaterMark;
+ n = 0;
+ } else {
+ state.length -= n;
+ state.awaitDrain = 0;
+ }
+ if (state.length === 0) {
+ // If we have nothing in the buffer, then we want to know
+ // as soon as we *do* get something into the buffer.
+ if (!state.ended) state.needReadable = true;
+
+ // If we tried to read() past the EOF, then emit end on the next tick.
+ if (nOrig !== n && state.ended) endReadable(this);
+ }
+ if (ret !== null) this.emit('data', ret);
+ return ret;
+};
+function onEofChunk(stream, state) {
+ debug('onEofChunk');
+ if (state.ended) return;
+ if (state.decoder) {
+ var chunk = state.decoder.end();
+ if (chunk && chunk.length) {
+ state.buffer.push(chunk);
+ state.length += state.objectMode ? 1 : chunk.length;
+ }
+ }
+ state.ended = true;
+ if (state.sync) {
+ // if we are sync, wait until next tick to emit the data.
+ // Otherwise we risk emitting data in the flow()
+ // the readable code triggers during a read() call
+ emitReadable(stream);
+ } else {
+ // emit 'readable' now to make sure it gets picked up.
+ state.needReadable = false;
+ if (!state.emittedReadable) {
+ state.emittedReadable = true;
+ emitReadable_(stream);
+ }
+ }
+}
+
+// Don't emit readable right away in sync mode, because this can trigger
+// another read() call => stack overflow. This way, it might trigger
+// a nextTick recursion warning, but that's not so bad.
+function emitReadable(stream) {
+ var state = stream._readableState;
+ debug('emitReadable', state.needReadable, state.emittedReadable);
+ state.needReadable = false;
+ if (!state.emittedReadable) {
+ debug('emitReadable', state.flowing);
+ state.emittedReadable = true;
+ process.nextTick(emitReadable_, stream);
+ }
+}
+function emitReadable_(stream) {
+ var state = stream._readableState;
+ debug('emitReadable_', state.destroyed, state.length, state.ended);
+ if (!state.destroyed && (state.length || state.ended)) {
+ stream.emit('readable');
+ state.emittedReadable = false;
+ }
+
+ // The stream needs another readable event if
+ // 1. It is not flowing, as the flow mechanism will take
+ // care of it.
+ // 2. It is not ended.
+ // 3. It is below the highWaterMark, so we can schedule
+ // another readable later.
+ state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
+ flow(stream);
+}
+
+// at this point, the user has presumably seen the 'readable' event,
+// and called read() to consume some data. that may have triggered
+// in turn another _read(n) call, in which case reading = true if
+// it's in progress.
+// However, if we're not ended, or reading, and the length < hwm,
+// then go ahead and try to read some more preemptively.
+function maybeReadMore(stream, state) {
+ if (!state.readingMore) {
+ state.readingMore = true;
+ process.nextTick(maybeReadMore_, stream, state);
+ }
+}
+function maybeReadMore_(stream, state) {
+ // Attempt to read more data if we should.
+ //
+ // The conditions for reading more data are (one of):
+ // - Not enough data buffered (state.length < state.highWaterMark). The loop
+ // is responsible for filling the buffer with enough data if such data
+ // is available. If highWaterMark is 0 and we are not in the flowing mode
+ // we should _not_ attempt to buffer any extra data. We'll get more data
+ // when the stream consumer calls read() instead.
+ // - No data in the buffer, and the stream is in flowing mode. In this mode
+ // the loop below is responsible for ensuring read() is called. Failing to
+ // call read here would abort the flow and there's no other mechanism for
+ // continuing the flow if the stream consumer has just subscribed to the
+ // 'data' event.
+ //
+ // In addition to the above conditions to keep reading data, the following
+ // conditions prevent the data from being read:
+ // - The stream has ended (state.ended).
+ // - There is already a pending 'read' operation (state.reading). This is a
+ // case where the the stream has called the implementation defined _read()
+ // method, but they are processing the call asynchronously and have _not_
+ // called push() with new data. In this case we skip performing more
+ // read()s. The execution ends in this method again after the _read() ends
+ // up calling push() with more data.
+ while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
+ var len = state.length;
+ debug('maybeReadMore read 0');
+ stream.read(0);
+ if (len === state.length)
+ // didn't get any data, stop spinning.
+ break;
+ }
+ state.readingMore = false;
+}
+
+// abstract method. to be overridden in specific implementation classes.
+// call cb(er, data) where data is <= n in length.
+// for virtual (non-string, non-buffer) streams, "length" is somewhat
+// arbitrary, and perhaps not very meaningful.
+Readable.prototype._read = function (n) {
+ errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
+};
+Readable.prototype.pipe = function (dest, pipeOpts) {
+ var src = this;
+ var state = this._readableState;
+ switch (state.pipesCount) {
+ case 0:
+ state.pipes = dest;
+ break;
+ case 1:
+ state.pipes = [state.pipes, dest];
+ break;
+ default:
+ state.pipes.push(dest);
+ break;
+ }
+ state.pipesCount += 1;
+ debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
+ var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
+ var endFn = doEnd ? onend : unpipe;
+ if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
+ dest.on('unpipe', onunpipe);
+ function onunpipe(readable, unpipeInfo) {
+ debug('onunpipe');
+ if (readable === src) {
+ if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
+ unpipeInfo.hasUnpiped = true;
+ cleanup();
+ }
}
- /**
- * Create a Blob container. @see https://docs.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,
- };
- });
+ }
+ function onend() {
+ debug('onend');
+ dest.end();
+ }
+
+ // when the dest drains, it reduces the awaitDrain counter
+ // on the source. This would be more elegant with a .once()
+ // handler in flow(), but adding and removing repeatedly is
+ // too slow.
+ var ondrain = pipeOnDrain(src);
+ dest.on('drain', ondrain);
+ var cleanedUp = false;
+ function cleanup() {
+ debug('cleanup');
+ // cleanup event handlers once the pipe is broken
+ dest.removeListener('close', onclose);
+ dest.removeListener('finish', onfinish);
+ dest.removeListener('drain', ondrain);
+ dest.removeListener('error', onerror);
+ dest.removeListener('unpipe', onunpipe);
+ src.removeListener('end', onend);
+ src.removeListener('end', unpipe);
+ src.removeListener('data', ondata);
+ cleanedUp = true;
+
+ // if the reader is waiting for a drain event from this
+ // specific writer, then it would cause it to never start
+ // flowing again.
+ // So, if this is awaiting a drain, then we just call it now.
+ // If we don't know, then assume that we are waiting for one.
+ if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
+ }
+ src.on('data', ondata);
+ function ondata(chunk) {
+ debug('ondata');
+ var ret = dest.write(chunk);
+ debug('dest.write', ret);
+ if (ret === false) {
+ // If the user unpiped during `dest.write()`, it is possible
+ // to get stuck in a permanently paused state if that write
+ // also returned false.
+ // => Check whether `dest` is still a piping destination.
+ if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
+ debug('false write response, pause', state.awaitDrain);
+ state.awaitDrain++;
+ }
+ src.pause();
}
- /**
- * 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);
- });
+ }
+
+ // if the dest has an error, then stop piping into it.
+ // however, don't suppress the throwing behavior for this.
+ function onerror(er) {
+ debug('onerror', er);
+ unpipe();
+ dest.removeListener('error', onerror);
+ if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
+ }
+
+ // Make sure our error handler is attached before userland ones.
+ prependListener(dest, 'error', onerror);
+
+ // Both close and finish should trigger unpipe, but only once.
+ function onclose() {
+ dest.removeListener('finish', onfinish);
+ unpipe();
+ }
+ dest.once('close', onclose);
+ function onfinish() {
+ debug('onfinish');
+ dest.removeListener('close', onclose);
+ unpipe();
+ }
+ dest.once('finish', onfinish);
+ function unpipe() {
+ debug('unpipe');
+ src.unpipe(dest);
+ }
+
+ // tell the dest that it's being piped to
+ dest.emit('pipe', src);
+
+ // start the flow if it hasn't been started already.
+ if (!state.flowing) {
+ debug('pipe resume');
+ src.resume();
+ }
+ return dest;
+};
+function pipeOnDrain(src) {
+ return function pipeOnDrainFunctionResult() {
+ var state = src._readableState;
+ debug('pipeOnDrain', state.awaitDrain);
+ if (state.awaitDrain) state.awaitDrain--;
+ if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
+ state.flowing = true;
+ flow(src);
}
- /**
- * 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 };
- });
+ };
+}
+Readable.prototype.unpipe = function (dest) {
+ var state = this._readableState;
+ var unpipeInfo = {
+ hasUnpiped: false
+ };
+
+ // if we're not piping anywhere, then do nothing.
+ if (state.pipesCount === 0) return this;
+
+ // just one destination. most common case.
+ if (state.pipesCount === 1) {
+ // passed in one, but it's not the right one.
+ if (dest && dest !== state.pipes) return this;
+ if (!dest) dest = state.pipes;
+
+ // got a match.
+ state.pipes = null;
+ state.pipesCount = 0;
+ state.flowing = false;
+ if (dest) dest.emit('unpipe', this, unpipeInfo);
+ return this;
+ }
+
+ // slow case. multiple pipe destinations.
+
+ if (!dest) {
+ // remove all.
+ var dests = state.pipes;
+ var len = state.pipesCount;
+ state.pipes = null;
+ state.pipesCount = 0;
+ state.flowing = false;
+ for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, {
+ hasUnpiped: false
+ });
+ return this;
+ }
+
+ // try to find the right one.
+ var index = indexOf(state.pipes, dest);
+ if (index === -1) return this;
+ state.pipes.splice(index, 1);
+ state.pipesCount -= 1;
+ if (state.pipesCount === 1) state.pipes = state.pipes[0];
+ dest.emit('unpipe', this, unpipeInfo);
+ return this;
+};
+
+// set up data events if they are asked for
+// Ensure readable listeners eventually get something
+Readable.prototype.on = function (ev, fn) {
+ var res = Stream.prototype.on.call(this, ev, fn);
+ var state = this._readableState;
+ if (ev === 'data') {
+ // update readableListening so that resume() may be a no-op
+ // a few lines down. This is needed to support once('readable').
+ state.readableListening = this.listenerCount('readable') > 0;
+
+ // Try start flowing on next tick if stream isn't explicitly paused
+ if (state.flowing !== false) this.resume();
+ } else if (ev === 'readable') {
+ if (!state.endEmitted && !state.readableListening) {
+ state.readableListening = state.needReadable = true;
+ state.flowing = false;
+ state.emittedReadable = false;
+ debug('on readable', state.length, state.reading);
+ if (state.length) {
+ emitReadable(this);
+ } else if (!state.reading) {
+ process.nextTick(nReadingNextTick, this);
+ }
}
- /**
- * 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 };
- });
+ }
+ return res;
+};
+Readable.prototype.addListener = Readable.prototype.on;
+Readable.prototype.removeListener = function (ev, fn) {
+ var res = Stream.prototype.removeListener.call(this, ev, fn);
+ if (ev === 'readable') {
+ // We need to check if there is someone still listening to
+ // readable and reset the state. However this needs to happen
+ // after readable has been emitted but before I/O (nextTick) to
+ // support once('readable', fn) cycles. This means that calling
+ // resume within the same tick will have no
+ // effect.
+ process.nextTick(updateReadableListening, this);
+ }
+ return res;
+};
+Readable.prototype.removeAllListeners = function (ev) {
+ var res = Stream.prototype.removeAllListeners.apply(this, arguments);
+ if (ev === 'readable' || ev === undefined) {
+ // We need to check if there is someone still listening to
+ // readable and reset the state. However this needs to happen
+ // after readable has been emitted but before I/O (nextTick) to
+ // support once('readable', fn) cycles. This means that calling
+ // resume within the same tick will have no
+ // effect.
+ process.nextTick(updateReadableListening, this);
+ }
+ return res;
+};
+function updateReadableListening(self) {
+ var state = self._readableState;
+ state.readableListening = self.listenerCount('readable') > 0;
+ if (state.resumeScheduled && !state.paused) {
+ // flowing needs to be set to true now, otherwise
+ // the upcoming resume will not flow.
+ state.flowing = true;
+
+ // crude way to check if we should resume
+ } else if (self.listenerCount('data') > 0) {
+ self.resume();
+ }
+}
+function nReadingNextTick(self) {
+ debug('readable nexttick read 0');
+ self.read(0);
+}
+
+// pause() and resume() are remnants of the legacy readable stream API
+// If the user uses them, then switch into old mode.
+Readable.prototype.resume = function () {
+ var state = this._readableState;
+ if (!state.flowing) {
+ debug('resume');
+ // we flow only if there is no one listening
+ // for readable, but we still have to call
+ // resume()
+ state.flowing = !state.readableListening;
+ resume(this, state);
+ }
+ state.paused = false;
+ return this;
+};
+function resume(stream, state) {
+ if (!state.resumeScheduled) {
+ state.resumeScheduled = true;
+ process.nextTick(resume_, stream, state);
+ }
+}
+function resume_(stream, state) {
+ debug('resume', state.reading);
+ if (!state.reading) {
+ stream.read(0);
+ }
+ state.resumeScheduled = false;
+ stream.emit('resume');
+ flow(stream);
+ if (state.flowing && !state.reading) stream.read(0);
+}
+Readable.prototype.pause = function () {
+ debug('call pause flowing=%j', this._readableState.flowing);
+ if (this._readableState.flowing !== false) {
+ debug('pause');
+ this._readableState.flowing = false;
+ this.emit('pause');
+ }
+ this._readableState.paused = true;
+ return this;
+};
+function flow(stream) {
+ var state = stream._readableState;
+ debug('flow', state.flowing);
+ while (state.flowing && stream.read() !== null);
+}
+
+// wrap an old-style stream as the async data source.
+// This is *not* part of the readable stream interface.
+// It is an ugly unfortunate mess of history.
+Readable.prototype.wrap = function (stream) {
+ var _this = this;
+ var state = this._readableState;
+ var paused = false;
+ stream.on('end', function () {
+ debug('wrapped end');
+ if (state.decoder && !state.ended) {
+ var chunk = state.decoder.end();
+ if (chunk && chunk.length) _this.push(chunk);
+ }
+ _this.push(null);
+ });
+ stream.on('data', function (chunk) {
+ debug('wrapped data');
+ if (state.decoder) chunk = state.decoder.write(chunk);
+
+ // don't skip over falsy values in objectMode
+ if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
+ var ret = _this.push(chunk);
+ if (!ret) {
+ paused = true;
+ stream.pause();
}
- /**
- * Gets the properties of a storage account’s Blob service, including properties
- * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules.
- * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties
- *
- * @param 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,
- }));
- });
+ });
+
+ // proxy all the other methods.
+ // important when wrapping filters and duplexes.
+ for (var i in stream) {
+ if (this[i] === undefined && typeof stream[i] === 'function') {
+ this[i] = function methodWrap(method) {
+ return function methodWrapReturnFunction() {
+ return stream[method].apply(stream, arguments);
+ };
+ }(i);
}
- /**
- * Sets properties for a storage account’s Blob service endpoint, including properties
- * for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules and soft delete settings.
- * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties
- *
- * @param 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,
- }));
- });
+ }
+
+ // proxy certain important events.
+ for (var n = 0; n < kProxyEvents.length; n++) {
+ stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
+ }
+
+ // when we try to consume some more bytes, simply unpause the
+ // underlying stream.
+ this._read = function (n) {
+ debug('wrapped _read', n);
+ if (paused) {
+ paused = false;
+ stream.resume();
}
- /**
- * Retrieves statistics related to replication for the Blob service. It is only
- * available on the secondary location endpoint when read-access geo-redundant
- * replication is enabled for the storage account.
- * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-stats
- *
- * @param 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,
- }));
- });
+ };
+ return this;
+};
+if (typeof Symbol === 'function') {
+ Readable.prototype[Symbol.asyncIterator] = function () {
+ if (createReadableStreamAsyncIterator === undefined) {
+ createReadableStreamAsyncIterator = __nccwpck_require__(14868);
}
- /**
- * The Get Account Information operation returns the sku name and account kind
- * for the specified account.
- * The Get Account Information operation is available on service versions beginning
- * with version 2018-03-28.
- * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information
- *
- * @param 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,
- }));
- });
+ return createReadableStreamAsyncIterator(this);
+ };
+}
+Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._readableState.highWaterMark;
+ }
+});
+Object.defineProperty(Readable.prototype, 'readableBuffer', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._readableState && this._readableState.buffer;
+ }
+});
+Object.defineProperty(Readable.prototype, 'readableFlowing', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._readableState.flowing;
+ },
+ set: function set(state) {
+ if (this._readableState) {
+ this._readableState.flowing = state;
}
- /**
- * Returns a list of the containers under the specified account.
- * @see https://docs.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 })));
- });
+ }
+});
+
+// exposed for testing purposes only.
+Readable._fromList = fromList;
+Object.defineProperty(Readable.prototype, 'readableLength', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._readableState.length;
+ }
+});
+
+// Pluck off n bytes from an array of buffers.
+// Length is the combined lengths of all the buffers in the list.
+// This function is designed to be inlinable, so please take care when making
+// changes to the function body.
+function fromList(n, state) {
+ // nothing buffered
+ if (state.length === 0) return null;
+ var ret;
+ if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
+ // read it all, truncate the list
+ if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
+ state.buffer.clear();
+ } else {
+ // read part of list
+ ret = state.buffer.consume(n, state.decoder);
+ }
+ return ret;
+}
+function endReadable(stream) {
+ var state = stream._readableState;
+ debug('endReadable', state.endEmitted);
+ if (!state.endEmitted) {
+ state.ended = true;
+ process.nextTick(endReadableNT, state, stream);
+ }
+}
+function endReadableNT(state, stream) {
+ debug('endReadableNT', state.endEmitted, state.length);
+
+ // Check that we didn't get one last unshift.
+ if (!state.endEmitted && state.length === 0) {
+ state.endEmitted = true;
+ stream.readable = false;
+ stream.emit('end');
+ if (state.autoDestroy) {
+ // In case of duplex streams we need a way to detect
+ // if the writable side is ready for autoDestroy as well
+ var wState = stream._writableState;
+ if (!wState || wState.autoDestroy && wState.finished) {
+ stream.destroy();
+ }
}
- /**
- * 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;
- });
+ }
+}
+if (typeof Symbol === 'function') {
+ Readable.from = function (iterable, opts) {
+ if (from === undefined) {
+ from = __nccwpck_require__(4659);
}
- /**
- * 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);
- }
- });
+ return from(Readable, iterable, opts);
+ };
+}
+function indexOf(xs, x) {
+ for (var i = 0, l = xs.length; i < l; i++) {
+ if (xs[i] === x) return i;
+ }
+ return -1;
+}
+
+/***/ }),
+
+/***/ 12337:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// 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.
+
+// a transform stream is a readable/writable stream where you do
+// something with the data. Sometimes it's called a "filter",
+// but that's not a great name for it, since that implies a thing where
+// some bits pass through, and others are simply ignored. (That would
+// be a valid example of a transform, of course.)
+//
+// While the output is causally related to the input, it's not a
+// necessarily symmetric or synchronous transformation. For example,
+// a zlib stream might take multiple plain-text writes(), and then
+// emit a single compressed chunk some time in the future.
+//
+// Here's how this works:
+//
+// The Transform stream has all the aspects of the readable and writable
+// stream classes. When you write(chunk), that calls _write(chunk,cb)
+// internally, and returns false if there's a lot of pending writes
+// buffered up. When you call read(), that calls _read(n) until
+// there's enough pending readable data buffered up.
+//
+// In a transform stream, the written data is placed in a buffer. When
+// _read(n) is called, it transforms the queued up data, calling the
+// buffered _write cb's as it consumes chunks. If consuming a single
+// written chunk would result in multiple output chunks, then the first
+// outputted bit calls the readcb, and subsequent chunks just go into
+// the read buffer, and will cause it to emit 'readable' if necessary.
+//
+// This way, back-pressure is actually determined by the reading side,
+// since _read has to be called to start processing a new chunk. However,
+// a pathological inflate type of transform can cause excessive buffering
+// here. For example, imagine a stream where every byte of input is
+// interpreted as an integer from 0-255, and then results in that many
+// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
+// 1kb of data being output. In this case, you could write a very small
+// amount of input, and end up with a very large amount of output. In
+// such a pathological inflating mechanism, there'd be no way to tell
+// the system to stop doing the transform. A single 4MB write could
+// cause the system to run out of memory.
+//
+// However, even in such a pathological case, only a single written chunk
+// would be consumed, and then the rest would wait (un-transformed) until
+// the results of the previous transformed chunk were consumed.
+
+
+
+module.exports = Transform;
+var _require$codes = (__nccwpck_require__(25500)/* .codes */ .F),
+ ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
+ ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
+ ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
+ ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
+var Duplex = __nccwpck_require__(82063);
+__nccwpck_require__(39598)(Transform, Duplex);
+function afterTransform(er, data) {
+ var ts = this._transformState;
+ ts.transforming = false;
+ var cb = ts.writecb;
+ if (cb === null) {
+ return this.emit('error', new ERR_MULTIPLE_CALLBACK());
+ }
+ ts.writechunk = null;
+ ts.writecb = null;
+ if (data != null)
+ // single equals check for both `null` and `undefined`
+ this.push(data);
+ cb(er);
+ var rs = this._readableState;
+ rs.reading = false;
+ if (rs.needReadable || rs.length < rs.highWaterMark) {
+ this._read(rs.highWaterMark);
+ }
+}
+function Transform(options) {
+ if (!(this instanceof Transform)) return new Transform(options);
+ Duplex.call(this, options);
+ this._transformState = {
+ afterTransform: afterTransform.bind(this),
+ needTransform: false,
+ transforming: false,
+ writecb: null,
+ writechunk: null,
+ writeencoding: null
+ };
+
+ // start out asking for a readable event once data is transformed.
+ this._readableState.needReadable = true;
+
+ // we have implemented the _read method, and done the other things
+ // that Readable wants before the first _read call, so unset the
+ // sync guard flag.
+ this._readableState.sync = false;
+ if (options) {
+ if (typeof options.transform === 'function') this._transform = options.transform;
+ if (typeof options.flush === 'function') this._flush = options.flush;
+ }
+
+ // When the writable side finishes, then flush out anything remaining.
+ this.on('prefinish', prefinish);
+}
+function prefinish() {
+ var _this = this;
+ if (typeof this._flush === 'function' && !this._readableState.destroyed) {
+ this._flush(function (er, data) {
+ done(_this, er, data);
+ });
+ } else {
+ done(this, null, null);
+ }
+}
+Transform.prototype.push = function (chunk, encoding) {
+ this._transformState.needTransform = false;
+ return Duplex.prototype.push.call(this, chunk, encoding);
+};
+
+// This is the part where you do stuff!
+// override this function in implementation classes.
+// 'chunk' is an input chunk.
+//
+// Call `push(newChunk)` to pass along transformed output
+// to the readable side. You may call 'push' zero or more times.
+//
+// Call `cb(err)` when you are done with this chunk. If you pass
+// an error, then that'll put the hurt on the whole operation. If you
+// never call cb(), then you'll never get another chunk.
+Transform.prototype._transform = function (chunk, encoding, cb) {
+ cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
+};
+Transform.prototype._write = function (chunk, encoding, cb) {
+ var ts = this._transformState;
+ ts.writecb = cb;
+ ts.writechunk = chunk;
+ ts.writeencoding = encoding;
+ if (!ts.transforming) {
+ var rs = this._readableState;
+ if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
+ }
+};
+
+// Doesn't matter what the args are here.
+// _transform does all the work.
+// That we got here means that the readable side wants more data.
+Transform.prototype._read = function (n) {
+ var ts = this._transformState;
+ if (ts.writechunk !== null && !ts.transforming) {
+ ts.transforming = true;
+ this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
+ } else {
+ // mark that we need a transform, so that any data that comes in
+ // will get processed, now that we've asked for it.
+ ts.needTransform = true;
+ }
+};
+Transform.prototype._destroy = function (err, cb) {
+ Duplex.prototype._destroy.call(this, err, function (err2) {
+ cb(err2);
+ });
+};
+function done(stream, er, data) {
+ if (er) return stream.emit('error', er);
+ if (data != null)
+ // single equals check for both `null` and `undefined`
+ stream.push(data);
+
+ // TODO(BridgeAR): Write a test for these two error cases
+ // if there's nothing in the write buffer, then that means
+ // that nothing more will ever be provided
+ if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
+ if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
+ return stream.push(null);
+}
+
+/***/ }),
+
+/***/ 38797:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// 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.
+
+// A bit simpler than readable streams.
+// Implement an async ._write(chunk, encoding, cb), and it'll handle all
+// the drain event emission and buffering.
+
+
+
+module.exports = Writable;
+
+/* */
+function WriteReq(chunk, encoding, cb) {
+ this.chunk = chunk;
+ this.encoding = encoding;
+ this.callback = cb;
+ this.next = null;
+}
+
+// It seems a linked list but it is not
+// there will be only 2 of these for each stream
+function CorkedRequest(state) {
+ var _this = this;
+ this.next = null;
+ this.entry = null;
+ this.finish = function () {
+ onCorkedFinish(_this, state);
+ };
+}
+/* */
+
+/**/
+var Duplex;
+/**/
+
+Writable.WritableState = WritableState;
+
+/**/
+var internalUtil = {
+ deprecate: __nccwpck_require__(24488)
+};
+/**/
+
+/**/
+var Stream = __nccwpck_require__(63283);
+/**/
+
+var Buffer = (__nccwpck_require__(20181).Buffer);
+var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
+function _uint8ArrayToBuffer(chunk) {
+ return Buffer.from(chunk);
+}
+function _isUint8Array(obj) {
+ return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
+}
+var destroyImpl = __nccwpck_require__(65089);
+var _require = __nccwpck_require__(54874),
+ getHighWaterMark = _require.getHighWaterMark;
+var _require$codes = (__nccwpck_require__(25500)/* .codes */ .F),
+ ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
+ ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
+ ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
+ ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
+ ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
+ ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
+ ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
+ ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
+var errorOrDestroy = destroyImpl.errorOrDestroy;
+__nccwpck_require__(39598)(Writable, Stream);
+function nop() {}
+function WritableState(options, stream, isDuplex) {
+ Duplex = Duplex || __nccwpck_require__(82063);
+ options = options || {};
+
+ // Duplex streams are both readable and writable, but share
+ // the same options object.
+ // However, some cases require setting options to different
+ // values for the readable and the writable sides of the duplex stream,
+ // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
+ if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;
+
+ // object stream flag to indicate whether or not this stream
+ // contains buffers or objects.
+ this.objectMode = !!options.objectMode;
+ if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
+
+ // the point at which write() starts returning false
+ // Note: 0 is a valid value, means that we always return false if
+ // the entire buffer is not flushed immediately on write()
+ this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex);
+
+ // if _final has been called
+ this.finalCalled = false;
+
+ // drain event flag.
+ this.needDrain = false;
+ // at the start of calling end()
+ this.ending = false;
+ // when end() has been called, and returned
+ this.ended = false;
+ // when 'finish' is emitted
+ this.finished = false;
+
+ // has it been destroyed
+ this.destroyed = false;
+
+ // should we decode strings into buffers before passing to _write?
+ // this is here so that some node-core streams can optimize string
+ // handling at a lower level.
+ var noDecode = options.decodeStrings === false;
+ this.decodeStrings = !noDecode;
+
+ // Crypto is kind of old and crusty. Historically, its default string
+ // encoding is 'binary' so we have to make this configurable.
+ // Everything else in the universe uses 'utf8', though.
+ this.defaultEncoding = options.defaultEncoding || 'utf8';
+
+ // not an actual buffer we keep track of, but a measurement
+ // of how much we're waiting to get pushed to some underlying
+ // socket or file.
+ this.length = 0;
+
+ // a flag to see when we're in the middle of a write.
+ this.writing = false;
+
+ // when true all writes will be buffered until .uncork() call
+ this.corked = 0;
+
+ // a flag to be able to tell if the onwrite cb is called immediately,
+ // or on a later tick. We set this to true at first, because any
+ // actions that shouldn't happen until "later" should generally also
+ // not happen before the first write call.
+ this.sync = true;
+
+ // a flag to know if we're processing previously buffered items, which
+ // may call the _write() callback in the same tick, so that we don't
+ // end up in an overlapped onwrite situation.
+ this.bufferProcessing = false;
+
+ // the callback that's passed to _write(chunk,cb)
+ this.onwrite = function (er) {
+ onwrite(stream, er);
+ };
+
+ // the callback that the user supplies to write(chunk,encoding,cb)
+ this.writecb = null;
+
+ // the amount that is being written when _write is called.
+ this.writelen = 0;
+ this.bufferedRequest = null;
+ this.lastBufferedRequest = null;
+
+ // number of pending user-supplied write callbacks
+ // this must be 0 before 'finish' can be emitted
+ this.pendingcb = 0;
+
+ // emit prefinish if the only thing we're waiting for is _write cbs
+ // This is relevant for synchronous Transform streams
+ this.prefinished = false;
+
+ // True if the error was already emitted and should not be thrown again
+ this.errorEmitted = false;
+
+ // Should close be emitted on destroy. Defaults to true.
+ this.emitClose = options.emitClose !== false;
+
+ // Should .destroy() be called after 'finish' (and potentially 'end')
+ this.autoDestroy = !!options.autoDestroy;
+
+ // count buffered requests
+ this.bufferedRequestCount = 0;
+
+ // allocate the first CorkedRequest, there is always
+ // one allocated and free to use, and we maintain at most two
+ this.corkedRequestsFree = new CorkedRequest(this);
+}
+WritableState.prototype.getBuffer = function getBuffer() {
+ var current = this.bufferedRequest;
+ var out = [];
+ while (current) {
+ out.push(current);
+ current = current.next;
+ }
+ return out;
+};
+(function () {
+ try {
+ Object.defineProperty(WritableState.prototype, 'buffer', {
+ get: internalUtil.deprecate(function writableStateBufferGetter() {
+ return this.getBuffer();
+ }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
+ });
+ } catch (_) {}
+})();
+
+// Test _writableState for inheritance to account for Duplex streams,
+// whose prototype chain only points to Readable.
+var realHasInstance;
+if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
+ realHasInstance = Function.prototype[Symbol.hasInstance];
+ Object.defineProperty(Writable, Symbol.hasInstance, {
+ value: function value(object) {
+ if (realHasInstance.call(this, object)) return true;
+ if (this !== Writable) return false;
+ return object && object._writableState instanceof WritableState;
}
- /**
- * 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; }
- }
- });
+ });
+} else {
+ realHasInstance = function realHasInstance(object) {
+ return object instanceof this;
+ };
+}
+function Writable(options) {
+ Duplex = Duplex || __nccwpck_require__(82063);
+
+ // Writable ctor is applied to Duplexes, too.
+ // `realHasInstance` is necessary because using plain `instanceof`
+ // would return false, as no `_writableState` property is attached.
+
+ // Trying to use the custom `instanceof` for Writable here will also break the
+ // Node.js LazyTransform implementation, which has a non-trivial getter for
+ // `_writableState` that would lead to infinite recursion.
+
+ // Checking for a Stream.Duplex instance is faster here instead of inside
+ // the WritableState constructor, at least with V8 6.5
+ var isDuplex = this instanceof Duplex;
+ if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
+ this._writableState = new WritableState(options, this, isDuplex);
+
+ // legacy.
+ this.writable = true;
+ if (options) {
+ if (typeof options.write === 'function') this._write = options.write;
+ if (typeof options.writev === 'function') this._writev = options.writev;
+ if (typeof options.destroy === 'function') this._destroy = options.destroy;
+ if (typeof options.final === 'function') this._final = options.final;
+ }
+ Stream.call(this);
+}
+
+// Otherwise people can pipe Writable streams, which is just wrong.
+Writable.prototype.pipe = function () {
+ errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
+};
+function writeAfterEnd(stream, cb) {
+ var er = new ERR_STREAM_WRITE_AFTER_END();
+ // TODO: defer error events consistently everywhere, not just the cb
+ errorOrDestroy(stream, er);
+ process.nextTick(cb, er);
+}
+
+// Checks that a user-supplied chunk is valid, especially for the particular
+// mode the stream is in. Currently this means that `null` is never accepted
+// and undefined/non-string values are only allowed in object mode.
+function validChunk(stream, state, chunk, cb) {
+ var er;
+ if (chunk === null) {
+ er = new ERR_STREAM_NULL_VALUES();
+ } else if (typeof chunk !== 'string' && !state.objectMode) {
+ er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
+ }
+ if (er) {
+ errorOrDestroy(stream, er);
+ process.nextTick(cb, er);
+ return false;
+ }
+ return true;
+}
+Writable.prototype.write = function (chunk, encoding, cb) {
+ var state = this._writableState;
+ var ret = false;
+ var isBuf = !state.objectMode && _isUint8Array(chunk);
+ if (isBuf && !Buffer.isBuffer(chunk)) {
+ chunk = _uint8ArrayToBuffer(chunk);
+ }
+ if (typeof encoding === 'function') {
+ cb = encoding;
+ encoding = null;
+ }
+ if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
+ if (typeof cb !== 'function') cb = nop;
+ if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
+ state.pendingcb++;
+ ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
+ }
+ return ret;
+};
+Writable.prototype.cork = function () {
+ this._writableState.corked++;
+};
+Writable.prototype.uncork = function () {
+ var state = this._writableState;
+ if (state.corked) {
+ state.corked--;
+ if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
+ }
+};
+Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
+ // node::ParseEncoding() requires lower case.
+ if (typeof encoding === 'string') encoding = encoding.toLowerCase();
+ if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
+ this._writableState.defaultEncoding = encoding;
+ return this;
+};
+Object.defineProperty(Writable.prototype, 'writableBuffer', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._writableState && this._writableState.getBuffer();
+ }
+});
+function decodeChunk(state, chunk, encoding) {
+ if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
+ chunk = Buffer.from(chunk, encoding);
+ }
+ return chunk;
+}
+Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._writableState.highWaterMark;
+ }
+});
+
+// if we're already writing something, then just put this
+// in the queue, and wait our turn. Otherwise, call _write
+// If we return false, then we need a drain event, so set that flag.
+function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
+ if (!isBuf) {
+ var newChunk = decodeChunk(state, chunk, encoding);
+ if (chunk !== newChunk) {
+ isBuf = true;
+ encoding = 'buffer';
+ chunk = newChunk;
+ }
+ }
+ var len = state.objectMode ? 1 : chunk.length;
+ state.length += len;
+ var ret = state.length < state.highWaterMark;
+ // we must ensure that previous needDrain will not be reset to false.
+ if (!ret) state.needDrain = true;
+ if (state.writing || state.corked) {
+ var last = state.lastBufferedRequest;
+ state.lastBufferedRequest = {
+ chunk: chunk,
+ encoding: encoding,
+ isBuf: isBuf,
+ callback: cb,
+ next: null
+ };
+ if (last) {
+ last.next = state.lastBufferedRequest;
+ } else {
+ state.bufferedRequest = state.lastBufferedRequest;
}
- /**
- * Returns an async iterable iterator to find all blobs with specified tag
- * under the specified account.
- *
- * .byPage() returns an async iterable iterator to list the blobs in pages.
- *
- * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties
- *
- * Example using `for await` syntax:
- *
- * ```js
- * let i = 1;
- * for await (const blob of blobServiceClient.findBlobsByTags("tagkey='tagvalue'")) {
- * console.log(`Blob ${i++}: ${container.name}`);
- * }
- * ```
- *
- * Example using `iter.next()`:
- *
- * ```js
- * let i = 1;
- * const iter = blobServiceClient.findBlobsByTags("tagkey='tagvalue'");
- * let blobItem = await iter.next();
- * while (!blobItem.done) {
- * console.log(`Blob ${i++}: ${blobItem.value.name}`);
- * blobItem = await iter.next();
- * }
- * ```
- *
- * Example using `byPage()`:
- *
- * ```js
- * // passing optional maxPageSize in the page settings
- * let i = 1;
- * for await (const response of blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) {
- * if (response.blobs) {
- * for (const blob of response.blobs) {
- * console.log(`Blob ${i++}: ${blob.name}`);
- * }
- * }
- * }
- * ```
- *
- * Example using paging with a marker:
- *
- * ```js
- * let i = 1;
- * let iterator = blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 });
- * let response = (await iterator.next()).value;
- *
- * // Prints 2 blob names
- * if (response.blobs) {
- * for (const blob of response.blobs) {
- * console.log(`Blob ${i++}: ${blob.name}`);
- * }
- * }
- *
- * // Gets next marker
- * let marker = response.continuationToken;
- * // Passing next marker as continuationToken
- * iterator = blobServiceClient
- * .findBlobsByTags("tagkey='tagvalue'")
- * .byPage({ continuationToken: marker, maxPageSize: 10 });
- * response = (await iterator.next()).value;
- *
- * // Prints blob names
- * if (response.blobs) {
- * for (const blob of response.blobs) {
- * console.log(`Blob ${i++}: ${blob.name}`);
- * }
- * }
- * ```
- *
- * @param 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));
- },
- };
+ state.bufferedRequestCount += 1;
+ } else {
+ doWrite(stream, state, false, len, chunk, encoding, cb);
+ }
+ return ret;
+}
+function doWrite(stream, state, writev, len, chunk, encoding, cb) {
+ state.writelen = len;
+ state.writecb = cb;
+ state.writing = true;
+ state.sync = true;
+ if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
+ state.sync = false;
+}
+function onwriteError(stream, state, sync, er, cb) {
+ --state.pendingcb;
+ if (sync) {
+ // defer the callback if we are being called synchronously
+ // to avoid piling up things on the stack
+ process.nextTick(cb, er);
+ // this can emit finish, and it will always happen
+ // after error
+ process.nextTick(finishMaybe, stream, state);
+ stream._writableState.errorEmitted = true;
+ errorOrDestroy(stream, er);
+ } else {
+ // the caller expect this to happen before if
+ // it is async
+ cb(er);
+ stream._writableState.errorEmitted = true;
+ errorOrDestroy(stream, er);
+ // this can emit finish, but finish must
+ // always follow error
+ finishMaybe(stream, state);
+ }
+}
+function onwriteStateUpdate(state) {
+ state.writing = false;
+ state.writecb = null;
+ state.length -= state.writelen;
+ state.writelen = 0;
+}
+function onwrite(stream, er) {
+ var state = stream._writableState;
+ var sync = state.sync;
+ var cb = state.writecb;
+ if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
+ onwriteStateUpdate(state);
+ if (er) onwriteError(stream, state, sync, er, cb);else {
+ // Check if we're actually ready to finish, but don't emit yet
+ var finished = needFinish(state) || stream.destroyed;
+ if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
+ clearBuffer(stream, state);
+ }
+ if (sync) {
+ process.nextTick(afterWrite, stream, state, finished, cb);
+ } else {
+ afterWrite(stream, state, finished, cb);
+ }
+ }
+}
+function afterWrite(stream, state, finished, cb) {
+ if (!finished) onwriteDrain(stream, state);
+ state.pendingcb--;
+ cb();
+ finishMaybe(stream, state);
+}
+
+// Must force callback to be called on nextTick, so that we don't
+// emit 'drain' before the write() consumer gets the 'false' return
+// value, and has a chance to attach a 'drain' listener.
+function onwriteDrain(stream, state) {
+ if (state.length === 0 && state.needDrain) {
+ state.needDrain = false;
+ stream.emit('drain');
+ }
+}
+
+// if there's something in the buffer waiting, then process it
+function clearBuffer(stream, state) {
+ state.bufferProcessing = true;
+ var entry = state.bufferedRequest;
+ if (stream._writev && entry && entry.next) {
+ // Fast case, write everything using _writev()
+ var l = state.bufferedRequestCount;
+ var buffer = new Array(l);
+ var holder = state.corkedRequestsFree;
+ holder.entry = entry;
+ var count = 0;
+ var allBuffers = true;
+ while (entry) {
+ buffer[count] = entry;
+ if (!entry.isBuf) allBuffers = false;
+ entry = entry.next;
+ count += 1;
+ }
+ buffer.allBuffers = allBuffers;
+ doWrite(stream, state, true, state.length, buffer, '', holder.finish);
+
+ // doWrite is almost always async, defer these to save a bit of time
+ // as the hot path ends with doWrite
+ state.pendingcb++;
+ state.lastBufferedRequest = null;
+ if (holder.next) {
+ state.corkedRequestsFree = holder.next;
+ holder.next = null;
+ } else {
+ state.corkedRequestsFree = new CorkedRequest(state);
}
- /**
- * 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);
- }
- });
+ state.bufferedRequestCount = 0;
+ } else {
+ // Slow case, write chunks one-by-one
+ while (entry) {
+ var chunk = entry.chunk;
+ var encoding = entry.encoding;
+ var cb = entry.callback;
+ var len = state.objectMode ? 1 : chunk.length;
+ doWrite(stream, state, false, len, chunk, encoding, cb);
+ entry = entry.next;
+ state.bufferedRequestCount--;
+ // if we didn't call the onwrite immediately, then
+ // it means that we need to wait until it does.
+ // also, that means that the chunk and cb are currently
+ // being processed, so move the buffer counter past them.
+ if (state.writing) {
+ break;
+ }
}
- /**
- * 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; }
- }
- });
+ if (entry === null) state.lastBufferedRequest = null;
+ }
+ state.bufferedRequest = entry;
+ state.bufferProcessing = false;
+}
+Writable.prototype._write = function (chunk, encoding, cb) {
+ cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
+};
+Writable.prototype._writev = null;
+Writable.prototype.end = function (chunk, encoding, cb) {
+ var state = this._writableState;
+ if (typeof chunk === 'function') {
+ cb = chunk;
+ chunk = null;
+ encoding = null;
+ } else if (typeof encoding === 'function') {
+ cb = encoding;
+ encoding = null;
+ }
+ if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
+
+ // .end() fully uncorks
+ if (state.corked) {
+ state.corked = 1;
+ this.uncork();
+ }
+
+ // ignore unnecessary end() calls.
+ if (!state.ending) endWritable(this, state, cb);
+ return this;
+};
+Object.defineProperty(Writable.prototype, 'writableLength', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._writableState.length;
+ }
+});
+function needFinish(state) {
+ return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
+}
+function callFinal(stream, state) {
+ stream._final(function (err) {
+ state.pendingcb--;
+ if (err) {
+ errorOrDestroy(stream, err);
}
- /**
- * 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");
+ state.prefinished = true;
+ stream.emit('prefinish');
+ finishMaybe(stream, state);
+ });
+}
+function prefinish(stream, state) {
+ if (!state.prefinished && !state.finalCalled) {
+ if (typeof stream._final === 'function' && !state.destroyed) {
+ state.pendingcb++;
+ state.finalCalled = true;
+ process.nextTick(callFinal, stream, state);
+ } else {
+ state.prefinished = true;
+ stream.emit('prefinish');
+ }
+ }
+}
+function finishMaybe(stream, state) {
+ var need = needFinish(state);
+ if (need) {
+ prefinish(stream, state);
+ if (state.pendingcb === 0) {
+ state.finished = true;
+ stream.emit('finish');
+ if (state.autoDestroy) {
+ // In case of duplex streams we need a way to detect
+ // if the readable side is ready for autoDestroy as well
+ var rState = stream._readableState;
+ if (!rState || rState.autoDestroy && rState.endEmitted) {
+ stream.destroy();
}
- // 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://docs.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;
+ }
+ return need;
+}
+function endWritable(stream, state, cb) {
+ state.ending = true;
+ finishMaybe(stream, state);
+ if (cb) {
+ if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
+ }
+ state.ended = true;
+ stream.writable = false;
+}
+function onCorkedFinish(corkReq, state, err) {
+ var entry = corkReq.entry;
+ corkReq.entry = null;
+ while (entry) {
+ var cb = entry.callback;
+ state.pendingcb--;
+ cb(err);
+ entry = entry.next;
+ }
+
+ // reuse the free corkReq.
+ state.corkedRequestsFree.next = corkReq;
+}
+Object.defineProperty(Writable.prototype, 'destroyed', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ if (this._writableState === undefined) {
+ return false;
+ }
+ return this._writableState.destroyed;
+ },
+ set: function set(value) {
+ // we ignore the value if the stream
+ // has not been initialized yet
+ if (!this._writableState) {
+ return;
+ }
+
+ // backward compatibility, the user is explicitly
+ // managing destroyed
+ this._writableState.destroyed = value;
+ }
+});
+Writable.prototype.destroy = destroyImpl.destroy;
+Writable.prototype._undestroy = destroyImpl.undestroy;
+Writable.prototype._destroy = function (err, cb) {
+ cb(err);
+};
+
+/***/ }),
+
+/***/ 14868:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var _Object$setPrototypeO;
+function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
+function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
+function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
+var finished = __nccwpck_require__(36815);
+var kLastResolve = Symbol('lastResolve');
+var kLastReject = Symbol('lastReject');
+var kError = Symbol('error');
+var kEnded = Symbol('ended');
+var kLastPromise = Symbol('lastPromise');
+var kHandlePromise = Symbol('handlePromise');
+var kStream = Symbol('stream');
+function createIterResult(value, done) {
+ return {
+ value: value,
+ done: done
+ };
+}
+function readAndResolve(iter) {
+ var resolve = iter[kLastResolve];
+ if (resolve !== null) {
+ var data = iter[kStream].read();
+ // we defer if data is null
+ // we can be expecting either 'end' or
+ // 'error'
+ if (data !== null) {
+ iter[kLastPromise] = null;
+ iter[kLastResolve] = null;
+ iter[kLastReject] = null;
+ resolve(createIterResult(data, false));
+ }
+ }
+}
+function onReadable(iter) {
+ // we wait for the next tick, because it might
+ // emit an error with process.nextTick
+ process.nextTick(readAndResolve, iter);
+}
+function wrapForNext(lastPromise, iter) {
+ return function (resolve, reject) {
+ lastPromise.then(function () {
+ if (iter[kEnded]) {
+ resolve(createIterResult(undefined, true));
+ return;
+ }
+ iter[kHandlePromise](resolve, reject);
+ }, reject);
+ };
+}
+var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
+var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
+ get stream() {
+ return this[kStream];
+ },
+ next: function next() {
+ var _this = this;
+ // if we have detected an error in the meanwhile
+ // reject straight away
+ var error = this[kError];
+ if (error !== null) {
+ return Promise.reject(error);
+ }
+ if (this[kEnded]) {
+ return Promise.resolve(createIterResult(undefined, true));
+ }
+ if (this[kStream].destroyed) {
+ // We need to defer via nextTick because if .destroy(err) is
+ // called, the error will be emitted via nextTick, and
+ // we cannot guarantee that there is no error lingering around
+ // waiting to be emitted.
+ return new Promise(function (resolve, reject) {
+ process.nextTick(function () {
+ if (_this[kError]) {
+ reject(_this[kError]);
+ } else {
+ resolve(createIterResult(undefined, true));
+ }
});
+ });
}
- /**
- * Creates a BlobBatchClient object to conduct batch operations.
- *
- * @see https://docs.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);
+
+ // if we have multiple next() calls
+ // we will wait for the previous Promise to finish
+ // this logic is optimized to support for await loops,
+ // where next() is only called once at a time
+ var lastPromise = this[kLastPromise];
+ var promise;
+ if (lastPromise) {
+ promise = new Promise(wrapForNext(lastPromise, this));
+ } else {
+ // fast path needed to support multiple this.push()
+ // without triggering the next() queue
+ var data = this[kStream].read();
+ if (data !== null) {
+ return Promise.resolve(createIterResult(data, false));
+ }
+ promise = new Promise(this[kHandlePromise]);
+ }
+ this[kLastPromise] = promise;
+ return promise;
+ }
+}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
+ return this;
+}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
+ var _this2 = this;
+ // destroy(err, cb) is a private API
+ // we can guarantee we have that here, because we control the
+ // Readable class this is attached to
+ return new Promise(function (resolve, reject) {
+ _this2[kStream].destroy(null, function (err) {
+ if (err) {
+ reject(err);
+ return;
+ }
+ resolve(createIterResult(undefined, true));
+ });
+ });
+}), _Object$setPrototypeO), AsyncIteratorPrototype);
+var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
+ var _Object$create;
+ var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
+ value: stream,
+ writable: true
+ }), _defineProperty(_Object$create, kLastResolve, {
+ value: null,
+ writable: true
+ }), _defineProperty(_Object$create, kLastReject, {
+ value: null,
+ writable: true
+ }), _defineProperty(_Object$create, kError, {
+ value: null,
+ writable: true
+ }), _defineProperty(_Object$create, kEnded, {
+ value: stream._readableState.endEmitted,
+ writable: true
+ }), _defineProperty(_Object$create, kHandlePromise, {
+ value: function value(resolve, reject) {
+ var data = iterator[kStream].read();
+ if (data) {
+ iterator[kLastPromise] = null;
+ iterator[kLastResolve] = null;
+ iterator[kLastReject] = null;
+ resolve(createIterResult(data, false));
+ } else {
+ iterator[kLastResolve] = resolve;
+ iterator[kLastReject] = reject;
+ }
+ },
+ writable: true
+ }), _Object$create));
+ iterator[kLastPromise] = null;
+ finished(stream, function (err) {
+ if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
+ var reject = iterator[kLastReject];
+ // reject if we are waiting for data in the Promise
+ // returned by next() and store the error
+ if (reject !== null) {
+ iterator[kLastPromise] = null;
+ iterator[kLastResolve] = null;
+ iterator[kLastReject] = null;
+ reject(err);
+ }
+ iterator[kError] = err;
+ return;
}
- /**
- * 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://docs.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");
+ var resolve = iterator[kLastResolve];
+ if (resolve !== null) {
+ iterator[kLastPromise] = null;
+ iterator[kLastResolve] = null;
+ iterator[kLastReject] = null;
+ resolve(createIterResult(undefined, true));
+ }
+ iterator[kEnded] = true;
+ });
+ stream.on('readable', onReadable.bind(null, iterator));
+ return iterator;
+};
+module.exports = createReadableStreamAsyncIterator;
+
+/***/ }),
+
+/***/ 77336:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
+function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
+function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
+function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
+function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
+var _require = __nccwpck_require__(20181),
+ Buffer = _require.Buffer;
+var _require2 = __nccwpck_require__(39023),
+ inspect = _require2.inspect;
+var custom = inspect && inspect.custom || 'inspect';
+function copyBuffer(src, target, offset) {
+ Buffer.prototype.copy.call(src, target, offset);
+}
+module.exports = /*#__PURE__*/function () {
+ function BufferList() {
+ _classCallCheck(this, BufferList);
+ this.head = null;
+ this.tail = null;
+ this.length = 0;
+ }
+ _createClass(BufferList, [{
+ key: "push",
+ value: function push(v) {
+ var entry = {
+ data: v,
+ next: null
+ };
+ if (this.length > 0) this.tail.next = entry;else this.head = entry;
+ this.tail = entry;
+ ++this.length;
+ }
+ }, {
+ key: "unshift",
+ value: function unshift(v) {
+ var entry = {
+ data: v,
+ next: this.head
+ };
+ if (this.length === 0) this.tail = entry;
+ this.head = entry;
+ ++this.length;
+ }
+ }, {
+ key: "shift",
+ value: function shift() {
+ if (this.length === 0) return;
+ var ret = this.head.data;
+ if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
+ --this.length;
+ return ret;
+ }
+ }, {
+ key: "clear",
+ value: function clear() {
+ this.head = this.tail = null;
+ this.length = 0;
+ }
+ }, {
+ key: "join",
+ value: function join(s) {
+ if (this.length === 0) return '';
+ var p = this.head;
+ var ret = '' + p.data;
+ while (p = p.next) ret += s + p.data;
+ return ret;
+ }
+ }, {
+ key: "concat",
+ value: function concat(n) {
+ if (this.length === 0) return Buffer.alloc(0);
+ var ret = Buffer.allocUnsafe(n >>> 0);
+ var p = this.head;
+ var i = 0;
+ while (p) {
+ copyBuffer(p.data, ret, i);
+ i += p.data.length;
+ p = p.next;
+ }
+ return ret;
+ }
+
+ // Consumes a specified amount of bytes or characters from the buffered data.
+ }, {
+ key: "consume",
+ value: function consume(n, hasStrings) {
+ var ret;
+ if (n < this.head.data.length) {
+ // `slice` is the same for buffers and strings.
+ ret = this.head.data.slice(0, n);
+ this.head.data = this.head.data.slice(n);
+ } else if (n === this.head.data.length) {
+ // First chunk is a perfect match.
+ ret = this.shift();
+ } else {
+ // Result spans more than one buffer.
+ ret = hasStrings ? this._getString(n) : this._getBuffer(n);
+ }
+ return ret;
+ }
+ }, {
+ key: "first",
+ value: function first() {
+ return this.head.data;
+ }
+
+ // Consumes a specified amount of characters from the buffered data.
+ }, {
+ key: "_getString",
+ value: function _getString(n) {
+ var p = this.head;
+ var c = 1;
+ var ret = p.data;
+ n -= ret.length;
+ while (p = p.next) {
+ var str = p.data;
+ var nb = n > str.length ? str.length : n;
+ if (nb === str.length) ret += str;else ret += str.slice(0, n);
+ n -= nb;
+ if (n === 0) {
+ if (nb === str.length) {
+ ++c;
+ if (p.next) this.head = p.next;else this.head = this.tail = null;
+ } else {
+ this.head = p;
+ p.data = str.slice(nb);
+ }
+ break;
}
- if (expiresOn === undefined) {
- const now = new Date();
- expiresOn = new Date(now.getTime() + 3600 * 1000);
+ ++c;
+ }
+ this.length -= c;
+ return ret;
+ }
+
+ // Consumes a specified amount of bytes from the buffered data.
+ }, {
+ key: "_getBuffer",
+ value: function _getBuffer(n) {
+ var ret = Buffer.allocUnsafe(n);
+ var p = this.head;
+ var c = 1;
+ p.data.copy(ret);
+ n -= p.data.length;
+ while (p = p.next) {
+ var buf = p.data;
+ var nb = n > buf.length ? buf.length : n;
+ buf.copy(ret, ret.length - n, 0, nb);
+ n -= nb;
+ if (n === 0) {
+ if (nb === buf.length) {
+ ++c;
+ if (p.next) this.head = p.next;else this.head = this.tail = null;
+ } else {
+ this.head = p;
+ p.data = buf.slice(nb);
+ }
+ break;
}
- const sas = generateAccountSASQueryParameters(Object.assign({ permissions,
- expiresOn,
- resourceTypes, services: AccountSASServices.parse("b").toString() }, options), this.credential).toString();
- return appendToURLQuery(this.url, sas);
+ ++c;
+ }
+ this.length -= c;
+ return ret;
}
- /**
- * 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://docs.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);
+
+ // Make sure the linked list only shows the minimal necessary information.
+ }, {
+ key: custom,
+ value: function value(_, options) {
+ return inspect(this, _objectSpread(_objectSpread({}, options), {}, {
+ // Only inspect one level.
+ depth: 0,
+ // It should not recurse.
+ customInspect: false
+ }));
+ }
+ }]);
+ return BufferList;
+}();
+
+/***/ }),
+
+/***/ 65089:
+/***/ ((module) => {
+
+"use strict";
+
+
+// undocumented cb() API, needed for core, not for public API
+function destroy(err, cb) {
+ var _this = this;
+ var readableDestroyed = this._readableState && this._readableState.destroyed;
+ var writableDestroyed = this._writableState && this._writableState.destroyed;
+ if (readableDestroyed || writableDestroyed) {
+ if (cb) {
+ cb(err);
+ } else if (err) {
+ if (!this._writableState) {
+ process.nextTick(emitErrorNT, this, err);
+ } else if (!this._writableState.errorEmitted) {
+ this._writableState.errorEmitted = true;
+ process.nextTick(emitErrorNT, this, err);
+ }
+ }
+ return this;
+ }
+
+ // we set destroyed to true before firing error callbacks in order
+ // to make it re-entrance safe in case destroy() is called within callbacks
+
+ if (this._readableState) {
+ this._readableState.destroyed = true;
+ }
+
+ // if this is a duplex stream mark the writable part as destroyed as well
+ if (this._writableState) {
+ this._writableState.destroyed = true;
+ }
+ this._destroy(err || null, function (err) {
+ if (!cb && err) {
+ if (!_this._writableState) {
+ process.nextTick(emitErrorAndCloseNT, _this, err);
+ } else if (!_this._writableState.errorEmitted) {
+ _this._writableState.errorEmitted = true;
+ process.nextTick(emitErrorAndCloseNT, _this, err);
+ } else {
+ process.nextTick(emitCloseNT, _this);
+ }
+ } else if (cb) {
+ process.nextTick(emitCloseNT, _this);
+ cb(err);
+ } else {
+ process.nextTick(emitCloseNT, _this);
+ }
+ });
+ return this;
+}
+function emitErrorAndCloseNT(self, err) {
+ emitErrorNT(self, err);
+ emitCloseNT(self);
+}
+function emitCloseNT(self) {
+ if (self._writableState && !self._writableState.emitClose) return;
+ if (self._readableState && !self._readableState.emitClose) return;
+ self.emit('close');
+}
+function undestroy() {
+ if (this._readableState) {
+ this._readableState.destroyed = false;
+ this._readableState.reading = false;
+ this._readableState.ended = false;
+ this._readableState.endEmitted = false;
+ }
+ if (this._writableState) {
+ this._writableState.destroyed = false;
+ this._writableState.ended = false;
+ this._writableState.ending = false;
+ this._writableState.finalCalled = false;
+ this._writableState.prefinished = false;
+ this._writableState.finished = false;
+ this._writableState.errorEmitted = false;
+ }
+}
+function emitErrorNT(self, err) {
+ self.emit('error', err);
+}
+function errorOrDestroy(stream, err) {
+ // We have tests that rely on errors being emitted
+ // in the same tick, so changing this is semver major.
+ // For now when you opt-in to autoDestroy we allow
+ // the error to be emitted nextTick. In a future
+ // semver major update we should change the default to this.
+
+ var rState = stream._readableState;
+ var wState = stream._writableState;
+ if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
+}
+module.exports = {
+ destroy: destroy,
+ undestroy: undestroy,
+ errorOrDestroy: errorOrDestroy
+};
+
+/***/ }),
+
+/***/ 36815:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+// Ported from https://github.com/mafintosh/end-of-stream with
+// permission from the author, Mathias Buus (@mafintosh).
+
+
+
+var ERR_STREAM_PREMATURE_CLOSE = (__nccwpck_require__(25500)/* .codes */ .F).ERR_STREAM_PREMATURE_CLOSE;
+function once(callback) {
+ var called = false;
+ return function () {
+ if (called) return;
+ called = true;
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+ callback.apply(this, args);
+ };
+}
+function noop() {}
+function isRequest(stream) {
+ return stream.setHeader && typeof stream.abort === 'function';
+}
+function eos(stream, opts, callback) {
+ if (typeof opts === 'function') return eos(stream, null, opts);
+ if (!opts) opts = {};
+ callback = once(callback || noop);
+ var readable = opts.readable || opts.readable !== false && stream.readable;
+ var writable = opts.writable || opts.writable !== false && stream.writable;
+ var onlegacyfinish = function onlegacyfinish() {
+ if (!stream.writable) onfinish();
+ };
+ var writableEnded = stream._writableState && stream._writableState.finished;
+ var onfinish = function onfinish() {
+ writable = false;
+ writableEnded = true;
+ if (!readable) callback.call(stream);
+ };
+ var readableEnded = stream._readableState && stream._readableState.endEmitted;
+ var onend = function onend() {
+ readable = false;
+ readableEnded = true;
+ if (!writable) callback.call(stream);
+ };
+ var onerror = function onerror(err) {
+ callback.call(stream, err);
+ };
+ var onclose = function onclose() {
+ var err;
+ if (readable && !readableEnded) {
+ if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
+ return callback.call(stream, err);
+ }
+ if (writable && !writableEnded) {
+ if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
+ return callback.call(stream, err);
+ }
+ };
+ var onrequest = function onrequest() {
+ stream.req.on('finish', onfinish);
+ };
+ if (isRequest(stream)) {
+ stream.on('complete', onfinish);
+ stream.on('abort', onclose);
+ if (stream.req) onrequest();else stream.on('request', onrequest);
+ } else if (writable && !stream._writableState) {
+ // legacy streams
+ stream.on('end', onlegacyfinish);
+ stream.on('close', onlegacyfinish);
+ }
+ stream.on('end', onend);
+ stream.on('finish', onfinish);
+ if (opts.error !== false) stream.on('error', onerror);
+ stream.on('close', onclose);
+ return function () {
+ stream.removeListener('complete', onfinish);
+ stream.removeListener('abort', onclose);
+ stream.removeListener('request', onrequest);
+ if (stream.req) stream.req.removeListener('finish', onfinish);
+ stream.removeListener('end', onlegacyfinish);
+ stream.removeListener('close', onlegacyfinish);
+ stream.removeListener('finish', onfinish);
+ stream.removeListener('end', onend);
+ stream.removeListener('error', onerror);
+ stream.removeListener('close', onclose);
+ };
+}
+module.exports = eos;
+
+/***/ }),
+
+/***/ 4659:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
+function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
+function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
+function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
+function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
+function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
+function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
+var ERR_INVALID_ARG_TYPE = (__nccwpck_require__(25500)/* .codes */ .F).ERR_INVALID_ARG_TYPE;
+function from(Readable, iterable, opts) {
+ var iterator;
+ if (iterable && typeof iterable.next === 'function') {
+ iterator = iterable;
+ } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable);
+ var readable = new Readable(_objectSpread({
+ objectMode: true
+ }, opts));
+ // Reading boolean to protect against _read
+ // being called before last iteration completion.
+ var reading = false;
+ readable._read = function () {
+ if (!reading) {
+ reading = true;
+ next();
+ }
+ };
+ function next() {
+ return _next2.apply(this, arguments);
+ }
+ function _next2() {
+ _next2 = _asyncToGenerator(function* () {
+ try {
+ var _yield$iterator$next = yield iterator.next(),
+ value = _yield$iterator$next.value,
+ done = _yield$iterator$next.done;
+ if (done) {
+ readable.push(null);
+ } else if (readable.push(yield value)) {
+ next();
+ } else {
+ reading = false;
}
- return generateAccountSASQueryParametersInternal(Object.assign({ permissions,
- expiresOn,
- resourceTypes, services: AccountSASServices.parse("b").toString() }, options), this.credential).stringToSign;
+ } catch (err) {
+ readable.destroy(err);
+ }
+ });
+ return _next2.apply(this, arguments);
+ }
+ return readable;
+}
+module.exports = from;
+
+
+/***/ }),
+
+/***/ 16701:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+// Ported from https://github.com/mafintosh/pump with
+// permission from the author, Mathias Buus (@mafintosh).
+
+
+
+var eos;
+function once(callback) {
+ var called = false;
+ return function () {
+ if (called) return;
+ called = true;
+ callback.apply(void 0, arguments);
+ };
+}
+var _require$codes = (__nccwpck_require__(25500)/* .codes */ .F),
+ ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
+ ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
+function noop(err) {
+ // Rethrow the error if it exists to avoid swallowing it
+ if (err) throw err;
+}
+function isRequest(stream) {
+ return stream.setHeader && typeof stream.abort === 'function';
+}
+function destroyer(stream, reading, writing, callback) {
+ callback = once(callback);
+ var closed = false;
+ stream.on('close', function () {
+ closed = true;
+ });
+ if (eos === undefined) eos = __nccwpck_require__(36815);
+ eos(stream, {
+ readable: reading,
+ writable: writing
+ }, function (err) {
+ if (err) return callback(err);
+ closed = true;
+ callback();
+ });
+ var destroyed = false;
+ return function (err) {
+ if (closed) return;
+ if (destroyed) return;
+ destroyed = true;
+
+ // request.destroy just do .end - .abort is what we want
+ if (isRequest(stream)) return stream.abort();
+ if (typeof stream.destroy === 'function') return stream.destroy();
+ callback(err || new ERR_STREAM_DESTROYED('pipe'));
+ };
+}
+function call(fn) {
+ fn();
+}
+function pipe(from, to) {
+ return from.pipe(to);
+}
+function popCallback(streams) {
+ if (!streams.length) return noop;
+ if (typeof streams[streams.length - 1] !== 'function') return noop;
+ return streams.pop();
+}
+function pipeline() {
+ for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
+ streams[_key] = arguments[_key];
+ }
+ var callback = popCallback(streams);
+ if (Array.isArray(streams[0])) streams = streams[0];
+ if (streams.length < 2) {
+ throw new ERR_MISSING_ARGS('streams');
+ }
+ var error;
+ var destroys = streams.map(function (stream, i) {
+ var reading = i < streams.length - 1;
+ var writing = i > 0;
+ return destroyer(stream, reading, writing, function (err) {
+ if (!error) error = err;
+ if (err) destroys.forEach(call);
+ if (reading) return;
+ destroys.forEach(call);
+ callback(error);
+ });
+ });
+ return streams.reduce(pipe);
+}
+module.exports = pipeline;
+
+/***/ }),
+
+/***/ 54874:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var ERR_INVALID_OPT_VALUE = (__nccwpck_require__(25500)/* .codes */ .F).ERR_INVALID_OPT_VALUE;
+function highWaterMarkFrom(options, isDuplex, duplexKey) {
+ return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
+}
+function getHighWaterMark(state, options, duplexKey, isDuplex) {
+ var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
+ if (hwm != null) {
+ if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
+ var name = isDuplex ? duplexKey : 'highWaterMark';
+ throw new ERR_INVALID_OPT_VALUE(name, hwm);
}
+ return Math.floor(hwm);
+ }
+
+ // Default value
+ return state.objectMode ? 16 : 16 * 1024;
}
+module.exports = {
+ getHighWaterMark: getHighWaterMark
+};
-// 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
+/***/ 63283:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+module.exports = __nccwpck_require__(2203);
+
+
+/***/ }),
+
+/***/ 86131:
+/***/ ((module, exports, __nccwpck_require__) => {
+
+var Stream = __nccwpck_require__(2203);
+if (process.env.READABLE_STREAM === 'disable' && Stream) {
+ module.exports = Stream.Readable;
+ Object.assign(module.exports, Stream);
+ module.exports.Stream = Stream;
+} else {
+ exports = module.exports = __nccwpck_require__(86893);
+ exports.Stream = Stream || exports;
+ exports.Readable = exports;
+ exports.Writable = __nccwpck_require__(38797);
+ exports.Duplex = __nccwpck_require__(82063);
+ exports.Transform = __nccwpck_require__(12337);
+ exports.PassThrough = __nccwpck_require__(35283);
+ exports.finished = __nccwpck_require__(36815);
+ exports.pipeline = __nccwpck_require__(16701);
+}
+
+
+/***/ }),
+
+/***/ 67842:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+const {PassThrough} = __nccwpck_require__(2203);
+const extend = __nccwpck_require__(23860);
+
+let debug = () => {};
+if (
+ typeof process !== 'undefined' &&
+ 'env' in process &&
+ typeof process.env === 'object' &&
+ process.env.DEBUG === 'retry-request'
+) {
+ debug = message => {
+ console.log('retry-request:', message);
+ };
+}
+
+const DEFAULTS = {
+ objectMode: false,
+ retries: 2,
+
+ /*
+ The maximum time to delay in seconds. If retryDelayMultiplier results in a
+ delay greater than maxRetryDelay, retries should delay by maxRetryDelay
+ seconds instead.
+ */
+ maxRetryDelay: 64,
+
+ /*
+ The multiplier by which to increase the delay time between the completion of
+ failed requests, and the initiation of the subsequent retrying request.
+ */
+ retryDelayMultiplier: 2,
+
+ /*
+ The length of time to keep retrying in seconds. The last sleep period will
+ be shortened as necessary, so that the last retry runs at deadline (and not
+ considerably beyond it). The total time starting from when the initial
+ request is sent, after which an error will be returned, regardless of the
+ retrying attempts made meanwhile.
+ */
+ totalTimeout: 600,
+
+ noResponseRetries: 2,
+ currentRetryAttempt: 0,
+ shouldRetryFn: function (response) {
+ const retryRanges = [
+ // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
+ // 1xx - Retry (Informational, request still processing)
+ // 2xx - Do not retry (Success)
+ // 3xx - Do not retry (Redirect)
+ // 4xx - Do not retry (Client errors)
+ // 429 - Retry ("Too Many Requests")
+ // 5xx - Retry (Server errors)
+ [100, 199],
+ [429, 429],
+ [500, 599],
+ ];
+
+ const statusCode = response.statusCode;
+ debug(`Response status: ${statusCode}`);
+
+ let range;
+ while ((range = retryRanges.shift())) {
+ if (statusCode >= range[0] && statusCode <= range[1]) {
+ // Not a successful status or redirect.
+ return true;
+ }
+ }
+ },
+};
+
+function retryRequest(requestOpts, opts, callback) {
+ if (typeof requestOpts === 'string') {
+ requestOpts = {url: requestOpts};
+ }
+
+ const streamMode = typeof arguments[arguments.length - 1] !== 'function';
+
+ if (typeof opts === 'function') {
+ callback = opts;
+ }
+
+ const manualCurrentRetryAttemptWasSet =
+ opts && typeof opts.currentRetryAttempt === 'number';
+ opts = extend({}, DEFAULTS, opts);
+
+ if (typeof opts.request === 'undefined') {
+ throw new Error('A request library must be provided to retry-request.');
+ }
+
+ let currentRetryAttempt = opts.currentRetryAttempt;
+
+ let numNoResponseAttempts = 0;
+ let streamResponseHandled = false;
+
+ let retryStream;
+ let requestStream;
+ let delayStream;
+
+ let activeRequest;
+ const retryRequest = {
+ abort: function () {
+ if (activeRequest && activeRequest.abort) {
+ activeRequest.abort();
+ }
+ },
+ };
+
+ if (streamMode) {
+ retryStream = new PassThrough({objectMode: opts.objectMode});
+ retryStream.abort = resetStreams;
+ }
+
+ const timeOfFirstRequest = Date.now();
+ if (currentRetryAttempt > 0) {
+ retryAfterDelay(currentRetryAttempt);
+ } else {
+ makeRequest();
+ }
+
+ if (streamMode) {
+ return retryStream;
+ } else {
+ return retryRequest;
+ }
+
+ function resetStreams() {
+ delayStream = null;
+
+ if (requestStream) {
+ requestStream.abort && requestStream.abort();
+ requestStream.cancel && requestStream.cancel();
+
+ if (requestStream.destroy) {
+ requestStream.destroy();
+ } else if (requestStream.end) {
+ requestStream.end();
+ }
+ }
+ }
+
+ function makeRequest() {
+ let finishHandled = false;
+ currentRetryAttempt++;
+ debug(`Current retry attempt: ${currentRetryAttempt}`);
+
+ function handleFinish(args = []) {
+ if (!finishHandled) {
+ finishHandled = true;
+ retryStream.emit('complete', ...args);
+ }
+ }
+
+ if (streamMode) {
+ streamResponseHandled = false;
+
+ delayStream = new PassThrough({objectMode: opts.objectMode});
+ requestStream = opts.request(requestOpts);
+
+ setImmediate(() => {
+ retryStream.emit('request');
+ });
+
+ requestStream
+ // gRPC via google-cloud-node can emit an `error` as well as a `response`
+ // Whichever it emits, we run with-- we can't run with both. That's what
+ // is up with the `streamResponseHandled` tracking.
+ .on('error', err => {
+ if (streamResponseHandled) {
+ return;
+ }
+
+ streamResponseHandled = true;
+ onResponse(err);
+ })
+ .on('response', (resp, body) => {
+ if (streamResponseHandled) {
+ return;
+ }
+
+ streamResponseHandled = true;
+ onResponse(null, resp, body);
+ })
+ .on('complete', (...params) => handleFinish(params))
+ .on('finish', (...params) => handleFinish(params));
+
+ requestStream.pipe(delayStream);
+ } else {
+ activeRequest = opts.request(requestOpts, onResponse);
+ }
+ }
+
+ function retryAfterDelay(currentRetryAttempt) {
+ if (streamMode) {
+ resetStreams();
+ }
+
+ const nextRetryDelay = getNextRetryDelay({
+ maxRetryDelay: opts.maxRetryDelay,
+ retryDelayMultiplier: opts.retryDelayMultiplier,
+ retryNumber: currentRetryAttempt,
+ timeOfFirstRequest,
+ totalTimeout: opts.totalTimeout,
+ });
+ debug(`Next retry delay: ${nextRetryDelay}`);
+ if (nextRetryDelay <= 0) {
+ numNoResponseAttempts = opts.noResponseRetries + 1;
+ return;
+ }
-/***/ }),
+ setTimeout(makeRequest, nextRetryDelay);
+ }
-/***/ 7889:
-/***/ (function(__unused_webpack_module, exports) {
+ function onResponse(err, response, body) {
+ // An error such as DNS resolution.
+ if (err) {
+ numNoResponseAttempts++;
-"use strict";
+ if (numNoResponseAttempts <= opts.noResponseRetries) {
+ retryAfterDelay(numNoResponseAttempts);
+ } else {
+ if (streamMode) {
+ retryStream.emit('error', err);
+ retryStream.end();
+ } else {
+ callback(err, response, body);
+ }
+ }
-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;
+ return;
}
- /**
- * 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));
+
+ // Send the response to see if we should try again.
+ // NOTE: "currentRetryAttempt" isn't accurate by default, as it counts
+ // the very first request sent as the first "retry". It is only accurate
+ // when a user provides their own "currentRetryAttempt" option at
+ // instantiation.
+ const adjustedCurrentRetryAttempt = manualCurrentRetryAttemptWasSet
+ ? currentRetryAttempt
+ : currentRetryAttempt - 1;
+ if (
+ adjustedCurrentRetryAttempt < opts.retries &&
+ opts.shouldRetryFn(response)
+ ) {
+ retryAfterDelay(currentRetryAttempt);
+ return;
}
- 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
- };
- });
+
+ // No more attempts need to be made, just continue on.
+ if (streamMode) {
+ retryStream.emit('response', response);
+ delayStream.pipe(retryStream);
+ requestStream.on('error', err => {
+ retryStream.destroy(err);
+ });
+ } else {
+ callback(err, response, body);
}
+ }
+}
+
+module.exports = retryRequest;
+
+function getNextRetryDelay(config) {
+ const {
+ maxRetryDelay,
+ retryDelayMultiplier,
+ retryNumber,
+ timeOfFirstRequest,
+ totalTimeout,
+ } = config;
+
+ const maxRetryDelayMs = maxRetryDelay * 1000;
+ const totalTimeoutMs = totalTimeout * 1000;
+
+ const jitter = Math.floor(Math.random() * 1000);
+ const calculatedNextRetryDelay =
+ Math.pow(retryDelayMultiplier, retryNumber) * 1000 + jitter;
+
+ const maxAllowableDelayMs =
+ totalTimeoutMs - (Date.now() - timeOfFirstRequest);
+
+ return Math.min(
+ calculatedNextRetryDelay,
+ maxAllowableDelayMs,
+ maxRetryDelayMs
+ );
}
-exports.ClientStreamingCall = ClientStreamingCall;
+
+module.exports.defaults = DEFAULTS;
+module.exports.getNextRetryDelay = getNextRetryDelay;
/***/ }),
-/***/ 1409:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 5546:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-"use strict";
+module.exports = __nccwpck_require__(67084);
-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;
+/***/ }),
+
+/***/ 67084:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+var RetryOperation = __nccwpck_require__(39538);
+
+exports.operation = function(options) {
+ var timeouts = exports.timeouts(options);
+ return new RetryOperation(timeouts, {
+ forever: options && (options.forever || options.retries === Infinity),
+ unref: options && options.unref,
+ maxRetryTime: options && options.maxRetryTime
+ });
+};
+
+exports.timeouts = function(options) {
+ if (options instanceof Array) {
+ return [].concat(options);
+ }
+
+ var opts = {
+ retries: 10,
+ factor: 2,
+ minTimeout: 1 * 1000,
+ maxTimeout: Infinity,
+ randomize: false
+ };
+ for (var key in options) {
+ opts[key] = options[key];
+ }
+
+ if (opts.minTimeout > opts.maxTimeout) {
+ throw new Error('minTimeout is greater than maxTimeout');
+ }
+
+ var timeouts = [];
+ for (var i = 0; i < opts.retries; i++) {
+ timeouts.push(this.createTimeout(i, opts));
+ }
+
+ if (options && options.forever && !timeouts.length) {
+ timeouts.push(this.createTimeout(i, opts));
+ }
+
+ // sort the array numerically ascending
+ timeouts.sort(function(a,b) {
+ return a - b;
+ });
+
+ return timeouts;
+};
+
+exports.createTimeout = function(attempt, opts) {
+ var random = (opts.randomize)
+ ? (Math.random() + 1)
+ : 1;
+
+ var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));
+ timeout = Math.min(timeout, opts.maxTimeout);
+
+ return timeout;
+};
+
+exports.wrap = function(obj, options, methods) {
+ if (options instanceof Array) {
+ methods = options;
+ options = null;
+ }
+
+ if (!methods) {
+ methods = [];
+ for (var key in obj) {
+ if (typeof obj[key] === 'function') {
+ methods.push(key);
+ }
}
- /**
- * 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;
+ }
+
+ for (var i = 0; i < methods.length; i++) {
+ var method = methods[i];
+ var original = obj[method];
+
+ obj[method] = function retryWrapper(original) {
+ var op = exports.operation(options);
+ var args = Array.prototype.slice.call(arguments, 1);
+ var callback = args.pop();
+
+ args.push(function(err) {
+ if (op.retry(err)) {
+ return;
+ }
+ if (err) {
+ arguments[0] = op.mainError();
+ }
+ callback.apply(this, arguments);
+ });
+
+ op.attempt(function() {
+ original.apply(obj, args);
+ });
+ }.bind(obj, original);
+ obj[method].options = options;
+ }
+};
+
+
+/***/ }),
+
+/***/ 39538:
+/***/ ((module) => {
+
+function RetryOperation(timeouts, options) {
+ // Compatibility for the old (timeouts, retryForever) signature
+ if (typeof options === 'boolean') {
+ options = { forever: options };
+ }
+
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
+ this._timeouts = timeouts;
+ this._options = options || {};
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
+ this._fn = null;
+ this._errors = [];
+ this._attempts = 1;
+ this._operationTimeout = null;
+ this._operationTimeoutCb = null;
+ this._timeout = null;
+ this._operationStart = null;
+ this._timer = null;
+
+ if (this._options.forever) {
+ this._cachedTimeouts = this._timeouts.slice(0);
+ }
+}
+module.exports = RetryOperation;
+
+RetryOperation.prototype.reset = function() {
+ this._attempts = 1;
+ this._timeouts = this._originalTimeouts.slice(0);
+}
+
+RetryOperation.prototype.stop = function() {
+ if (this._timeout) {
+ clearTimeout(this._timeout);
+ }
+ if (this._timer) {
+ clearTimeout(this._timer);
+ }
+
+ this._timeouts = [];
+ this._cachedTimeouts = null;
+};
+
+RetryOperation.prototype.retry = function(err) {
+ if (this._timeout) {
+ clearTimeout(this._timeout);
+ }
+
+ if (!err) {
+ return false;
+ }
+ var currentTime = new Date().getTime();
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
+ this._errors.push(err);
+ this._errors.unshift(new Error('RetryOperation timeout occurred'));
+ return false;
+ }
+
+ this._errors.push(err);
+
+ var timeout = this._timeouts.shift();
+ if (timeout === undefined) {
+ if (this._cachedTimeouts) {
+ // retry forever, only keep last error
+ this._errors.splice(0, this._errors.length - 1);
+ timeout = this._cachedTimeouts.slice(-1);
+ } else {
+ return false;
}
- /**
- * 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;
+ }
+
+ var self = this;
+ this._timer = setTimeout(function() {
+ self._attempts++;
+
+ if (self._operationTimeoutCb) {
+ self._timeout = setTimeout(function() {
+ self._operationTimeoutCb(self._attempts);
+ }, self._operationTimeout);
+
+ if (self._options.unref) {
+ self._timeout.unref();
+ }
}
- /**
- * Resolve the promise. Ignore if not pending.
- */
- resolvePending(val) {
- if (this._state === DeferredState.PENDING)
- this.resolve(val);
+
+ self._fn(self._attempts);
+ }, timeout);
+
+ if (this._options.unref) {
+ this._timer.unref();
+ }
+
+ return true;
+};
+
+RetryOperation.prototype.attempt = function(fn, timeoutOps) {
+ this._fn = fn;
+
+ if (timeoutOps) {
+ if (timeoutOps.timeout) {
+ this._operationTimeout = timeoutOps.timeout;
}
- /**
- * Reject the promise. Ignore if not pending.
- */
- rejectPending(reason) {
- if (this._state === DeferredState.PENDING)
- this.reject(reason);
+ if (timeoutOps.cb) {
+ this._operationTimeoutCb = timeoutOps.cb;
}
-}
-exports.Deferred = Deferred;
+ }
+ var self = this;
+ if (this._operationTimeoutCb) {
+ this._timeout = setTimeout(function() {
+ self._operationTimeoutCb();
+ }, self._operationTimeout);
+ }
-/***/ }),
+ this._operationStart = new Date().getTime();
-/***/ 6826:
-/***/ (function(__unused_webpack_module, exports) {
+ this._fn(this._attempts);
+};
-"use strict";
+RetryOperation.prototype.try = function(fn) {
+ console.log('Using RetryOperation.try() is deprecated');
+ this.attempt(fn);
+};
-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());
- });
+RetryOperation.prototype.start = function(fn) {
+ console.log('Using RetryOperation.start() is deprecated');
+ this.attempt(fn);
};
-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));
+
+RetryOperation.prototype.start = RetryOperation.prototype.try;
+
+RetryOperation.prototype.errors = function() {
+ return this._errors;
+};
+
+RetryOperation.prototype.attempts = function() {
+ return this._attempts;
+};
+
+RetryOperation.prototype.mainError = function() {
+ if (this._errors.length === 0) {
+ return null;
+ }
+
+ var counts = {};
+ var mainError = null;
+ var mainErrorCount = 0;
+
+ for (var i = 0; i < this._errors.length; i++) {
+ var error = this._errors[i];
+ var message = error.message;
+ var count = (counts[message] || 0) + 1;
+
+ counts[message] = count;
+
+ if (count >= mainErrorCount) {
+ mainError = error;
+ mainErrorCount = count;
}
- 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,
- };
- });
+ }
+
+ return mainError;
+};
+
+
+/***/ }),
+
+/***/ 93058:
+/***/ ((module, exports, __nccwpck_require__) => {
+
+/*! safe-buffer. MIT License. Feross Aboukhadijeh */
+/* eslint-disable node/no-deprecated-api */
+var buffer = __nccwpck_require__(20181)
+var Buffer = buffer.Buffer
+
+// alternative to using Object.keys for old browsers
+function copyProps (src, dst) {
+ for (var key in src) {
+ dst[key] = src[key]
+ }
+}
+if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
+ module.exports = buffer
+} else {
+ // Copy properties from require('buffer')
+ copyProps(buffer, exports)
+ exports.Buffer = SafeBuffer
+}
+
+function SafeBuffer (arg, encodingOrOffset, length) {
+ return Buffer(arg, encodingOrOffset, length)
+}
+
+SafeBuffer.prototype = Object.create(Buffer.prototype)
+
+// Copy static methods from Buffer
+copyProps(Buffer, SafeBuffer)
+
+SafeBuffer.from = function (arg, encodingOrOffset, length) {
+ if (typeof arg === 'number') {
+ throw new TypeError('Argument must not be a number')
+ }
+ return Buffer(arg, encodingOrOffset, length)
+}
+
+SafeBuffer.alloc = function (size, fill, encoding) {
+ if (typeof size !== 'number') {
+ throw new TypeError('Argument must be a number')
+ }
+ var buf = Buffer(size)
+ if (fill !== undefined) {
+ if (typeof encoding === 'string') {
+ buf.fill(fill, encoding)
+ } else {
+ buf.fill(fill)
}
+ } else {
+ buf.fill(0)
+ }
+ return buf
+}
+
+SafeBuffer.allocUnsafe = function (size) {
+ if (typeof size !== 'number') {
+ throw new TypeError('Argument must be a number')
+ }
+ return Buffer(size)
+}
+
+SafeBuffer.allocUnsafeSlow = function (size) {
+ if (typeof size !== 'number') {
+ throw new TypeError('Argument must be a number')
+ }
+ return buffer.SlowBuffer(size)
}
-exports.DuplexStreamingCall = DuplexStreamingCall;
/***/ }),
-/***/ 4420:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 39318:
+/***/ ((module, exports) => {
-"use strict";
+exports = module.exports = SemVer
-// 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__(6892);
-Object.defineProperty(exports, "ServiceType", ({ enumerable: true, get: function () { return service_type_1.ServiceType; } }));
-var reflection_info_1 = __nccwpck_require__(2496);
-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__(8636);
-Object.defineProperty(exports, "RpcError", ({ enumerable: true, get: function () { return rpc_error_1.RpcError; } }));
-var rpc_options_1 = __nccwpck_require__(8576);
-Object.defineProperty(exports, "mergeRpcOptions", ({ enumerable: true, get: function () { return rpc_options_1.mergeRpcOptions; } }));
-var rpc_output_stream_1 = __nccwpck_require__(2726);
-Object.defineProperty(exports, "RpcOutputStreamController", ({ enumerable: true, get: function () { return rpc_output_stream_1.RpcOutputStreamController; } }));
-var test_transport_1 = __nccwpck_require__(9122);
-Object.defineProperty(exports, "TestTransport", ({ enumerable: true, get: function () { return test_transport_1.TestTransport; } }));
-var deferred_1 = __nccwpck_require__(1409);
-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__(6826);
-Object.defineProperty(exports, "DuplexStreamingCall", ({ enumerable: true, get: function () { return duplex_streaming_call_1.DuplexStreamingCall; } }));
-var client_streaming_call_1 = __nccwpck_require__(7889);
-Object.defineProperty(exports, "ClientStreamingCall", ({ enumerable: true, get: function () { return client_streaming_call_1.ClientStreamingCall; } }));
-var server_streaming_call_1 = __nccwpck_require__(6173);
-Object.defineProperty(exports, "ServerStreamingCall", ({ enumerable: true, get: function () { return server_streaming_call_1.ServerStreamingCall; } }));
-var unary_call_1 = __nccwpck_require__(9288);
-Object.defineProperty(exports, "UnaryCall", ({ enumerable: true, get: function () { return unary_call_1.UnaryCall; } }));
-var rpc_interceptor_1 = __nccwpck_require__(2849);
-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__(3352);
-Object.defineProperty(exports, "ServerCallContextController", ({ enumerable: true, get: function () { return server_call_context_1.ServerCallContextController; } }));
+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
-/***/ 2496:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// Max safe segment length for coercion.
+var MAX_SAFE_COMPONENT_LENGTH = 16
-"use strict";
+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] + '?'
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.readServiceOption = exports.readMethodOption = exports.readMethodOptions = exports.normalizeMethodInfo = void 0;
-const runtime_1 = __nccwpck_require__(8886);
-/**
- * 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;
+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|\\*'
-/***/ 8636:
-/***/ ((__unused_webpack_module, exports) => {
+tok('XRANGEPLAIN')
+src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' +
+ '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' +
+ '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' +
+ '(?:' + src[t.PRERELEASE] + ')?' +
+ src[t.BUILD] + '?' +
+ ')?)?'
-"use strict";
+tok('XRANGEPLAINLOOSE')
+src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
+ '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
+ '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
+ '(?:' + src[t.PRERELEASELOOSE] + ')?' +
+ src[t.BUILD] + '?' +
+ ')?)?'
-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;
+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] = '(?:~>?)'
-/***/ 2849:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+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~'
-"use strict";
+tok('TILDE')
+src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$'
+tok('TILDELOOSE')
+src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$'
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.stackDuplexStreamingInterceptors = exports.stackClientStreamingInterceptors = exports.stackServerStreamingInterceptors = exports.stackUnaryInterceptors = exports.stackIntercept = void 0;
-const runtime_1 = __nccwpck_require__(8886);
-/**
- * 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;
+// 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] + '$'
-/***/ 8576:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// 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] + ')$|^$'
-"use strict";
+// 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] + ')'
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.mergeRpcOptions = void 0;
-const runtime_1 = __nccwpck_require__(8886);
-/**
- * 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;
- }
-}
+// 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*$'
-/***/ 2726:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// Star ranges basically just allow anything at all.
+tok('STAR')
+src[t.STAR] = '(<|>)?=?\\s*\\*'
-"use strict";
+// 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])
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.RpcOutputStreamController = void 0;
-const deferred_1 = __nccwpck_require__(1409);
-const runtime_1 = __nccwpck_require__(8886);
-/**
- * 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);
- }
- }
+ // 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.RpcOutputStreamController = RpcOutputStreamController;
+exports.parse = parse
+function parse (version, options) {
+ if (!options || typeof options !== 'object') {
+ options = {
+ loose: !!options,
+ includePrerelease: false
+ }
+ }
-/***/ }),
+ if (version instanceof SemVer) {
+ return version
+ }
-/***/ 3352:
-/***/ ((__unused_webpack_module, exports) => {
+ if (typeof version !== 'string') {
+ return null
+ }
-"use strict";
+ if (version.length > MAX_LENGTH) {
+ return null
+ }
-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;
+ 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
+}
-/***/ 6173:
-/***/ (function(__unused_webpack_module, exports) {
+exports.clean = clean
+function clean (version, options) {
+ var s = parse(version.trim().replace(/^[=v]+/, ''), options)
+ return s ? s.version : null
+}
-"use strict";
+exports.SemVer = SemVer
-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));
+function SemVer (version, options) {
+ if (!options || typeof options !== 'object') {
+ options = {
+ loose: !!options,
+ includePrerelease: false
}
- 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,
- };
- });
+ }
+ if (version instanceof SemVer) {
+ if (version.loose === options.loose) {
+ return version
+ } else {
+ version = version.version
}
-}
-exports.ServerStreamingCall = ServerStreamingCall;
+ } 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)
+ }
-/***/ 6892:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ debug('SemVer', version, options)
+ this.options = options
+ this.loose = !!options.loose
-"use strict";
+ var m = version.trim().match(options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL])
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ServiceType = void 0;
-const reflection_info_1 = __nccwpck_require__(2496);
-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;
+ 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]
-/***/ 9122:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
+ throw new TypeError('Invalid major version')
+ }
-"use strict";
+ if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
+ throw new TypeError('Invalid minor version')
+ }
-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__(8636);
-const runtime_1 = __nccwpck_require__(8886);
-const rpc_output_stream_1 = __nccwpck_require__(2726);
-const rpc_options_1 = __nccwpck_require__(8576);
-const unary_call_1 = __nccwpck_require__(9288);
-const server_streaming_call_1 = __nccwpck_require__(6173);
-const client_streaming_call_1 = __nccwpck_require__(7889);
-const duplex_streaming_call_1 = __nccwpck_require__(6826);
-/**
- * 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(() => {
- });
- }
+ 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)
}
- 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);
+ } 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)
}
-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"));
- });
- }
+
+// 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
+ }
}
- });
-}
-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);
+ if (i === -1) {
+ // didn't increment anything
+ this.prerelease.push(0)
}
- 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);
+ }
+ 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]
}
- const delayMs = this.data.inputComplete === undefined
- ? 10
- : this.data.inputComplete;
- return Promise.resolve(undefined)
- .then(() => {
- this._completed = true;
- })
- .then(delay(delayMs, this.abort));
- }
-}
-
+ }
+ break
-/***/ }),
+ default:
+ throw new Error('invalid increment argument: ' + release)
+ }
+ this.format()
+ this.raw = this.version
+ return this
+}
-/***/ 9288:
-/***/ (function(__unused_webpack_module, exports) {
+exports.inc = inc
+function inc (version, release, loose, identifier) {
+ if (typeof (loose) === 'string') {
+ identifier = loose
+ loose = undefined
+ }
-"use strict";
+ try {
+ return new SemVer(version, loose).inc(release, identifier).version
+ } catch (er) {
+ return null
+ }
+}
-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));
+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'
}
- 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
- };
- });
+ 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.UnaryCall = UnaryCall;
+exports.compareIdentifiers = compareIdentifiers
-/***/ }),
-
-/***/ 8602:
-/***/ ((__unused_webpack_module, exports) => {
+var numeric = /^[0-9]+$/
+function compareIdentifiers (a, b) {
+ var anum = numeric.test(a)
+ var bnum = numeric.test(b)
-"use strict";
+ if (anum && bnum) {
+ a = +a
+ b = +b
+ }
-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);
- }
+ return a === b ? 0
+ : (anum && !bnum) ? -1
+ : (bnum && !anum) ? 1
+ : a < b ? -1
+ : 1
}
-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.rcompareIdentifiers = rcompareIdentifiers
+function rcompareIdentifiers (a, b) {
+ return compareIdentifiers(b, a)
}
-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.major = major
+function major (a, loose) {
+ return new SemVer(a, loose).major
}
-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.minor = minor
+function minor (a, loose) {
+ return new SemVer(a, loose).minor
}
-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.patch = patch
+function patch (a, loose) {
+ return new SemVer(a, loose).patch
}
-exports.assertFloat32 = assertFloat32;
+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)
+}
-/***/ 6335:
-/***/ ((__unused_webpack_module, exports) => {
+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)
+}
-"use strict";
+exports.rcompare = rcompare
+function rcompare (a, b, loose) {
+ return compare(b, a, loose)
+}
-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.sort = sort
+function sort (list, loose) {
+ return list.sort(function (a, b) {
+ return exports.compareBuild(a, b, loose)
+ })
}
-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.rsort = rsort
+function rsort (list, loose) {
+ return list.sort(function (a, b) {
+ return exports.compareBuild(b, a, loose)
+ })
}
-exports.base64encode = base64encode;
+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
+}
-/***/ 4816:
-/***/ ((__unused_webpack_module, exports) => {
+exports.eq = eq
+function eq (a, b, loose) {
+ return compare(a, b, loose) === 0
+}
-"use strict";
+exports.neq = neq
+function neq (a, b, loose) {
+ return compare(a, b, loose) !== 0
+}
-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.gte = gte
+function gte (a, b, loose) {
+ return compare(a, b, loose) >= 0
}
-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 = {}));
+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
-/***/ 2889:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ case '!==':
+ if (typeof a === 'object')
+ a = a.version
+ if (typeof b === 'object')
+ b = b.version
+ return a !== b
-"use strict";
+ case '':
+ case '=':
+ case '==':
+ return eq(a, b, loose)
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.BinaryReader = exports.binaryReadOptions = void 0;
-const binary_format_contract_1 = __nccwpck_require__(4816);
-const pb_long_1 = __nccwpck_require__(1753);
-const goog_varint_1 = __nccwpck_require__(3223);
-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;
+ case '!=':
+ return neq(a, b, loose)
+ case '>':
+ return gt(a, b, loose)
-/***/ }),
+ case '>=':
+ return gte(a, b, loose)
-/***/ 3957:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ case '<':
+ return lt(a, b, loose)
-"use strict";
+ case '<=':
+ return lte(a, b, loose)
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.BinaryWriter = exports.binaryWriteOptions = void 0;
-const pb_long_1 = __nccwpck_require__(1753);
-const goog_varint_1 = __nccwpck_require__(3223);
-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;
+ default:
+ throw new TypeError('Invalid operator: ' + op)
+ }
}
-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);
+
+exports.Comparator = Comparator
+function Comparator (comp, options) {
+ if (!options || typeof options !== 'object') {
+ options = {
+ loose: !!options,
+ includePrerelease: false
}
- /**
- * 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;
+ }
+
+ if (comp instanceof Comparator) {
+ if (comp.loose === !!options.loose) {
+ return comp
+ } else {
+ comp = comp.value
}
- /**
- * 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);
+ }
+
+ 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
}
- /**
- * 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);
+ }
+
+ 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
}
- /**
- * 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;
+ }
+
+ var rangeTmp
+
+ if (this.operator === '') {
+ if (this.value === '') {
+ return true
}
- /**
- * 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;
+ rangeTmp = new Range(comp.value, options)
+ return satisfies(this.value, rangeTmp, options)
+ } else if (comp.operator === '') {
+ if (comp.value === '') {
+ return true
}
- /**
- * 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;
+ 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()
}
-exports.BinaryWriter = BinaryWriter;
+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
+}
-/***/ 257:
-/***/ ((__unused_webpack_module, exports) => {
+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])
-"use strict";
+ // `~ 1.2.3` => `~1.2.3`
+ range = range.replace(safeRe[t.TILDETRIM], tildeTrimReplace)
-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;
+ // `^ 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'
}
- 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;
+
+ 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 {
- // 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;
+ } 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'
+ }
}
- 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);
+
+ debug('caret return', ret)
+ return ret
+ })
}
-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);
+
+function replaceXRanges (comp, options) {
+ debug('replaceXRanges', comp, options)
+ return comp.split(/\s+/).map(function (comp) {
+ return replaceXRange(comp, options)
+ }).join(' ')
}
-exports.listEnumNumbers = listEnumNumbers;
+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 = ''
+ }
-/***/ 3223:
-/***/ ((__unused_webpack_module, exports) => {
+ // 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' : ''
-"use strict";
+ 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
-// 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];
+ 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
}
- }
- 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];
+ } 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
}
- throw new Error('invalid varint');
+
+ debug('xRange return', ret)
+
+ return ret
+ })
}
-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);
+
+// 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], '')
}
-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];
+
+// 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()
}
-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;
+
+// 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
}
- // 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;
+ }
+
+ for (var i = 0; i < this.set.length; i++) {
+ if (testSet(this.set[i], version, this.options)) {
+ return true
}
- 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);
+ }
+ return false
}
-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);
+
+function testSet (set, version, options) {
+ for (var i = 0; i < set.length; i++) {
+ if (!set[i].test(version)) {
+ return false
}
- else {
- for (let i = 0; i < 9; i++) {
- bytes.push(value & 127 | 128);
- value = value >> 7;
+ }
+
+ 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
}
- bytes.push(1);
+ }
}
+
+ // Version has a -pre, but it's not one of the ones we like.
+ return false
+ }
+
+ return true
}
-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;
+
+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)
+ }
}
- b = this.buf[this.pos++];
- result |= (b & 0x7F) << 21;
- if ((b & 0x80) == 0) {
- this.assertBounds();
- return result;
+ })
+ 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)
+ }
}
- // 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;
+ })
+ return min
}
-exports.varint32read = varint32read;
+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
+ }
-/***/ 8886:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ return null
+}
-"use strict";
+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
+ }
+}
-// 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__(9999);
-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__(6335);
-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__(8950);
-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__(4816);
-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__(2889);
-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__(3957);
-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__(1753);
-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__(9367);
-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__(3785);
-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__(5106);
-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__(7910);
-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__(5167);
-Object.defineProperty(exports, "ReflectionTypeCheck", ({ enumerable: true, get: function () { return reflection_type_check_1.ReflectionTypeCheck; } }));
-var reflection_create_1 = __nccwpck_require__(5726);
-Object.defineProperty(exports, "reflectionCreate", ({ enumerable: true, get: function () { return reflection_create_1.reflectionCreate; } }));
-var reflection_scalar_default_1 = __nccwpck_require__(9526);
-Object.defineProperty(exports, "reflectionScalarDefault", ({ enumerable: true, get: function () { return reflection_scalar_default_1.reflectionScalarDefault; } }));
-var reflection_merge_partial_1 = __nccwpck_require__(8044);
-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__(9611);
-Object.defineProperty(exports, "ReflectionBinaryReader", ({ enumerable: true, get: function () { return reflection_binary_reader_1.ReflectionBinaryReader; } }));
-var reflection_binary_writer_1 = __nccwpck_require__(6907);
-Object.defineProperty(exports, "ReflectionBinaryWriter", ({ enumerable: true, get: function () { return reflection_binary_writer_1.ReflectionBinaryWriter; } }));
-var reflection_json_reader_1 = __nccwpck_require__(6790);
-Object.defineProperty(exports, "ReflectionJsonReader", ({ enumerable: true, get: function () { return reflection_json_reader_1.ReflectionJsonReader; } }));
-var reflection_json_writer_1 = __nccwpck_require__(1094);
-Object.defineProperty(exports, "ReflectionJsonWriter", ({ enumerable: true, get: function () { return reflection_json_writer_1.ReflectionJsonWriter; } }));
-var reflection_contains_message_type_1 = __nccwpck_require__(9946);
-Object.defineProperty(exports, "containsMessageType", ({ enumerable: true, get: function () { return reflection_contains_message_type_1.containsMessageType; } }));
-// Oneof helpers
-var oneof_1 = __nccwpck_require__(8063);
-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__(257);
-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; } }));
+// 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)
-/***/ 9367:
-/***/ ((__unused_webpack_module, exports) => {
+ 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 ">"')
+ }
-"use strict";
+ // If it satisifes the range it is not outside
+ if (satisfies(version, range, options)) {
+ return false
+ }
-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;
+ // 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
-/***/ 9999:
-/***/ ((__unused_webpack_module, exports) => {
+ 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
+ }
+ })
-"use strict";
+ // If the edge version comparator has a operator then our version
+ // isn't outside it
+ if (high.operator === comp || high.operator === ecomp) {
+ return false
+ }
-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";
+ // 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 t;
+ }
+ return true
}
-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.prerelease = prerelease
+function prerelease (version, options) {
+ var parsed = parse(version, options)
+ return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
}
-exports.isJsonObject = isJsonObject;
+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
+ }
-/***/ 4073:
-/***/ ((__unused_webpack_module, exports) => {
+ if (typeof version === 'number') {
+ version = String(version)
+ }
-"use strict";
+ if (typeof version !== 'string') {
+ return null
+ }
-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);
- }
+ 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
}
- return sb.join('');
+ // 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)
}
-exports.lowerCamelCase = lowerCamelCase;
/***/ }),
-/***/ 3785:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 71546:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"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.
+
+var stubs = __nccwpck_require__(33897)
+
+/*
+ * StreamEvents can be used 2 ways:
*
- * Note that this is an experimental feature - it is here to stay, but
- * implementation details may change without notice.
+ * 1:
+ * function MyStream() {
+ * require('stream-events').call(this)
+ * }
+ *
+ * 2:
+ * require('stream-events')(myStream)
*/
-exports.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type");
+function StreamEvents(stream) {
+ stream = stream || this
+ var cfg = {
+ callthrough: true,
+ calls: 1
+ }
-/***/ }),
+ stubs(stream, '_read', cfg, stream.emit.bind(stream, 'reading'))
+ stubs(stream, '_write', cfg, stream.emit.bind(stream, 'writing'))
-/***/ 5106:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ return stream
+}
-"use strict";
+module.exports = StreamEvents
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.MessageType = void 0;
-const message_type_contract_1 = __nccwpck_require__(3785);
-const reflection_info_1 = __nccwpck_require__(7910);
-const reflection_type_check_1 = __nccwpck_require__(5167);
-const reflection_json_reader_1 = __nccwpck_require__(6790);
-const reflection_json_writer_1 = __nccwpck_require__(1094);
-const reflection_binary_reader_1 = __nccwpck_require__(9611);
-const reflection_binary_writer_1 = __nccwpck_require__(6907);
-const reflection_create_1 = __nccwpck_require__(5726);
-const reflection_merge_partial_1 = __nccwpck_require__(8044);
-const json_typings_1 = __nccwpck_require__(9999);
-const json_format_contract_1 = __nccwpck_require__(9367);
-const reflection_equals_1 = __nccwpck_require__(4827);
-const binary_writer_1 = __nccwpck_require__(3957);
-const binary_reader_1 = __nccwpck_require__(2889);
-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;
+
+/***/ }),
+
+/***/ 34633:
+/***/ ((module) => {
+
+module.exports = shift
+
+function shift (stream) {
+ var rs = stream._readableState
+ if (!rs) return null
+ return (rs.objectMode || typeof stream._duplexState === 'number') ? stream.read() : stream.read(getStateLength(rs))
+}
+
+function getStateLength (state) {
+ if (state.buffer.length) {
+ var idx = state.bufferIndex || 0
+ // Since node 6.3.0 state.buffer is a BufferList not an array
+ if (state.buffer.head) {
+ return state.buffer.head.data.length
+ } else if (state.buffer.length - idx > 0 && state.buffer[idx]) {
+ return state.buffer[idx].length
}
+ }
+
+ return state.length
}
-exports.MessageType = MessageType;
/***/ }),
-/***/ 8063:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 80634:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// 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.
-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;
+
+
+/**/
+
+var Buffer = (__nccwpck_require__(93058).Buffer);
+/**/
+
+var isEncoding = Buffer.isEncoding || function (encoding) {
+ encoding = '' + encoding;
+ switch (encoding && encoding.toLowerCase()) {
+ case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
+ return true;
+ default:
+ return false;
+ }
+};
+
+function _normalizeEncoding(enc) {
+ if (!enc) return 'utf8';
+ var retried;
+ while (true) {
+ switch (enc) {
+ case 'utf8':
+ case 'utf-8':
+ return 'utf8';
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return 'utf16le';
+ case 'latin1':
+ case 'binary':
+ return 'latin1';
+ case 'base64':
+ case 'ascii':
+ case 'hex':
+ return enc;
+ default:
+ if (retried) return; // undefined
+ enc = ('' + enc).toLowerCase();
+ retried = true;
}
+ }
+};
+
+// Do not cache `Buffer.isEncoding` when checking encoding names as some
+// modules monkey-patch it to support additional encodings
+function normalizeEncoding(enc) {
+ var nenc = _normalizeEncoding(enc);
+ if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
+ return nenc || enc;
}
-exports.isOneofGroup = isOneofGroup;
-/**
- * Returns the value of the given field in a oneof group.
- */
-function getOneofValue(oneof, kind) {
- return oneof[kind];
+
+// StringDecoder provides an interface for efficiently splitting a series of
+// buffers into a series of JS strings without breaking apart multi-byte
+// characters.
+exports.I = StringDecoder;
+function StringDecoder(encoding) {
+ this.encoding = normalizeEncoding(encoding);
+ var nb;
+ switch (this.encoding) {
+ case 'utf16le':
+ this.text = utf16Text;
+ this.end = utf16End;
+ nb = 4;
+ break;
+ case 'utf8':
+ this.fillLast = utf8FillLast;
+ nb = 4;
+ break;
+ case 'base64':
+ this.text = base64Text;
+ this.end = base64End;
+ nb = 3;
+ break;
+ default:
+ this.write = simpleWrite;
+ this.end = simpleEnd;
+ return;
+ }
+ this.lastNeed = 0;
+ this.lastTotal = 0;
+ this.lastChar = Buffer.allocUnsafe(nb);
}
-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;
+
+StringDecoder.prototype.write = function (buf) {
+ if (buf.length === 0) return '';
+ var r;
+ var i;
+ if (this.lastNeed) {
+ r = this.fillLast(buf);
+ if (r === undefined) return '';
+ i = this.lastNeed;
+ this.lastNeed = 0;
+ } else {
+ i = 0;
+ }
+ if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
+ return r || '';
+};
+
+StringDecoder.prototype.end = utf8End;
+
+// Returns only complete characters in a Buffer
+StringDecoder.prototype.text = utf8Text;
+
+// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
+StringDecoder.prototype.fillLast = function (buf) {
+ if (this.lastNeed <= buf.length) {
+ buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
+ return this.lastChar.toString(this.encoding, 0, this.lastTotal);
+ }
+ buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
+ this.lastNeed -= buf.length;
+};
+
+// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
+// continuation byte. If an invalid byte is detected, -2 is returned.
+function utf8CheckByte(byte) {
+ if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
+ return byte >> 6 === 0x02 ? -1 : -2;
+}
+
+// Checks at most 3 bytes at the end of a Buffer in order to detect an
+// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
+// needed to complete the UTF-8 character (if applicable) are returned.
+function utf8CheckIncomplete(self, buf, i) {
+ var j = buf.length - 1;
+ if (j < i) return 0;
+ var nb = utf8CheckByte(buf[j]);
+ if (nb >= 0) {
+ if (nb > 0) self.lastNeed = nb - 1;
+ return nb;
+ }
+ if (--j < i || nb === -2) return 0;
+ nb = utf8CheckByte(buf[j]);
+ if (nb >= 0) {
+ if (nb > 0) self.lastNeed = nb - 2;
+ return nb;
+ }
+ if (--j < i || nb === -2) return 0;
+ nb = utf8CheckByte(buf[j]);
+ if (nb >= 0) {
+ if (nb > 0) {
+ if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
+ }
+ return nb;
+ }
+ return 0;
+}
+
+// Validates as many continuation bytes for a multi-byte UTF-8 character as
+// needed or are available. If we see a non-continuation byte where we expect
+// one, we "replace" the validated continuation bytes we've seen so far with
+// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
+// behavior. The continuation byte check is included three times in the case
+// where all of the continuation bytes for a character exist in the same buffer.
+// It is also done this way as a slight performance increase instead of using a
+// loop.
+function utf8CheckExtraBytes(self, buf, p) {
+ if ((buf[0] & 0xC0) !== 0x80) {
+ self.lastNeed = 0;
+ return '\ufffd';
+ }
+ if (self.lastNeed > 1 && buf.length > 1) {
+ if ((buf[1] & 0xC0) !== 0x80) {
+ self.lastNeed = 1;
+ return '\ufffd';
+ }
+ if (self.lastNeed > 2 && buf.length > 2) {
+ if ((buf[2] & 0xC0) !== 0x80) {
+ self.lastNeed = 2;
+ return '\ufffd';
+ }
}
+ }
}
-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;
+
+// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
+function utf8FillLast(buf) {
+ var p = this.lastTotal - this.lastNeed;
+ var r = utf8CheckExtraBytes(this, buf, p);
+ if (r !== undefined) return r;
+ if (this.lastNeed <= buf.length) {
+ buf.copy(this.lastChar, p, 0, this.lastNeed);
+ return this.lastChar.toString(this.encoding, 0, this.lastTotal);
+ }
+ buf.copy(this.lastChar, p, 0, buf.length);
+ this.lastNeed -= buf.length;
+}
+
+// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
+// partial character, the character's bytes are buffered until the required
+// number of bytes are available.
+function utf8Text(buf, i) {
+ var total = utf8CheckIncomplete(this, buf, i);
+ if (!this.lastNeed) return buf.toString('utf8', i);
+ this.lastTotal = total;
+ var end = buf.length - (total - this.lastNeed);
+ buf.copy(this.lastChar, 0, end);
+ return buf.toString('utf8', i, end);
+}
+
+// For UTF-8, a replacement character is added when ending on a partial
+// character.
+function utf8End(buf) {
+ var r = buf && buf.length ? this.write(buf) : '';
+ if (this.lastNeed) return r + '\ufffd';
+ return r;
+}
+
+// UTF-16LE typically needs two bytes per character, but even if we have an even
+// number of bytes available, we need to check if we end on a leading/high
+// surrogate. In that case, we need to wait for the next two bytes in order to
+// decode the last character properly.
+function utf16Text(buf, i) {
+ if ((buf.length - i) % 2 === 0) {
+ var r = buf.toString('utf16le', i);
+ if (r) {
+ var c = r.charCodeAt(r.length - 1);
+ if (c >= 0xD800 && c <= 0xDBFF) {
+ this.lastNeed = 2;
+ this.lastTotal = 4;
+ this.lastChar[0] = buf[buf.length - 2];
+ this.lastChar[1] = buf[buf.length - 1];
+ return r.slice(0, -1);
+ }
}
+ return r;
+ }
+ this.lastNeed = 1;
+ this.lastTotal = 2;
+ this.lastChar[0] = buf[buf.length - 1];
+ return buf.toString('utf16le', i, buf.length - 1);
}
-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;
+
+// For UTF-16LE we do not explicitly append special replacement characters if we
+// end on a partial character, we simply let v8 handle that.
+function utf16End(buf) {
+ var r = buf && buf.length ? this.write(buf) : '';
+ if (this.lastNeed) {
+ var end = this.lastTotal - this.lastNeed;
+ return r + this.lastChar.toString('utf16le', 0, end);
+ }
+ return r;
}
-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];
+
+function base64Text(buf, i) {
+ var n = (buf.length - i) % 3;
+ if (n === 0) return buf.toString('base64', i);
+ this.lastNeed = 3 - n;
+ this.lastTotal = 3;
+ if (n === 1) {
+ this.lastChar[0] = buf[buf.length - 1];
+ } else {
+ this.lastChar[0] = buf[buf.length - 2];
+ this.lastChar[1] = buf[buf.length - 1];
+ }
+ return buf.toString('base64', i, buf.length - n);
+}
+
+function base64End(buf) {
+ var r = buf && buf.length ? this.write(buf) : '';
+ if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
+ return r;
+}
+
+// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
+function simpleWrite(buf) {
+ return buf.toString(this.encoding);
}
-exports.getSelectedOneofValue = getSelectedOneofValue;
+function simpleEnd(buf) {
+ return buf && buf.length ? this.write(buf) : '';
+}
/***/ }),
-/***/ 1753:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 56496:
+/***/ ((module) => {
-"use strict";
+const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;
+const numRegex = /^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;
+// const octRegex = /0x[a-z0-9]+/;
+// const binRegex = /0x[a-z0-9]+/;
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.PbLong = exports.PbULong = exports.detectBi = void 0;
-const goog_varint_1 = __nccwpck_require__(3223);
-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");
+
+//polyfill
+if (!Number.parseInt && window.parseInt) {
+ Number.parseInt = window.parseInt;
}
-// 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;
- }
+if (!Number.parseFloat && window.parseFloat) {
+ Number.parseFloat = window.parseFloat;
}
-/**
- * 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);
+
+
+const consider = {
+ hex : true,
+ leadingZeros: true,
+ decimalPoint: "\.",
+ eNotation: true
+ //skipLike: /regex/
+};
+
+function toNumber(str, options = {}){
+ // const options = Object.assign({}, consider);
+ // if(opt.leadingZeros === false){
+ // options.leadingZeros = false;
+ // }else if(opt.hex === false){
+ // options.hex = false;
+ // }
+
+ options = Object.assign({}, consider, options );
+ if(!str || typeof str !== "string" ) return str;
+
+ let trimmedStr = str.trim();
+ // if(trimmedStr === "0.0") return 0;
+ // else if(trimmedStr === "+0.0") return 0;
+ // else if(trimmedStr === "-0.0") return -0;
+
+ if(options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str;
+ else if (options.hex && hexRegex.test(trimmedStr)) {
+ return Number.parseInt(trimmedStr, 16);
+ // } else if (options.parseOct && octRegex.test(str)) {
+ // return Number.parseInt(val, 8);
+ // }else if (options.parseBin && binRegex.test(str)) {
+ // return Number.parseInt(val, 2);
+ }else{
+ //separate negative sign, leading zeros, and rest number
+ const match = numRegex.exec(trimmedStr);
+ if(match){
+ const sign = match[1];
+ const leadingZeros = match[2];
+ let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros
+ //trim ending zeros for floating number
+
+ const eNotation = match[4] || match[6];
+ if(!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str; //-0123
+ else if(!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str; //0123
+ else{//no leading zeros or leading zeros are allowed
+ const num = Number(trimmedStr);
+ const numStr = "" + num;
+ if(numStr.search(/[eE]/) !== -1){ //given number is long and parsed to eNotation
+ if(options.eNotation) return num;
+ else return str;
+ }else if(eNotation){ //given number has enotation
+ if(options.eNotation) return num;
+ else return str;
+ }else if(trimmedStr.indexOf(".") !== -1){ //floating number
+ // const decimalPart = match[5].substr(1);
+ // const intPart = trimmedStr.substr(0,trimmedStr.indexOf("."));
+
+
+ // const p = numStr.indexOf(".");
+ // const givenIntPart = numStr.substr(0,p);
+ // const givenDecPart = numStr.substr(p+1);
+ if(numStr === "0" && (numTrimmedByZeros === "") ) return num; //0.0
+ else if(numStr === numTrimmedByZeros) return num; //0.456. 0.79000
+ else if( sign && numStr === "-"+numTrimmedByZeros) return num;
+ else return str;
+ }
+
+ if(leadingZeros){
+ // if(numTrimmedByZeros === numStr){
+ // if(options.leadingZeros) return num;
+ // else return str;
+ // }else return str;
+ if(numTrimmedByZeros === numStr) return num;
+ else if(sign+numTrimmedByZeros === numStr) return num;
+ else return str;
+ }
+
+ if(trimmedStr === numStr) return num;
+ else if(trimmedStr === sign+numStr) return num;
+ // else{
+ // //number with +/- sign
+ // trimmedStr.test(/[-+][0-9]);
+
+ // }
+ return str;
}
- 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);
+ // else if(!eNotation && trimmedStr && trimmedStr !== Number(trimmedStr) ) return str;
+
+ }else{ //non-numeric string
+ return str;
+ }
}
}
-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.
+ *
+ * @param {string} numStr without leading zeros
+ * @returns
*/
-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);
+function trimZeros(numStr){
+ if(numStr && numStr.indexOf(".") !== -1){//float
+ numStr = numStr.replace(/0+$/, ""); //remove ending zeros
+ if(numStr === ".") numStr = "0";
+ else if(numStr[0] === ".") numStr = "0"+numStr;
+ else if(numStr[numStr.length-1] === ".") numStr = numStr.substr(0,numStr.length-1);
+ return numStr;
}
+ return numStr;
+}
+module.exports = toNumber
+
+
+/***/ }),
+
+/***/ 33897:
+/***/ ((module) => {
+
+"use strict";
+
+
+module.exports = function stubs(obj, method, cfg, stub) {
+ if (!obj || !method || !obj[method])
+ throw new Error('You must provide an object and a key for an existing method')
+
+ if (!stub) {
+ stub = cfg
+ cfg = {}
+ }
+
+ stub = stub || function() {}
+
+ cfg.callthrough = cfg.callthrough || false
+ cfg.calls = cfg.calls || 0
+
+ var norevert = cfg.calls === 0
+
+ var cached = obj[method].bind(obj)
+
+ obj[method] = function() {
+ var args = [].slice.call(arguments)
+ var returnVal
+
+ if (cfg.callthrough)
+ returnVal = cached.apply(obj, args)
+
+ returnVal = stub.apply(obj, args) || returnVal
+
+ if (!norevert && --cfg.calls === 0)
+ obj[method] = cached
+
+ return returnVal
+ }
}
-exports.PbLong = PbLong;
-/**
- * long 0 singleton.
- */
-PbLong.ZERO = new PbLong(0, 0);
/***/ }),
-/***/ 8950:
+/***/ 97745:
/***/ ((__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
+ * @license
+ * Copyright 2020 Google LLC
*
- * Reads UTF8 bytes as a string.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * See [protobufjs / utf8](https://github.com/protobufjs/protobuf.js/blob/9893e35b854621cce64af4bf6be2cff4fb892796/lib/utf8/index.js#L40)
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Copyright (c) 2016, Daniel Wirtz
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*/
-function 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("");
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.TeenyStatistics = exports.TeenyStatisticsWarning = void 0;
+/**
+ * @class TeenyStatisticsWarning
+ * @extends Error
+ * @description While an error, is used for emitting warnings when
+ * meeting certain configured thresholds.
+ * @see process.emitWarning
+ */
+class TeenyStatisticsWarning extends Error {
+ /**
+ * @param {string} message
+ */
+ constructor(message) {
+ super(message);
+ this.threshold = 0;
+ this.type = '';
+ this.value = 0;
+ this.name = this.constructor.name;
+ Error.captureStackTrace(this, this.constructor);
}
- return fromCharCodes(chunk.slice(0, i));
}
-exports.utf8read = utf8read;
-
-
-/***/ }),
-
-/***/ 9611:
-/***/ ((__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__(4816);
-const reflection_info_1 = __nccwpck_require__(7910);
-const reflection_long_convert_1 = __nccwpck_require__(3402);
-const reflection_scalar_default_1 = __nccwpck_require__(9526);
+exports.TeenyStatisticsWarning = TeenyStatisticsWarning;
+TeenyStatisticsWarning.CONCURRENT_REQUESTS = 'ConcurrentRequestsExceededWarning';
/**
- * Reads proto3 messages in binary format using reflection information.
- *
- * https://developers.google.com/protocol-buffers/docs/encoding
+ * @class TeenyStatistics
+ * @description Maintain various statistics internal to teeny-request. Tracking
+ * is not automatic and must be instrumented within teeny-request.
*/
-class ReflectionBinaryReader {
- constructor(info) {
- this.info = info;
+class TeenyStatistics {
+ /**
+ * @param {TeenyStatisticsOptions} [opts]
+ */
+ constructor(opts) {
+ /**
+ * @type {number}
+ * @private
+ * @default 0
+ */
+ this._concurrentRequests = 0;
+ /**
+ * @type {boolean}
+ * @private
+ * @default false
+ */
+ this._didConcurrentRequestWarn = false;
+ this._options = TeenyStatistics._prepareOptions(opts);
}
- 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]));
- }
+ /**
+ * Returns a copy of the current options.
+ * @return {TeenyStatisticsOptions}
+ */
+ getOptions() {
+ return Object.assign({}, this._options);
}
/**
- * 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.
+ * Change configured statistics options. This will not preserve unspecified
+ * options that were previously specified, i.e. this is a reset of options.
+ * @param {TeenyStatisticsOptions} [opts]
+ * @returns {TeenyStatisticsConfig} The previous options.
+ * @see _prepareOptions
*/
- 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;
- }
- }
+ setOptions(opts) {
+ const oldOpts = this._options;
+ this._options = TeenyStatistics._prepareOptions(opts);
+ return oldOpts;
}
/**
- * Read a map field, expecting key field = 1, value field = 2
+ * @readonly
+ * @return {TeenyStatisticsCounters}
*/
- 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;
+ get counters() {
+ return {
+ concurrentRequests: this._concurrentRequests,
+ };
+ }
+ /**
+ * @description Should call this right before making a request.
+ */
+ requestStarting() {
+ this._concurrentRequests++;
+ if (this._options.concurrentRequests > 0 &&
+ this._concurrentRequests >= this._options.concurrentRequests &&
+ !this._didConcurrentRequestWarn) {
+ this._didConcurrentRequestWarn = true;
+ const warning = new TeenyStatisticsWarning('Possible excessive concurrent requests detected. ' +
+ this._concurrentRequests +
+ ' requests in-flight, which exceeds the configured threshold of ' +
+ this._options.concurrentRequests +
+ '. Use the TEENY_REQUEST_WARN_CONCURRENT_REQUESTS environment ' +
+ 'variable or the concurrentRequests option of teeny-request to ' +
+ 'increase or disable (0) this warning.');
+ warning.type = TeenyStatisticsWarning.CONCURRENT_REQUESTS;
+ warning.value = this._concurrentRequests;
+ warning.threshold = this._options.concurrentRequests;
+ process.emitWarning(warning);
}
- 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);
+ /**
+ * @description When using `requestStarting`, call this after the request
+ * has finished.
+ */
+ requestFinished() {
+ // TODO negative?
+ this._concurrentRequests--;
+ }
+ /**
+ * Configuration Precedence:
+ * 1. Dependency inversion via defined option.
+ * 2. Global numeric environment variable.
+ * 3. Built-in default.
+ * This will not preserve unspecified options previously specified.
+ * @param {TeenyStatisticsOptions} [opts]
+ * @returns {TeenyStatisticsOptions}
+ * @private
+ */
+ static _prepareOptions({ concurrentRequests: diConcurrentRequests, } = {}) {
+ let concurrentRequests = this.DEFAULT_WARN_CONCURRENT_REQUESTS;
+ const envConcurrentRequests = Number(process.env.TEENY_REQUEST_WARN_CONCURRENT_REQUESTS);
+ if (diConcurrentRequests !== undefined) {
+ concurrentRequests = diConcurrentRequests;
}
+ else if (!Number.isNaN(envConcurrentRequests)) {
+ concurrentRequests = envConcurrentRequests;
+ }
+ return { concurrentRequests };
}
}
-exports.ReflectionBinaryReader = ReflectionBinaryReader;
-
+exports.TeenyStatistics = TeenyStatistics;
+/**
+ * @description A default threshold representing when to warn about excessive
+ * in-flight/concurrent requests.
+ * @type {number}
+ * @static
+ * @readonly
+ * @default 5000
+ */
+TeenyStatistics.DEFAULT_WARN_CONCURRENT_REQUESTS = 5000;
+//# sourceMappingURL=TeenyStatistics.js.map
/***/ }),
-/***/ 6907:
+/***/ 34003:
/***/ ((__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__(4816);
-const reflection_info_1 = __nccwpck_require__(7910);
-const assert_1 = __nccwpck_require__(8602);
-const pb_long_1 = __nccwpck_require__(1753);
/**
- * Writes proto3 messages in binary format using reflection information.
+ * @license
+ * Copyright 2019 Google LLC
*
- * 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;
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getAgent = exports.pool = void 0;
+const http_1 = __nccwpck_require__(58611);
+const https_1 = __nccwpck_require__(65692);
+// eslint-disable-next-line node/no-deprecated-api
+const url_1 = __nccwpck_require__(87016);
+exports.pool = new Map();
+/**
+ * Determines if a proxy should be considered based on the environment.
+ *
+ * @param uri The request uri
+ * @returns {boolean}
+ */
+function shouldUseProxyForURI(uri) {
+ const noProxyEnv = process.env.NO_PROXY || process.env.no_proxy;
+ if (!noProxyEnv) {
+ return true;
+ }
+ const givenURI = new URL(uri);
+ for (const noProxyRaw of noProxyEnv.split(',')) {
+ const noProxy = noProxyRaw.trim();
+ if (noProxy === givenURI.origin || noProxy === givenURI.hostname) {
+ return false;
+ }
+ else if (noProxy.startsWith('*.') || noProxy.startsWith('.')) {
+ const noProxyWildcard = noProxy.replace(/^\*\./, '.');
+ if (givenURI.hostname.endsWith(noProxyWildcard)) {
+ return false;
+ }
}
- return [t, m, i || d];
}
+ return true;
}
-exports.ReflectionBinaryWriter = ReflectionBinaryWriter;
-
+/**
+ * Returns a custom request Agent if one is found, otherwise returns undefined
+ * which will result in the global http(s) Agent being used.
+ * @private
+ * @param {string} uri The request uri
+ * @param {Options} reqOpts The request options
+ * @returns {HttpAnyAgent|undefined}
+ */
+function getAgent(uri, reqOpts) {
+ const isHttp = uri.startsWith('http://');
+ const proxy = reqOpts.proxy ||
+ process.env.HTTP_PROXY ||
+ process.env.http_proxy ||
+ process.env.HTTPS_PROXY ||
+ process.env.https_proxy;
+ const poolOptions = Object.assign({}, reqOpts.pool);
+ const manuallyProvidedProxy = !!reqOpts.proxy;
+ const shouldUseProxy = manuallyProvidedProxy || shouldUseProxyForURI(uri);
+ if (proxy && shouldUseProxy) {
+ // tslint:disable-next-line variable-name
+ const Agent = isHttp
+ ? __nccwpck_require__(875)
+ : __nccwpck_require__(6518);
+ const proxyOpts = { ...(0, url_1.parse)(proxy), ...poolOptions };
+ return new Agent(proxyOpts);
+ }
+ let key = isHttp ? 'http' : 'https';
+ if (reqOpts.forever) {
+ key += ':forever';
+ if (!exports.pool.has(key)) {
+ // tslint:disable-next-line variable-name
+ const Agent = isHttp ? http_1.Agent : https_1.Agent;
+ exports.pool.set(key, new Agent({ ...poolOptions, keepAlive: true }));
+ }
+ }
+ return exports.pool.get(key);
+}
+exports.getAgent = getAgent;
+//# sourceMappingURL=agents.js.map
/***/ }),
-/***/ 9946:
+/***/ 80321:
/***/ ((__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__(3785);
/**
- * Check if the provided object is a proto message.
+ * @license
+ * Copyright 2018 Google LLC
*
- * Note that this is an experimental feature - it is here to stay, but
- * implementation details may change without notice.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*/
-function containsMessageType(msg) {
- return msg[message_type_contract_1.MESSAGE_TYPE] != null;
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.teenyRequest = exports.RequestError = void 0;
+const node_fetch_1 = __nccwpck_require__(26705);
+const stream_1 = __nccwpck_require__(2203);
+const uuid = __nccwpck_require__(58993);
+const agents_1 = __nccwpck_require__(34003);
+const TeenyStatistics_1 = __nccwpck_require__(97745);
+// eslint-disable-next-line @typescript-eslint/no-var-requires
+const streamEvents = __nccwpck_require__(71546);
+class RequestError extends Error {
+}
+exports.RequestError = RequestError;
+/**
+ * Convert options from Request to Fetch format
+ * @private
+ * @param reqOpts Request options
+ */
+function requestToFetchOptions(reqOpts) {
+ const options = {
+ method: reqOpts.method || 'GET',
+ ...(reqOpts.timeout && { timeout: reqOpts.timeout }),
+ ...(typeof reqOpts.gzip === 'boolean' && { compress: reqOpts.gzip }),
+ };
+ if (typeof reqOpts.json === 'object') {
+ // Add Content-type: application/json header
+ reqOpts.headers = reqOpts.headers || {};
+ reqOpts.headers['Content-Type'] = 'application/json';
+ // Set body to JSON representation of value
+ options.body = JSON.stringify(reqOpts.json);
+ }
+ else {
+ if (Buffer.isBuffer(reqOpts.body)) {
+ options.body = reqOpts.body;
+ }
+ else if (typeof reqOpts.body !== 'string') {
+ options.body = JSON.stringify(reqOpts.body);
+ }
+ else {
+ options.body = reqOpts.body;
+ }
+ }
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ options.headers = reqOpts.headers;
+ let uri = (reqOpts.uri ||
+ reqOpts.url);
+ if (!uri) {
+ throw new Error('Missing uri or url in reqOpts.');
+ }
+ if (reqOpts.useQuerystring === true || typeof reqOpts.qs === 'object') {
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const qs = __nccwpck_require__(83480);
+ const params = qs.stringify(reqOpts.qs);
+ uri = uri + '?' + params;
+ }
+ options.agent = (0, agents_1.getAgent)(uri, reqOpts);
+ return { uri, options };
+}
+/**
+ * Convert a response from `fetch` to `request` format.
+ * @private
+ * @param opts The `request` options used to create the request.
+ * @param res The Fetch response
+ * @returns A `request` response object
+ */
+function fetchToRequestResponse(opts, res) {
+ const request = {};
+ request.agent = opts.agent || false;
+ request.headers = (opts.headers || {});
+ request.href = res.url;
+ // headers need to be converted from a map to an obj
+ const resHeaders = {};
+ res.headers.forEach((value, key) => (resHeaders[key] = value));
+ const response = Object.assign(res.body, {
+ statusCode: res.status,
+ statusMessage: res.statusText,
+ request,
+ body: res.body,
+ headers: resHeaders,
+ toJSON: () => ({ headers: resHeaders }),
+ });
+ return response;
}
-exports.containsMessageType = containsMessageType;
+/**
+ * Create POST body from two parts as multipart/related content-type
+ * @private
+ * @param boundary
+ * @param multipart
+ */
+function createMultipartStream(boundary, multipart) {
+ const finale = `--${boundary}--`;
+ const stream = new stream_1.PassThrough();
+ for (const part of multipart) {
+ const preamble = `--${boundary}\r\nContent-Type: ${part['Content-Type']}\r\n\r\n`;
+ stream.write(preamble);
+ if (typeof part.body === 'string') {
+ stream.write(part.body);
+ stream.write('\r\n');
+ }
+ else {
+ part.body.pipe(stream, { end: false });
+ part.body.on('end', () => {
+ stream.write('\r\n');
+ stream.write(finale);
+ stream.end();
+ });
+ }
+ }
+ return stream;
+}
+function teenyRequest(reqOpts, callback) {
+ const { uri, options } = requestToFetchOptions(reqOpts);
+ const multipart = reqOpts.multipart;
+ if (reqOpts.multipart && multipart.length === 2) {
+ if (!callback) {
+ // TODO: add support for multipart uploads through streaming
+ throw new Error('Multipart without callback is not implemented.');
+ }
+ const boundary = uuid.v4();
+ options.headers['Content-Type'] = `multipart/related; boundary=${boundary}`;
+ options.body = createMultipartStream(boundary, multipart);
+ // Multipart upload
+ teenyRequest.stats.requestStarting();
+ (0, node_fetch_1.default)(uri, options).then(res => {
+ teenyRequest.stats.requestFinished();
+ const header = res.headers.get('content-type');
+ const response = fetchToRequestResponse(options, res);
+ const body = response.body;
+ if (header === 'application/json' ||
+ header === 'application/json; charset=utf-8') {
+ res.json().then(json => {
+ response.body = json;
+ callback(null, response, json);
+ }, (err) => {
+ callback(err, response, body);
+ });
+ return;
+ }
+ res.text().then(text => {
+ response.body = text;
+ callback(null, response, text);
+ }, err => {
+ callback(err, response, body);
+ });
+ }, err => {
+ teenyRequest.stats.requestFinished();
+ callback(err, null, null);
+ });
+ return;
+ }
+ if (callback === undefined) {
+ // Stream mode
+ const requestStream = streamEvents(new stream_1.PassThrough());
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ let responseStream;
+ requestStream.once('reading', () => {
+ if (responseStream) {
+ (0, stream_1.pipeline)(responseStream, requestStream, () => { });
+ }
+ else {
+ requestStream.once('response', () => {
+ (0, stream_1.pipeline)(responseStream, requestStream, () => { });
+ });
+ }
+ });
+ options.compress = false;
+ teenyRequest.stats.requestStarting();
+ (0, node_fetch_1.default)(uri, options).then(res => {
+ teenyRequest.stats.requestFinished();
+ responseStream = res.body;
+ responseStream.on('error', (err) => {
+ requestStream.emit('error', err);
+ });
+ const response = fetchToRequestResponse(options, res);
+ requestStream.emit('response', response);
+ }, err => {
+ teenyRequest.stats.requestFinished();
+ requestStream.emit('error', err);
+ });
+ // fetch doesn't supply the raw HTTP stream, instead it
+ // returns a PassThrough piped from the HTTP response
+ // stream.
+ return requestStream;
+ }
+ // GET or POST with callback
+ teenyRequest.stats.requestStarting();
+ (0, node_fetch_1.default)(uri, options).then(res => {
+ teenyRequest.stats.requestFinished();
+ const header = res.headers.get('content-type');
+ const response = fetchToRequestResponse(options, res);
+ const body = response.body;
+ if (header === 'application/json' ||
+ header === 'application/json; charset=utf-8') {
+ if (response.statusCode === 204) {
+ // Probably a DELETE
+ callback(null, response, body);
+ return;
+ }
+ res.json().then(json => {
+ response.body = json;
+ callback(null, response, json);
+ }, err => {
+ callback(err, response, body);
+ });
+ return;
+ }
+ res.text().then(text => {
+ const response = fetchToRequestResponse(options, res);
+ response.body = text;
+ callback(null, response, text);
+ }, err => {
+ callback(err, response, body);
+ });
+ }, err => {
+ teenyRequest.stats.requestFinished();
+ callback(err, null, null);
+ });
+ return;
+}
+exports.teenyRequest = teenyRequest;
+teenyRequest.defaults = (defaults) => {
+ return (reqOpts, callback) => {
+ const opts = { ...defaults, ...reqOpts };
+ if (callback === undefined) {
+ return teenyRequest(opts);
+ }
+ teenyRequest(opts, callback);
+ };
+};
+/**
+ * Single instance of an interface for keeping track of things.
+ */
+teenyRequest.stats = new TeenyStatistics_1.TeenyStatistics();
+teenyRequest.resetStats = () => {
+ teenyRequest.stats = new TeenyStatistics_1.TeenyStatistics(teenyRequest.stats.getOptions());
+};
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 77954:
+/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) {
+
+"use strict";
+
+var __importDefault = (this && this.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+const events_1 = __nccwpck_require__(24434);
+const debug_1 = __importDefault(__nccwpck_require__(2830));
+const promisify_1 = __importDefault(__nccwpck_require__(44446));
+const debug = debug_1.default('agent-base');
+function isAgent(v) {
+ return Boolean(v) && typeof v.addRequest === 'function';
+}
+function isSecureEndpoint() {
+ 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);
+}
+function createAgent(callback, opts) {
+ return new createAgent.Agent(callback, opts);
+}
+(function (createAgent) {
+ /**
+ * Base `http.Agent` implementation.
+ * No pooling/keep-alive is implemented by default.
+ *
+ * @param {Function} callback
+ * @api public
+ */
+ class Agent extends events_1.EventEmitter {
+ constructor(callback, _opts) {
+ super();
+ let opts = _opts;
+ if (typeof callback === 'function') {
+ this.callback = callback;
+ }
+ else if (callback) {
+ opts = callback;
+ }
+ // Timeout for the socket to be returned from the callback
+ this.timeout = null;
+ if (opts && typeof opts.timeout === 'number') {
+ this.timeout = opts.timeout;
+ }
+ // These aren't actually used by `agent-base`, but are required
+ // for the TypeScript definition files in `@types/node` :/
+ this.maxFreeSockets = 1;
+ this.maxSockets = 1;
+ this.maxTotalSockets = Infinity;
+ this.sockets = {};
+ this.freeSockets = {};
+ this.requests = {};
+ this.options = {};
+ }
+ get defaultPort() {
+ if (typeof this.explicitDefaultPort === 'number') {
+ return this.explicitDefaultPort;
+ }
+ return isSecureEndpoint() ? 443 : 80;
+ }
+ set defaultPort(v) {
+ this.explicitDefaultPort = v;
+ }
+ get protocol() {
+ if (typeof this.explicitProtocol === 'string') {
+ return this.explicitProtocol;
+ }
+ return isSecureEndpoint() ? 'https:' : 'http:';
+ }
+ set protocol(v) {
+ this.explicitProtocol = v;
+ }
+ callback(req, opts, fn) {
+ throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`');
+ }
+ /**
+ * Called by node-core's "_http_client.js" module when creating
+ * a new HTTP request with this Agent instance.
+ *
+ * @api public
+ */
+ addRequest(req, _opts) {
+ const opts = Object.assign({}, _opts);
+ if (typeof opts.secureEndpoint !== 'boolean') {
+ opts.secureEndpoint = isSecureEndpoint();
+ }
+ if (opts.host == null) {
+ opts.host = 'localhost';
+ }
+ if (opts.port == null) {
+ opts.port = opts.secureEndpoint ? 443 : 80;
+ }
+ if (opts.protocol == null) {
+ opts.protocol = opts.secureEndpoint ? 'https:' : 'http:';
+ }
+ if (opts.host && opts.path) {
+ // If both a `host` and `path` are specified then it's most
+ // likely the result of a `url.parse()` call... we need to
+ // remove the `path` portion so that `net.connect()` doesn't
+ // attempt to open that as a unix socket file.
+ delete opts.path;
+ }
+ delete opts.agent;
+ delete opts.hostname;
+ delete opts._defaultAgent;
+ delete opts.defaultPort;
+ delete opts.createConnection;
+ // Hint to use "Connection: close"
+ // XXX: non-documented `http` module API :(
+ req._last = true;
+ req.shouldKeepAlive = false;
+ let timedOut = false;
+ let timeoutId = null;
+ const timeoutMs = opts.timeout || this.timeout;
+ const onerror = (err) => {
+ if (req._hadError)
+ return;
+ req.emit('error', err);
+ // For Safety. Some additional errors might fire later on
+ // and we need to make sure we don't double-fire the error event.
+ req._hadError = true;
+ };
+ const ontimeout = () => {
+ timeoutId = null;
+ timedOut = true;
+ const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`);
+ err.code = 'ETIMEOUT';
+ onerror(err);
+ };
+ const callbackError = (err) => {
+ if (timedOut)
+ return;
+ if (timeoutId !== null) {
+ clearTimeout(timeoutId);
+ timeoutId = null;
+ }
+ onerror(err);
+ };
+ const onsocket = (socket) => {
+ if (timedOut)
+ return;
+ if (timeoutId != null) {
+ clearTimeout(timeoutId);
+ timeoutId = null;
+ }
+ if (isAgent(socket)) {
+ // `socket` is actually an `http.Agent` instance, so
+ // relinquish responsibility for this `req` to the Agent
+ // from here on
+ debug('Callback returned another Agent instance %o', socket.constructor.name);
+ socket.addRequest(req, opts);
+ return;
+ }
+ if (socket) {
+ socket.once('free', () => {
+ this.freeSocket(socket, opts);
+ });
+ req.onSocket(socket);
+ return;
+ }
+ const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``);
+ onerror(err);
+ };
+ if (typeof this.callback !== 'function') {
+ onerror(new Error('`callback` is not defined'));
+ return;
+ }
+ if (!this.promisifiedCallback) {
+ if (this.callback.length >= 3) {
+ debug('Converting legacy callback function to promise');
+ this.promisifiedCallback = promisify_1.default(this.callback);
+ }
+ else {
+ this.promisifiedCallback = this.callback;
+ }
+ }
+ if (typeof timeoutMs === 'number' && timeoutMs > 0) {
+ timeoutId = setTimeout(ontimeout, timeoutMs);
+ }
+ if ('port' in opts && typeof opts.port !== 'number') {
+ opts.port = Number(opts.port);
+ }
+ try {
+ debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`);
+ Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError);
+ }
+ catch (err) {
+ Promise.reject(err).catch(callbackError);
+ }
+ }
+ freeSocket(socket, opts) {
+ debug('Freeing socket %o %o', socket.constructor.name, opts);
+ socket.destroy();
+ }
+ destroy() {
+ debug('Destroying agent %o', this.constructor.name);
+ }
+ }
+ createAgent.Agent = Agent;
+ // So that `instanceof` works correctly
+ createAgent.prototype = createAgent.Agent.prototype;
+})(createAgent || (createAgent = {}));
+module.exports = createAgent;
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 44446:
+/***/ ((__unused_webpack_module, exports) => {
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+function promisify(fn) {
+ return function (req, opts) {
+ return new Promise((resolve, reject) => {
+ fn.call(this, req, opts, (err, rtn) => {
+ if (err) {
+ reject(err);
+ }
+ else {
+ resolve(rtn);
+ }
+ });
+ });
+ };
+}
+exports["default"] = promisify;
+//# sourceMappingURL=promisify.js.map
/***/ }),
-/***/ 5726:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 23034:
+/***/ (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());
+ });
+};
+var __importDefault = (this && this.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.reflectionCreate = void 0;
-const reflection_scalar_default_1 = __nccwpck_require__(9526);
-const message_type_contract_1 = __nccwpck_require__(3785);
+const net_1 = __importDefault(__nccwpck_require__(69278));
+const tls_1 = __importDefault(__nccwpck_require__(64756));
+const url_1 = __importDefault(__nccwpck_require__(87016));
+const debug_1 = __importDefault(__nccwpck_require__(2830));
+const once_1 = __importDefault(__nccwpck_require__(48662));
+const agent_base_1 = __nccwpck_require__(77954);
+const debug = (0, debug_1.default)('http-proxy-agent');
+function isHTTPS(protocol) {
+ return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false;
+}
/**
- * Creates an instance of the generic message, using the field
- * information.
+ * The `HttpProxyAgent` implements an HTTP Agent subclass that connects
+ * to the specified "HTTP proxy server" in order to proxy HTTP requests.
+ *
+ * @api public
*/
-function reflectionCreate(type) {
+class HttpProxyAgent extends agent_base_1.Agent {
+ constructor(_opts) {
+ let opts;
+ if (typeof _opts === 'string') {
+ opts = url_1.default.parse(_opts);
+ }
+ else {
+ opts = _opts;
+ }
+ if (!opts) {
+ throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!');
+ }
+ debug('Creating new HttpProxyAgent instance: %o', opts);
+ super(opts);
+ const proxy = Object.assign({}, opts);
+ // If `true`, then connect to the proxy server over TLS.
+ // Defaults to `false`.
+ this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol);
+ // Prefer `hostname` over `host`, and set the `port` if needed.
+ proxy.host = proxy.hostname || proxy.host;
+ if (typeof proxy.port === 'string') {
+ proxy.port = parseInt(proxy.port, 10);
+ }
+ if (!proxy.port && proxy.host) {
+ proxy.port = this.secureProxy ? 443 : 80;
+ }
+ if (proxy.host && proxy.path) {
+ // If both a `host` and `path` are specified then it's most likely
+ // the result of a `url.parse()` call... we need to remove the
+ // `path` portion so that `net.connect()` doesn't attempt to open
+ // that as a Unix socket file.
+ delete proxy.path;
+ delete proxy.pathname;
+ }
+ this.proxy = proxy;
+ }
/**
- * 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.
+ * Called when the node-core HTTP client library is creating a
+ * new HTTP request.
+ *
+ * @api protected
*/
- 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;
+ callback(req, opts) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const { proxy, secureProxy } = this;
+ const parsed = url_1.default.parse(req.path);
+ if (!parsed.protocol) {
+ parsed.protocol = 'http:';
+ }
+ if (!parsed.hostname) {
+ parsed.hostname = opts.hostname || opts.host || null;
+ }
+ if (parsed.port == null && typeof opts.port) {
+ parsed.port = String(opts.port);
+ }
+ if (parsed.port === '80') {
+ // if port is 80, then we can remove the port so that the
+ // ":80" portion is not on the produced URL
+ parsed.port = '';
+ }
+ // Change the `http.ClientRequest` instance's "path" field
+ // to the absolute path of the URL that will be requested.
+ req.path = url_1.default.format(parsed);
+ // Inject the `Proxy-Authorization` header if necessary.
+ if (proxy.auth) {
+ req.setHeader('Proxy-Authorization', `Basic ${Buffer.from(proxy.auth).toString('base64')}`);
+ }
+ // Create a socket connection to the proxy server.
+ let socket;
+ if (secureProxy) {
+ debug('Creating `tls.Socket`: %o', proxy);
+ socket = tls_1.default.connect(proxy);
+ }
+ else {
+ debug('Creating `net.Socket`: %o', proxy);
+ socket = net_1.default.connect(proxy);
+ }
+ // At this point, the http ClientRequest's internal `_header` field
+ // might have already been set. If this is the case then we'll need
+ // to re-generate the string since we just changed the `req.path`.
+ if (req._header) {
+ let first;
+ let endOfHeaders;
+ debug('Regenerating stored HTTP header string for request');
+ req._header = null;
+ req._implicitHeader();
+ if (req.output && req.output.length > 0) {
+ // Node < 12
+ debug('Patching connection write() output buffer with updated header');
+ first = req.output[0];
+ endOfHeaders = first.indexOf('\r\n\r\n') + 4;
+ req.output[0] = req._header + first.substring(endOfHeaders);
+ debug('Output buffer: %o', req.output);
+ }
+ else if (req.outputData && req.outputData.length > 0) {
+ // Node >= 12
+ debug('Patching connection write() output buffer with updated header');
+ first = req.outputData[0].data;
+ endOfHeaders = first.indexOf('\r\n\r\n') + 4;
+ req.outputData[0].data =
+ req._header + first.substring(endOfHeaders);
+ debug('Output buffer: %o', req.outputData[0].data);
+ }
}
+ // Wait for the socket's `connect` event, so that this `callback()`
+ // function throws instead of the `http` request machinery. This is
+ // important for i.e. `PacProxyAgent` which determines a failed proxy
+ // connection via the `callback()` function throwing.
+ yield (0, once_1.default)(socket, 'connect');
+ return socket;
+ });
}
- return msg;
}
-exports.reflectionCreate = reflectionCreate;
+exports["default"] = HttpProxyAgent;
+//# sourceMappingURL=agent.js.map
+
+/***/ }),
+/***/ 875:
+/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) {
+
+"use strict";
+
+var __importDefault = (this && this.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+const agent_1 = __importDefault(__nccwpck_require__(23034));
+function createHttpProxyAgent(opts) {
+ return new agent_1.default(opts);
+}
+(function (createHttpProxyAgent) {
+ createHttpProxyAgent.HttpProxyAgent = agent_1.default;
+ createHttpProxyAgent.prototype = agent_1.default.prototype;
+})(createHttpProxyAgent || (createHttpProxyAgent = {}));
+module.exports = createHttpProxyAgent;
+//# sourceMappingURL=index.js.map
/***/ }),
-/***/ 4827:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 15299:
+/***/ (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());
+ });
+};
+var __importDefault = (this && this.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.reflectionEquals = void 0;
-const reflection_info_1 = __nccwpck_require__(7910);
+const net_1 = __importDefault(__nccwpck_require__(69278));
+const tls_1 = __importDefault(__nccwpck_require__(64756));
+const url_1 = __importDefault(__nccwpck_require__(87016));
+const assert_1 = __importDefault(__nccwpck_require__(42613));
+const debug_1 = __importDefault(__nccwpck_require__(2830));
+const agent_base_1 = __nccwpck_require__(77954);
+const parse_proxy_response_1 = __importDefault(__nccwpck_require__(27742));
+const debug = debug_1.default('https-proxy-agent:agent');
/**
- * 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`.
+ * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to
+ * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests.
+ *
+ * Outgoing HTTP requests are first tunneled through the proxy server using the
+ * `CONNECT` HTTP request method to establish a connection to the proxy server,
+ * and then the proxy server connects to the destination target and issues the
+ * HTTP request from the proxy server.
+ *
+ * `https:` requests have their socket connection upgraded to TLS once
+ * the connection to the proxy server has been established.
+ *
+ * @api public
*/
-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;
+class HttpsProxyAgent extends agent_base_1.Agent {
+ constructor(_opts) {
+ let opts;
+ if (typeof _opts === 'string') {
+ opts = url_1.default.parse(_opts);
+ }
+ else {
+ opts = _opts;
+ }
+ if (!opts) {
+ throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!');
}
+ debug('creating new HttpsProxyAgent instance: %o', opts);
+ super(opts);
+ const proxy = Object.assign({}, opts);
+ // If `true`, then connect to the proxy server over TLS.
+ // Defaults to `false`.
+ this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol);
+ // Prefer `hostname` over `host`, and set the `port` if needed.
+ proxy.host = proxy.hostname || proxy.host;
+ if (typeof proxy.port === 'string') {
+ proxy.port = parseInt(proxy.port, 10);
+ }
+ if (!proxy.port && proxy.host) {
+ proxy.port = this.secureProxy ? 443 : 80;
+ }
+ // ALPN is supported by Node.js >= v5.
+ // attempt to negotiate http/1.1 for proxy servers that support http/2
+ if (this.secureProxy && !('ALPNProtocols' in proxy)) {
+ proxy.ALPNProtocols = ['http 1.1'];
+ }
+ if (proxy.host && proxy.path) {
+ // If both a `host` and `path` are specified then it's most likely
+ // the result of a `url.parse()` call... we need to remove the
+ // `path` portion so that `net.connect()` doesn't attempt to open
+ // that as a Unix socket file.
+ delete proxy.path;
+ delete proxy.pathname;
+ }
+ this.proxy = proxy;
+ }
+ /**
+ * Called when the node-core HTTP client library is creating a
+ * new HTTP request.
+ *
+ * @api protected
+ */
+ callback(req, opts) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const { proxy, secureProxy } = this;
+ // Create a socket connection to the proxy server.
+ let socket;
+ if (secureProxy) {
+ debug('Creating `tls.Socket`: %o', proxy);
+ socket = tls_1.default.connect(proxy);
+ }
+ else {
+ debug('Creating `net.Socket`: %o', proxy);
+ socket = net_1.default.connect(proxy);
+ }
+ const headers = Object.assign({}, proxy.headers);
+ const hostname = `${opts.host}:${opts.port}`;
+ let payload = `CONNECT ${hostname} HTTP/1.1\r\n`;
+ // Inject the `Proxy-Authorization` header if necessary.
+ if (proxy.auth) {
+ headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`;
+ }
+ // The `Host` header should only include the port
+ // number when it is not the default port.
+ let { host, port, secureEndpoint } = opts;
+ if (!isDefaultPort(port, secureEndpoint)) {
+ host += `:${port}`;
+ }
+ headers.Host = host;
+ headers.Connection = 'close';
+ for (const name of Object.keys(headers)) {
+ payload += `${name}: ${headers[name]}\r\n`;
+ }
+ const proxyResponsePromise = parse_proxy_response_1.default(socket);
+ socket.write(`${payload}\r\n`);
+ const { statusCode, buffered } = yield proxyResponsePromise;
+ if (statusCode === 200) {
+ req.once('socket', resume);
+ if (opts.secureEndpoint) {
+ // The proxy is connecting to a TLS server, so upgrade
+ // this socket connection to a TLS connection.
+ debug('Upgrading socket connection to TLS');
+ const servername = opts.servername || opts.host;
+ return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket,
+ servername }));
+ }
+ return socket;
+ }
+ // Some other status code that's not 200... need to re-play the HTTP
+ // header "data" events onto the socket once the HTTP machinery is
+ // attached so that the node core `http` can parse and handle the
+ // error status code.
+ // Close the original socket, and a new "fake" socket is returned
+ // instead, so that the proxy doesn't get the HTTP request
+ // written to it (which may contain `Authorization` headers or other
+ // sensitive data).
+ //
+ // See: https://hackerone.com/reports/541502
+ socket.destroy();
+ const fakeSocket = new net_1.default.Socket({ writable: false });
+ fakeSocket.readable = true;
+ // Need to wait for the "socket" event to re-play the "data" events.
+ req.once('socket', (s) => {
+ debug('replaying proxy buffer for failed request');
+ assert_1.default(s.listenerCount('data') > 0);
+ // Replay the "buffered" Buffer onto the fake `socket`, since at
+ // this point the HTTP module machinery has been hooked up for
+ // the user.
+ s.push(buffered);
+ s.push(null);
+ });
+ return fakeSocket;
+ });
}
- 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;
+exports["default"] = HttpsProxyAgent;
+function resume(socket) {
+ socket.resume();
}
-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 isDefaultPort(port, secure) {
+ return Boolean((!secure && port === 80) || (secure && port === 443));
}
-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;
+function isHTTPS(protocol) {
+ return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false;
+}
+function omit(obj, ...keys) {
+ const ret = {};
+ let key;
+ for (key in obj) {
+ if (!keys.includes(key)) {
+ ret[key] = obj[key];
+ }
+ }
+ return ret;
+}
+//# sourceMappingURL=agent.js.map
+
+/***/ }),
+
+/***/ 6518:
+/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) {
+
+"use strict";
+
+var __importDefault = (this && this.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+const agent_1 = __importDefault(__nccwpck_require__(15299));
+function createHttpsProxyAgent(opts) {
+ return new agent_1.default(opts);
+}
+(function (createHttpsProxyAgent) {
+ createHttpsProxyAgent.HttpsProxyAgent = agent_1.default;
+ createHttpsProxyAgent.prototype = agent_1.default.prototype;
+})(createHttpsProxyAgent || (createHttpsProxyAgent = {}));
+module.exports = createHttpsProxyAgent;
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 27742:
+/***/ (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 }));
+const debug_1 = __importDefault(__nccwpck_require__(2830));
+const debug = debug_1.default('https-proxy-agent:parse-proxy-response');
+function parseProxyResponse(socket) {
+ return new Promise((resolve, reject) => {
+ // we need to buffer any HTTP traffic that happens with the proxy before we get
+ // the CONNECT response, so that if the response is anything other than an "200"
+ // response code, then we can re-play the "data" events on the socket once the
+ // HTTP parser is hooked up...
+ let buffersLength = 0;
+ const buffers = [];
+ function read() {
+ const b = socket.read();
+ if (b)
+ ondata(b);
+ else
+ socket.once('readable', read);
+ }
+ function cleanup() {
+ socket.removeListener('end', onend);
+ socket.removeListener('error', onerror);
+ socket.removeListener('close', onclose);
+ socket.removeListener('readable', read);
+ }
+ function onclose(err) {
+ debug('onclose had error %o', err);
+ }
+ function onend() {
+ debug('onend');
+ }
+ function onerror(err) {
+ cleanup();
+ debug('onerror %o', err);
+ reject(err);
+ }
+ function ondata(b) {
+ buffers.push(b);
+ buffersLength += b.length;
+ const buffered = Buffer.concat(buffers, buffersLength);
+ const endOfHeaders = buffered.indexOf('\r\n\r\n');
+ if (endOfHeaders === -1) {
+ // keep buffering
+ debug('have not received end of HTTP headers yet...');
+ read();
+ return;
+ }
+ const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n'));
+ const statusCode = +firstLine.split(' ')[1];
+ debug('got proxy server response: %o', firstLine);
+ resolve({
+ statusCode,
+ buffered
+ });
+ }
+ socket.on('error', onerror);
+ socket.on('close', onclose);
+ socket.on('end', onend);
+ read();
+ });
+}
+exports["default"] = parseProxyResponse;
+//# sourceMappingURL=parse-proxy-response.js.map
+
+/***/ }),
+
+/***/ 58993:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+Object.defineProperty(exports, "NIL", ({
+ enumerable: true,
+ get: function () {
+ return _nil.default;
+ }
+}));
+Object.defineProperty(exports, "parse", ({
+ enumerable: true,
+ get: function () {
+ return _parse.default;
+ }
+}));
+Object.defineProperty(exports, "stringify", ({
+ enumerable: true,
+ get: function () {
+ return _stringify.default;
+ }
+}));
+Object.defineProperty(exports, "v1", ({
+ enumerable: true,
+ get: function () {
+ return _v.default;
+ }
+}));
+Object.defineProperty(exports, "v3", ({
+ enumerable: true,
+ get: function () {
+ return _v2.default;
+ }
+}));
+Object.defineProperty(exports, "v4", ({
+ enumerable: true,
+ get: function () {
+ return _v3.default;
+ }
+}));
+Object.defineProperty(exports, "v5", ({
+ enumerable: true,
+ get: function () {
+ return _v4.default;
+ }
+}));
+Object.defineProperty(exports, "validate", ({
+ enumerable: true,
+ get: function () {
+ return _validate.default;
+ }
+}));
+Object.defineProperty(exports, "version", ({
+ enumerable: true,
+ get: function () {
+ return _version.default;
+ }
+}));
+
+var _v = _interopRequireDefault(__nccwpck_require__(64684));
+
+var _v2 = _interopRequireDefault(__nccwpck_require__(53142));
+
+var _v3 = _interopRequireDefault(__nccwpck_require__(69655));
+
+var _v4 = _interopRequireDefault(__nccwpck_require__(70880));
+
+var _nil = _interopRequireDefault(__nccwpck_require__(40194));
+
+var _version = _interopRequireDefault(__nccwpck_require__(66257));
+
+var _validate = _interopRequireDefault(__nccwpck_require__(61579));
+
+var _stringify = _interopRequireDefault(__nccwpck_require__(71400));
+
+var _parse = _interopRequireDefault(__nccwpck_require__(7814));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+/***/ }),
+
+/***/ 88061:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _crypto = _interopRequireDefault(__nccwpck_require__(76982));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function md5(bytes) {
+ if (Array.isArray(bytes)) {
+ bytes = Buffer.from(bytes);
+ } else if (typeof bytes === 'string') {
+ bytes = Buffer.from(bytes, 'utf8');
+ }
+
+ return _crypto.default.createHash('md5').update(bytes).digest();
}
+var _default = md5;
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 7966:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _crypto = _interopRequireDefault(__nccwpck_require__(76982));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+var _default = {
+ randomUUID: _crypto.default.randomUUID
+};
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 40194:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+var _default = '00000000-0000-0000-0000-000000000000';
+exports["default"] = _default;
/***/ }),
-/***/ 7910:
+/***/ 7814:
/***/ ((__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;
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _validate = _interopRequireDefault(__nccwpck_require__(61579));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function parse(uuid) {
+ if (!(0, _validate.default)(uuid)) {
+ throw TypeError('Invalid UUID');
+ }
+
+ let v;
+ const arr = new Uint8Array(16); // Parse ########-....-....-....-............
+
+ arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
+ arr[1] = v >>> 16 & 0xff;
+ arr[2] = v >>> 8 & 0xff;
+ arr[3] = v & 0xff; // Parse ........-####-....-....-............
+
+ arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
+ arr[5] = v & 0xff; // Parse ........-....-####-....-............
+
+ arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
+ arr[7] = v & 0xff; // Parse ........-....-....-####-............
+
+ arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
+ arr[9] = v & 0xff; // Parse ........-....-....-....-############
+ // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
+
+ arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
+ arr[11] = v / 0x100000000 & 0xff;
+ arr[12] = v >>> 24 & 0xff;
+ arr[13] = v >>> 16 & 0xff;
+ arr[14] = v >>> 8 & 0xff;
+ arr[15] = v & 0xff;
+ return arr;
}
-exports.readMessageOption = readMessageOption;
+var _default = parse;
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 1118:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
+exports["default"] = _default;
/***/ }),
-/***/ 6790:
+/***/ 88540:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ReflectionJsonReader = void 0;
-const json_typings_1 = __nccwpck_require__(9999);
-const base64_1 = __nccwpck_require__(6335);
-const reflection_info_1 = __nccwpck_require__(7910);
-const pb_long_1 = __nccwpck_require__(1753);
-const assert_1 = __nccwpck_require__(8602);
-const reflection_long_convert_1 = __nccwpck_require__(3402);
-/**
- * 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":
- let val = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields);
- if (val === false)
- continue;
- target[localName] = val;
- break;
- case "scalar":
- 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);
- }
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = rng;
+
+var _crypto = _interopRequireDefault(__nccwpck_require__(76982));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate
+
+let poolPtr = rnds8Pool.length;
+
+function rng() {
+ if (poolPtr > rnds8Pool.length - 16) {
+ _crypto.default.randomFillSync(rnds8Pool);
+
+ poolPtr = 0;
+ }
+
+ return rnds8Pool.slice(poolPtr, poolPtr += 16);
+}
+
+/***/ }),
+
+/***/ 11352:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _crypto = _interopRequireDefault(__nccwpck_require__(76982));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function sha1(bytes) {
+ if (Array.isArray(bytes)) {
+ bytes = Buffer.from(bytes);
+ } else if (typeof bytes === 'string') {
+ bytes = Buffer.from(bytes, 'utf8');
+ }
+
+ return _crypto.default.createHash('sha1').update(bytes).digest();
}
-exports.ReflectionJsonReader = ReflectionJsonReader;
+var _default = sha1;
+exports["default"] = _default;
/***/ }),
-/***/ 1094:
+/***/ 71400:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ReflectionJsonWriter = void 0;
-const base64_1 = __nccwpck_require__(6335);
-const pb_long_1 = __nccwpck_require__(1753);
-const reflection_info_1 = __nccwpck_require__(7910);
-const assert_1 = __nccwpck_require__(8602);
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+exports.unsafeStringify = unsafeStringify;
+
+var _validate = _interopRequireDefault(__nccwpck_require__(61579));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
/**
- * Writes proto3 messages in canonical JSON format using reflection
- * information.
- *
- * https://developers.google.com/protocol-buffers/docs/proto3#json
+ * Convert array of 16 byte values to UUID string format of the form:
+ * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
*/
-class ReflectionJsonWriter {
- constructor(info) {
- var _a;
- this.fields = (_a = info.fields) !== null && _a !== void 0 ? _a : [];
+const byteToHex = [];
+
+for (let i = 0; i < 256; ++i) {
+ byteToHex.push((i + 0x100).toString(16).slice(1));
+}
+
+function unsafeStringify(arr, offset = 0) {
+ // Note: Be careful editing this code! It's been tuned for performance
+ // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
+ return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
+}
+
+function stringify(arr, offset = 0) {
+ const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one
+ // of the following:
+ // - One or more input array values don't map to a hex octet (leading to
+ // "undefined" in the uuid)
+ // - Invalid input values for the RFC `version` or `variant` fields
+
+ if (!(0, _validate.default)(uuid)) {
+ throw TypeError('Stringified UUID is invalid');
+ }
+
+ return uuid;
+}
+
+var _default = stringify;
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 64684:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _rng = _interopRequireDefault(__nccwpck_require__(88540));
+
+var _stringify = __nccwpck_require__(71400);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+// **`v1()` - Generate time-based UUID**
+//
+// Inspired by https://github.com/LiosK/UUID.js
+// and http://docs.python.org/library/uuid.html
+let _nodeId;
+
+let _clockseq; // Previous uuid creation time
+
+
+let _lastMSecs = 0;
+let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
+
+function v1(options, buf, offset) {
+ let i = buf && offset || 0;
+ const b = buf || new Array(16);
+ options = options || {};
+ let node = options.node || _nodeId;
+ let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
+ // specified. We do this lazily to minimize issues related to insufficient
+ // system entropy. See #189
+
+ if (node == null || clockseq == null) {
+ const seedBytes = options.random || (options.rng || _rng.default)();
+
+ if (node == null) {
+ // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
+ node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
}
- /**
- * 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;
+
+ if (clockseq == null) {
+ // Per 4.2.2, randomize (14 bit) clockseq
+ clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
}
- 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;
+ } // UUID timestamps are 100 nano-second units since the Gregorian epoch,
+ // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
+ // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
+ // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
+
+
+ let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
+ // cycle to simulate higher resolution clock
+
+ let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
+
+ const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
+
+ if (dt < 0 && options.clockseq === undefined) {
+ clockseq = clockseq + 1 & 0x3fff;
+ } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
+ // time interval
+
+
+ if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
+ nsecs = 0;
+ } // Per 4.2.1.2 Throw error if too many uuids are requested
+
+
+ if (nsecs >= 10000) {
+ throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
+ }
+
+ _lastMSecs = msecs;
+ _lastNSecs = nsecs;
+ _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
+
+ msecs += 12219292800000; // `time_low`
+
+ const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
+ b[i++] = tl >>> 24 & 0xff;
+ b[i++] = tl >>> 16 & 0xff;
+ b[i++] = tl >>> 8 & 0xff;
+ b[i++] = tl & 0xff; // `time_mid`
+
+ const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
+ b[i++] = tmh >>> 8 & 0xff;
+ b[i++] = tmh & 0xff; // `time_high_and_version`
+
+ b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
+
+ b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
+
+ b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
+
+ b[i++] = clockseq & 0xff; // `node`
+
+ for (let n = 0; n < 6; ++n) {
+ b[i + n] = node[n];
+ }
+
+ return buf || (0, _stringify.unsafeStringify)(b);
+}
+
+var _default = v1;
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 53142:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _v = _interopRequireDefault(__nccwpck_require__(44575));
+
+var _md = _interopRequireDefault(__nccwpck_require__(88061));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+const v3 = (0, _v.default)('v3', 0x30, _md.default);
+var _default = v3;
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 44575:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports.URL = exports.DNS = void 0;
+exports["default"] = v35;
+
+var _stringify = __nccwpck_require__(71400);
+
+var _parse = _interopRequireDefault(__nccwpck_require__(7814));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function stringToBytes(str) {
+ str = unescape(encodeURIComponent(str)); // UTF8 escape
+
+ const bytes = [];
+
+ for (let i = 0; i < str.length; ++i) {
+ bytes.push(str.charCodeAt(i));
+ }
+
+ return bytes;
+}
+
+const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
+exports.DNS = DNS;
+const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
+exports.URL = URL;
+
+function v35(name, version, hashfunc) {
+ function generateUUID(value, namespace, buf, offset) {
+ var _namespace;
+
+ if (typeof value === 'string') {
+ value = stringToBytes(value);
}
- /**
- * 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];
+
+ if (typeof namespace === 'string') {
+ namespace = (0, _parse.default)(namespace);
}
- message(type, value, fieldName, options) {
- if (value === undefined)
- return options.emitDefaultValues ? null : undefined;
- return type.internalJsonWrite(value, options);
+
+ if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {
+ throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
+ } // Compute hash of namespace and value, Per 4.3
+ // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
+ // hashfunc([...namespace, ... value])`
+
+
+ let bytes = new Uint8Array(16 + value.length);
+ bytes.set(namespace);
+ bytes.set(value, namespace.length);
+ bytes = hashfunc(bytes);
+ bytes[6] = bytes[6] & 0x0f | version;
+ bytes[8] = bytes[8] & 0x3f | 0x80;
+
+ if (buf) {
+ offset = offset || 0;
+
+ for (let i = 0; i < 16; ++i) {
+ buf[offset + i] = bytes[i];
+ }
+
+ return buf;
}
- 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);
- }
+
+ return (0, _stringify.unsafeStringify)(bytes);
+ } // Function#name is not settable on some platforms (#270)
+
+
+ try {
+ generateUUID.name = name; // eslint-disable-next-line no-empty
+ } catch (err) {} // For CommonJS default export support
+
+
+ generateUUID.DNS = DNS;
+ generateUUID.URL = URL;
+ return generateUUID;
+}
+
+/***/ }),
+
+/***/ 69655:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _native = _interopRequireDefault(__nccwpck_require__(7966));
+
+var _rng = _interopRequireDefault(__nccwpck_require__(88540));
+
+var _stringify = __nccwpck_require__(71400);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function v4(options, buf, offset) {
+ if (_native.default.randomUUID && !buf && !options) {
+ return _native.default.randomUUID();
+ }
+
+ options = options || {};
+
+ const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
+
+
+ rnds[6] = rnds[6] & 0x0f | 0x40;
+ rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
+
+ if (buf) {
+ offset = offset || 0;
+
+ for (let i = 0; i < 16; ++i) {
+ buf[offset + i] = rnds[i];
}
+
+ return buf;
+ }
+
+ return (0, _stringify.unsafeStringify)(rnds);
}
-exports.ReflectionJsonWriter = ReflectionJsonWriter;
+var _default = v4;
+exports["default"] = _default;
/***/ }),
-/***/ 3402:
+/***/ 70880:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.reflectionLongConvert = void 0;
-const reflection_info_1 = __nccwpck_require__(7910);
-/**
- * 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();
- }
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _v = _interopRequireDefault(__nccwpck_require__(44575));
+
+var _sha = _interopRequireDefault(__nccwpck_require__(11352));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+const v5 = (0, _v.default)('v5', 0x50, _sha.default);
+var _default = v5;
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 61579:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _regex = _interopRequireDefault(__nccwpck_require__(1118));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function validate(uuid) {
+ return typeof uuid === 'string' && _regex.default.test(uuid);
}
-exports.reflectionLongConvert = reflectionLongConvert;
+var _default = validate;
+exports["default"] = _default;
/***/ }),
-/***/ 8044:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 66257:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"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
- }
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _validate = _interopRequireDefault(__nccwpck_require__(61579));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function version(uuid) {
+ if (!(0, _validate.default)(uuid)) {
+ throw TypeError('Invalid UUID');
+ }
+
+ return parseInt(uuid.slice(14, 15), 16);
+}
+
+var _default = version;
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 1552:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var punycode = __nccwpck_require__(24876);
+var mappingTable = __nccwpck_require__(92472);
+
+var PROCESSING_OPTIONS = {
+ TRANSITIONAL: 0,
+ NONTRANSITIONAL: 1
+};
+
+function normalize(str) { // fix bug in v8
+ return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000');
+}
+
+function findStatus(val) {
+ var start = 0;
+ var end = mappingTable.length - 1;
+
+ while (start <= end) {
+ var mid = Math.floor((start + end) / 2);
+
+ var target = mappingTable[mid];
+ if (target[0][0] <= val && target[0][1] >= val) {
+ return target;
+ } else if (target[0][0] > val) {
+ end = mid - 1;
+ } else {
+ start = mid + 1;
+ }
+ }
+
+ return null;
+}
+
+var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
+
+function countSymbols(string) {
+ return string
+ // replace every surrogate pair with a BMP symbol
+ .replace(regexAstralSymbols, '_')
+ // then get the length
+ .length;
+}
+
+function mapChars(domain_name, useSTD3, processing_option) {
+ var hasError = false;
+ var processed = "";
+
+ var len = countSymbols(domain_name);
+ for (var i = 0; i < len; ++i) {
+ var codePoint = domain_name.codePointAt(i);
+ var status = findStatus(codePoint);
+
+ switch (status[1]) {
+ case "disallowed":
+ hasError = true;
+ processed += String.fromCodePoint(codePoint);
+ break;
+ case "ignored":
+ break;
+ case "mapped":
+ processed += String.fromCodePoint.apply(String, status[2]);
+ break;
+ case "deviation":
+ if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) {
+ processed += String.fromCodePoint.apply(String, status[2]);
+ } else {
+ processed += String.fromCodePoint(codePoint);
}
- 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
- }
+ break;
+ case "valid":
+ processed += String.fromCodePoint(codePoint);
+ break;
+ case "disallowed_STD3_mapped":
+ if (useSTD3) {
+ hasError = true;
+ processed += String.fromCodePoint(codePoint);
+ } else {
+ processed += String.fromCodePoint.apply(String, status[2]);
}
- 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;
+ break;
+ case "disallowed_STD3_valid":
+ if (useSTD3) {
+ hasError = true;
}
+
+ processed += String.fromCodePoint(codePoint);
+ break;
}
+ }
+
+ return {
+ string: processed,
+ error: hasError
+ };
}
-exports.reflectionMergePartial = reflectionMergePartial;
+var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/;
-/***/ }),
+function validateLabel(label, processing_option) {
+ if (label.substr(0, 4) === "xn--") {
+ label = punycode.toUnicode(label);
+ processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL;
+ }
-/***/ 9526:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ var error = false;
-"use strict";
+ if (normalize(label) !== label ||
+ (label[3] === "-" && label[4] === "-") ||
+ label[0] === "-" || label[label.length - 1] === "-" ||
+ label.indexOf(".") !== -1 ||
+ label.search(combiningMarksRegex) === 0) {
+ error = true;
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.reflectionScalarDefault = void 0;
-const reflection_info_1 = __nccwpck_require__(7910);
-const reflection_long_convert_1 = __nccwpck_require__(3402);
-const pb_long_1 = __nccwpck_require__(1753);
-/**
- * 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;
+ var len = countSymbols(label);
+ for (var i = 0; i < len; ++i) {
+ var status = findStatus(label.codePointAt(i));
+ if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") ||
+ (processing === PROCESSING_OPTIONS.NONTRANSITIONAL &&
+ status[1] !== "valid" && status[1] !== "deviation")) {
+ error = true;
+ break;
}
+ }
+
+ return {
+ label: label,
+ error: error
+ };
}
-exports.reflectionScalarDefault = reflectionScalarDefault;
+
+function processing(domain_name, useSTD3, processing_option) {
+ var result = mapChars(domain_name, useSTD3, processing_option);
+ result.string = normalize(result.string);
+
+ var labels = result.string.split(".");
+ for (var i = 0; i < labels.length; ++i) {
+ try {
+ var validation = validateLabel(labels[i]);
+ labels[i] = validation.label;
+ result.error = result.error || validation.error;
+ } catch(e) {
+ result.error = true;
+ }
+ }
+
+ return {
+ string: labels.join("."),
+ error: result.error
+ };
+}
+
+module.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) {
+ var result = processing(domain_name, useSTD3, processing_option);
+ var labels = result.string.split(".");
+ labels = labels.map(function(l) {
+ try {
+ return punycode.toASCII(l);
+ } catch(e) {
+ result.error = true;
+ return l;
+ }
+ });
+
+ if (verifyDnsLength) {
+ var total = labels.slice(0, labels.length - 1).join(".").length;
+ if (total.length > 253 || total.length === 0) {
+ result.error = true;
+ }
+
+ for (var i=0; i < labels.length; ++i) {
+ if (labels.length > 63 || labels.length === 0) {
+ result.error = true;
+ break;
+ }
+ }
+ }
+
+ if (result.error) return null;
+ return labels.join(".");
+};
+
+module.exports.toUnicode = function(domain_name, useSTD3) {
+ var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL);
+
+ return {
+ domain: result.string,
+ error: result.error
+ };
+};
+
+module.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS;
/***/ }),
-/***/ 5167:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 61860:
+/***/ ((module) => {
-"use strict";
+/******************************************************************************
+Copyright (c) Microsoft Corporation.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ReflectionTypeCheck = void 0;
-const reflection_info_1 = __nccwpck_require__(7910);
-const oneof_1 = __nccwpck_require__(8063);
-// noinspection JSMethodCanBeStatic
-class ReflectionTypeCheck {
- constructor(info) {
- var _a;
- this.fields = (_a = info.fields) !== null && _a !== void 0 ? _a : [];
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+PERFORMANCE OF THIS SOFTWARE.
+***************************************************************************** */
+/* global global, define, Symbol, Reflect, Promise, SuppressedError, Iterator */
+var __extends;
+var __assign;
+var __rest;
+var __decorate;
+var __param;
+var __esDecorate;
+var __runInitializers;
+var __propKey;
+var __setFunctionName;
+var __metadata;
+var __awaiter;
+var __generator;
+var __exportStar;
+var __values;
+var __read;
+var __spread;
+var __spreadArrays;
+var __spreadArray;
+var __await;
+var __asyncGenerator;
+var __asyncDelegator;
+var __asyncValues;
+var __makeTemplateObject;
+var __importStar;
+var __importDefault;
+var __classPrivateFieldGet;
+var __classPrivateFieldSet;
+var __classPrivateFieldIn;
+var __createBinding;
+var __addDisposableResource;
+var __disposeResources;
+var __rewriteRelativeImportExtension;
+(function (factory) {
+ var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {};
+ if (typeof define === "function" && define.amd) {
+ define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); });
}
- 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 if ( true && typeof module.exports === "object") {
+ factory(createExporter(root, createExporter(module.exports)));
+ }
+ else {
+ factory(createExporter(root));
+ }
+ function createExporter(exports, previous) {
+ if (exports !== root) {
+ if (typeof Object.create === "function") {
+ Object.defineProperty(exports, "__esModule", { value: true });
}
else {
- 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;
- }
+ exports.__esModule = true;
}
}
- this.data = { req, known, oneofs: Object.values(oneofs) };
+ return function (id, v) { return exports[id] = previous ? previous(id, v) : v; };
}
- /**
- * 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;
+})
+(function (exporter) {
+ var extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
+
+ __extends = function (d, b) {
+ if (typeof b !== "function" && b !== null)
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
+ extendStatics(d, b);
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+ };
+
+ __assign = Object.assign || function (t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
- // 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;
+ return t;
+ };
+
+ __rest = function (s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
+ t[p[i]] = s[p[i]];
+ }
+ return t;
+ };
+
+ __decorate = function (decorators, target, key, desc) {
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
+ };
+
+ __param = function (paramIndex, decorator) {
+ return function (target, key) { decorator(target, key, paramIndex); }
+ };
+
+ __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
+ var _, done = false;
+ for (var i = decorators.length - 1; i >= 0; i--) {
+ var context = {};
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
+ if (kind === "accessor") {
+ if (result === void 0) continue;
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
+ if (_ = accept(result.get)) descriptor.get = _;
+ if (_ = accept(result.set)) descriptor.set = _;
+ if (_ = accept(result.init)) initializers.unshift(_);
+ }
+ else if (_ = accept(result)) {
+ if (kind === "field") initializers.unshift(_);
+ else descriptor[key] = _;
+ }
}
- // check types
- for (const field of this.fields) {
- if (field.oneof !== undefined)
- continue;
- if (!this.field(message[field.localName], field, allowExcessProperties, depth))
- return false;
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
+ done = true;
+ };
+
+ __runInitializers = function (thisArg, initializers, value) {
+ var useValue = arguments.length > 2;
+ for (var i = 0; i < initializers.length; i++) {
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
}
- 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);
+ return useValue ? value : void 0;
+ };
+
+ __propKey = function (x) {
+ return typeof x === "symbol" ? x : "".concat(x);
+ };
+
+ __setFunctionName = function (f, name, prefix) {
+ if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
+ return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
+ };
+
+ __metadata = function (metadataKey, metadataValue) {
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
+ };
+
+ __awaiter = function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+ };
+
+ __generator = function (thisArg, body) {
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
+ function verb(n) { return function (v) { return step([n, v]); }; }
+ function step(op) {
+ if (f) throw new TypeError("Generator is already executing.");
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
+ if (y = 0, t) op = [op[0] & 2, t.value];
+ switch (op[0]) {
+ case 0: case 1: t = op; break;
+ case 4: _.label++; return { value: op[1], done: false };
+ case 5: _.label++; y = op[1]; op = [0]; continue;
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
+ default:
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
+ if (t[2]) _.ops.pop();
+ _.trys.pop(); continue;
}
- 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;
+ op = body.call(thisArg, _);
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
- else {
- for (let i = 0; i < arg.length && i < depth; i++)
- if (!type.is(arg[i], depth - 1))
- return false;
+ };
+
+ __exportStar = function(m, o) {
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
+ };
+
+ __createBinding = Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ 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]; } };
}
- 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);
+ Object.defineProperty(o, k2, desc);
+ }) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+ });
+
+ __values = function (o) {
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
+ if (m) return m.call(o);
+ if (o && typeof o.length === "number") return {
+ next: function () {
+ if (o && i >= o.length) o = void 0;
+ return { value: o && o[i++], done: !o };
+ }
+ };
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
+ };
+
+ __read = function (o, n) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
+ if (!m) return o;
+ var i = m.call(o), r, ar = [], e;
+ try {
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
- }
- 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);
+ catch (error) { e = { error: error }; }
+ finally {
+ try {
+ if (r && !r.done && (m = i["return"])) m.call(i);
+ }
+ finally { if (e) throw e.error; }
}
- }
-}
-exports.ReflectionTypeCheck = ReflectionTypeCheck;
+ return ar;
+ };
+ /** @deprecated */
+ __spread = function () {
+ for (var ar = [], i = 0; i < arguments.length; i++)
+ ar = ar.concat(__read(arguments[i]));
+ return ar;
+ };
-/***/ }),
+ /** @deprecated */
+ __spreadArrays = function () {
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
+ r[k] = a[j];
+ return r;
+ };
-/***/ 5183:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ __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));
+ };
-"use strict";
+ __await = function (v) {
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
+ };
-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__(8611));
-const https = __importStar(__nccwpck_require__(5692));
-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
+ __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 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
+ function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
+ function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
+ function fulfill(value) { resume("next", value); }
+ function reject(value) { resume("throw", value); }
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
+ };
-/***/ }),
+ __asyncDelegator = function (o) {
+ var i, p;
+ return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
+ function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
+ };
-/***/ 8894:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ __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); }
+ };
-"use strict";
+ __makeTemplateObject = function (cooked, raw) {
+ if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
+ return cooked;
+ };
-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__(9278));
-const http = __importStar(__nccwpck_require__(8611));
-const https_1 = __nccwpck_require__(5692);
-__exportStar(__nccwpck_require__(5183), 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;
+ var __setModuleDefault = Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+ }) : function(o, v) {
+ o["default"] = v;
+ };
+
+ 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);
+ };
+
+ __importStar = 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;
+ };
+
+ __importDefault = function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+ };
+
+ __classPrivateFieldGet = function (receiver, state, kind, f) {
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
+ };
+
+ __classPrivateFieldSet = function (receiver, state, value, kind, f) {
+ if (kind === "m") throw new TypeError("Private method is not writable");
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
+ };
+
+ __classPrivateFieldIn = function (state, receiver) {
+ if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
+ return typeof state === "function" ? receiver === state : state.has(receiver);
+ };
+
+ __addDisposableResource = function (env, value, async) {
+ if (value !== null && value !== void 0) {
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
+ var dispose, inner;
+ if (async) {
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
+ dispose = value[Symbol.asyncDispose];
}
- // 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:';
+ if (dispose === void 0) {
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
+ dispose = value[Symbol.dispose];
+ if (async) inner = dispose;
}
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
+ env.stack.push({ value: value, dispose: dispose, async: async });
}
- // 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];
- }
+ else if (async) {
+ env.stack.push({ async: true });
}
- }
- // 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);
+ return value;
+ };
+
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
+ var e = new Error(message);
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
+ };
+
+ __disposeResources = function (env) {
+ function fail(e) {
+ env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
+ env.hasError = true;
}
- // @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) {
+ var r, s = 0;
+ function next() {
+ while (r = env.stack.pop()) {
try {
- // @ts-expect-error `addRequest()` isn't defined in `@types/node`
- return socket.addRequest(req, connectOpts);
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
+ if (r.dispose) {
+ var result = r.dispose.call(r.value);
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
+ }
+ else s |= 1;
}
- catch (err) {
- return cb(err);
+ catch (e) {
+ fail(e);
}
}
- 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;
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
+ if (env.hasError) throw env.error;
}
- }
-}
-exports.Agent = Agent;
-//# sourceMappingURL=index.js.map
-
-/***/ }),
-
-/***/ 9380:
-/***/ ((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;
-}
+ return next();
+ };
-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;
+ __rewriteRelativeImportExtension = function (path, preserveJsx) {
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
+ });
+ }
+ return path;
+ };
- if (ai >= 0 && bi > 0) {
- if(a===b) {
- return [ai, bi];
- }
- begs = [];
- left = str.length;
+ exporter("__extends", __extends);
+ exporter("__assign", __assign);
+ exporter("__rest", __rest);
+ exporter("__decorate", __decorate);
+ exporter("__param", __param);
+ exporter("__esDecorate", __esDecorate);
+ exporter("__runInitializers", __runInitializers);
+ exporter("__propKey", __propKey);
+ exporter("__setFunctionName", __setFunctionName);
+ exporter("__metadata", __metadata);
+ exporter("__awaiter", __awaiter);
+ exporter("__generator", __generator);
+ exporter("__exportStar", __exportStar);
+ exporter("__createBinding", __createBinding);
+ exporter("__values", __values);
+ exporter("__read", __read);
+ exporter("__spread", __spread);
+ exporter("__spreadArrays", __spreadArrays);
+ exporter("__spreadArray", __spreadArray);
+ exporter("__await", __await);
+ exporter("__asyncGenerator", __asyncGenerator);
+ exporter("__asyncDelegator", __asyncDelegator);
+ exporter("__asyncValues", __asyncValues);
+ exporter("__makeTemplateObject", __makeTemplateObject);
+ exporter("__importStar", __importStar);
+ exporter("__importDefault", __importDefault);
+ exporter("__classPrivateFieldGet", __classPrivateFieldGet);
+ exporter("__classPrivateFieldSet", __classPrivateFieldSet);
+ exporter("__classPrivateFieldIn", __classPrivateFieldIn);
+ exporter("__addDisposableResource", __addDisposableResource);
+ exporter("__disposeResources", __disposeResources);
+ exporter("__rewriteRelativeImportExtension", __rewriteRelativeImportExtension);
+});
- 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;
- }
+0 && (0);
- bi = str.indexOf(b, i + 1);
- }
- i = ai < bi && ai >= 0 ? ai : bi;
- }
+/***/ }),
- if (begs.length) {
- result = [ left, right ];
- }
- }
+/***/ 20770:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- return result;
-}
+module.exports = __nccwpck_require__(20218);
/***/ }),
-/***/ 4691:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 20218:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-var concatMap = __nccwpck_require__(7087);
-var balanced = __nccwpck_require__(9380);
+"use strict";
-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';
+var net = __nccwpck_require__(69278);
+var tls = __nccwpck_require__(64756);
+var http = __nccwpck_require__(58611);
+var https = __nccwpck_require__(65692);
+var events = __nccwpck_require__(24434);
+var assert = __nccwpck_require__(42613);
+var util = __nccwpck_require__(39023);
-function numeric(str) {
- return parseInt(str, 10) == str
- ? parseInt(str, 10)
- : str.charCodeAt(0);
+
+exports.httpOverHttp = httpOverHttp;
+exports.httpsOverHttp = httpsOverHttp;
+exports.httpOverHttps = httpOverHttps;
+exports.httpsOverHttps = httpsOverHttps;
+
+
+function httpOverHttp(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = http.request;
+ return agent;
}
-function escapeBraces(str) {
- return str.split('\\\\').join(escSlash)
- .split('\\{').join(escOpen)
- .split('\\}').join(escClose)
- .split('\\,').join(escComma)
- .split('\\.').join(escPeriod);
+function httpsOverHttp(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = http.request;
+ agent.createSocket = createSecureSocket;
+ agent.defaultPort = 443;
+ return agent;
}
-function unescapeBraces(str) {
- return str.split(escSlash).join('\\')
- .split(escOpen).join('{')
- .split(escClose).join('}')
- .split(escComma).join(',')
- .split(escPeriod).join('.');
+function httpOverHttps(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = https.request;
+ return agent;
}
+function httpsOverHttps(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = https.request;
+ agent.createSocket = createSecureSocket;
+ agent.defaultPort = 443;
+ return agent;
+}
-// 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);
+function TunnelingAgent(options) {
+ var self = this;
+ self.options = options || {};
+ self.proxyOptions = self.options.proxy || {};
+ self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;
+ self.requests = [];
+ self.sockets = [];
- if (!m)
- return str.split(',');
+ self.on('free', function onFree(socket, host, port, localAddress) {
+ var options = toOptions(host, port, localAddress);
+ for (var i = 0, len = self.requests.length; i < len; ++i) {
+ var pending = self.requests[i];
+ if (pending.host === options.host && pending.port === options.port) {
+ // Detect the request to connect same origin server,
+ // reuse the connection.
+ self.requests.splice(i, 1);
+ pending.request.onSocket(socket);
+ return;
+ }
+ }
+ socket.destroy();
+ self.removeSocket(socket);
+ });
+}
+util.inherits(TunnelingAgent, events.EventEmitter);
- var pre = m.pre;
- var body = m.body;
- var post = m.post;
- var p = pre.split(',');
+TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {
+ var self = this;
+ var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));
- p[p.length-1] += '{' + body + '}';
- var postParts = parseCommaParts(post);
- if (post.length) {
- p[p.length-1] += postParts.shift();
- p.push.apply(p, postParts);
+ if (self.sockets.length >= this.maxSockets) {
+ // We are over limit so we'll add it to the queue.
+ self.requests.push(options);
+ return;
}
- parts.push.apply(parts, p);
+ // If we are under maxSockets create a new one.
+ self.createSocket(options, function(socket) {
+ socket.on('free', onFree);
+ socket.on('close', onCloseOrRemove);
+ socket.on('agentRemove', onCloseOrRemove);
+ req.onSocket(socket);
- return parts;
-}
+ function onFree() {
+ self.emit('free', socket, options);
+ }
-function expandTop(str) {
- if (!str)
- return [];
+ function onCloseOrRemove(err) {
+ self.removeSocket(socket);
+ socket.removeListener('free', onFree);
+ socket.removeListener('close', onCloseOrRemove);
+ socket.removeListener('agentRemove', onCloseOrRemove);
+ }
+ });
+};
- // 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);
+TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
+ var self = this;
+ var placeholder = {};
+ self.sockets.push(placeholder);
+
+ var connectOptions = mergeOptions({}, self.proxyOptions, {
+ method: 'CONNECT',
+ path: options.host + ':' + options.port,
+ agent: false,
+ headers: {
+ host: options.host + ':' + options.port
+ }
+ });
+ if (options.localAddress) {
+ connectOptions.localAddress = options.localAddress;
+ }
+ if (connectOptions.proxyAuth) {
+ connectOptions.headers = connectOptions.headers || {};
+ connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
+ new Buffer(connectOptions.proxyAuth).toString('base64');
}
- return expand(escapeBraces(str), true).map(unescapeBraces);
-}
+ debug('making CONNECT request');
+ var connectReq = self.request(connectOptions);
+ connectReq.useChunkedEncodingByDefault = false; // for v0.6
+ connectReq.once('response', onResponse); // for v0.6
+ connectReq.once('upgrade', onUpgrade); // for v0.6
+ connectReq.once('connect', onConnect); // for v0.7 or later
+ connectReq.once('error', onError);
+ connectReq.end();
-function identity(e) {
- return e;
-}
+ function onResponse(res) {
+ // Very hacky. This is necessary to avoid http-parser leaks.
+ res.upgrade = true;
+ }
-function embrace(str) {
- return '{' + str + '}';
-}
-function isPadded(el) {
- return /^-?0\d/.test(el);
-}
+ function onUpgrade(res, socket, head) {
+ // Hacky.
+ process.nextTick(function() {
+ onConnect(res, socket, head);
+ });
+ }
-function lte(i, y) {
- return i <= y;
-}
-function gte(i, y) {
- return i >= y;
-}
+ function onConnect(res, socket, head) {
+ connectReq.removeAllListeners();
+ socket.removeAllListeners();
-function expand(str, isTop) {
- var expansions = [];
+ if (res.statusCode !== 200) {
+ debug('tunneling socket could not be established, statusCode=%d',
+ res.statusCode);
+ socket.destroy();
+ var error = new Error('tunneling socket could not be established, ' +
+ 'statusCode=' + res.statusCode);
+ error.code = 'ECONNRESET';
+ options.request.emit('error', error);
+ self.removeSocket(placeholder);
+ return;
+ }
+ if (head.length > 0) {
+ debug('got illegal response body from proxy');
+ socket.destroy();
+ var error = new Error('got illegal response body from proxy');
+ error.code = 'ECONNRESET';
+ options.request.emit('error', error);
+ self.removeSocket(placeholder);
+ return;
+ }
+ debug('tunneling connection has established');
+ self.sockets[self.sockets.indexOf(placeholder)] = socket;
+ return cb(socket);
+ }
- var m = balanced('{', '}', str);
- if (!m || /\$$/.test(m.pre)) return [str];
+ function onError(cause) {
+ connectReq.removeAllListeners();
- 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];
+ debug('tunneling socket could not be established, cause=%s\n',
+ cause.message, cause.stack);
+ var error = new Error('tunneling socket could not be established, ' +
+ 'cause=' + cause.message);
+ error.code = 'ECONNRESET';
+ options.request.emit('error', error);
+ self.removeSocket(placeholder);
}
+};
- 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;
- });
- }
- }
+TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
+ var pos = this.sockets.indexOf(socket)
+ if (pos === -1) {
+ return;
}
+ this.sockets.splice(pos, 1);
- // at this point, n is the parts, and we know it's not a comma set
- // with a single entry.
+ var pending = this.requests.shift();
+ if (pending) {
+ // If we have pending requests and a socket gets closed a new one
+ // needs to be created to take over in the pool for the one that closed.
+ this.createSocket(pending, function(socket) {
+ pending.request.onSocket(socket);
+ });
+ }
+};
- // 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)
- : [''];
+function createSecureSocket(options, cb) {
+ var self = this;
+ TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
+ var hostHeader = options.request.getHeader('host');
+ var tlsOptions = mergeOptions({}, self.options, {
+ socket: socket,
+ servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host
+ });
- var N;
+ // 0 is dummy port for v0.6
+ var secureSocket = tls.connect(0, tlsOptions);
+ self.sockets[self.sockets.indexOf(socket)] = secureSocket;
+ cb(secureSocket);
+ });
+}
- 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 = [];
+function toOptions(host, port, localAddress) {
+ if (typeof host === 'string') { // since v0.10
+ return {
+ host: host,
+ port: port,
+ localAddress: localAddress
+ };
+ }
+ return host; // for v0.11 or later
+}
- 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;
- }
+function mergeOptions(target) {
+ for (var i = 1, len = arguments.length; i < len; ++i) {
+ var overrides = arguments[i];
+ if (typeof overrides === 'object') {
+ var keys = Object.keys(overrides);
+ for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
+ var k = keys[j];
+ if (overrides[k] !== undefined) {
+ target[k] = overrides[k];
}
}
- N.push(c);
}
- } else {
- N = concatMap(n, function(el) { return expand(el, false) });
}
+ return target;
+}
- 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);
+
+var debug;
+if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
+ debug = function() {
+ var args = Array.prototype.slice.call(arguments);
+ if (typeof args[0] === 'string') {
+ args[0] = 'TUNNEL: ' + args[0];
+ } else {
+ args.unshift('TUNNEL:');
}
+ console.error.apply(console, args);
}
-
- return expansions;
+} else {
+ debug = function() {};
}
-
+exports.debug = debug; // for test
/***/ }),
-/***/ 7087:
-/***/ ((module) => {
+/***/ 45497:
+/***/ ((__unused_webpack_module, exports) => {
-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;
-};
+"use strict";
-var isArray = Array.isArray || function (xs) {
- return Object.prototype.toString.call(xs) === '[object Array]';
-};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
/***/ }),
-/***/ 6110:
-/***/ ((module, exports, __nccwpck_require__) => {
+/***/ 13315:
+/***/ ((__unused_webpack_module, exports) => {
-/* eslint-env browser */
+"use strict";
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isValidErrorCode = exports.httpStatusFromErrorCode = exports.TwirpErrorCode = exports.BadRouteError = exports.InternalServerErrorWith = exports.InternalServerError = exports.RequiredArgumentError = exports.InvalidArgumentError = exports.NotFoundError = exports.TwirpError = void 0;
+/**
+ * Represents a twirp error
+ */
+class TwirpError extends Error {
+ constructor(code, msg) {
+ super(msg);
+ this.code = TwirpErrorCode.Internal;
+ this.meta = {};
+ this.code = code;
+ this.msg = msg;
+ Object.setPrototypeOf(this, TwirpError.prototype);
+ }
+ /**
+ * Adds a metadata kv to the error
+ * @param key
+ * @param value
+ */
+ withMeta(key, value) {
+ this.meta[key] = value;
+ return this;
+ }
+ /**
+ * Returns a single metadata value
+ * return "" if not found
+ * @param key
+ */
+ getMeta(key) {
+ return this.meta[key] || "";
+ }
+ /**
+ * Add the original error cause
+ * @param err
+ * @param addMeta
+ */
+ withCause(err, addMeta = false) {
+ this._originalCause = err;
+ if (addMeta) {
+ this.withMeta("cause", err.message);
+ }
+ return this;
+ }
+ cause() {
+ return this._originalCause;
+ }
+ /**
+ * Returns the error representation to JSON
+ */
+ toJSON() {
+ try {
+ return JSON.stringify({
+ code: this.code,
+ msg: this.msg,
+ meta: this.meta,
+ });
+ }
+ catch (e) {
+ return `{"code": "internal", "msg": "There was an error but it could not be serialized into JSON"}`;
+ }
+ }
+ /**
+ * Create a twirp error from an object
+ * @param obj
+ */
+ static fromObject(obj) {
+ const code = obj["code"] || TwirpErrorCode.Unknown;
+ const msg = obj["msg"] || "unknown";
+ const error = new TwirpError(code, msg);
+ if (obj["meta"]) {
+ Object.keys(obj["meta"]).forEach((key) => {
+ error.withMeta(key, obj["meta"][key]);
+ });
+ }
+ return error;
+ }
+}
+exports.TwirpError = TwirpError;
+/**
+ * NotFoundError constructor for the common NotFound error.
+ */
+class NotFoundError extends TwirpError {
+ constructor(msg) {
+ super(TwirpErrorCode.NotFound, msg);
+ }
+}
+exports.NotFoundError = NotFoundError;
+/**
+ * InvalidArgumentError constructor for the common InvalidArgument error. Can be
+ * used when an argument has invalid format, is a number out of range, is a bad
+ * option, etc).
+ */
+class InvalidArgumentError extends TwirpError {
+ constructor(argument, validationMsg) {
+ super(TwirpErrorCode.InvalidArgument, argument + " " + validationMsg);
+ this.withMeta("argument", argument);
+ }
+}
+exports.InvalidArgumentError = InvalidArgumentError;
/**
- * This is the web browser implementation of `debug()`.
+ * RequiredArgumentError is a more specific constructor for InvalidArgument
+ * error. Should be used when the argument is required (expected to have a
+ * non-zero value).
*/
-
-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`.');
- }
- };
-})();
-
+class RequiredArgumentError extends InvalidArgumentError {
+ constructor(argument) {
+ super(argument, "is required");
+ }
+}
+exports.RequiredArgumentError = RequiredArgumentError;
/**
- * Colors.
+ * InternalError constructor for the common Internal error. Should be used to
+ * specify that something bad or unexpected happened.
*/
-
-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'
-];
-
+class InternalServerError extends TwirpError {
+ constructor(msg) {
+ super(TwirpErrorCode.Internal, msg);
+ }
+}
+exports.InternalServerError = InternalServerError;
/**
- * 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
+ * InternalErrorWith makes an internal error, wrapping the original error and using it
+ * for the error message, and with metadata "cause" with the original error type.
+ * This function is used by Twirp services to wrap non-Twirp errors as internal errors.
+ * The wrapped error can be extracted later with err.cause()
*/
-
-// 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+)/));
+class InternalServerErrorWith extends InternalServerError {
+ constructor(err) {
+ super(err.message);
+ this.withMeta("cause", err.name);
+ this.withCause(err);
+ }
}
-
+exports.InternalServerErrorWith = InternalServerErrorWith;
/**
- * Colorize log arguments if enabled.
- *
- * @api public
+ * A standard BadRoute Error
*/
+class BadRouteError extends TwirpError {
+ constructor(msg, method, url) {
+ super(TwirpErrorCode.BadRoute, msg);
+ this.withMeta("twirp_invalid_route", method + " " + url);
+ }
+}
+exports.BadRouteError = BadRouteError;
+var TwirpErrorCode;
+(function (TwirpErrorCode) {
+ // Canceled indicates the operation was cancelled (typically by the caller).
+ TwirpErrorCode["Canceled"] = "canceled";
+ // Unknown error. For example when handling errors raised by APIs that do not
+ // return enough error information.
+ TwirpErrorCode["Unknown"] = "unknown";
+ // InvalidArgument indicates client specified an invalid argument. It
+ // indicates arguments that are problematic regardless of the state of the
+ // system (i.e. a malformed file name, required argument, number out of range,
+ // etc.).
+ TwirpErrorCode["InvalidArgument"] = "invalid_argument";
+ // Malformed indicates an error occurred while decoding the client's request.
+ // This may mean that the message was encoded improperly, or that there is a
+ // disagreement in message format between the client and server.
+ TwirpErrorCode["Malformed"] = "malformed";
+ // DeadlineExceeded means operation expired before completion. For operations
+ // that change the state of the system, this error may be returned even if the
+ // operation has completed successfully (timeout).
+ TwirpErrorCode["DeadlineExceeded"] = "deadline_exceeded";
+ // NotFound means some requested entity was not found.
+ TwirpErrorCode["NotFound"] = "not_found";
+ // BadRoute means that the requested URL path wasn't routable to a Twirp
+ // service and method. This is returned by the generated server, and usually
+ // shouldn't be returned by applications. Instead, applications should use
+ // NotFound or Unimplemented.
+ TwirpErrorCode["BadRoute"] = "bad_route";
+ // AlreadyExists means an attempt to create an entity failed because one
+ // already exists.
+ TwirpErrorCode["AlreadyExists"] = "already_exists";
+ // PermissionDenied indicates the caller does not have permission to execute
+ // the specified operation. It must not be used if the caller cannot be
+ // identified (Unauthenticated).
+ TwirpErrorCode["PermissionDenied"] = "permission_denied";
+ // Unauthenticated indicates the request does not have valid authentication
+ // credentials for the operation.
+ TwirpErrorCode["Unauthenticated"] = "unauthenticated";
+ // ResourceExhausted indicates some resource has been exhausted, perhaps a
+ // per-user quota, or perhaps the entire file system is out of space.
+ TwirpErrorCode["ResourceExhausted"] = "resource_exhausted";
+ // FailedPrecondition indicates operation was rejected because the system is
+ // not in a state required for the operation's execution. For example, doing
+ // an rmdir operation on a directory that is non-empty, or on a non-directory
+ // object, or when having conflicting read-modify-write on the same resource.
+ TwirpErrorCode["FailedPrecondition"] = "failed_precondition";
+ // Aborted indicates the operation was aborted, typically due to a concurrency
+ // issue like sequencer check failures, transaction aborts, etc.
+ TwirpErrorCode["Aborted"] = "aborted";
+ // OutOfRange means operation was attempted past the valid range. For example,
+ // seeking or reading past end of a paginated collection.
+ //
+ // Unlike InvalidArgument, this error indicates a problem that may be fixed if
+ // the system state changes (i.e. adding more items to the collection).
+ //
+ // There is a fair bit of overlap between FailedPrecondition and OutOfRange.
+ // We recommend using OutOfRange (the more specific error) when it applies so
+ // that callers who are iterating through a space can easily look for an
+ // OutOfRange error to detect when they are done.
+ TwirpErrorCode["OutOfRange"] = "out_of_range";
+ // Unimplemented indicates operation is not implemented or not
+ // supported/enabled in this service.
+ TwirpErrorCode["Unimplemented"] = "unimplemented";
+ // Internal errors. When some invariants expected by the underlying system
+ // have been broken. In other words, something bad happened in the library or
+ // backend service. Do not confuse with HTTP Internal Server Error; an
+ // Internal error could also happen on the client code, i.e. when parsing a
+ // server response.
+ TwirpErrorCode["Internal"] = "internal";
+ // Unavailable indicates the service is currently unavailable. This is a most
+ // likely a transient condition and may be corrected by retrying with a
+ // backoff.
+ TwirpErrorCode["Unavailable"] = "unavailable";
+ // DataLoss indicates unrecoverable data loss or corruption.
+ TwirpErrorCode["DataLoss"] = "data_loss";
+})(TwirpErrorCode = exports.TwirpErrorCode || (exports.TwirpErrorCode = {}));
+// ServerHTTPStatusFromErrorCode maps a Twirp error type into a similar HTTP
+// response status. It is used by the Twirp server handler to set the HTTP
+// response status code. Returns 0 if the ErrorCode is invalid.
+function httpStatusFromErrorCode(code) {
+ switch (code) {
+ case TwirpErrorCode.Canceled:
+ return 408; // RequestTimeout
+ case TwirpErrorCode.Unknown:
+ return 500; // Internal Server Error
+ case TwirpErrorCode.InvalidArgument:
+ return 400; // BadRequest
+ case TwirpErrorCode.Malformed:
+ return 400; // BadRequest
+ case TwirpErrorCode.DeadlineExceeded:
+ return 408; // RequestTimeout
+ case TwirpErrorCode.NotFound:
+ return 404; // Not Found
+ case TwirpErrorCode.BadRoute:
+ return 404; // Not Found
+ case TwirpErrorCode.AlreadyExists:
+ return 409; // Conflict
+ case TwirpErrorCode.PermissionDenied:
+ return 403; // Forbidden
+ case TwirpErrorCode.Unauthenticated:
+ return 401; // Unauthorized
+ case TwirpErrorCode.ResourceExhausted:
+ return 429; // Too Many Requests
+ case TwirpErrorCode.FailedPrecondition:
+ return 412; // Precondition Failed
+ case TwirpErrorCode.Aborted:
+ return 409; // Conflict
+ case TwirpErrorCode.OutOfRange:
+ return 400; // Bad Request
+ case TwirpErrorCode.Unimplemented:
+ return 501; // Not Implemented
+ case TwirpErrorCode.Internal:
+ return 500; // Internal Server Error
+ case TwirpErrorCode.Unavailable:
+ return 503; // Service Unavailable
+ case TwirpErrorCode.DataLoss:
+ return 500; // Internal Server Error
+ default:
+ return 0; // Invalid!
+ }
+}
+exports.httpStatusFromErrorCode = httpStatusFromErrorCode;
+// IsValidErrorCode returns true if is one of the valid predefined constants.
+function isValidErrorCode(code) {
+ return httpStatusFromErrorCode(code) != 0;
+}
+exports.isValidErrorCode = isValidErrorCode;
-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');
+/***/ 69636:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
- // 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;
- }
- });
+"use strict";
- args.splice(lastC, 0, c);
+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.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 __rest = (this && this.__rest) || function (s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
+ t[p[i]] = s[p[i]];
+ }
+ return t;
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Gateway = exports.Pattern = void 0;
+const querystring_1 = __nccwpck_require__(83480);
+const dotObject = __importStar(__nccwpck_require__(95129));
+const request_1 = __nccwpck_require__(9647);
+const errors_1 = __nccwpck_require__(13315);
+const http_client_1 = __nccwpck_require__(15683);
+const server_1 = __nccwpck_require__(11035);
+var Pattern;
+(function (Pattern) {
+ Pattern["POST"] = "post";
+ Pattern["GET"] = "get";
+ Pattern["PATCH"] = "patch";
+ Pattern["PUT"] = "put";
+ Pattern["DELETE"] = "delete";
+})(Pattern = exports.Pattern || (exports.Pattern = {}));
+/**
+ * The Gateway proxies http requests to Twirp Compliant
+ * handlers
+ */
+class Gateway {
+ constructor(routes) {
+ this.routes = routes;
+ }
+ /**
+ * Middleware that rewrite the current request
+ * to a Twirp compliant request
+ */
+ twirpRewrite(prefix = "/twirp") {
+ return (req, resp, next) => {
+ this.rewrite(req, resp, prefix)
+ .then(() => next())
+ .catch((e) => {
+ if (e instanceof errors_1.TwirpError) {
+ if (e.code !== errors_1.TwirpErrorCode.NotFound) {
+ server_1.writeError(resp, e);
+ }
+ else {
+ next();
+ }
+ }
+ });
+ };
+ }
+ /**
+ * Rewrite an incoming request to a Twirp compliant request
+ * @param req
+ * @param resp
+ * @param prefix
+ */
+ rewrite(req, resp, prefix = "/twirp") {
+ return __awaiter(this, void 0, void 0, function* () {
+ const [match, route] = this.matchRoute(req);
+ const body = yield this.prepareTwirpBody(req, match, route);
+ const twirpUrl = `${prefix}/${route.packageName}.${route.serviceName}/${route.methodName}`;
+ req.url = twirpUrl;
+ req.originalUrl = twirpUrl;
+ req.method = "POST";
+ req.headers["content-type"] = "application/json";
+ req.rawBody = Buffer.from(JSON.stringify(body));
+ if (route.responseBodyKey) {
+ const endFn = resp.end.bind(resp);
+ resp.end = function (chunk) {
+ if (resp.statusCode === 200) {
+ endFn(`{ "${route.responseBodyKey}": ${chunk} }`);
+ }
+ else {
+ endFn(chunk);
+ }
+ };
+ }
+ });
+ }
+ /**
+ * Create a reverse proxy handler to
+ * proxy http requests to Twirp Compliant handlers
+ * @param httpClientOption
+ */
+ reverseProxy(httpClientOption) {
+ const client = http_client_1.NodeHttpRPC(httpClientOption);
+ return (req, res) => __awaiter(this, void 0, void 0, function* () {
+ try {
+ const [match, route] = this.matchRoute(req);
+ const body = yield this.prepareTwirpBody(req, match, route);
+ const response = yield client.request(`${route.packageName}.${route.serviceName}`, route.methodName, "application/json", body);
+ res.statusCode = 200;
+ res.setHeader("content-type", "application/json");
+ let jsonResponse;
+ if (route.responseBodyKey) {
+ jsonResponse = JSON.stringify({ [route.responseBodyKey]: response });
+ }
+ else {
+ jsonResponse = JSON.stringify(response);
+ }
+ res.end(jsonResponse);
+ }
+ catch (e) {
+ server_1.writeError(res, e);
+ }
+ });
+ }
+ /**
+ * Prepares twirp body requests using http.google.annotions
+ * compliant spec
+ *
+ * @param req
+ * @param match
+ * @param route
+ * @protected
+ */
+ prepareTwirpBody(req, match, route) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const _a = match.params, { query_string } = _a, params = __rest(_a, ["query_string"]);
+ let requestBody = Object.assign({}, params);
+ if (query_string && route.bodyKey !== "*") {
+ const queryParams = this.parseQueryString(query_string);
+ requestBody = Object.assign(Object.assign({}, queryParams), requestBody);
+ }
+ let body = {};
+ if (route.bodyKey) {
+ const data = yield request_1.getRequestData(req);
+ try {
+ const jsonBody = JSON.parse(data.toString() || "{}");
+ if (route.bodyKey === "*") {
+ body = jsonBody;
+ }
+ else {
+ body[route.bodyKey] = jsonBody;
+ }
+ }
+ catch (e) {
+ const msg = "the json request could not be decoded";
+ throw new errors_1.TwirpError(errors_1.TwirpErrorCode.Malformed, msg).withCause(e, true);
+ }
+ }
+ return Object.assign(Object.assign({}, body), requestBody);
+ });
+ }
+ /**
+ * Matches a route
+ * @param req
+ */
+ matchRoute(req) {
+ var _a;
+ const httpMethod = (_a = req.method) === null || _a === void 0 ? void 0 : _a.toLowerCase();
+ if (!httpMethod) {
+ throw new errors_1.BadRouteError(`method not allowed`, req.method || "", req.url || "");
+ }
+ const routes = this.routes[httpMethod];
+ for (const route of routes) {
+ const match = route.matcher(req.url || "/");
+ if (match) {
+ return [match, route];
+ }
+ }
+ throw new errors_1.NotFoundError(`url ${req.url} not found`);
+ }
+ /**
+ * Parse query string
+ * @param queryString
+ */
+ parseQueryString(queryString) {
+ const queryParams = querystring_1.parse(queryString.replace("?", ""));
+ return dotObject.object(queryParams);
+ }
}
+exports.Gateway = Gateway;
-/**
- * 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?
- }
+/***/ 3898:
+/***/ (function(__unused_webpack_module, exports) {
- // 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;
- }
+"use strict";
- return r;
+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.isHook = exports.chainHooks = void 0;
+// ChainHooks creates a new ServerHook which chains the callbacks in
+// each of the constituent hooks passed in. Each hook function will be
+// called in the order of the ServerHooks values passed in.
+//
+// For the erroring hooks, RequestReceived and RequestRouted, any returned
+// errors prevent processing by later hooks.
+function chainHooks(...hooks) {
+ if (hooks.length === 0) {
+ return null;
+ }
+ if (hooks.length === 1) {
+ return hooks[0];
+ }
+ const serverHook = {
+ requestReceived(ctx) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.requestReceived) {
+ continue;
+ }
+ yield hook.requestReceived(ctx);
+ }
+ });
+ },
+ requestPrepared(ctx) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.requestPrepared) {
+ continue;
+ }
+ console.warn("hook requestPrepared is deprecated and will be removed in the next release. " +
+ "Please use responsePrepared instead.");
+ yield hook.requestPrepared(ctx);
+ }
+ });
+ },
+ responsePrepared(ctx) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.responsePrepared) {
+ continue;
+ }
+ yield hook.responsePrepared(ctx);
+ }
+ });
+ },
+ requestSent(ctx) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.requestSent) {
+ continue;
+ }
+ console.warn("hook requestSent is deprecated and will be removed in the next release. " +
+ "Please use responseSent instead.");
+ yield hook.requestSent(ctx);
+ }
+ });
+ },
+ responseSent(ctx) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.responseSent) {
+ continue;
+ }
+ yield hook.responseSent(ctx);
+ }
+ });
+ },
+ requestRouted(ctx) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.requestRouted) {
+ continue;
+ }
+ yield hook.requestRouted(ctx);
+ }
+ });
+ },
+ error(ctx, err) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.error) {
+ continue;
+ }
+ yield hook.error(ctx, err);
+ }
+ });
+ },
+ };
+ return serverHook;
}
-
-/**
- * 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?
- }
+exports.chainHooks = chainHooks;
+function isHook(object) {
+ return ("requestReceived" in object ||
+ "requestPrepared" in object ||
+ "requestSent" in object ||
+ "requestRouted" in object ||
+ "responsePrepared" in object ||
+ "responseSent" in object ||
+ "error" in object);
}
-
-module.exports = __nccwpck_require__(897)(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;
- }
-};
+exports.isHook = isHook;
/***/ }),
-/***/ 897:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 15683:
+/***/ (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.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.FetchRPC = exports.wrapErrorResponseToTwirpError = exports.NodeHttpRPC = void 0;
+const http = __importStar(__nccwpck_require__(58611));
+const https = __importStar(__nccwpck_require__(65692));
+const url_1 = __nccwpck_require__(87016);
+const errors_1 = __nccwpck_require__(13315);
/**
- * This is the common logic for both the Node.js and web browser
- * implementations of `debug()`.
+ * a node HTTP RPC implementation
+ * @param options
+ * @constructor
*/
+const NodeHttpRPC = (options) => ({
+ request(service, method, contentType, data) {
+ let client;
+ return new Promise((resolve, rejected) => {
+ const responseChunks = [];
+ const requestData = contentType === "application/protobuf"
+ ? Buffer.from(data)
+ : JSON.stringify(data);
+ const url = new url_1.URL(options.baseUrl);
+ const isHttps = url.protocol === "https:";
+ if (isHttps) {
+ client = https;
+ }
+ else {
+ client = http;
+ }
+ const prefix = url.pathname !== "/" ? url.pathname : "";
+ const req = client
+ .request(Object.assign(Object.assign({}, (options ? options : {})), { method: "POST", protocol: url.protocol, host: url.hostname, port: url.port ? url.port : isHttps ? 443 : 80, path: `${prefix}/${service}/${method}`, headers: Object.assign(Object.assign({}, (options.headers ? options.headers : {})), { "Content-Type": contentType, "Content-Length": contentType === "application/protobuf"
+ ? Buffer.byteLength(requestData)
+ : Buffer.from(requestData).byteLength }) }), (res) => {
+ res.on("data", (chunk) => responseChunks.push(chunk));
+ res.on("end", () => {
+ const data = Buffer.concat(responseChunks);
+ if (res.statusCode != 200) {
+ rejected(wrapErrorResponseToTwirpError(data.toString()));
+ }
+ else {
+ if (contentType === "application/json") {
+ resolve(JSON.parse(data.toString()));
+ }
+ else {
+ resolve(data);
+ }
+ }
+ });
+ res.on("error", (err) => {
+ rejected(err);
+ });
+ })
+ .on("error", (err) => {
+ rejected(err);
+ });
+ req.end(requestData);
+ });
+ },
+});
+exports.NodeHttpRPC = NodeHttpRPC;
+function wrapErrorResponseToTwirpError(errorResponse) {
+ return errors_1.TwirpError.fromObject(JSON.parse(errorResponse));
+}
+exports.wrapErrorResponseToTwirpError = wrapErrorResponseToTwirpError;
+/**
+ * a browser fetch RPC implementation
+ */
+const FetchRPC = (options) => ({
+ request(service, method, contentType, data) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const headers = new Headers(options.headers);
+ headers.set("content-type", contentType);
+ const response = yield fetch(`${options.baseUrl}/${service}/${method}`, Object.assign(Object.assign({}, options), { method: "POST", headers, body: data instanceof Uint8Array ? data : JSON.stringify(data) }));
+ if (response.status === 200) {
+ if (contentType === "application/json") {
+ return yield response.json();
+ }
+ return new Uint8Array(yield response.arrayBuffer());
+ }
+ throw errors_1.TwirpError.fromObject(yield response.json());
+ });
+ },
+});
+exports.FetchRPC = FetchRPC;
-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__(744);
- 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;
- }
+/***/ 30430:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
- /**
- * 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;
- }
- }
+"use strict";
- for (const ns of createDebug.names) {
- if (matchesTemplate(name, ns)) {
- return true;
- }
- }
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __exportStar = (this && this.__exportStar) || function(m, exports) {
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.TwirpContentType = void 0;
+__exportStar(__nccwpck_require__(45497), exports);
+__exportStar(__nccwpck_require__(11035), exports);
+__exportStar(__nccwpck_require__(84036), exports);
+__exportStar(__nccwpck_require__(3898), exports);
+__exportStar(__nccwpck_require__(13315), exports);
+__exportStar(__nccwpck_require__(69636), exports);
+__exportStar(__nccwpck_require__(15683), exports);
+var request_1 = __nccwpck_require__(9647);
+Object.defineProperty(exports, "TwirpContentType", ({ enumerable: true, get: function () { return request_1.TwirpContentType; } }));
- 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`.');
- }
+/***/ 84036:
+/***/ (function(__unused_webpack_module, exports) {
- createDebug.enable(createDebug.load());
+"use strict";
- return createDebug;
+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.chainInterceptors = void 0;
+// chains multiple Interceptors into a single Interceptor.
+// The first interceptor wraps the second one, and so on.
+// Returns null if interceptors is empty.
+function chainInterceptors(...interceptors) {
+ if (interceptors.length === 0) {
+ return;
+ }
+ if (interceptors.length === 1) {
+ return interceptors[0];
+ }
+ const first = interceptors[0];
+ return (ctx, request, handler) => __awaiter(this, void 0, void 0, function* () {
+ let next = handler;
+ for (let i = interceptors.length - 1; i > 0; i--) {
+ next = ((next) => (ctx, typedRequest) => {
+ return interceptors[i](ctx, typedRequest, next);
+ })(next);
+ }
+ return first(ctx, request, next);
+ });
}
-
-module.exports = setup;
+exports.chainInterceptors = chainInterceptors;
/***/ }),
-/***/ 2830:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 9647:
+/***/ (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.parseTwirpPath = exports.getRequestData = exports.validateRequest = exports.getContentType = exports.TwirpContentType = void 0;
+const errors_1 = __nccwpck_require__(13315);
/**
- * Detect Electron renderer / nwjs process, which is node, but we should
- * treat as a browser.
+ * Supported Twirp Content-Type
*/
-
-if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
- module.exports = __nccwpck_require__(6110);
-} else {
- module.exports = __nccwpck_require__(5108);
+var TwirpContentType;
+(function (TwirpContentType) {
+ TwirpContentType[TwirpContentType["Protobuf"] = 0] = "Protobuf";
+ TwirpContentType[TwirpContentType["JSON"] = 1] = "JSON";
+ TwirpContentType[TwirpContentType["Unknown"] = 2] = "Unknown";
+})(TwirpContentType = exports.TwirpContentType || (exports.TwirpContentType = {}));
+/**
+ * Get supported content-type
+ * @param mimeType
+ */
+function getContentType(mimeType) {
+ switch (mimeType) {
+ case "application/protobuf":
+ return TwirpContentType.Protobuf;
+ case "application/json":
+ return TwirpContentType.JSON;
+ default:
+ return TwirpContentType.Unknown;
+ }
}
-
-
-/***/ }),
-
-/***/ 5108:
-/***/ ((module, exports, __nccwpck_require__) => {
-
+exports.getContentType = getContentType;
/**
- * Module dependencies.
+ * Validate a twirp request
+ * @param ctx
+ * @param request
+ * @param pathPrefix
*/
-
-const tty = __nccwpck_require__(2018);
-const util = __nccwpck_require__(9023);
-
+function validateRequest(ctx, request, pathPrefix) {
+ if (request.method !== "POST") {
+ const msg = `unsupported method ${request.method} (only POST is allowed)`;
+ throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
+ }
+ const path = parseTwirpPath(request.url || "");
+ if (path.pkgService !==
+ (ctx.packageName ? ctx.packageName + "." : "") + ctx.serviceName) {
+ const msg = `no handler for path ${request.url}`;
+ throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
+ }
+ if (path.prefix !== pathPrefix) {
+ const msg = `invalid path prefix ${path.prefix}, expected ${pathPrefix}, on path ${request.url}`;
+ throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
+ }
+ const mimeContentType = request.headers["content-type"] || "";
+ if (ctx.contentType === TwirpContentType.Unknown) {
+ const msg = `unexpected Content-Type: ${request.headers["content-type"]}`;
+ throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
+ }
+ return Object.assign(Object.assign({}, path), { mimeContentType, contentType: ctx.contentType });
+}
+exports.validateRequest = validateRequest;
/**
- * This is the Node.js implementation of `debug()`.
+ * Get request data from the body
+ * @param req
*/
-
-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`.'
-);
-
+function getRequestData(req) {
+ return new Promise((resolve, reject) => {
+ const reqWithRawBody = req;
+ if (reqWithRawBody.rawBody instanceof Buffer) {
+ resolve(reqWithRawBody.rawBody);
+ return;
+ }
+ const chunks = [];
+ req.on("data", (chunk) => chunks.push(chunk));
+ req.on("end", () => __awaiter(this, void 0, void 0, function* () {
+ const data = Buffer.concat(chunks);
+ resolve(data);
+ }));
+ req.on("error", (err) => {
+ if (req.aborted) {
+ reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.DeadlineExceeded, "failed to read request: deadline exceeded"));
+ }
+ else {
+ reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.Malformed, err.message).withCause(err));
+ }
+ });
+ req.on("close", () => {
+ reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.Canceled, "failed to read request: context canceled"));
+ });
+ });
+}
+exports.getRequestData = getRequestData;
/**
- * Colors.
+ * Parses twirp url path
+ * @param path
*/
+function parseTwirpPath(path) {
+ const parts = path.split("/");
+ if (parts.length < 2) {
+ return {
+ pkgService: "",
+ method: "",
+ prefix: "",
+ };
+ }
+ return {
+ method: parts[parts.length - 1],
+ pkgService: parts[parts.length - 2],
+ prefix: parts.slice(0, parts.length - 2).join("/"),
+ };
+}
+exports.parseTwirpPath = parseTwirpPath;
-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__(75);
+/***/ }),
- 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.
+/***/ 11035:
+/***/ (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.writeError = exports.TwirpServer = void 0;
+const hooks_1 = __nccwpck_require__(3898);
+const request_1 = __nccwpck_require__(9647);
+const errors_1 = __nccwpck_require__(13315);
+/**
+ * Runtime server implementation of a TwirpServer
+ */
+class TwirpServer {
+ constructor(options) {
+ this.pathPrefix = "/twirp";
+ this.hooks = [];
+ this.interceptors = [];
+ this.packageName = options.packageName;
+ this.serviceName = options.serviceName;
+ this.methodList = options.methodList;
+ this.matchRoute = options.matchRoute;
+ this.service = options.service;
+ }
+ /**
+ * Returns the prefix for this server
+ */
+ get prefix() {
+ return this.pathPrefix;
+ }
+ /**
+ * The http handler for twirp complaint endpoints
+ * @param options
+ */
+ httpHandler(options) {
+ return (req, resp) => {
+ // setup prefix
+ if ((options === null || options === void 0 ? void 0 : options.prefix) !== undefined) {
+ this.withPrefix(options.prefix);
+ }
+ return this._httpHandler(req, resp);
+ };
+ }
+ /**
+ * Adds interceptors or hooks to the request stack
+ * @param middlewares
+ */
+ use(...middlewares) {
+ middlewares.forEach((middleware) => {
+ if (hooks_1.isHook(middleware)) {
+ this.hooks.push(middleware);
+ return this;
+ }
+ this.interceptors.push(middleware);
+ });
+ return this;
+ }
+ /**
+ * Adds a prefix to the service url path
+ * @param prefix
+ */
+ withPrefix(prefix) {
+ if (prefix === false) {
+ this.pathPrefix = "";
+ }
+ else {
+ this.pathPrefix = prefix;
+ }
+ return this;
+ }
+ /**
+ * Returns the regex matching path for this twirp server
+ */
+ matchingPath() {
+ const baseRegex = this.baseURI().replace(/\./g, "\\.");
+ return new RegExp(`${baseRegex}\/(${this.methodList.join("|")})`);
+ }
+ /**
+ * Returns the base URI for this twirp server
+ */
+ baseURI() {
+ return `${this.pathPrefix}/${this.packageName ? this.packageName + "." : ""}${this.serviceName}`;
+ }
+ /**
+ * Create a twirp context
+ * @param req
+ * @param res
+ * @private
+ */
+ createContext(req, res) {
+ return {
+ packageName: this.packageName,
+ serviceName: this.serviceName,
+ methodName: "",
+ contentType: request_1.getContentType(req.headers["content-type"]),
+ req: req,
+ res: res,
+ };
+ }
+ /**
+ * Twrip server http handler implementation
+ * @param req
+ * @param resp
+ * @private
+ */
+ _httpHandler(req, resp) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const ctx = this.createContext(req, resp);
+ try {
+ yield this.invokeHook("requestReceived", ctx);
+ const { method, mimeContentType } = request_1.validateRequest(ctx, req, this.pathPrefix || "");
+ const handler = this.matchRoute(method, {
+ onMatch: (ctx) => {
+ return this.invokeHook("requestRouted", ctx);
+ },
+ onNotFound: () => {
+ const msg = `no handler for path ${req.url}`;
+ throw new errors_1.BadRouteError(msg, req.method || "", req.url || "");
+ },
+ });
+ const body = yield request_1.getRequestData(req);
+ const response = yield handler(ctx, this.service, body, this.interceptors);
+ yield Promise.all([
+ this.invokeHook("responsePrepared", ctx),
+ // keep backwards compatibility till next release
+ this.invokeHook("requestPrepared", ctx),
+ ]);
+ resp.statusCode = 200;
+ resp.setHeader("Content-Type", mimeContentType);
+ resp.end(response);
+ }
+ catch (e) {
+ yield this.invokeHook("error", ctx, mustBeTwirpError(e));
+ if (!resp.headersSent) {
+ writeError(resp, e);
+ }
+ }
+ finally {
+ yield Promise.all([
+ this.invokeHook("responseSent", ctx),
+ // keep backwards compatibility till next release
+ this.invokeHook("requestSent", ctx),
+ ]);
+ }
+ });
+ }
+ /**
+ * Invoke a hook
+ * @param hookName
+ * @param ctx
+ * @param err
+ * @protected
+ */
+ invokeHook(hookName, ctx, err) {
+ return __awaiter(this, void 0, void 0, function* () {
+ if (this.hooks.length === 0) {
+ return;
+ }
+ const chainedHooks = hooks_1.chainHooks(...this.hooks);
+ const hook = chainedHooks === null || chainedHooks === void 0 ? void 0 : chainedHooks[hookName];
+ if (hook) {
+ yield hook(ctx, err || new errors_1.InternalServerError("internal server error"));
+ }
+ });
+ }
}
-
-/**
- * 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;
-}, {});
-
+exports.TwirpServer = TwirpServer;
/**
- * Is stdout a TTY? Colored output is enabled when `true`.
+ * Write http error response
+ * @param res
+ * @param error
*/
-
-function useColors() {
- return 'colors' in exports.inspectOpts ?
- Boolean(exports.inspectOpts.colors) :
- tty.isatty(process.stderr.fd);
+function writeError(res, error) {
+ const twirpError = mustBeTwirpError(error);
+ res.setHeader("Content-Type", "application/json");
+ res.statusCode = errors_1.httpStatusFromErrorCode(twirpError.code);
+ res.end(twirpError.toJSON());
}
-
+exports.writeError = writeError;
/**
- * Adds ANSI color escape codes if enabled.
- *
- * @api public
+ * Make sure that the error passed is a TwirpError
+ * otherwise it will wrap it into an InternalError
+ * @param err
*/
-
-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() + ' ';
+function mustBeTwirpError(err) {
+ if (err instanceof errors_1.TwirpError) {
+ return err;
+ }
+ return new errors_1.InternalServerErrorWith(err);
}
-/**
- * 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
- */
+/***/ 46752:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-function load() {
- return process.env.DEBUG;
-}
+"use strict";
-/**
- * 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 Client = __nccwpck_require__(86197)
+const Dispatcher = __nccwpck_require__(28611)
+const errors = __nccwpck_require__(68707)
+const Pool = __nccwpck_require__(35076)
+const BalancedPool = __nccwpck_require__(81093)
+const Agent = __nccwpck_require__(59965)
+const util = __nccwpck_require__(3440)
+const { InvalidArgumentError } = errors
+const api = __nccwpck_require__(56615)
+const buildConnector = __nccwpck_require__(59136)
+const MockClient = __nccwpck_require__(47365)
+const MockAgent = __nccwpck_require__(47501)
+const MockPool = __nccwpck_require__(94004)
+const mockErrors = __nccwpck_require__(52429)
+const ProxyAgent = __nccwpck_require__(22720)
+const RetryHandler = __nccwpck_require__(53573)
+const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(32581)
+const DecoratorHandler = __nccwpck_require__(78840)
+const RedirectHandler = __nccwpck_require__(48299)
+const createRedirectInterceptor = __nccwpck_require__(64415)
- const keys = Object.keys(exports.inspectOpts);
- for (let i = 0; i < keys.length; i++) {
- debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
- }
+let hasCrypto
+try {
+ __nccwpck_require__(76982)
+ hasCrypto = true
+} catch {
+ hasCrypto = false
}
-module.exports = __nccwpck_require__(897)(exports);
+Object.assign(Dispatcher.prototype, api)
-const {formatters} = module.exports;
+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.RetryHandler = RetryHandler
-/**
- * Map %o to `util.inspect()`, all on a single line.
- */
+module.exports.DecoratorHandler = DecoratorHandler
+module.exports.RedirectHandler = RedirectHandler
+module.exports.createRedirectInterceptor = createRedirectInterceptor
-formatters.o = function (v) {
- this.inspectOpts.colors = this.useColors;
- return util.inspect(v, this.inspectOpts)
- .split('\n')
- .map(str => str.trim())
- .join(' ');
-};
+module.exports.buildConnector = buildConnector
+module.exports.errors = errors
-/**
- * Map %O to `util.inspect()`, allowing multiple lines if needed.
- */
+function makeDispatcher (fn) {
+ return (url, opts, handler) => {
+ if (typeof opts === 'function') {
+ handler = opts
+ opts = null
+ }
-formatters.O = function (v) {
- this.inspectOpts.colors = this.useColors;
- return util.inspect(v, this.inspectOpts);
-};
+ 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')
+ }
-/***/ 5129:
-/***/ ((module) => {
+ let path = opts.path
+ if (!opts.path.startsWith('/')) {
+ path = `/${path}`
+ }
-"use strict";
+ url = new URL(util.parseOrigin(url).origin + path)
+ } else {
+ if (!opts) {
+ opts = typeof url === 'object' ? url : {}
+ }
+ url = util.parseURL(url)
+ }
-function _process (v, mod) {
- var i
- var r
+ const { agent, dispatcher = getGlobalDispatcher() } = opts
- if (typeof mod === 'function') {
- r = mod(v)
- if (r !== undefined) {
- v = r
- }
- } else if (Array.isArray(mod)) {
- for (i = 0; i < mod.length; i++) {
- r = mod[i](v)
- if (r !== undefined) {
- v = r
- }
+ if (agent) {
+ throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?')
}
- }
-
- return v
-}
-function parseKey (key, val) {
- // detect negative index notation
- if (key[0] === '-' && Array.isArray(val) && /^-\d+$/.test(key)) {
- return val.length + parseInt(key, 10)
+ 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)
}
- return key
-}
-
-function isIndex (k) {
- return /^\d+$/.test(k)
-}
-
-function isObject (val) {
- return Object.prototype.toString.call(val) === '[object Object]'
}
-function isArrayOrObject (val) {
- return Object(val) === val
-}
+module.exports.setGlobalDispatcher = setGlobalDispatcher
+module.exports.getGlobalDispatcher = getGlobalDispatcher
-function isEmptyObject (val) {
- return Object.keys(val).length === 0
-}
+if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) {
+ let fetchImpl = null
+ module.exports.fetch = async function fetch (resource) {
+ if (!fetchImpl) {
+ fetchImpl = (__nccwpck_require__(12315).fetch)
+ }
-var blacklist = ['__proto__', 'prototype', 'constructor']
-var blacklistFilter = function (part) { return blacklist.indexOf(part) === -1 }
+ try {
+ return await fetchImpl(...arguments)
+ } catch (err) {
+ if (typeof err === 'object') {
+ Error.captureStackTrace(err, this)
+ }
-function parsePath (path, sep) {
- if (path.indexOf('[') >= 0) {
- path = path.replace(/\[/g, sep).replace(/]/g, '')
+ throw err
+ }
}
+ module.exports.Headers = __nccwpck_require__(26349).Headers
+ module.exports.Response = __nccwpck_require__(48676).Response
+ module.exports.Request = __nccwpck_require__(25194).Request
+ module.exports.FormData = __nccwpck_require__(43073).FormData
+ module.exports.File = __nccwpck_require__(63041).File
+ module.exports.FileReader = __nccwpck_require__(82160).FileReader
- var parts = path.split(sep)
+ const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(75628)
- var check = parts.filter(blacklistFilter)
+ module.exports.setGlobalOrigin = setGlobalOrigin
+ module.exports.getGlobalOrigin = getGlobalOrigin
- if (check.length !== parts.length) {
- throw Error('Refusing to update blacklisted property ' + path)
- }
+ const { CacheStorage } = __nccwpck_require__(44738)
+ const { kConstruct } = __nccwpck_require__(80296)
- return parts
+ // 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)
}
-var hasOwnProperty = Object.prototype.hasOwnProperty
+if (util.nodeMajor >= 16) {
+ const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(53168)
-function DotObject (separator, override, useArray, useBrackets) {
- if (!(this instanceof DotObject)) {
- return new DotObject(separator, override, useArray, useBrackets)
- }
+ module.exports.deleteCookie = deleteCookie
+ module.exports.getCookies = getCookies
+ module.exports.getSetCookies = getSetCookies
+ module.exports.setCookie = setCookie
- if (typeof override === 'undefined') override = false
- if (typeof useArray === 'undefined') useArray = true
- if (typeof useBrackets === 'undefined') useBrackets = true
- this.separator = separator || '.'
- this.override = override
- this.useArray = useArray
- this.useBrackets = useBrackets
- this.keepArray = false
+ const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(94322)
- // contains touched arrays
- this.cleanup = []
+ module.exports.parseMIMEType = parseMIMEType
+ module.exports.serializeAMimeType = serializeAMimeType
}
-var dotDefault = new DotObject('.', false, true, true)
-function wrap (method) {
- return function () {
- return dotDefault[method].apply(dotDefault, arguments)
- }
-}
+if (util.nodeMajor >= 18 && hasCrypto) {
+ const { WebSocket } = __nccwpck_require__(55171)
-DotObject.prototype._fill = function (a, obj, v, mod) {
- var k = a.shift()
+ module.exports.WebSocket = WebSocket
+}
- if (a.length > 0) {
- obj[k] = obj[k] || (this.useArray && isIndex(a[0]) ? [] : {})
+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)
- if (!isArrayOrObject(obj[k])) {
- if (this.override) {
- obj[k] = {}
- } else {
- if (!(isArrayOrObject(v) && isEmptyObject(v))) {
- throw new Error(
- 'Trying to redefine `' + k + '` which is a ' + typeof obj[k]
- )
- }
+module.exports.MockClient = MockClient
+module.exports.MockPool = MockPool
+module.exports.MockAgent = MockAgent
+module.exports.mockErrors = mockErrors
- return
- }
- }
- this._fill(a, obj[k], v, mod)
- } else {
- if (!this.override && isArrayOrObject(obj[k]) && !isEmptyObject(obj[k])) {
- if (!(isArrayOrObject(v) && isEmptyObject(v))) {
- throw new Error("Trying to redefine non-empty obj['" + k + "']")
- }
+/***/ }),
- return
- }
+/***/ 59965:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- obj[k] = _process(v, mod)
- }
-}
+"use strict";
-/**
- *
- * Converts an object with dotted-key/value pairs to it's expanded version
- *
- * Optionally transformed by a set of modifiers.
- *
- * Usage:
- *
- * var row = {
- * 'nr': 200,
- * 'doc.name': ' My Document '
- * }
- *
- * var mods = {
- * 'doc.name': [_s.trim, _s.underscored]
- * }
- *
- * dot.object(row, mods)
- *
- * @param {Object} obj
- * @param {Object} mods
- */
-DotObject.prototype.object = function (obj, mods) {
- var self = this
- Object.keys(obj).forEach(function (k) {
- var mod = mods === undefined ? null : mods[k]
- // normalize array notation.
- var ok = parsePath(k, self.separator).join(self.separator)
+const { InvalidArgumentError } = __nccwpck_require__(68707)
+const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(36443)
+const DispatcherBase = __nccwpck_require__(50001)
+const Pool = __nccwpck_require__(35076)
+const Client = __nccwpck_require__(86197)
+const util = __nccwpck_require__(3440)
+const createRedirectInterceptor = __nccwpck_require__(64415)
+const { WeakRef, FinalizationRegistry } = __nccwpck_require__(13194)()
- if (ok.indexOf(self.separator) !== -1) {
- self._fill(ok.split(self.separator), obj, obj[k], mod)
- delete obj[k]
- } else {
- obj[k] = _process(obj[k], mod)
- }
- })
+const kOnConnect = Symbol('onConnect')
+const kOnDisconnect = Symbol('onDisconnect')
+const kOnConnectionError = Symbol('onConnectionError')
+const kMaxRedirections = Symbol('maxRedirections')
+const kOnDrain = Symbol('onDrain')
+const kFactory = Symbol('factory')
+const kFinalizer = Symbol('finalizer')
+const kOptions = Symbol('options')
- return obj
+function defaultFactory (origin, opts) {
+ return opts && opts.connections === 1
+ ? new Client(origin, opts)
+ : new Pool(origin, opts)
}
-/**
- * @param {String} path dotted path
- * @param {String} v value to be set
- * @param {Object} obj object to be modified
- * @param {Function|Array} mod optional modifier
- */
-DotObject.prototype.str = function (path, v, obj, mod) {
- var ok = parsePath(path, this.separator).join(this.separator)
+class Agent extends DispatcherBase {
+ constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {
+ super()
- if (path.indexOf(this.separator) !== -1) {
- this._fill(ok.split(this.separator), obj, v, mod)
- } else {
- obj[path] = _process(v, mod)
- }
+ if (typeof factory !== 'function') {
+ throw new InvalidArgumentError('factory must be a function.')
+ }
- return obj
-}
+ if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
+ throw new InvalidArgumentError('connect must be a function or an object')
+ }
-/**
- *
- * Pick a value from an object using dot notation.
- *
- * Optionally remove the value
- *
- * @param {String} path
- * @param {Object} obj
- * @param {Boolean} remove
- */
-DotObject.prototype.pick = function (path, obj, remove, reindexArray) {
- var i
- var keys
- var val
- var key
- var cp
+ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) {
+ throw new InvalidArgumentError('maxRedirections must be a positive number')
+ }
- keys = parsePath(path, this.separator)
- for (i = 0; i < keys.length; i++) {
- key = parseKey(keys[i], obj)
- if (obj && typeof obj === 'object' && key in obj) {
- if (i === keys.length - 1) {
- if (remove) {
- val = obj[key]
- if (reindexArray && Array.isArray(obj)) {
- obj.splice(key, 1)
- } else {
- delete obj[key]
- }
- if (Array.isArray(obj)) {
- cp = keys.slice(0, -1).join('.')
- if (this.cleanup.indexOf(cp) === -1) {
- this.cleanup.push(cp)
- }
- }
- return val
- } else {
- return obj[key]
- }
- } else {
- obj = obj[key]
+ if (connect && typeof connect !== 'function') {
+ connect = { ...connect }
+ }
+
+ this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent)
+ ? options.interceptors.Agent
+ : [createRedirectInterceptor({ maxRedirections })]
+
+ this[kOptions] = { ...util.deepClone(options), connect }
+ this[kOptions].interceptors = options.interceptors
+ ? { ...options.interceptors }
+ : undefined
+ this[kMaxRedirections] = maxRedirections
+ this[kFactory] = factory
+ this[kClients] = new Map()
+ this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => {
+ const ref = this[kClients].get(key)
+ if (ref !== undefined && ref.deref() === undefined) {
+ this[kClients].delete(key)
}
- } else {
- return undefined
+ })
+
+ const agent = this
+
+ this[kOnDrain] = (origin, targets) => {
+ agent.emit('drain', origin, [agent, ...targets])
+ }
+
+ this[kOnConnect] = (origin, targets) => {
+ agent.emit('connect', origin, [agent, ...targets])
+ }
+
+ this[kOnDisconnect] = (origin, targets, err) => {
+ agent.emit('disconnect', origin, [agent, ...targets], err)
+ }
+
+ this[kOnConnectionError] = (origin, targets, err) => {
+ agent.emit('connectionError', origin, [agent, ...targets], err)
}
}
- if (remove && Array.isArray(obj)) {
- obj = obj.filter(function (n) {
- return n !== undefined
- })
+
+ get [kRunning] () {
+ let ret = 0
+ for (const ref of this[kClients].values()) {
+ const client = ref.deref()
+ /* istanbul ignore next: gc is undeterministic */
+ if (client) {
+ ret += client[kRunning]
+ }
+ }
+ return ret
}
- return obj
-}
-/**
- *
- * Delete value from an object using dot notation.
- *
- * @param {String} path
- * @param {Object} obj
- * @return {any} The removed value
- */
-DotObject.prototype.delete = function (path, obj) {
- return this.remove(path, obj, true)
-}
-/**
- *
- * Remove value from an object using dot notation.
- *
- * Will remove multiple items if path is an array.
- * In this case array indexes will be retained until all
- * removals have been processed.
- *
- * Use dot.delete() to automatically re-index arrays.
- *
- * @param {String|Array} path
- * @param {Object} obj
- * @param {Boolean} reindexArray
- * @return {any} The removed value
- */
-DotObject.prototype.remove = function (path, obj, reindexArray) {
- var i
+ [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.')
+ }
- this.cleanup = []
- if (Array.isArray(path)) {
- for (i = 0; i < path.length; i++) {
- this.pick(path[i], obj, true, reindexArray)
+ const ref = this[kClients].get(key)
+
+ let dispatcher = ref ? ref.deref() : null
+ 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, new WeakRef(dispatcher))
+ this[kFinalizer].register(dispatcher, key)
}
- if (!reindexArray) {
- this._cleanup(obj)
+
+ return dispatcher.dispatch(opts, handler)
+ }
+
+ async [kClose] () {
+ const closePromises = []
+ for (const ref of this[kClients].values()) {
+ const client = ref.deref()
+ /* istanbul ignore else: gc is undeterministic */
+ if (client) {
+ closePromises.push(client.close())
+ }
}
- return obj
- } else {
- return this.pick(path, obj, true, reindexArray)
+
+ await Promise.all(closePromises)
}
-}
-DotObject.prototype._cleanup = function (obj) {
- var ret
- var i
- var keys
- var root
- if (this.cleanup.length) {
- for (i = 0; i < this.cleanup.length; i++) {
- keys = this.cleanup[i].split('.')
- root = keys.splice(0, -1).join('.')
- ret = root ? this.pick(root, obj) : obj
- ret = ret[keys[0]].filter(function (v) {
- return v !== undefined
- })
- this.set(this.cleanup[i], ret, obj)
+ async [kDestroy] (err) {
+ const destroyPromises = []
+ for (const ref of this[kClients].values()) {
+ const client = ref.deref()
+ /* istanbul ignore else: gc is undeterministic */
+ if (client) {
+ destroyPromises.push(client.destroy(err))
+ }
}
- this.cleanup = []
+
+ await Promise.all(destroyPromises)
}
}
-/**
- * Alias method for `dot.remove`
- *
- * Note: this is not an alias for dot.delete()
- *
- * @param {String|Array} path
- * @param {Object} obj
- * @param {Boolean} reindexArray
- * @return {any} The removed value
- */
-DotObject.prototype.del = DotObject.prototype.remove
+module.exports = Agent
-/**
- *
- * Move a property from one place to the other.
- *
- * If the source path does not exist (undefined)
- * the target property will not be set.
- *
- * @param {String} source
- * @param {String} target
- * @param {Object} obj
- * @param {Function|Array} mods
- * @param {Boolean} merge
- */
-DotObject.prototype.move = function (source, target, obj, mods, merge) {
- if (typeof mods === 'function' || Array.isArray(mods)) {
- this.set(target, _process(this.pick(source, obj, true), mods), obj, merge)
+
+/***/ }),
+
+/***/ 80158:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+const { addAbortListener } = __nccwpck_require__(3440)
+const { RequestAbortedError } = __nccwpck_require__(68707)
+
+const kListener = Symbol('kListener')
+const kSignal = Symbol('kSignal')
+
+function abort (self) {
+ if (self.abort) {
+ self.abort()
} else {
- merge = mods
- this.set(target, this.pick(source, obj, true), obj, merge)
+ self.onError(new RequestAbortedError())
}
-
- return obj
}
-/**
- *
- * Transfer a property from one object to another object.
- *
- * If the source path does not exist (undefined)
- * the property on the other object will not be set.
- *
- * @param {String} source
- * @param {String} target
- * @param {Object} obj1
- * @param {Object} obj2
- * @param {Function|Array} mods
- * @param {Boolean} merge
- */
-DotObject.prototype.transfer = function (
- source,
- target,
- obj1,
- obj2,
- mods,
- merge
-) {
- if (typeof mods === 'function' || Array.isArray(mods)) {
- this.set(
- target,
- _process(this.pick(source, obj1, true), mods),
- obj2,
- merge
- )
- } else {
- merge = mods
- this.set(target, this.pick(source, obj1, true), obj2, merge)
+function addSignal (self, signal) {
+ self[kSignal] = null
+ self[kListener] = null
+
+ if (!signal) {
+ return
}
- return obj2
-}
+ if (signal.aborted) {
+ abort(self)
+ return
+ }
-/**
- *
- * Copy a property from one object to another object.
- *
- * If the source path does not exist (undefined)
- * the property on the other object will not be set.
- *
- * @param {String} source
- * @param {String} target
- * @param {Object} obj1
- * @param {Object} obj2
- * @param {Function|Array} mods
- * @param {Boolean} merge
- */
-DotObject.prototype.copy = function (source, target, obj1, obj2, mods, merge) {
- if (typeof mods === 'function' || Array.isArray(mods)) {
- this.set(
- target,
- _process(
- // clone what is picked
- JSON.parse(JSON.stringify(this.pick(source, obj1, false))),
- mods
- ),
- obj2,
- merge
- )
- } else {
- merge = mods
- this.set(target, this.pick(source, obj1, false), obj2, merge)
+ self[kSignal] = signal
+ self[kListener] = () => {
+ abort(self)
}
- return obj2
+ addAbortListener(self[kSignal], self[kListener])
}
-/**
- *
- * Set a property on an object using dot notation.
- *
- * @param {String} path
- * @param {any} val
- * @param {Object} obj
- * @param {Boolean} merge
- */
-DotObject.prototype.set = function (path, val, obj, merge) {
- var i
- var k
- var keys
- var key
-
- // Do not operate if the value is undefined.
- if (typeof val === 'undefined') {
- return obj
+function removeSignal (self) {
+ if (!self[kSignal]) {
+ return
}
- keys = parsePath(path, this.separator)
- for (i = 0; i < keys.length; i++) {
- key = keys[i]
- if (i === keys.length - 1) {
- if (merge && isObject(val) && isObject(obj[key])) {
- for (k in val) {
- if (hasOwnProperty.call(val, k)) {
- obj[key][k] = val[k]
- }
- }
- } else if (merge && Array.isArray(obj[key]) && Array.isArray(val)) {
- for (var j = 0; j < val.length; j++) {
- obj[keys[i]].push(val[j])
- }
- } else {
- obj[key] = val
- }
- } else if (
- // force the value to be an object
- !hasOwnProperty.call(obj, key) ||
- (!isObject(obj[key]) && !Array.isArray(obj[key]))
- ) {
- // initialize as array if next key is numeric
- if (/^\d+$/.test(keys[i + 1])) {
- obj[key] = []
- } else {
- obj[key] = {}
- }
- }
- obj = obj[key]
+ if ('removeEventListener' in self[kSignal]) {
+ self[kSignal].removeEventListener('abort', self[kListener])
+ } else {
+ self[kSignal].removeListener('abort', self[kListener])
}
- return obj
+
+ self[kSignal] = null
+ self[kListener] = null
}
-/**
- *
- * Transform an object
- *
- * Usage:
- *
- * var obj = {
- * "id": 1,
- * "some": {
- * "thing": "else"
- * }
- * }
- *
- * var transform = {
- * "id": "nr",
- * "some.thing": "name"
- * }
- *
- * var tgt = dot.transform(transform, obj)
- *
- * @param {Object} recipe Transform recipe
- * @param {Object} obj Object to be transformed
- * @param {Array} mods modifiers for the target
- */
-DotObject.prototype.transform = function (recipe, obj, tgt) {
- obj = obj || {}
- tgt = tgt || {}
- Object.keys(recipe).forEach(
- function (key) {
- this.set(recipe[key], this.pick(key, obj), tgt)
- }.bind(this)
- )
- return tgt
+module.exports = {
+ addSignal,
+ removeSignal
}
-/**
- *
- * Convert object to dotted-key/value pair
- *
- * Usage:
- *
- * var tgt = dot.dot(obj)
- *
- * or
- *
- * var tgt = {}
- * dot.dot(obj, tgt)
- *
- * @param {Object} obj source object
- * @param {Object} tgt target object
- * @param {Array} path path array (internal)
- */
-DotObject.prototype.dot = function (obj, tgt, path) {
- tgt = tgt || {}
- path = path || []
- var isArray = Array.isArray(obj)
- Object.keys(obj).forEach(
- function (key) {
- var index = isArray && this.useBrackets ? '[' + key + ']' : key
- if (
- isArrayOrObject(obj[key]) &&
- ((isObject(obj[key]) && !isEmptyObject(obj[key])) ||
- (Array.isArray(obj[key]) && !this.keepArray && obj[key].length !== 0))
- ) {
- if (isArray && this.useBrackets) {
- var previousKey = path[path.length - 1] || ''
- return this.dot(
- obj[key],
- tgt,
- path.slice(0, -1).concat(previousKey + index)
- )
- } else {
- return this.dot(obj[key], tgt, path.concat(index))
- }
- } else {
- if (isArray && this.useBrackets) {
- tgt[path.join(this.separator).concat('[' + key + ']')] = obj[key]
- } else {
- tgt[path.concat(index).join(this.separator)] = obj[key]
- }
- }
- }.bind(this)
- )
- return tgt
-}
+/***/ }),
-DotObject.pick = wrap('pick')
-DotObject.move = wrap('move')
-DotObject.transfer = wrap('transfer')
-DotObject.transform = wrap('transform')
-DotObject.copy = wrap('copy')
-DotObject.object = wrap('object')
-DotObject.str = wrap('str')
-DotObject.set = wrap('set')
-DotObject.delete = wrap('delete')
-DotObject.del = DotObject.remove = wrap('remove')
-DotObject.dot = wrap('dot');
-['override', 'overwrite'].forEach(function (prop) {
- Object.defineProperty(DotObject, prop, {
- get: function () {
- return dotDefault.override
- },
- set: function (val) {
- dotDefault.override = !!val
+/***/ 34660:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+const { AsyncResource } = __nccwpck_require__(90290)
+const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(68707)
+const util = __nccwpck_require__(3440)
+const { addSignal, removeSignal } = __nccwpck_require__(80158)
+
+class ConnectHandler extends AsyncResource {
+ constructor (opts, callback) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
}
- })
-});
-['useArray', 'keepArray', 'useBrackets'].forEach(function (prop) {
- Object.defineProperty(DotObject, prop, {
- get: function () {
- return dotDefault[prop]
- },
- set: function (val) {
- dotDefault[prop] = val
+
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
}
- })
-})
-DotObject._process = _process
+ const { signal, opaque, responseHeaders } = opts
-module.exports = DotObject
+ 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
-/***/ 9741:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ addSignal(this, signal)
+ }
-"use strict";
+ onConnect (abort, context) {
+ if (!this.callback) {
+ throw new RequestAbortedError()
+ }
+ this.abort = abort
+ this.context = context
+ }
-const validator = __nccwpck_require__(9433);
-const XMLParser = __nccwpck_require__(9844);
-const XMLBuilder = __nccwpck_require__(659);
+ onHeaders () {
+ throw new SocketError('bad connect', null)
+ }
-module.exports = {
- XMLParser: XMLParser,
- XMLValidator: validator,
- XMLBuilder: XMLBuilder
+ 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 })
+ })
+ }
+ }
}
-/***/ }),
-
-/***/ 812:
-/***/ ((module) => {
+function connect (opts, callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ connect.call(this, opts, (err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
+ }
-function getIgnoreAttributesFn(ignoreAttributes) {
- if (typeof ignoreAttributes === 'function') {
- return ignoreAttributes
- }
- if (Array.isArray(ignoreAttributes)) {
- return (attrName) => {
- for (const pattern of ignoreAttributes) {
- if (typeof pattern === 'string' && attrName === pattern) {
- return true
- }
- if (pattern instanceof RegExp && pattern.test(attrName)) {
- return true
- }
- }
- }
+ try {
+ const connectHandler = new ConnectHandler(opts, callback)
+ this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler)
+ } catch (err) {
+ if (typeof callback !== 'function') {
+ throw err
}
- return () => false
+ const opaque = opts && opts.opaque
+ queueMicrotask(() => callback(err, { opaque }))
+ }
}
-module.exports = getIgnoreAttributesFn
+module.exports = connect
+
/***/ }),
-/***/ 7019:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 76862:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-const nameStartChar = ':A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD';
-const nameChar = nameStartChar + '\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040';
-const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*'
-const regexName = new RegExp('^' + nameRegexp + '$');
+const {
+ Readable,
+ Duplex,
+ PassThrough
+} = __nccwpck_require__(2203)
+const {
+ InvalidArgumentError,
+ InvalidReturnValueError,
+ RequestAbortedError
+} = __nccwpck_require__(68707)
+const util = __nccwpck_require__(3440)
+const { AsyncResource } = __nccwpck_require__(90290)
+const { addSignal, removeSignal } = __nccwpck_require__(80158)
+const assert = __nccwpck_require__(42613)
-const getAllMatches = function(string, regex) {
- const matches = [];
- let match = regex.exec(string);
- while (match) {
- const allmatches = [];
- allmatches.startIndex = regex.lastIndex - match[0].length;
- const len = match.length;
- for (let index = 0; index < len; index++) {
- allmatches.push(match[index]);
- }
- matches.push(allmatches);
- match = regex.exec(string);
- }
- return matches;
-};
+const kResume = Symbol('resume')
-const isName = function(string) {
- const match = regexName.exec(string);
- return !(match === null || typeof match === 'undefined');
-};
+class PipelineRequest extends Readable {
+ constructor () {
+ super({ autoDestroy: true })
-exports.isExist = function(v) {
- return typeof v !== 'undefined';
-};
+ this[kResume] = null
+ }
-exports.isEmptyObject = function(obj) {
- return Object.keys(obj).length === 0;
-};
+ _read () {
+ const { [kResume]: resume } = this
-/**
- * Copy all the properties of a into b.
- * @param {*} target
- * @param {*} a
- */
-exports.merge = function(target, a, arrayMode) {
- if (a) {
- const keys = Object.keys(a); // will return an array of own properties
- const len = keys.length; //don't make it inline
- for (let i = 0; i < len; i++) {
- if (arrayMode === 'strict') {
- target[keys[i]] = [ a[keys[i]] ];
- } else {
- target[keys[i]] = a[keys[i]];
- }
+ if (resume) {
+ this[kResume] = null
+ resume()
}
}
-};
-/* exports.merge =function (b,a){
- return Object.assign(b,a);
-} */
-exports.getValue = function(v) {
- if (exports.isExist(v)) {
- return v;
- } else {
- return '';
+ _destroy (err, callback) {
+ this._read()
+
+ callback(err)
}
-};
+}
-// const fakeCall = function(a) {return a;};
-// const fakeCallNoReturn = function() {};
+class PipelineResponse extends Readable {
+ constructor (resume) {
+ super({ autoDestroy: true })
+ this[kResume] = resume
+ }
-exports.isName = isName;
-exports.getAllMatches = getAllMatches;
-exports.nameRegexp = nameRegexp;
+ _read () {
+ this[kResume]()
+ }
+ _destroy (err, callback) {
+ if (!err && !this._readableState.endEmitted) {
+ err = new RequestAbortedError()
+ }
-/***/ }),
+ callback(err)
+ }
+}
-/***/ 9433:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+class PipelineHandler extends AsyncResource {
+ constructor (opts, handler) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
-"use strict";
+ if (typeof handler !== 'function') {
+ throw new InvalidArgumentError('invalid handler')
+ }
+ const { signal, method, opaque, onInfo, responseHeaders } = opts
-const util = __nccwpck_require__(7019);
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ }
-const defaultOptions = {
- allowBooleanAttributes: false, //A tag can have attributes without any value
- unpairedTags: []
-};
+ if (method === 'CONNECT') {
+ throw new InvalidArgumentError('invalid method')
+ }
-//const tagsPattern = new RegExp("<\\/?([\\w:\\-_\.]+)\\s*\/?>","g");
-exports.validate = function (xmlData, options) {
- options = Object.assign({}, defaultOptions, options);
+ if (onInfo && typeof onInfo !== 'function') {
+ throw new InvalidArgumentError('invalid onInfo callback')
+ }
- //xmlData = xmlData.replace(/(\r\n|\n|\r)/gm,"");//make it single line
- //xmlData = xmlData.replace(/(^\s*<\?xml.*?\?>)/g,"");//Remove XML starting tag
- //xmlData = xmlData.replace(/()/g,"");//Remove DOCTYPE
- const tags = [];
- let tagFound = false;
+ super('UNDICI_PIPELINE')
- //indicates that the root tag has been closed (aka. depth 0 has been reached)
- let reachedRoot = false;
+ this.opaque = opaque || null
+ this.responseHeaders = responseHeaders || null
+ this.handler = handler
+ this.abort = null
+ this.context = null
+ this.onInfo = onInfo || null
- if (xmlData[0] === '\ufeff') {
- // check for byte order mark (BOM)
- xmlData = xmlData.substr(1);
- }
-
- for (let i = 0; i < xmlData.length; i++) {
+ this.req = new PipelineRequest().on('error', util.nop)
- if (xmlData[i] === '<' && xmlData[i+1] === '?') {
- i+=2;
- i = readPI(xmlData,i);
- if (i.err) return i;
- }else if (xmlData[i] === '<') {
- //starting of tag
- //read until you reach to '>' avoiding any '>' in attribute value
- let tagStartPos = i;
- i++;
-
- if (xmlData[i] === '!') {
- i = readCommentAndCDATA(xmlData, i);
- continue;
- } else {
- let closingTag = false;
- if (xmlData[i] === '/') {
- //closing tag
- closingTag = true;
- i++;
- }
- //read tagname
- let tagName = '';
- for (; i < xmlData.length &&
- xmlData[i] !== '>' &&
- xmlData[i] !== ' ' &&
- xmlData[i] !== '\t' &&
- xmlData[i] !== '\n' &&
- xmlData[i] !== '\r'; i++
- ) {
- tagName += xmlData[i];
- }
- tagName = tagName.trim();
- //console.log(tagName);
+ this.ret = new Duplex({
+ readableObjectMode: opts.objectMode,
+ autoDestroy: true,
+ read: () => {
+ const { body } = this
- if (tagName[tagName.length - 1] === '/') {
- //self closing tag without attributes
- tagName = tagName.substring(0, tagName.length - 1);
- //continue;
- i--;
+ if (body && body.resume) {
+ body.resume()
}
- if (!validateTagName(tagName)) {
- let msg;
- if (tagName.trim().length === 0) {
- msg = "Invalid space after '<'.";
- } else {
- msg = "Tag '"+tagName+"' is an invalid name.";
- }
- return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i));
+ },
+ 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
- const result = readAttributeStr(xmlData, i);
- if (result === false) {
- return getErrorObject('InvalidAttr', "Attributes for '"+tagName+"' have open quote.", getLineNumberForPosition(xmlData, i));
+ if (!err && !ret._readableState.endEmitted) {
+ err = new RequestAbortedError()
}
- let attrStr = result.value;
- i = result.index;
- if (attrStr[attrStr.length - 1] === '/') {
- //self closing tag
- const attrStrStart = i - attrStr.length;
- attrStr = attrStr.substring(0, attrStr.length - 1);
- const isValid = validateAttributeString(attrStr, options);
- if (isValid === true) {
- tagFound = true;
- //continue; //text may presents after self closing tag
- } else {
- //the result from the nested function returns the position of the error within the attribute
- //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute
- //this gives us the absolute index in the entire xml, which we can use to find the line at last
- return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));
- }
- } else if (closingTag) {
- if (!result.tagClosed) {
- return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' doesn't have proper closing.", getLineNumberForPosition(xmlData, i));
- } else if (attrStr.trim().length > 0) {
- return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos));
- } else if (tags.length === 0) {
- return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos));
- } else {
- const otg = tags.pop();
- if (tagName !== otg.tagName) {
- let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);
- return getErrorObject('InvalidTag',
- "Expected closing tag '"+otg.tagName+"' (opened in line "+openPos.line+", col "+openPos.col+") instead of closing tag '"+tagName+"'.",
- getLineNumberForPosition(xmlData, tagStartPos));
- }
+ if (abort && err) {
+ abort()
+ }
- //when there are no more tags, we reached the root level.
- if (tags.length == 0) {
- reachedRoot = true;
- }
- }
- } else {
- const isValid = validateAttributeString(attrStr, options);
- if (isValid !== true) {
- //the result from the nested function returns the position of the error within the attribute
- //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute
- //this gives us the absolute index in the entire xml, which we can use to find the line at last
- return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));
- }
+ util.destroy(body, err)
+ util.destroy(req, err)
+ util.destroy(res, err)
- //if the root level has been reached before ...
- if (reachedRoot === true) {
- return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i));
- } else if(options.unpairedTags.indexOf(tagName) !== -1){
- //don't push into stack
- } else {
- tags.push({tagName, tagStartPos});
- }
- tagFound = true;
- }
+ removeSignal(this)
- //skip tag text value
- //It may include comments and CDATA value
- for (i++; i < xmlData.length; i++) {
- if (xmlData[i] === '<') {
- if (xmlData[i + 1] === '!') {
- //comment or CADATA
- i++;
- i = readCommentAndCDATA(xmlData, i);
- continue;
- } else if (xmlData[i+1] === '?') {
- i = readPI(xmlData, ++i);
- if (i.err) return i;
- } else{
- break;
- }
- } else if (xmlData[i] === '&') {
- const afterAmp = validateAmpersand(xmlData, i);
- if (afterAmp == -1)
- return getErrorObject('InvalidChar', "char '&' is not expected.", getLineNumberForPosition(xmlData, i));
- i = afterAmp;
- }else{
- if (reachedRoot === true && !isWhiteSpace(xmlData[i])) {
- return getErrorObject('InvalidXml', "Extra text at the end", getLineNumberForPosition(xmlData, i));
- }
- }
- } //end of reading tag text value
- if (xmlData[i] === '<') {
- i--;
- }
- }
- } else {
- if ( isWhiteSpace(xmlData[i])) {
- continue;
+ callback(err)
}
- return getErrorObject('InvalidChar', "char '"+xmlData[i]+"' is not expected.", getLineNumberForPosition(xmlData, i));
- }
- }
+ }).on('prefinish', () => {
+ const { req } = this
- if (!tagFound) {
- return getErrorObject('InvalidXml', 'Start tag expected.', 1);
- }else if (tags.length == 1) {
- return getErrorObject('InvalidTag', "Unclosed tag '"+tags[0].tagName+"'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos));
- }else if (tags.length > 0) {
- return getErrorObject('InvalidXml', "Invalid '"+
- JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\r?\n/g, '')+
- "' found.", {line: 1, col: 1});
- }
+ // Node < 15 does not call _final in same tick.
+ req.push(null)
+ })
- return true;
-};
+ this.res = null
-function isWhiteSpace(char){
- return char === ' ' || char === '\t' || char === '\n' || char === '\r';
-}
-/**
- * Read Processing insstructions and skip
- * @param {*} xmlData
- * @param {*} i
- */
-function readPI(xmlData, i) {
- const start = i;
- for (; i < xmlData.length; i++) {
- if (xmlData[i] == '?' || xmlData[i] == ' ') {
- //tagname
- const tagname = xmlData.substr(start, i - start);
- if (i > 5 && tagname === 'xml') {
- return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i));
- } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') {
- //check if valid attribut string
- i++;
- break;
- } else {
- continue;
- }
- }
+ addSignal(this, signal)
}
- return i;
-}
-function readCommentAndCDATA(xmlData, i) {
- if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') {
- //comment
- for (i += 3; i < xmlData.length; i++) {
- if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') {
- i += 2;
- break;
- }
- }
- } else if (
- xmlData.length > i + 8 &&
- xmlData[i + 1] === 'D' &&
- xmlData[i + 2] === 'O' &&
- xmlData[i + 3] === 'C' &&
- xmlData[i + 4] === 'T' &&
- xmlData[i + 5] === 'Y' &&
- xmlData[i + 6] === 'P' &&
- xmlData[i + 7] === 'E'
- ) {
- let angleBracketsCount = 1;
- for (i += 8; i < xmlData.length; i++) {
- if (xmlData[i] === '<') {
- angleBracketsCount++;
- } else if (xmlData[i] === '>') {
- angleBracketsCount--;
- if (angleBracketsCount === 0) {
- break;
- }
- }
- }
- } else if (
- xmlData.length > i + 9 &&
- xmlData[i + 1] === '[' &&
- xmlData[i + 2] === 'C' &&
- xmlData[i + 3] === 'D' &&
- xmlData[i + 4] === 'A' &&
- xmlData[i + 5] === 'T' &&
- xmlData[i + 6] === 'A' &&
- xmlData[i + 7] === '['
- ) {
- for (i += 8; i < xmlData.length; i++) {
- if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') {
- i += 2;
- break;
- }
+ onConnect (abort, context) {
+ const { ret, res } = this
+
+ assert(!res, 'pipeline cannot be retried')
+
+ if (ret.destroyed) {
+ throw new RequestAbortedError()
}
- }
- return i;
-}
+ this.abort = abort
+ this.context = context
+ }
-const doubleQuote = '"';
-const singleQuote = "'";
+ onHeaders (statusCode, rawHeaders, resume) {
+ const { opaque, handler, context } = this
-/**
- * Keep reading xmlData until '<' is found outside the attribute value.
- * @param {string} xmlData
- * @param {number} i
- */
-function readAttributeStr(xmlData, i) {
- let attrStr = '';
- let startChar = '';
- let tagClosed = false;
- for (; i < xmlData.length; i++) {
- if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) {
- if (startChar === '') {
- startChar = xmlData[i];
- } else if (startChar !== xmlData[i]) {
- //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa
- } else {
- startChar = '';
- }
- } else if (xmlData[i] === '>') {
- if (startChar === '') {
- tagClosed = true;
- break;
+ if (statusCode < 200) {
+ if (this.onInfo) {
+ const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ this.onInfo({ statusCode, headers })
}
+ return
}
- attrStr += xmlData[i];
- }
- if (startChar !== '') {
- return false;
- }
- return {
- value: attrStr,
- index: i,
- tagClosed: tagClosed
- };
-}
+ this.res = new PipelineResponse(resume)
-/**
- * Select all the attributes whether valid or invalid.
- */
-const validAttrStrRegxp = new RegExp('(\\s*)([^\\s=]+)(\\s*=)?(\\s*([\'"])(([\\s\\S])*?)\\5)?', 'g');
+ 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', util.nop)
+ throw err
+ }
-//attr, ="sd", a="amit's", a="sd"b="saf", ab cd=""
+ if (!body || typeof body.on !== 'function') {
+ throw new InvalidReturnValueError('expected Readable')
+ }
-function validateAttributeString(attrStr, options) {
- //console.log("start:"+attrStr+":end");
+ body
+ .on('data', (chunk) => {
+ const { ret, body } = this
- //if(attrStr.trim().length === 0) return true; //empty string
+ if (!ret.push(chunk) && body.pause) {
+ body.pause()
+ }
+ })
+ .on('error', (err) => {
+ const { ret } = this
- const matches = util.getAllMatches(attrStr, validAttrStrRegxp);
- const attrNames = {};
+ util.destroy(ret, err)
+ })
+ .on('end', () => {
+ const { ret } = this
- for (let i = 0; i < matches.length; i++) {
- if (matches[i][1].length === 0) {
- //nospace before attribute name: a="sd"b="saf"
- return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' has no space in starting.", getPositionFromMatch(matches[i]))
- } else if (matches[i][3] !== undefined && matches[i][4] === undefined) {
- return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' is without value.", getPositionFromMatch(matches[i]));
- } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {
- //independent attribute: ab
- return getErrorObject('InvalidAttr', "boolean attribute '"+matches[i][2]+"' is not allowed.", getPositionFromMatch(matches[i]));
- }
- /* else if(matches[i][6] === undefined){//attribute without value: ab=
- return { err: { code:"InvalidAttr",msg:"attribute " + matches[i][2] + " has no value assigned."}};
- } */
- const attrName = matches[i][2];
- if (!validateAttrName(attrName)) {
- return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is an invalid name.", getPositionFromMatch(matches[i]));
- }
- if (!attrNames.hasOwnProperty(attrName)) {
- //check for duplicate attribute.
- attrNames[attrName] = 1;
- } else {
- return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is repeated.", getPositionFromMatch(matches[i]));
- }
- }
+ ret.push(null)
+ })
+ .on('close', () => {
+ const { ret } = this
- return true;
-}
+ if (!ret._readableState.ended) {
+ util.destroy(ret, new RequestAbortedError())
+ }
+ })
-function validateNumberAmpersand(xmlData, i) {
- let re = /\d/;
- if (xmlData[i] === 'x') {
- i++;
- re = /[\da-fA-F]/;
- }
- for (; i < xmlData.length; i++) {
- if (xmlData[i] === ';')
- return i;
- if (!xmlData[i].match(re))
- break;
+ this.body = body
}
- return -1;
-}
-function validateAmpersand(xmlData, i) {
- // https://www.w3.org/TR/xml/#dt-charref
- i++;
- if (xmlData[i] === ';')
- return -1;
- if (xmlData[i] === '#') {
- i++;
- return validateNumberAmpersand(xmlData, i);
- }
- let count = 0;
- for (; i < xmlData.length; i++, count++) {
- if (xmlData[i].match(/\w/) && count < 20)
- continue;
- if (xmlData[i] === ';')
- break;
- return -1;
+ onData (chunk) {
+ const { res } = this
+ return res.push(chunk)
}
- return i;
-}
-
-function getErrorObject(code, message, lineNumber) {
- return {
- err: {
- code: code,
- msg: message,
- line: lineNumber.line || lineNumber,
- col: lineNumber.col,
- },
- };
-}
-
-function validateAttrName(attrName) {
- return util.isName(attrName);
-}
-// const startsWithXML = /^xml/i;
+ onComplete (trailers) {
+ const { res } = this
+ res.push(null)
+ }
-function validateTagName(tagname) {
- return util.isName(tagname) /* && !tagname.match(startsWithXML) */;
+ onError (err) {
+ const { ret } = this
+ this.handler = null
+ util.destroy(ret, err)
+ }
}
-//this function returns the line number for the character at the given index
-function getLineNumberForPosition(xmlData, index) {
- const lines = xmlData.substring(0, index).split(/\r?\n/);
- return {
- line: lines.length,
-
- // column number is last line's length + 1, because column numbering starts at 1:
- col: lines[lines.length - 1].length + 1
- };
+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)
+ }
}
-//this function returns the position of the first character of match within attrStr
-function getPositionFromMatch(match) {
- return match.startIndex + match[1].length;
-}
+module.exports = pipeline
/***/ }),
-/***/ 659:
+/***/ 14043:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-//parse Empty Node as self closing node
-const buildFromOrderedJs = __nccwpck_require__(3997);
-const getIgnoreAttributesFn = __nccwpck_require__(812)
-
-const defaultOptions = {
- attributeNamePrefix: '@_',
- attributesGroupName: false,
- textNodeName: '#text',
- ignoreAttributes: true,
- cdataPropName: false,
- format: false,
- indentBy: ' ',
- suppressEmptyNode: false,
- suppressUnpairedNode: true,
- suppressBooleanAttributes: true,
- tagValueProcessor: function(key, a) {
- return a;
- },
- attributeValueProcessor: function(attrName, a) {
- return a;
- },
- preserveOrder: false,
- commentPropName: false,
- unpairedTags: [],
- entities: [
- { regex: new RegExp("&", "g"), val: "&" },//it must be on top
- { regex: new RegExp(">", "g"), val: ">" },
- { regex: new RegExp("<", "g"), val: "<" },
- { regex: new RegExp("\'", "g"), val: "'" },
- { regex: new RegExp("\"", "g"), val: """ }
- ],
- processEntities: true,
- stopNodes: [],
- // transformTagName: false,
- // transformAttributeName: false,
- oneListGroup: false
-};
-function Builder(options) {
- this.options = Object.assign({}, defaultOptions, options);
- if (this.options.ignoreAttributes === true || this.options.attributesGroupName) {
- this.isAttribute = function(/*a*/) {
- return false;
- };
- } else {
- this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)
- this.attrPrefixLen = this.options.attributeNamePrefix.length;
- this.isAttribute = isAttribute;
- }
+const Readable = __nccwpck_require__(49927)
+const {
+ InvalidArgumentError,
+ RequestAbortedError
+} = __nccwpck_require__(68707)
+const util = __nccwpck_require__(3440)
+const { getResolveErrorBodyCallback } = __nccwpck_require__(87655)
+const { AsyncResource } = __nccwpck_require__(90290)
+const { addSignal, removeSignal } = __nccwpck_require__(80158)
- this.processTextOrObjNode = processTextOrObjNode
+class RequestHandler extends AsyncResource {
+ constructor (opts, callback) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
- if (this.options.format) {
- this.indentate = indentate;
- this.tagEndChar = '>\n';
- this.newLine = '\n';
- } else {
- this.indentate = function() {
- return '';
- };
- this.tagEndChar = '>';
- this.newLine = '';
- }
-}
+ const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts
-Builder.prototype.build = function(jObj) {
- if(this.options.preserveOrder){
- return buildFromOrderedJs(jObj, this.options);
- }else {
- if(Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1){
- jObj = {
- [this.options.arrayNodeName] : jObj
+ try {
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
}
- }
- return this.j2x(jObj, 0, []).val;
- }
-};
-Builder.prototype.j2x = function(jObj, level, ajPath) {
- let attrStr = '';
- let val = '';
- const jPath = ajPath.join('.')
- for (let key in jObj) {
- if(!Object.prototype.hasOwnProperty.call(jObj, key)) continue;
- if (typeof jObj[key] === 'undefined') {
- // supress undefined node only if it is not an attribute
- if (this.isAttribute(key)) {
- val += '';
- }
- } else if (jObj[key] === null) {
- // null attribute should be ignored by the attribute list, but should not cause the tag closing
- if (this.isAttribute(key)) {
- val += '';
- } else if (key[0] === '?') {
- val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;
- } else {
- val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
+ if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) {
+ throw new InvalidArgumentError('invalid highWaterMark')
}
- // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
- } else if (jObj[key] instanceof Date) {
- val += this.buildTextValNode(jObj[key], key, '', level);
- } else if (typeof jObj[key] !== 'object') {
- //premitive type
- const attr = this.isAttribute(key);
- if (attr && !this.ignoreAttributesFn(attr, jPath)) {
- attrStr += this.buildAttrPairStr(attr, '' + jObj[key]);
- } else if (!attr) {
- //tag value
- if (key === this.options.textNodeName) {
- let newval = this.options.tagValueProcessor(key, '' + jObj[key]);
- val += this.replaceEntitiesValue(newval);
- } else {
- val += this.buildTextValNode(jObj[key], key, '', level);
- }
+
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
}
- } else if (Array.isArray(jObj[key])) {
- //repeated nodes
- const arrLen = jObj[key].length;
- let listTagVal = "";
- let listTagAttr = "";
- for (let j = 0; j < arrLen; j++) {
- const item = jObj[key][j];
- if (typeof item === 'undefined') {
- // supress undefined node
- } else if (item === null) {
- if(key[0] === "?") val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;
- else val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
- // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
- } else if (typeof item === 'object') {
- if(this.options.oneListGroup){
- const result = this.j2x(item, level + 1, ajPath.concat(key));
- listTagVal += result.val;
- if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) {
- listTagAttr += result.attrStr
- }
- }else{
- listTagVal += this.processTextOrObjNode(item, key, level, ajPath)
- }
- } else {
- if (this.options.oneListGroup) {
- let textValue = this.options.tagValueProcessor(key, item);
- textValue = this.replaceEntitiesValue(textValue);
- listTagVal += textValue;
- } else {
- listTagVal += this.buildTextValNode(item, key, '', level);
- }
- }
+
+ if (method === 'CONNECT') {
+ throw new InvalidArgumentError('invalid method')
}
- if(this.options.oneListGroup){
- listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level);
+
+ if (onInfo && typeof onInfo !== 'function') {
+ throw new InvalidArgumentError('invalid onInfo callback')
}
- val += listTagVal;
- } else {
- //nested node
- if (this.options.attributesGroupName && key === this.options.attributesGroupName) {
- const Ks = Object.keys(jObj[key]);
- const L = Ks.length;
- for (let j = 0; j < L; j++) {
- attrStr += this.buildAttrPairStr(Ks[j], '' + jObj[key][Ks[j]]);
- }
- } else {
- val += this.processTextOrObjNode(jObj[key], key, level, ajPath)
+
+ super('UNDICI_REQUEST')
+ } catch (err) {
+ if (util.isStream(body)) {
+ util.destroy(body.on('error', util.nop), err)
}
+ throw err
}
- }
- return {attrStr: attrStr, val: val};
-};
-Builder.prototype.buildAttrPairStr = function(attrName, val){
- val = this.options.attributeValueProcessor(attrName, '' + val);
- val = this.replaceEntitiesValue(val);
- if (this.options.suppressBooleanAttributes && val === "true") {
- return ' ' + attrName;
- } else return ' ' + attrName + '="' + val + '"';
-}
+ 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.throwOnError = throwOnError
+ this.highWaterMark = highWaterMark
-function processTextOrObjNode (object, key, level, ajPath) {
- const result = this.j2x(object, level + 1, ajPath.concat(key));
- if (object[this.options.textNodeName] !== undefined && Object.keys(object).length === 1) {
- return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level);
- } else {
- return this.buildObjectNode(result.val, key, result.attrStr, level);
+ if (util.isStream(body)) {
+ body.on('error', (err) => {
+ this.onError(err)
+ })
+ }
+
+ addSignal(this, signal)
}
-}
-Builder.prototype.buildObjectNode = function(val, key, attrStr, level) {
- if(val === ""){
- if(key[0] === "?") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar;
- else {
- return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;
+ onConnect (abort, context) {
+ if (!this.callback) {
+ throw new RequestAbortedError()
}
- }else{
- let tagEndExp = '' + key + this.tagEndChar;
- let piClosingChar = "";
-
- if(key[0] === "?") {
- piClosingChar = "?";
- tagEndExp = "";
+ 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
}
-
- // attrStr is an empty string in case the attribute came as undefined or null
- if ((attrStr || attrStr === '') && val.indexOf('<') === -1) {
- return ( this.indentate(level) + '<' + key + attrStr + piClosingChar + '>' + val + tagEndExp );
- } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {
- return this.indentate(level) + `` + this.newLine;
- }else {
- return (
- this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar +
- val +
- this.indentate(level) + tagEndExp );
+
+ const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
+ const contentType = parsedHeaders['content-type']
+ const body = new Readable({ resume, abort, contentType, highWaterMark })
+
+ this.callback = null
+ this.res = body
+ if (callback !== null) {
+ if (this.throwOnError && statusCode >= 400) {
+ this.runInAsyncScope(getResolveErrorBodyCallback, null,
+ { callback, body, contentType, statusCode, statusMessage, headers }
+ )
+ } else {
+ this.runInAsyncScope(callback, null, null, {
+ statusCode,
+ headers,
+ trailers: this.trailers,
+ opaque,
+ body,
+ context
+ })
+ }
}
}
-}
-Builder.prototype.closeTag = function(key){
- let closeTag = "";
- if(this.options.unpairedTags.indexOf(key) !== -1){ //unpaired
- if(!this.options.suppressUnpairedNode) closeTag = "/"
- }else if(this.options.suppressEmptyNode){ //empty
- closeTag = "/";
- }else{
- closeTag = `>${key}`
+ onData (chunk) {
+ const { res } = this
+ return res.push(chunk)
}
- return closeTag;
-}
-function buildEmptyObjNode(val, key, attrStr, level) {
- if (val !== '') {
- return this.buildObjectNode(val, key, attrStr, level);
- } else {
- if(key[0] === "?") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar;
- else {
- return this.indentate(level) + '<' + key + attrStr + '/' + this.tagEndChar;
- // return this.buildTagStr(level,key, attrStr);
- }
+ onComplete (trailers) {
+ const { res } = this
+
+ removeSignal(this)
+
+ util.parseHeaders(trailers, this.trailers)
+
+ res.push(null)
}
-}
-Builder.prototype.buildTextValNode = function(val, key, attrStr, level) {
- if (this.options.cdataPropName !== false && key === this.options.cdataPropName) {
- return this.indentate(level) + `` + this.newLine;
- }else if (this.options.commentPropName !== false && key === this.options.commentPropName) {
- return this.indentate(level) + `` + this.newLine;
- }else if(key[0] === "?") {//PI tag
- return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar;
- }else{
- let textValue = this.options.tagValueProcessor(key, val);
- textValue = this.replaceEntitiesValue(textValue);
-
- if( textValue === ''){
- return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;
- }else{
- return this.indentate(level) + '<' + key + attrStr + '>' +
- textValue +
- '' + key + this.tagEndChar;
+ onError (err) {
+ const { res, callback, body, opaque } = this
+
+ removeSignal(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, err)
+ })
+ }
+
+ if (body) {
+ this.body = null
+ util.destroy(body, err)
}
}
}
-Builder.prototype.replaceEntitiesValue = function(textValue){
- if(textValue && textValue.length > 0 && this.options.processEntities){
- for (let i=0; i {
+ request.call(this, opts, (err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
}
- return textValue;
-}
-
-function indentate(level) {
- return this.options.indentBy.repeat(level);
-}
-function isAttribute(name /*, options*/) {
- if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) {
- return name.substr(this.attrPrefixLen);
- } else {
- return false;
+ try {
+ this.dispatch(opts, new RequestHandler(opts, callback))
+ } catch (err) {
+ if (typeof callback !== 'function') {
+ throw err
+ }
+ const opaque = opts && opts.opaque
+ queueMicrotask(() => callback(err, { opaque }))
}
}
-module.exports = Builder;
+module.exports = request
+module.exports.RequestHandler = RequestHandler
/***/ }),
-/***/ 3997:
-/***/ ((module) => {
+/***/ 3560:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const EOL = "\n";
+"use strict";
-/**
- *
- * @param {array} jArray
- * @param {any} options
- * @returns
- */
-function toXml(jArray, options) {
- let indentation = "";
- if (options.format && options.indentBy.length > 0) {
- indentation = EOL;
+
+const { finished, PassThrough } = __nccwpck_require__(2203)
+const {
+ InvalidArgumentError,
+ InvalidReturnValueError,
+ RequestAbortedError
+} = __nccwpck_require__(68707)
+const util = __nccwpck_require__(3440)
+const { getResolveErrorBodyCallback } = __nccwpck_require__(87655)
+const { AsyncResource } = __nccwpck_require__(90290)
+const { addSignal, removeSignal } = __nccwpck_require__(80158)
+
+class StreamHandler extends AsyncResource {
+ constructor (opts, factory, callback) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
}
- return arrToStr(jArray, options, "", indentation);
-}
-function arrToStr(arr, options, jPath, indentation) {
- let xmlStr = "";
- let isPreviousElementTag = false;
+ const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts
- for (let i = 0; i < arr.length; i++) {
- const tagObj = arr[i];
- const tagName = propName(tagObj);
- if(tagName === undefined) continue;
+ try {
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
+ }
- let newJPath = "";
- if (jPath.length === 0) newJPath = tagName
- else newJPath = `${jPath}.${tagName}`;
+ if (typeof factory !== 'function') {
+ throw new InvalidArgumentError('invalid factory')
+ }
- if (tagName === options.textNodeName) {
- let tagText = tagObj[tagName];
- if (!isStopNode(newJPath, options)) {
- tagText = options.tagValueProcessor(tagName, tagText);
- tagText = replaceEntitiesValue(tagText, options);
- }
- if (isPreviousElementTag) {
- xmlStr += indentation;
- }
- xmlStr += tagText;
- isPreviousElementTag = false;
- continue;
- } else if (tagName === options.cdataPropName) {
- if (isPreviousElementTag) {
- xmlStr += indentation;
- }
- xmlStr += ``;
- isPreviousElementTag = false;
- continue;
- } else if (tagName === options.commentPropName) {
- xmlStr += indentation + ``;
- isPreviousElementTag = true;
- continue;
- } else if (tagName[0] === "?") {
- const attStr = attr_to_str(tagObj[":@"], options);
- const tempInd = tagName === "?xml" ? "" : indentation;
- let piTextNodeName = tagObj[tagName][0][options.textNodeName];
- piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; //remove extra spacing
- xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`;
- isPreviousElementTag = true;
- continue;
- }
- let newIdentation = indentation;
- if (newIdentation !== "") {
- newIdentation += options.indentBy;
- }
- const attStr = attr_to_str(tagObj[":@"], options);
- const tagStart = indentation + `<${tagName}${attStr}`;
- const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation);
- if (options.unpairedTags.indexOf(tagName) !== -1) {
- if (options.suppressUnpairedNode) xmlStr += tagStart + ">";
- else xmlStr += tagStart + "/>";
- } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {
- xmlStr += tagStart + "/>";
- } else if (tagValue && tagValue.endsWith(">")) {
- xmlStr += tagStart + `>${tagValue}${indentation}${tagName}>`;
- } else {
- xmlStr += tagStart + ">";
- if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes(""))) {
- xmlStr += indentation + options.indentBy + tagValue + indentation;
- } else {
- xmlStr += tagValue;
- }
- xmlStr += `${tagName}>`;
- }
- isPreviousElementTag = true;
- }
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ }
- return xmlStr;
-}
+ if (method === 'CONNECT') {
+ throw new InvalidArgumentError('invalid method')
+ }
-function propName(obj) {
- const keys = Object.keys(obj);
- for (let i = 0; i < keys.length; i++) {
- const key = keys[i];
- if(!obj.hasOwnProperty(key)) continue;
- if (key !== ":@") return key;
+ 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', util.nop), err)
+ }
+ throw err
}
-}
-function attr_to_str(attrMap, options) {
- let attrStr = "";
- if (attrMap && !options.ignoreAttributes) {
- for (let attr in attrMap) {
- if(!attrMap.hasOwnProperty(attr)) continue;
- let attrVal = options.attributeValueProcessor(attr, attrMap[attr]);
- attrVal = replaceEntitiesValue(attrVal, options);
- if (attrVal === true && options.suppressBooleanAttributes) {
- attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;
- } else {
- attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`;
- }
- }
+ 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
+ this.throwOnError = throwOnError || false
+
+ if (util.isStream(body)) {
+ body.on('error', (err) => {
+ this.onError(err)
+ })
}
- return attrStr;
-}
-function isStopNode(jPath, options) {
- jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1);
- let tagName = jPath.substr(jPath.lastIndexOf(".") + 1);
- for (let index in options.stopNodes) {
- if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true;
+ addSignal(this, signal)
+ }
+
+ onConnect (abort, context) {
+ if (!this.callback) {
+ throw new RequestAbortedError()
}
- return false;
-}
-function replaceEntitiesValue(textValue, options) {
- if (textValue && textValue.length > 0 && options.processEntities) {
- for (let i = 0; i < options.entities.length; i++) {
- const entity = options.entities[i];
- textValue = textValue.replace(entity.regex, entity.val);
- }
+ this.abort = abort
+ this.context = context
+ }
+
+ onHeaders (statusCode, rawHeaders, resume, statusMessage) {
+ const { factory, opaque, context, callback, responseHeaders } = this
+
+ const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+
+ if (statusCode < 200) {
+ if (this.onInfo) {
+ this.onInfo({ statusCode, headers })
+ }
+ return
}
- return textValue;
-}
-module.exports = toXml;
+ this.factory = null
-/***/ }),
+ let res
-/***/ 151:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (this.throwOnError && statusCode >= 400) {
+ const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
+ const contentType = parsedHeaders['content-type']
+ res = new PassThrough()
-const util = __nccwpck_require__(7019);
+ this.callback = null
+ this.runInAsyncScope(getResolveErrorBodyCallback, null,
+ { callback, body: res, contentType, statusCode, statusMessage, headers }
+ )
+ } else {
+ if (factory === null) {
+ return
+ }
-//TODO: handle comments
-function readDocType(xmlData, i){
-
- const entities = {};
- if( xmlData[i + 3] === 'O' &&
- xmlData[i + 4] === 'C' &&
- xmlData[i + 5] === 'T' &&
- xmlData[i + 6] === 'Y' &&
- xmlData[i + 7] === 'P' &&
- xmlData[i + 8] === 'E')
- {
- i = i+9;
- let angleBracketsCount = 1;
- let hasBody = false, comment = false;
- let exp = "";
- for(;i') { //Read tag content
- if(comment){
- if( xmlData[i - 1] === "-" && xmlData[i - 2] === "-"){
- comment = false;
- angleBracketsCount--;
- }
- }else{
- angleBracketsCount--;
- }
- if (angleBracketsCount === 0) {
- break;
- }
- }else if( xmlData[i] === '['){
- hasBody = true;
- }else{
- exp += xmlData[i];
- }
+ 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)
}
- if(angleBracketsCount !== 0){
- throw new Error(`Unclosed DOCTYPE`);
+
+ this.callback = null
+ this.runInAsyncScope(callback, null, err || null, { opaque, trailers })
+
+ if (err) {
+ abort()
}
- }else{
- throw new Error(`Invalid Tag instead of DOCTYPE`);
+ })
}
- return {entities, i};
-}
-function readEntityExp(xmlData,i){
- //External entities are not supported
- //
+ res.on('drain', resume)
- //Parameter entities are not supported
- //
+ this.res = res
- //Internal entities are supported
- //
-
- //read EntityName
- let entityName = "";
- for (; i < xmlData.length && (xmlData[i] !== "'" && xmlData[i] !== '"' ); i++) {
- // if(xmlData[i] === " ") continue;
- // else
- entityName += xmlData[i];
+ const needDrain = res.writableNeedDrain !== undefined
+ ? res.writableNeedDrain
+ : res._writableState && 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
}
- entityName = entityName.trim();
- if(entityName.indexOf(" ") !== -1) throw new Error("External entites are not supported");
- //read Entity Value
- const startChar = xmlData[i++];
- let val = ""
- for (; i < xmlData.length && xmlData[i] !== startChar ; i++) {
- val += xmlData[i];
+ 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 })
+ })
}
- return [entityName, val, i];
-}
-function isComment(xmlData, i){
- if(xmlData[i+1] === '!' &&
- xmlData[i+2] === '-' &&
- xmlData[i+3] === '-') return true
- return false
-}
-function isEntity(xmlData, i){
- if(xmlData[i+1] === '!' &&
- xmlData[i+2] === 'E' &&
- xmlData[i+3] === 'N' &&
- xmlData[i+4] === 'T' &&
- xmlData[i+5] === 'I' &&
- xmlData[i+6] === 'T' &&
- xmlData[i+7] === 'Y') return true
- return false
-}
-function isElement(xmlData, i){
- if(xmlData[i+1] === '!' &&
- xmlData[i+2] === 'E' &&
- xmlData[i+3] === 'L' &&
- xmlData[i+4] === 'E' &&
- xmlData[i+5] === 'M' &&
- xmlData[i+6] === 'E' &&
- xmlData[i+7] === 'N' &&
- xmlData[i+8] === 'T') return true
- return false
+ if (body) {
+ this.body = null
+ util.destroy(body, err)
+ }
+ }
}
-function isAttlist(xmlData, i){
- if(xmlData[i+1] === '!' &&
- xmlData[i+2] === 'A' &&
- xmlData[i+3] === 'T' &&
- xmlData[i+4] === 'T' &&
- xmlData[i+5] === 'L' &&
- xmlData[i+6] === 'I' &&
- xmlData[i+7] === 'S' &&
- xmlData[i+8] === 'T') return true
- return false
-}
-function isNotation(xmlData, i){
- if(xmlData[i+1] === '!' &&
- xmlData[i+2] === 'N' &&
- xmlData[i+3] === 'O' &&
- xmlData[i+4] === 'T' &&
- xmlData[i+5] === 'A' &&
- xmlData[i+6] === 'T' &&
- xmlData[i+7] === 'I' &&
- xmlData[i+8] === 'O' &&
- xmlData[i+9] === 'N') return true
- return false
-}
+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)
+ })
+ })
+ }
-function validateEntityName(name){
- if (util.isName(name))
- return name;
- else
- throw new Error(`Invalid entity name ${name}`);
+ try {
+ this.dispatch(opts, new StreamHandler(opts, factory, callback))
+ } catch (err) {
+ if (typeof callback !== 'function') {
+ throw err
+ }
+ const opaque = opts && opts.opaque
+ queueMicrotask(() => callback(err, { opaque }))
+ }
}
-module.exports = readDocType;
+module.exports = stream
/***/ }),
-/***/ 4769:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 61882:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+"use strict";
-const defaultOptions = {
- preserveOrder: false,
- attributeNamePrefix: '@_',
- attributesGroupName: false,
- textNodeName: '#text',
- ignoreAttributes: true,
- removeNSPrefix: false, // remove NS from tag name or attribute name if true
- allowBooleanAttributes: false, //a tag can have attributes without any value
- //ignoreRootElement : false,
- parseTagValue: true,
- parseAttributeValue: false,
- trimValues: true, //Trim string values of tag and attributes
- cdataPropName: false,
- numberParseOptions: {
- hex: true,
- leadingZeros: true,
- eNotation: true
- },
- tagValueProcessor: function(tagName, val) {
- return val;
- },
- attributeValueProcessor: function(attrName, val) {
- return val;
- },
- stopNodes: [], //nested tags will not be parsed even for errors
- alwaysCreateTextNode: false,
- isArray: () => false,
- commentPropName: false,
- unpairedTags: [],
- processEntities: true,
- htmlEntities: false,
- ignoreDeclaration: false,
- ignorePiTags: false,
- transformTagName: false,
- transformAttributeName: false,
- updateTag: function(tagName, jPath, attrs){
- return tagName
- },
- // skipEmptyListItem: false
-};
-
-const buildOptions = function(options) {
- return Object.assign({}, defaultOptions, options);
-};
-exports.buildOptions = buildOptions;
-exports.defaultOptions = defaultOptions;
+const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(68707)
+const { AsyncResource } = __nccwpck_require__(90290)
+const util = __nccwpck_require__(3440)
+const { addSignal, removeSignal } = __nccwpck_require__(80158)
+const assert = __nccwpck_require__(42613)
+
+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')
+ }
-/***/ 3017:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ const { signal, opaque, responseHeaders } = opts
-"use strict";
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ }
-///@ts-check
+ super('UNDICI_UPGRADE')
-const util = __nccwpck_require__(7019);
-const xmlNode = __nccwpck_require__(9307);
-const readDocType = __nccwpck_require__(151);
-const toNumber = __nccwpck_require__(6496);
-const getIgnoreAttributesFn = __nccwpck_require__(812)
+ this.responseHeaders = responseHeaders || null
+ this.opaque = opaque || null
+ this.callback = callback
+ this.abort = null
+ this.context = null
-// const regx =
-// '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)'
-// .replace(/NAME/g, util.nameRegexp);
+ addSignal(this, signal)
+ }
-//const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g");
-//const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g");
+ onConnect (abort, context) {
+ if (!this.callback) {
+ throw new RequestAbortedError()
+ }
-class OrderedObjParser{
- constructor(options){
- this.options = options;
- this.currentNode = null;
- this.tagsNodeStack = [];
- this.docTypeEntities = {};
- this.lastEntities = {
- "apos" : { regex: /&(apos|#39|#x27);/g, val : "'"},
- "gt" : { regex: /&(gt|#62|#x3E);/g, val : ">"},
- "lt" : { regex: /&(lt|#60|#x3C);/g, val : "<"},
- "quot" : { regex: /&(quot|#34|#x22);/g, val : "\""},
- };
- this.ampEntity = { regex: /&(amp|#38|#x26);/g, val : "&"};
- this.htmlEntities = {
- "space": { regex: /&(nbsp|#160);/g, val: " " },
- // "lt" : { regex: /&(lt|#60);/g, val: "<" },
- // "gt" : { regex: /&(gt|#62);/g, val: ">" },
- // "amp" : { regex: /&(amp|#38);/g, val: "&" },
- // "quot" : { regex: /&(quot|#34);/g, val: "\"" },
- // "apos" : { regex: /&(apos|#39);/g, val: "'" },
- "cent" : { regex: /&(cent|#162);/g, val: "¢" },
- "pound" : { regex: /&(pound|#163);/g, val: "£" },
- "yen" : { regex: /&(yen|#165);/g, val: "¥" },
- "euro" : { regex: /&(euro|#8364);/g, val: "€" },
- "copyright" : { regex: /&(copy|#169);/g, val: "©" },
- "reg" : { regex: /&(reg|#174);/g, val: "®" },
- "inr" : { regex: /&(inr|#8377);/g, val: "₹" },
- "num_dec": { regex: /([0-9]{1,7});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 10)) },
- "num_hex": { regex: /([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 16)) },
- };
- this.addExternalEntities = addExternalEntities;
- this.parseXml = parseXml;
- this.parseTextData = parseTextData;
- this.resolveNameSpace = resolveNameSpace;
- this.buildAttributesMap = buildAttributesMap;
- this.isItStopNode = isItStopNode;
- this.replaceEntitiesValue = replaceEntitiesValue;
- this.readStopNodeData = readStopNodeData;
- this.saveTextToParentTag = saveTextToParentTag;
- this.addChild = addChild;
- this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)
+ this.abort = abort
+ this.context = null
}
-}
+ onHeaders () {
+ throw new SocketError('bad upgrade', null)
+ }
-function addExternalEntities(externalEntities){
- const entKeys = Object.keys(externalEntities);
- for (let i = 0; i < entKeys.length; i++) {
- const ent = entKeys[i];
- this.lastEntities[ent] = {
- regex: new RegExp("&"+ent+";","g"),
- val : externalEntities[ent]
- }
+ onUpgrade (statusCode, rawHeaders, socket) {
+ const { callback, opaque, context } = this
+
+ assert.strictEqual(statusCode, 101)
+
+ 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
+ })
}
-}
-/**
- * @param {string} val
- * @param {string} tagName
- * @param {string} jPath
- * @param {boolean} dontTrim
- * @param {boolean} hasAttributes
- * @param {boolean} isLeafNode
- * @param {boolean} escapeEntities
- */
-function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
- if (val !== undefined) {
- if (this.options.trimValues && !dontTrim) {
- val = val.trim();
- }
- if(val.length > 0){
- if(!escapeEntities) val = this.replaceEntitiesValue(val);
-
- const newval = this.options.tagValueProcessor(tagName, val, jPath, hasAttributes, isLeafNode);
- if(newval === null || newval === undefined){
- //don't parse
- return val;
- }else if(typeof newval !== typeof val || newval !== val){
- //overwrite
- return newval;
- }else if(this.options.trimValues){
- return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);
- }else{
- const trimmedVal = val.trim();
- if(trimmedVal === val){
- return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);
- }else{
- return val;
- }
- }
+ onError (err) {
+ const { callback, opaque } = this
+
+ removeSignal(this)
+
+ if (callback) {
+ this.callback = null
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque })
+ })
}
}
}
-function resolveNameSpace(tagname) {
- if (this.options.removeNSPrefix) {
- const tags = tagname.split(':');
- const prefix = tagname.charAt(0) === '/' ? '/' : '';
- if (tags[0] === 'xmlns') {
- return '';
- }
- if (tags.length === 2) {
- tagname = prefix + tags[1];
+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)
+ this.dispatch({
+ ...opts,
+ method: opts.method || 'GET',
+ upgrade: opts.protocol || 'Websocket'
+ }, upgradeHandler)
+ } catch (err) {
+ if (typeof callback !== 'function') {
+ throw err
}
+ const opaque = opts && opts.opaque
+ queueMicrotask(() => callback(err, { opaque }))
}
- return tagname;
}
-//TODO: change regex to capture NS
-//const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm");
-const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm');
+module.exports = upgrade
-function buildAttributesMap(attrStr, jPath, tagName) {
- if (this.options.ignoreAttributes !== true && typeof attrStr === 'string') {
- // attrStr = attrStr.replace(/\r?\n/g, ' ');
- //attrStr = attrStr || attrStr.trim();
- const matches = util.getAllMatches(attrStr, attrsRegx);
- const len = matches.length; //don't make it inline
- const attrs = {};
- for (let i = 0; i < len; i++) {
- const attrName = this.resolveNameSpace(matches[i][1]);
- if (this.ignoreAttributesFn(attrName, jPath)) {
- continue
- }
- let oldVal = matches[i][4];
- let aName = this.options.attributeNamePrefix + attrName;
- if (attrName.length) {
- if (this.options.transformAttributeName) {
- aName = this.options.transformAttributeName(aName);
- }
- if(aName === "__proto__") aName = "#__proto__";
- if (oldVal !== undefined) {
- if (this.options.trimValues) {
- oldVal = oldVal.trim();
- }
- oldVal = this.replaceEntitiesValue(oldVal);
- const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath);
- if(newVal === null || newVal === undefined){
- //don't parse
- attrs[aName] = oldVal;
- }else if(typeof newVal !== typeof oldVal || newVal !== oldVal){
- //overwrite
- attrs[aName] = newVal;
- }else{
- //parse
- attrs[aName] = parseValue(
- oldVal,
- this.options.parseAttributeValue,
- this.options.numberParseOptions
- );
- }
- } else if (this.options.allowBooleanAttributes) {
- attrs[aName] = true;
- }
- }
- }
- if (!Object.keys(attrs).length) {
- return;
- }
- if (this.options.attributesGroupName) {
- const attrCollection = {};
- attrCollection[this.options.attributesGroupName] = attrs;
- return attrCollection;
- }
- return attrs
- }
-}
+/***/ }),
-const parseXml = function(xmlData) {
- xmlData = xmlData.replace(/\r\n?/g, "\n"); //TODO: remove this line
- const xmlObj = new xmlNode('!xml');
- let currentNode = xmlObj;
- let textData = "";
- let jPath = "";
- for(let i=0; i< xmlData.length; i++){//for each char in XML data
- const ch = xmlData[i];
- if(ch === '<'){
- // const nextIndex = i+1;
- // const _2ndChar = xmlData[nextIndex];
- if( xmlData[i+1] === '/') {//Closing Tag
- const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.")
- let tagName = xmlData.substring(i+2,closeIndex).trim();
+/***/ 56615:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if(this.options.removeNSPrefix){
- const colonIndex = tagName.indexOf(":");
- if(colonIndex !== -1){
- tagName = tagName.substr(colonIndex+1);
- }
- }
+"use strict";
- if(this.options.transformTagName) {
- tagName = this.options.transformTagName(tagName);
- }
- if(currentNode){
- textData = this.saveTextToParentTag(textData, currentNode, jPath);
- }
+module.exports.request = __nccwpck_require__(14043)
+module.exports.stream = __nccwpck_require__(3560)
+module.exports.pipeline = __nccwpck_require__(76862)
+module.exports.upgrade = __nccwpck_require__(61882)
+module.exports.connect = __nccwpck_require__(34660)
- //check if last tag of nested tag was unpaired tag
- const lastTagName = jPath.substring(jPath.lastIndexOf(".")+1);
- if(tagName && this.options.unpairedTags.indexOf(tagName) !== -1 ){
- throw new Error(`Unpaired tag can not be used as closing tag: ${tagName}>`);
- }
- let propIndex = 0
- if(lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1 ){
- propIndex = jPath.lastIndexOf('.', jPath.lastIndexOf('.')-1)
- this.tagsNodeStack.pop();
- }else{
- propIndex = jPath.lastIndexOf(".");
- }
- jPath = jPath.substring(0, propIndex);
- currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope
- textData = "";
- i = closeIndex;
- } else if( xmlData[i+1] === '?') {
+/***/ }),
- let tagData = readTagExp(xmlData,i, false, "?>");
- if(!tagData) throw new Error("Pi Tag is not closed.");
+/***/ 49927:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- textData = this.saveTextToParentTag(textData, currentNode, jPath);
- if( (this.options.ignoreDeclaration && tagData.tagName === "?xml") || this.options.ignorePiTags){
+"use strict";
+// Ported from https://github.com/nodejs/undici/pull/907
- }else{
-
- const childNode = new xmlNode(tagData.tagName);
- childNode.add(this.options.textNodeName, "");
-
- if(tagData.tagName !== tagData.tagExp && tagData.attrExpPresent){
- childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName);
- }
- this.addChild(currentNode, childNode, jPath)
- }
+const assert = __nccwpck_require__(42613)
+const { Readable } = __nccwpck_require__(2203)
+const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = __nccwpck_require__(68707)
+const util = __nccwpck_require__(3440)
+const { ReadableStreamFrom, toUSVString } = __nccwpck_require__(3440)
- i = tagData.closeIndex + 1;
- } else if(xmlData.substr(i + 1, 3) === '!--') {
- const endIndex = findClosingIndex(xmlData, "-->", i+4, "Comment is not closed.")
- if(this.options.commentPropName){
- const comment = xmlData.substring(i + 4, endIndex - 2);
+let Blob
- textData = this.saveTextToParentTag(textData, currentNode, jPath);
+const kConsume = Symbol('kConsume')
+const kReading = Symbol('kReading')
+const kBody = Symbol('kBody')
+const kAbort = Symbol('abort')
+const kContentType = Symbol('kContentType')
- currentNode.add(this.options.commentPropName, [ { [this.options.textNodeName] : comment } ]);
- }
- i = endIndex;
- } else if( xmlData.substr(i + 1, 2) === '!D') {
- const result = readDocType(xmlData, i);
- this.docTypeEntities = result.entities;
- i = result.i;
- }else if(xmlData.substr(i + 1, 2) === '![') {
- const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2;
- const tagExp = xmlData.substring(i + 9,closeIndex);
+const noop = () => {}
- textData = this.saveTextToParentTag(textData, currentNode, jPath);
+module.exports = class BodyReadable extends Readable {
+ constructor ({
+ resume,
+ abort,
+ contentType = '',
+ highWaterMark = 64 * 1024 // Same as nodejs fs streams.
+ }) {
+ super({
+ autoDestroy: true,
+ read: resume,
+ highWaterMark
+ })
- let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true);
- if(val == undefined) val = "";
+ this._readableState.dataEmitted = false
- //cdata should be set even if it is 0 length string
- if(this.options.cdataPropName){
- currentNode.add(this.options.cdataPropName, [ { [this.options.textNodeName] : tagExp } ]);
- }else{
- currentNode.add(this.options.textNodeName, val);
- }
-
- i = closeIndex + 2;
- }else {//Opening tag
- let result = readTagExp(xmlData,i, this.options.removeNSPrefix);
- let tagName= result.tagName;
- const rawTagName = result.rawTagName;
- let tagExp = result.tagExp;
- let attrExpPresent = result.attrExpPresent;
- let closeIndex = result.closeIndex;
+ this[kAbort] = abort
+ this[kConsume] = null
+ this[kBody] = null
+ this[kContentType] = contentType
- if (this.options.transformTagName) {
- tagName = this.options.transformTagName(tagName);
- }
-
- //save text as child node
- if (currentNode && textData) {
- if(currentNode.tagname !== '!xml'){
- //when nested tag is found
- textData = this.saveTextToParentTag(textData, currentNode, jPath, false);
- }
- }
+ // 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
+ }
- //check if last tag was unpaired tag
- const lastTag = currentNode;
- if(lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1 ){
- currentNode = this.tagsNodeStack.pop();
- jPath = jPath.substring(0, jPath.lastIndexOf("."));
- }
- if(tagName !== xmlObj.tagname){
- jPath += jPath ? "." + tagName : tagName;
- }
- if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) {
- let tagContent = "";
- //self-closing tag
- if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){
- if(tagName[tagName.length - 1] === "/"){ //remove trailing '/'
- tagName = tagName.substr(0, tagName.length - 1);
- jPath = jPath.substr(0, jPath.length - 1);
- tagExp = tagName;
- }else{
- tagExp = tagExp.substr(0, tagExp.length - 1);
- }
- i = result.closeIndex;
- }
- //unpaired tag
- else if(this.options.unpairedTags.indexOf(tagName) !== -1){
-
- i = result.closeIndex;
- }
- //normal tag
- else{
- //read until closing tag is found
- const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
- if(!result) throw new Error(`Unexpected end of ${rawTagName}`);
- i = result.i;
- tagContent = result.tagContent;
- }
+ destroy (err) {
+ if (this.destroyed) {
+ // Node < 16
+ return this
+ }
- const childNode = new xmlNode(tagName);
- if(tagName !== tagExp && attrExpPresent){
- childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
- }
- if(tagContent) {
- tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true);
- }
-
- jPath = jPath.substr(0, jPath.lastIndexOf("."));
- childNode.add(this.options.textNodeName, tagContent);
-
- this.addChild(currentNode, childNode, jPath)
- }else{
- //selfClosing tag
- if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){
- if(tagName[tagName.length - 1] === "/"){ //remove trailing '/'
- tagName = tagName.substr(0, tagName.length - 1);
- jPath = jPath.substr(0, jPath.length - 1);
- tagExp = tagName;
- }else{
- tagExp = tagExp.substr(0, tagExp.length - 1);
- }
-
- if(this.options.transformTagName) {
- tagName = this.options.transformTagName(tagName);
- }
+ if (!err && !this._readableState.endEmitted) {
+ err = new RequestAbortedError()
+ }
- const childNode = new xmlNode(tagName);
- if(tagName !== tagExp && attrExpPresent){
- childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
- }
- this.addChild(currentNode, childNode, jPath)
- jPath = jPath.substr(0, jPath.lastIndexOf("."));
- }
- //opening tag
- else{
- const childNode = new xmlNode( tagName);
- this.tagsNodeStack.push(currentNode);
-
- if(tagName !== tagExp && attrExpPresent){
- childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
- }
- this.addChild(currentNode, childNode, jPath)
- currentNode = childNode;
- }
- textData = "";
- i = closeIndex;
- }
- }
- }else{
- textData += xmlData[i];
+ if (err) {
+ this[kAbort]()
+ }
+
+ return super.destroy(err)
+ }
+
+ emit (ev, ...args) {
+ if (ev === 'data') {
+ // Node < 16.7
+ this._readableState.dataEmitted = true
+ } else if (ev === 'error') {
+ // Node < 16
+ this._readableState.errorEmitted = true
}
+ return super.emit(ev, ...args)
}
- return xmlObj.child;
-}
-function addChild(currentNode, childNode, jPath){
- const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"])
- if(result === false){
- }else if(typeof result === "string"){
- childNode.tagname = result
- currentNode.addChild(childNode);
- }else{
- currentNode.addChild(childNode);
+ on (ev, ...args) {
+ if (ev === 'data' || ev === 'readable') {
+ this[kReading] = true
+ }
+ return super.on(ev, ...args)
+ }
+
+ addListener (ev, ...args) {
+ return this.on(ev, ...args)
+ }
+
+ off (ev, ...args) {
+ const ret = super.off(ev, ...args)
+ if (ev === 'data' || ev === 'readable') {
+ this[kReading] = (
+ this.listenerCount('data') > 0 ||
+ this.listenerCount('readable') > 0
+ )
+ }
+ return ret
}
-}
-const replaceEntitiesValue = function(val){
+ removeListener (ev, ...args) {
+ return this.off(ev, ...args)
+ }
- if(this.options.processEntities){
- for(let entityName in this.docTypeEntities){
- const entity = this.docTypeEntities[entityName];
- val = val.replace( entity.regx, entity.val);
- }
- for(let entityName in this.lastEntities){
- const entity = this.lastEntities[entityName];
- val = val.replace( entity.regex, entity.val);
- }
- if(this.options.htmlEntities){
- for(let entityName in this.htmlEntities){
- const entity = this.htmlEntities[entityName];
- val = val.replace( entity.regex, entity.val);
- }
+ push (chunk) {
+ if (this[kConsume] && chunk !== null && this.readableLength === 0) {
+ consumePush(this[kConsume], chunk)
+ return this[kReading] ? super.push(chunk) : true
}
- val = val.replace( this.ampEntity.regex, this.ampEntity.val);
+ return super.push(chunk)
}
- return val;
-}
-function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) {
- if (textData) { //store previously collected data as textNode
- if(isLeafNode === undefined) isLeafNode = Object.keys(currentNode.child).length === 0
-
- textData = this.parseTextData(textData,
- currentNode.tagname,
- jPath,
- false,
- currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false,
- isLeafNode);
- if (textData !== undefined && textData !== "")
- currentNode.add(this.options.textNodeName, textData);
- textData = "";
+ // https://fetch.spec.whatwg.org/#dom-body-text
+ async text () {
+ return consume(this, 'text')
}
- return textData;
-}
-//TODO: use jPath to simplify the logic
-/**
- *
- * @param {string[]} stopNodes
- * @param {string} jPath
- * @param {string} currentTagName
- */
-function isItStopNode(stopNodes, jPath, currentTagName){
- const allNodesExp = "*." + currentTagName;
- for (const stopNodePath in stopNodes) {
- const stopNodeExp = stopNodes[stopNodePath];
- if( allNodesExp === stopNodeExp || jPath === stopNodeExp ) return true;
+ // https://fetch.spec.whatwg.org/#dom-body-json
+ async json () {
+ return consume(this, 'json')
}
- return false;
-}
-/**
- * Returns the tag Expression and where it is ending handling single-double quotes situation
- * @param {string} xmlData
- * @param {number} i starting index
- * @returns
- */
-function tagExpWithClosingIndex(xmlData, i, closingChar = ">"){
- let attrBoundary;
- let tagExp = "";
- for (let index = i; index < xmlData.length; index++) {
- let ch = xmlData[index];
- if (attrBoundary) {
- if (ch === attrBoundary) attrBoundary = "";//reset
- } else if (ch === '"' || ch === "'") {
- attrBoundary = ch;
- } else if (ch === closingChar[0]) {
- if(closingChar[1]){
- if(xmlData[index + 1] === closingChar[1]){
- return {
- data: tagExp,
- index: index
- }
- }
- }else{
- return {
- data: tagExp,
- index: index
- }
- }
- } else if (ch === '\t') {
- ch = " "
- }
- tagExp += ch;
+ // https://fetch.spec.whatwg.org/#dom-body-blob
+ async blob () {
+ return consume(this, 'blob')
}
-}
-function findClosingIndex(xmlData, str, i, errMsg){
- const closingIndex = xmlData.indexOf(str, i);
- if(closingIndex === -1){
- throw new Error(errMsg)
- }else{
- return closingIndex + str.length - 1;
+ // https://fetch.spec.whatwg.org/#dom-body-arraybuffer
+ async arrayBuffer () {
+ return consume(this, 'arrayBuffer')
}
-}
-function readTagExp(xmlData,i, removeNSPrefix, closingChar = ">"){
- const result = tagExpWithClosingIndex(xmlData, i+1, closingChar);
- if(!result) return;
- let tagExp = result.data;
- const closeIndex = result.index;
- const separatorIndex = tagExp.search(/\s/);
- let tagName = tagExp;
- let attrExpPresent = true;
- if(separatorIndex !== -1){//separate tag name and attributes expression
- tagName = tagExp.substring(0, separatorIndex);
- tagExp = tagExp.substring(separatorIndex + 1).trimStart();
+ // https://fetch.spec.whatwg.org/#dom-body-formdata
+ async formData () {
+ // TODO: Implement.
+ throw new NotSupportedError()
}
- const rawTagName = tagName;
- if(removeNSPrefix){
- const colonIndex = tagName.indexOf(":");
- if(colonIndex !== -1){
- tagName = tagName.substr(colonIndex+1);
- attrExpPresent = tagName !== result.data.substr(colonIndex + 1);
- }
+ // https://fetch.spec.whatwg.org/#dom-body-bodyused
+ get bodyUsed () {
+ return util.isDisturbed(this)
}
- return {
- tagName: tagName,
- tagExp: tagExp,
- closeIndex: closeIndex,
- attrExpPresent: attrExpPresent,
- rawTagName: rawTagName,
+ // https://fetch.spec.whatwg.org/#dom-body-body
+ 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]
}
-}
-/**
- * find paired tag for a stop node
- * @param {string} xmlData
- * @param {string} tagName
- * @param {number} i
- */
-function readStopNodeData(xmlData, tagName, i){
- const startIndex = i;
- // Starting at 1 since we already have an open tag
- let openTagCount = 1;
- for (; i < xmlData.length; i++) {
- if( xmlData[i] === "<"){
- if (xmlData[i+1] === "/") {//close tag
- const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`);
- let closeTagName = xmlData.substring(i+2,closeIndex).trim();
- if(closeTagName === tagName){
- openTagCount--;
- if (openTagCount === 0) {
- return {
- tagContent: xmlData.substring(startIndex, i),
- i : closeIndex
- }
- }
- }
- i=closeIndex;
- } else if(xmlData[i+1] === '?') {
- const closeIndex = findClosingIndex(xmlData, "?>", i+1, "StopNode is not closed.")
- i=closeIndex;
- } else if(xmlData.substr(i + 1, 3) === '!--') {
- const closeIndex = findClosingIndex(xmlData, "-->", i+3, "StopNode is not closed.")
- i=closeIndex;
- } else if(xmlData.substr(i + 1, 2) === '![') {
- const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2;
- i=closeIndex;
- } else {
- const tagData = readTagExp(xmlData, i, '>')
+ dump (opts) {
+ let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144
+ const signal = opts && opts.signal
- if (tagData) {
- const openTagName = tagData && tagData.tagName;
- if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== "/") {
- openTagCount++;
- }
- i=tagData.closeIndex;
- }
+ if (signal) {
+ try {
+ if (typeof signal !== 'object' || !('aborted' in signal)) {
+ throw new InvalidArgumentError('signal must be an AbortSignal')
}
+ util.throwIfAborted(signal)
+ } catch (err) {
+ return Promise.reject(err)
}
- }//end for loop
-}
+ }
-function parseValue(val, shouldParse, options) {
- if (shouldParse && typeof val === 'string') {
- //console.log(options)
- const newval = val.trim();
- if(newval === 'true' ) return true;
- else if(newval === 'false' ) return false;
- else return toNumber(val, options);
- } else {
- if (util.isExist(val)) {
- return val;
- } else {
- return '';
+ if (this.closed) {
+ return Promise.resolve(null)
}
- }
-}
+ return new Promise((resolve, reject) => {
+ const signalListenerCleanup = signal
+ ? util.addAbortListener(signal, () => {
+ this.destroy()
+ })
+ : noop
-module.exports = OrderedObjParser;
+ this
+ .on('close', function () {
+ signalListenerCleanup()
+ if (signal && signal.aborted) {
+ reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }))
+ } else {
+ resolve(null)
+ }
+ })
+ .on('error', noop)
+ .on('data', function (chunk) {
+ limit -= chunk.length
+ if (limit <= 0) {
+ this.destroy()
+ }
+ })
+ .resume()
+ })
+ }
+}
+// https://streams.spec.whatwg.org/#readablestream-locked
+function isLocked (self) {
+ // Consume is an implicit lock.
+ return (self[kBody] && self[kBody].locked === true) || self[kConsume]
+}
-/***/ }),
+// https://fetch.spec.whatwg.org/#body-unusable
+function isUnusable (self) {
+ return util.isDisturbed(self) || isLocked(self)
+}
-/***/ 9844:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+async function consume (stream, type) {
+ if (isUnusable(stream)) {
+ throw new TypeError('unusable')
+ }
-const { buildOptions} = __nccwpck_require__(4769);
-const OrderedObjParser = __nccwpck_require__(3017);
-const { prettify} = __nccwpck_require__(7594);
-const validator = __nccwpck_require__(9433);
+ assert(!stream[kConsume])
-class XMLParser{
-
- constructor(options){
- this.externalEntities = {};
- this.options = buildOptions(options);
-
- }
- /**
- * Parse XML dats to JS object
- * @param {string|Buffer} xmlData
- * @param {boolean|Object} validationOption
- */
- parse(xmlData,validationOption){
- if(typeof xmlData === "string"){
- }else if( xmlData.toString){
- xmlData = xmlData.toString();
- }else{
- throw new Error("XML data is accepted in String or Bytes[] form.")
- }
- if( validationOption){
- if(validationOption === true) validationOption = {}; //validate with default options
-
- const result = validator.validate(xmlData, validationOption);
- if (result !== true) {
- throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` )
- }
- }
- const orderedObjParser = new OrderedObjParser(this.options);
- orderedObjParser.addExternalEntities(this.externalEntities);
- const orderedResult = orderedObjParser.parseXml(xmlData);
- if(this.options.preserveOrder || orderedResult === undefined) return orderedResult;
- else return prettify(orderedResult, this.options);
+ return new Promise((resolve, reject) => {
+ stream[kConsume] = {
+ type,
+ stream,
+ resolve,
+ reject,
+ length: 0,
+ body: []
}
- /**
- * Add Entity which is not by default supported by this library
- * @param {string} key
- * @param {string} value
- */
- addEntity(key, value){
- if(value.indexOf("&") !== -1){
- throw new Error("Entity value can't have '&'")
- }else if(key.indexOf("&") !== -1 || key.indexOf(";") !== -1){
- throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'")
- }else if(value === "&"){
- throw new Error("An entity with value '&' is not permitted");
- }else{
- this.externalEntities[key] = value;
+ stream
+ .on('error', function (err) {
+ consumeFinish(this[kConsume], err)
+ })
+ .on('close', function () {
+ if (this[kConsume].body !== null) {
+ consumeFinish(this[kConsume], new RequestAbortedError())
}
- }
+ })
+
+ process.nextTick(consumeStart, stream[kConsume])
+ })
}
-module.exports = XMLParser;
+function consumeStart (consume) {
+ if (consume.body === null) {
+ return
+ }
-/***/ }),
+ const { _readableState: state } = consume.stream
-/***/ 7594:
-/***/ ((__unused_webpack_module, exports) => {
+ for (const chunk of state.buffer) {
+ consumePush(consume, chunk)
+ }
-"use strict";
+ if (state.endEmitted) {
+ consumeEnd(this[kConsume])
+ } else {
+ consume.stream.on('end', function () {
+ consumeEnd(this[kConsume])
+ })
+ }
+ consume.stream.resume()
-/**
- *
- * @param {array} node
- * @param {any} options
- * @returns
- */
-function prettify(node, options){
- return compress( node, options);
+ while (consume.stream.read() != null) {
+ // Loop
+ }
}
-/**
- *
- * @param {array} arr
- * @param {object} options
- * @param {string} jPath
- * @returns object
- */
-function compress(arr, options, jPath){
- let text;
- const compressedObj = {};
- for (let i = 0; i < arr.length; i++) {
- const tagObj = arr[i];
- const property = propName(tagObj);
- let newJpath = "";
- if(jPath === undefined) newJpath = property;
- else newJpath = jPath + "." + property;
+function consumeEnd (consume) {
+ const { type, body, resolve, stream, length } = consume
- if(property === options.textNodeName){
- if(text === undefined) text = tagObj[property];
- else text += "" + tagObj[property];
- }else if(property === undefined){
- continue;
- }else if(tagObj[property]){
-
- let val = compress(tagObj[property], options, newJpath);
- const isLeaf = isLeafTag(val, options);
+ try {
+ if (type === 'text') {
+ resolve(toUSVString(Buffer.concat(body)))
+ } else if (type === 'json') {
+ resolve(JSON.parse(Buffer.concat(body)))
+ } else if (type === 'arrayBuffer') {
+ const dst = new Uint8Array(length)
- if(tagObj[":@"]){
- assignAttributes( val, tagObj[":@"], newJpath, options);
- }else if(Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode){
- val = val[options.textNodeName];
- }else if(Object.keys(val).length === 0){
- if(options.alwaysCreateTextNode) val[options.textNodeName] = "";
- else val = "";
+ let pos = 0
+ for (const buf of body) {
+ dst.set(buf, pos)
+ pos += buf.byteLength
}
- if(compressedObj[property] !== undefined && compressedObj.hasOwnProperty(property)) {
- if(!Array.isArray(compressedObj[property])) {
- compressedObj[property] = [ compressedObj[property] ];
- }
- compressedObj[property].push(val);
- }else{
- //TODO: if a node is not an array, then check if it should be an array
- //also determine if it is a leaf node
- if (options.isArray(property, newJpath, isLeaf )) {
- compressedObj[property] = [val];
- }else{
- compressedObj[property] = val;
- }
+ resolve(dst.buffer)
+ } else if (type === 'blob') {
+ if (!Blob) {
+ Blob = (__nccwpck_require__(20181).Blob)
}
+ resolve(new Blob(body, { type: stream[kContentType] }))
}
-
+
+ consumeFinish(consume)
+ } catch (err) {
+ stream.destroy(err)
}
- // if(text && text.length > 0) compressedObj[options.textNodeName] = text;
- if(typeof text === "string"){
- if(text.length > 0) compressedObj[options.textNodeName] = text;
- }else if(text !== undefined) compressedObj[options.textNodeName] = text;
- return compressedObj;
}
-function propName(obj){
- const keys = Object.keys(obj);
- for (let i = 0; i < keys.length; i++) {
- const key = keys[i];
- if(key !== ":@") return key;
+function consumePush (consume, chunk) {
+ consume.length += chunk.length
+ consume.body.push(chunk)
+}
+
+function consumeFinish (consume, err) {
+ if (consume.body === null) {
+ return
+ }
+
+ if (err) {
+ consume.reject(err)
+ } else {
+ consume.resolve()
}
+
+ consume.type = null
+ consume.stream = null
+ consume.resolve = null
+ consume.reject = null
+ consume.length = 0
+ consume.body = null
}
-function assignAttributes(obj, attrMap, jpath, options){
- if (attrMap) {
- const keys = Object.keys(attrMap);
- const len = keys.length; //don't make it inline
- for (let i = 0; i < len; i++) {
- const atrrName = keys[i];
- if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) {
- obj[atrrName] = [ attrMap[atrrName] ];
- } else {
- obj[atrrName] = attrMap[atrrName];
- }
+
+/***/ }),
+
+/***/ 87655:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+const assert = __nccwpck_require__(42613)
+const {
+ ResponseStatusCodeError
+} = __nccwpck_require__(68707)
+const { toUSVString } = __nccwpck_require__(3440)
+
+async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) {
+ assert(body)
+
+ let chunks = []
+ let limit = 0
+
+ for await (const chunk of body) {
+ chunks.push(chunk)
+ limit += chunk.length
+ if (limit > 128 * 1024) {
+ chunks = null
+ break
}
}
-}
-function isLeafTag(obj, options){
- const { textNodeName } = options;
- const propCount = Object.keys(obj).length;
-
- if (propCount === 0) {
- return true;
+ if (statusCode === 204 || !contentType || !chunks) {
+ process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
+ return
}
- if (
- propCount === 1 &&
- (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)
- ) {
- return true;
+ try {
+ if (contentType.startsWith('application/json')) {
+ const payload = JSON.parse(toUSVString(Buffer.concat(chunks)))
+ process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
+ return
+ }
+
+ if (contentType.startsWith('text/')) {
+ const payload = toUSVString(Buffer.concat(chunks))
+ process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
+ return
+ }
+ } catch (err) {
+ // Process in a fallback if error
}
- return false;
+ process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
}
-exports.prettify = prettify;
+
+module.exports = { getResolveErrorBodyCallback }
/***/ }),
-/***/ 9307:
-/***/ ((module) => {
+/***/ 81093:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-class XmlNode{
- constructor(tagname) {
- this.tagname = tagname;
- this.child = []; //nested tags, text, cdata, comments in order
- this[":@"] = {}; //attributes map
- }
- add(key,val){
- // this.child.push( {name : key, val: val, isCdata: isCdata });
- if(key === "__proto__") key = "#__proto__";
- this.child.push( {[key]: val });
- }
- addChild(node) {
- if(node.tagname === "__proto__") node.tagname = "#__proto__";
- if(node[":@"] && Object.keys(node[":@"]).length > 0){
- this.child.push( { [node.tagname]: node.child, [":@"]: node[":@"] });
- }else{
- this.child.push( { [node.tagname]: node.child });
- }
- };
-};
+const {
+ BalancedPoolMissingUpstreamError,
+ InvalidArgumentError
+} = __nccwpck_require__(68707)
+const {
+ PoolBase,
+ kClients,
+ kNeedDrain,
+ kAddClient,
+ kRemoveClient,
+ kGetDispatcher
+} = __nccwpck_require__(58640)
+const Pool = __nccwpck_require__(35076)
+const { kUrl, kInterceptors } = __nccwpck_require__(36443)
+const { parseOrigin } = __nccwpck_require__(3440)
+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')
-module.exports = XmlNode;
+function getGreatestCommonDivisor (a, b) {
+ if (b === 0) return a
+ return getGreatestCommonDivisor(b, a % b)
+}
-/***/ }),
+function defaultFactory (origin, opts) {
+ return new Pool(origin, opts)
+}
-/***/ 1970:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+class BalancedPool extends PoolBase {
+ constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) {
+ super()
-"use strict";
+ this[kOptions] = opts
+ this[kIndex] = -1
+ this[kCurrentWeight] = 0
-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.HttpProxyAgent = void 0;
-const net = __importStar(__nccwpck_require__(9278));
-const tls = __importStar(__nccwpck_require__(4756));
-const debug_1 = __importDefault(__nccwpck_require__(2830));
-const events_1 = __nccwpck_require__(4434);
-const agent_base_1 = __nccwpck_require__(8894);
-const url_1 = __nccwpck_require__(7016);
-const debug = (0, debug_1.default)('http-proxy-agent');
-/**
- * The `HttpProxyAgent` implements an HTTP Agent subclass that connects
- * to the specified "HTTP proxy server" in order to proxy HTTP requests.
- */
-class HttpProxyAgent extends agent_base_1.Agent {
- constructor(proxy, opts) {
- super(opts);
- this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy;
- this.proxyHeaders = opts?.headers ?? {};
- debug('Creating new HttpProxyAgent instance: %o', this.proxy.href);
- // Trim off the brackets from IPv6 addresses
- const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, '');
- const port = this.proxy.port
- ? parseInt(this.proxy.port, 10)
- : this.proxy.protocol === 'https:'
- ? 443
- : 80;
- this.connectOpts = {
- ...(opts ? omit(opts, 'headers') : null),
- host,
- port,
- };
+ this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100
+ this[kErrorPenalty] = this[kOptions].errorPenalty || 15
+
+ if (!Array.isArray(upstreams)) {
+ upstreams = [upstreams]
}
- addRequest(req, opts) {
- req._header = null;
- this.setRequestProps(req, opts);
- // @ts-expect-error `addRequest()` isn't defined in `@types/node`
- super.addRequest(req, opts);
+
+ if (typeof factory !== 'function') {
+ throw new InvalidArgumentError('factory must be a function.')
}
- setRequestProps(req, opts) {
- const { proxy } = this;
- const protocol = opts.secureEndpoint ? 'https:' : 'http:';
- const hostname = req.getHeader('host') || 'localhost';
- const base = `${protocol}//${hostname}`;
- const url = new url_1.URL(req.path, base);
- if (opts.port !== 80) {
- url.port = String(opts.port);
- }
- // Change the `http.ClientRequest` instance's "path" field
- // to the absolute path of the URL that will be requested.
- req.path = String(url);
- // Inject the `Proxy-Authorization` header if necessary.
- const headers = typeof this.proxyHeaders === 'function'
- ? this.proxyHeaders()
- : { ...this.proxyHeaders };
- if (proxy.username || proxy.password) {
- const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
- headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
- }
- if (!headers['Proxy-Connection']) {
- headers['Proxy-Connection'] = this.keepAlive
- ? 'Keep-Alive'
- : 'close';
- }
- for (const name of Object.keys(headers)) {
- const value = headers[name];
- if (value) {
- req.setHeader(name, value);
- }
- }
+
+ this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool)
+ ? opts.interceptors.BalancedPool
+ : []
+ this[kFactory] = factory
+
+ for (const upstream of upstreams) {
+ this.addUpstream(upstream)
}
- async connect(req, opts) {
- req._header = null;
- if (!req.path.includes('://')) {
- this.setRequestProps(req, opts);
- }
- // At this point, the http ClientRequest's internal `_header` field
- // might have already been set. If this is the case then we'll need
- // to re-generate the string since we just changed the `req.path`.
- let first;
- let endOfHeaders;
- debug('Regenerating stored HTTP header string for request');
- req._implicitHeader();
- if (req.outputData && req.outputData.length > 0) {
- debug('Patching connection write() output buffer with updated header');
- first = req.outputData[0].data;
- endOfHeaders = first.indexOf('\r\n\r\n') + 4;
- req.outputData[0].data =
- req._header + first.substring(endOfHeaders);
- debug('Output buffer: %o', req.outputData[0].data);
- }
- // Create a socket connection to the proxy server.
- let socket;
- if (this.proxy.protocol === 'https:') {
- debug('Creating `tls.Socket`: %o', this.connectOpts);
- socket = tls.connect(this.connectOpts);
- }
- else {
- debug('Creating `net.Socket`: %o', this.connectOpts);
- socket = net.connect(this.connectOpts);
- }
- // Wait for the socket's `connect` event, so that this `callback()`
- // function throws instead of the `http` request machinery. This is
- // important for i.e. `PacProxyAgent` which determines a failed proxy
- // connection via the `callback()` function throwing.
- await (0, events_1.once)(socket, 'connect');
- return socket;
+ 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
}
-}
-HttpProxyAgent.protocols = ['http', 'https'];
-exports.HttpProxyAgent = HttpProxyAgent;
-function omit(obj, ...keys) {
- const ret = {};
- let key;
- for (key in obj) {
- if (!keys.includes(key)) {
- ret[key] = obj[key];
- }
+ 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]
}
- return ret;
-}
-//# sourceMappingURL=index.js.map
-/***/ }),
+ this._updateBalancedPoolStats()
-/***/ 3669:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ return this
+ }
-"use strict";
+ _updateBalancedPoolStats () {
+ this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0)
+ }
-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]; } };
+ 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)
}
- 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.HttpsProxyAgent = void 0;
-const net = __importStar(__nccwpck_require__(9278));
-const tls = __importStar(__nccwpck_require__(4756));
-const assert_1 = __importDefault(__nccwpck_require__(2613));
-const debug_1 = __importDefault(__nccwpck_require__(2830));
-const agent_base_1 = __nccwpck_require__(8894);
-const url_1 = __nccwpck_require__(7016);
-const parse_proxy_response_1 = __nccwpck_require__(7943);
-const debug = (0, debug_1.default)('https-proxy-agent');
-const setServernameFromNonIpHost = (options) => {
- if (options.servername === undefined &&
- options.host &&
- !net.isIP(options.host)) {
- return {
- ...options,
- servername: options.host,
- };
+
+ 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()
}
- return options;
-};
-/**
- * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to
- * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests.
- *
- * Outgoing HTTP requests are first tunneled through the proxy server using the
- * `CONNECT` HTTP request method to establish a connection to the proxy server,
- * and then the proxy server connects to the destination target and issues the
- * HTTP request from the proxy server.
- *
- * `https:` requests have their socket connection upgraded to TLS once
- * the connection to the proxy server has been established.
- */
-class HttpsProxyAgent extends agent_base_1.Agent {
- constructor(proxy, opts) {
- super(opts);
- this.options = { path: undefined };
- this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy;
- this.proxyHeaders = opts?.headers ?? {};
- debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href);
- // Trim off the brackets from IPv6 addresses
- const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, '');
- const port = this.proxy.port
- ? parseInt(this.proxy.port, 10)
- : this.proxy.protocol === 'https:'
- ? 443
- : 80;
- this.connectOpts = {
- // Attempt to negotiate http/1.1 for proxy servers that support http/2
- ALPNProtocols: ['http/1.1'],
- ...(opts ? omit(opts, 'headers') : null),
- host,
- port,
- };
+
+ const dispatcher = this[kClients].find(dispatcher => (
+ !dispatcher[kNeedDrain] &&
+ dispatcher.closed !== true &&
+ dispatcher.destroyed !== true
+ ))
+
+ if (!dispatcher) {
+ return
}
- /**
- * Called when the node-core HTTP client library is creating a
- * new HTTP request.
- */
- async connect(req, opts) {
- const { proxy } = this;
- if (!opts.host) {
- throw new TypeError('No "host" provided');
- }
- // Create a socket connection to the proxy server.
- let socket;
- if (proxy.protocol === 'https:') {
- debug('Creating `tls.Socket`: %o', this.connectOpts);
- socket = tls.connect(setServernameFromNonIpHost(this.connectOpts));
- }
- else {
- debug('Creating `net.Socket`: %o', this.connectOpts);
- socket = net.connect(this.connectOpts);
- }
- const headers = typeof this.proxyHeaders === 'function'
- ? this.proxyHeaders()
- : { ...this.proxyHeaders };
- const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
- let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`;
- // Inject the `Proxy-Authorization` header if necessary.
- if (proxy.username || proxy.password) {
- const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
- headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
- }
- headers.Host = `${host}:${opts.port}`;
- if (!headers['Proxy-Connection']) {
- headers['Proxy-Connection'] = this.keepAlive
- ? 'Keep-Alive'
- : 'close';
- }
- for (const name of Object.keys(headers)) {
- payload += `${name}: ${headers[name]}\r\n`;
- }
- const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket);
- socket.write(`${payload}\r\n`);
- const { connect, buffered } = await proxyResponsePromise;
- req.emit('proxyConnect', connect);
- this.emit('proxyConnect', connect, req);
- if (connect.statusCode === 200) {
- req.once('socket', resume);
- if (opts.secureEndpoint) {
- // The proxy is connecting to a TLS server, so upgrade
- // this socket connection to a TLS connection.
- debug('Upgrading socket connection to TLS');
- return tls.connect({
- ...omit(setServernameFromNonIpHost(opts), 'host', 'path', 'port'),
- socket,
- });
- }
- return socket;
- }
- // Some other status code that's not 200... need to re-play the HTTP
- // header "data" events onto the socket once the HTTP machinery is
- // attached so that the node core `http` can parse and handle the
- // error status code.
- // Close the original socket, and a new "fake" socket is returned
- // instead, so that the proxy doesn't get the HTTP request
- // written to it (which may contain `Authorization` headers or other
- // sensitive data).
- //
- // See: https://hackerone.com/reports/541502
- socket.destroy();
- const fakeSocket = new net.Socket({ writable: false });
- fakeSocket.readable = true;
- // Need to wait for the "socket" event to re-play the "data" events.
- req.once('socket', (s) => {
- debug('Replaying proxy buffer for failed request');
- (0, assert_1.default)(s.listenerCount('data') > 0);
- // Replay the "buffered" Buffer onto the fake `socket`, since at
- // this point the HTTP module machinery has been hooked up for
- // the user.
- s.push(buffered);
- s.push(null);
- });
- return fakeSocket;
+
+ const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true)
+
+ if (allClientsBusy) {
+ return
}
-}
-HttpsProxyAgent.protocols = ['http', 'https'];
-exports.HttpsProxyAgent = HttpsProxyAgent;
-function resume(socket) {
- socket.resume();
-}
-function omit(obj, ...keys) {
- const ret = {};
- let key;
- for (key in obj) {
- if (!keys.includes(key)) {
- ret[key] = obj[key];
+
+ 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
+ }
}
- return ret;
+
+ this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight]
+ this[kIndex] = maxWeightIndex
+ return this[kClients][maxWeightIndex]
+ }
}
-//# sourceMappingURL=index.js.map
+
+module.exports = BalancedPool
+
/***/ }),
-/***/ 7943:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ 50479:
+/***/ ((module, __unused_webpack_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.parseProxyResponse = void 0;
-const debug_1 = __importDefault(__nccwpck_require__(2830));
-const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response');
-function parseProxyResponse(socket) {
- return new Promise((resolve, reject) => {
- // we need to buffer any HTTP traffic that happens with the proxy before we get
- // the CONNECT response, so that if the response is anything other than an "200"
- // response code, then we can re-play the "data" events on the socket once the
- // HTTP parser is hooked up...
- let buffersLength = 0;
- const buffers = [];
- function read() {
- const b = socket.read();
- if (b)
- ondata(b);
- else
- socket.once('readable', read);
- }
- function cleanup() {
- socket.removeListener('end', onend);
- socket.removeListener('error', onerror);
- socket.removeListener('readable', read);
- }
- function onend() {
- cleanup();
- debug('onend');
- reject(new Error('Proxy connection ended before receiving CONNECT response'));
- }
- function onerror(err) {
- cleanup();
- debug('onerror %o', err);
- reject(err);
- }
- function ondata(b) {
- buffers.push(b);
- buffersLength += b.length;
- const buffered = Buffer.concat(buffers, buffersLength);
- const endOfHeaders = buffered.indexOf('\r\n\r\n');
- if (endOfHeaders === -1) {
- // keep buffering
- debug('have not received end of HTTP headers yet...');
- read();
- return;
- }
- const headerParts = buffered
- .slice(0, endOfHeaders)
- .toString('ascii')
- .split('\r\n');
- const firstLine = headerParts.shift();
- if (!firstLine) {
- socket.destroy();
- return reject(new Error('No header received from proxy CONNECT response'));
- }
- const firstLineParts = firstLine.split(' ');
- const statusCode = +firstLineParts[1];
- const statusText = firstLineParts.slice(2).join(' ');
- const headers = {};
- for (const header of headerParts) {
- if (!header)
- continue;
- const firstColon = header.indexOf(':');
- if (firstColon === -1) {
- socket.destroy();
- return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`));
- }
- const key = header.slice(0, firstColon).toLowerCase();
- const value = header.slice(firstColon + 1).trimStart();
- const current = headers[key];
- if (typeof current === 'string') {
- headers[key] = [current, value];
- }
- else if (Array.isArray(current)) {
- current.push(value);
- }
- else {
- headers[key] = value;
- }
- }
- debug('got proxy server response: %o %o', firstLine, headers);
- cleanup();
- resolve({
- connect: {
- statusCode,
- statusText,
- headers,
- },
- buffered,
- });
- }
- socket.on('error', onerror);
- socket.on('end', onend);
- read();
- });
-}
-exports.parseProxyResponse = parseProxyResponse;
-//# sourceMappingURL=parse-proxy-response.js.map
-/***/ }),
+const { kConstruct } = __nccwpck_require__(80296)
+const { urlEquals, fieldValues: getFieldValues } = __nccwpck_require__(23993)
+const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(3440)
+const { kHeadersList } = __nccwpck_require__(36443)
+const { webidl } = __nccwpck_require__(74222)
+const { Response, cloneResponse } = __nccwpck_require__(48676)
+const { Request } = __nccwpck_require__(25194)
+const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(89710)
+const { fetching } = __nccwpck_require__(12315)
+const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(15523)
+const assert = __nccwpck_require__(42613)
+const { getGlobalDispatcher } = __nccwpck_require__(32581)
-/***/ 3772:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/**
+ * @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
+ */
-module.exports = minimatch
-minimatch.Minimatch = Minimatch
+/**
+ * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list
+ * @typedef {[any, any][]} requestResponseList
+ */
-var path = (function () { try { return __nccwpck_require__(6928) } catch (e) {}}()) || {
- sep: '/'
-}
-minimatch.sep = path.sep
+class Cache {
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list
+ * @type {requestResponseList}
+ */
+ #relevantRequestResponseList
-var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
-var expand = __nccwpck_require__(4691)
+ constructor () {
+ if (arguments[0] !== kConstruct) {
+ webidl.illegalConstructor()
+ }
-var plTypes = {
- '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
- '?': { open: '(?:', close: ')?' },
- '+': { open: '(?:', close: ')+' },
- '*': { open: '(?:', close: ')*' },
- '@': { open: '(?:', close: ')' }
-}
+ this.#relevantRequestResponseList = arguments[1]
+ }
-// any single thing other than /
-// don't need to escape / when using new RegExp()
-var qmark = '[^/]'
+ async match (request, options = {}) {
+ webidl.brandCheck(this, Cache)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' })
-// * => any number of characters
-var star = qmark + '*?'
+ request = webidl.converters.RequestInfo(request)
+ options = webidl.converters.CacheQueryOptions(options)
-// ** when dots are allowed. Anything goes, except .. and .
-// not (^ or / followed by one or two dots followed by $ or /),
-// followed by anything, any number of times.
-var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
+ const p = await this.matchAll(request, options)
-// not a ^ or / followed by a dot,
-// followed by anything, any number of times.
-var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
+ if (p.length === 0) {
+ return
+ }
-// characters that need to be escaped in RegExp.
-var reSpecials = charSet('().*{}+?[]^$\\!')
+ return p[0]
+ }
-// "abc" -> { a:true, b:true, c:true }
-function charSet (s) {
- return s.split('').reduce(function (set, c) {
- set[c] = true
- return set
- }, {})
-}
+ async matchAll (request = undefined, options = {}) {
+ webidl.brandCheck(this, Cache)
-// normalizes slashes.
-var slashSplit = /\/+/
+ if (request !== undefined) request = webidl.converters.RequestInfo(request)
+ options = webidl.converters.CacheQueryOptions(options)
-minimatch.filter = filter
-function filter (pattern, options) {
- options = options || {}
- return function (p, i, list) {
- return minimatch(p, pattern, options)
- }
-}
+ // 1.
+ let r = null
-function ext (a, b) {
- b = b || {}
- var t = {}
- Object.keys(a).forEach(function (k) {
- t[k] = a[k]
- })
- Object.keys(b).forEach(function (k) {
- t[k] = b[k]
- })
- return t
-}
+ // 2.
+ if (request !== undefined) {
+ if (request instanceof Request) {
+ // 2.1.1
+ r = request[kState]
-minimatch.defaults = function (def) {
- if (!def || typeof def !== 'object' || !Object.keys(def).length) {
- return minimatch
- }
+ // 2.1.2
+ if (r.method !== 'GET' && !options.ignoreMethod) {
+ return []
+ }
+ } else if (typeof request === 'string') {
+ // 2.2.1
+ r = new Request(request)[kState]
+ }
+ }
- var orig = minimatch
+ // 5.
+ // 5.1
+ const responses = []
- var m = function minimatch (p, pattern, options) {
- return orig(p, pattern, ext(def, options))
- }
+ // 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)
- m.Minimatch = function Minimatch (pattern, options) {
- return new orig.Minimatch(pattern, ext(def, options))
- }
- m.Minimatch.defaults = function defaults (options) {
- return orig.defaults(ext(def, options)).Minimatch
- }
+ // 5.3.2
+ for (const requestResponse of requestResponses) {
+ responses.push(requestResponse[1])
+ }
+ }
- m.filter = function filter (pattern, options) {
- return orig.filter(pattern, ext(def, options))
- }
+ // 5.4
+ // We don't implement CORs so we don't need to loop over the responses, yay!
- m.defaults = function defaults (options) {
- return orig.defaults(ext(def, options))
- }
+ // 5.5.1
+ const responseList = []
- m.makeRe = function makeRe (pattern, options) {
- return orig.makeRe(pattern, ext(def, options))
- }
+ // 5.5.2
+ for (const response of responses) {
+ // 5.5.2.1
+ const responseObject = new Response(response.body?.source ?? null)
+ const body = responseObject[kState].body
+ responseObject[kState] = response
+ responseObject[kState].body = body
+ responseObject[kHeaders][kHeadersList] = response.headersList
+ responseObject[kHeaders][kGuard] = 'immutable'
- m.braceExpand = function braceExpand (pattern, options) {
- return orig.braceExpand(pattern, ext(def, options))
- }
+ responseList.push(responseObject)
+ }
- m.match = function (list, pattern, options) {
- return orig.match(list, pattern, ext(def, options))
+ // 6.
+ return Object.freeze(responseList)
}
- return m
-}
+ async add (request) {
+ webidl.brandCheck(this, Cache)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' })
-Minimatch.defaults = function (def) {
- return minimatch.defaults(def).Minimatch
-}
+ request = webidl.converters.RequestInfo(request)
-function minimatch (p, pattern, options) {
- assertValidPattern(pattern)
+ // 1.
+ const requests = [request]
- if (!options) options = {}
+ // 2.
+ const responseArrayPromise = this.addAll(requests)
- // shortcut: comments match nothing.
- if (!options.nocomment && pattern.charAt(0) === '#') {
- return false
+ // 3.
+ return await responseArrayPromise
}
- return new Minimatch(pattern, options).match(p)
-}
+ async addAll (requests) {
+ webidl.brandCheck(this, Cache)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' })
-function Minimatch (pattern, options) {
- if (!(this instanceof Minimatch)) {
- return new Minimatch(pattern, options)
- }
+ requests = webidl.converters['sequence'](requests)
- assertValidPattern(pattern)
+ // 1.
+ const responsePromises = []
- if (!options) options = {}
+ // 2.
+ const requestList = []
- pattern = pattern.trim()
+ // 3.
+ for (const request of requests) {
+ if (typeof request === 'string') {
+ continue
+ }
- // windows support: need to use /, not \
- if (!options.allowWindowsEscape && path.sep !== '/') {
- pattern = pattern.split(path.sep).join('/')
+ // 3.1
+ const r = request[kState]
+
+ // 3.2
+ if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') {
+ throw webidl.errors.exception({
+ header: 'Cache.addAll',
+ 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 = new Request(request)[kState]
+
+ // 5.2
+ if (!urlIsHttpHttpsScheme(r.url)) {
+ throw webidl.errors.exception({
+ header: 'Cache.addAll',
+ 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,
+ dispatcher: getGlobalDispatcher(),
+ 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
}
- this.options = options
- this.set = []
- this.pattern = pattern
- this.regexp = null
- this.negate = false
- this.comment = false
- this.empty = false
- this.partial = !!options.partial
+ async put (request, response) {
+ webidl.brandCheck(this, Cache)
+ webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' })
+
+ request = webidl.converters.RequestInfo(request)
+ response = webidl.converters.Response(response)
+
+ // 1.
+ let innerRequest = null
+
+ // 2.
+ if (request instanceof Request) {
+ innerRequest = request[kState]
+ } else { // 3.
+ innerRequest = new Request(request)[kState]
+ }
+
+ // 4.
+ if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') {
+ throw webidl.errors.exception({
+ header: 'Cache.put',
+ message: 'Expected an http/s scheme when method is not GET'
+ })
+ }
+
+ // 5.
+ const innerResponse = response[kState]
+
+ // 6.
+ if (innerResponse.status === 206) {
+ throw webidl.errors.exception({
+ header: 'Cache.put',
+ message: 'Got 206 status'
+ })
+ }
- // make the set of regexps etc.
- this.make()
-}
+ // 7.
+ if (innerResponse.headersList.contains('vary')) {
+ // 7.1.
+ const fieldValues = getFieldValues(innerResponse.headersList.get('vary'))
-Minimatch.prototype.debug = function () {}
+ // 7.2.
+ for (const fieldValue of fieldValues) {
+ // 7.2.1
+ if (fieldValue === '*') {
+ throw webidl.errors.exception({
+ header: 'Cache.put',
+ message: 'Got * vary field value'
+ })
+ }
+ }
+ }
-Minimatch.prototype.make = make
-function make () {
- var pattern = this.pattern
- var options = this.options
+ // 8.
+ if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) {
+ throw webidl.errors.exception({
+ header: 'Cache.put',
+ message: 'Response body is locked or disturbed'
+ })
+ }
- // empty patterns and comments match nothing.
- if (!options.nocomment && pattern.charAt(0) === '#') {
- this.comment = true
- return
- }
- if (!pattern) {
- this.empty = true
- return
- }
+ // 9.
+ const clonedResponse = cloneResponse(innerResponse)
- // step 1: figure out negation, etc.
- this.parseNegate()
+ // 10.
+ const bodyReadPromise = createDeferredPromise()
- // step 2: expand braces
- var set = this.globSet = this.braceExpand()
+ // 11.
+ if (innerResponse.body != null) {
+ // 11.1
+ const stream = innerResponse.body.stream
- if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) }
+ // 11.2
+ const reader = stream.getReader()
- this.debug(this.pattern, set)
+ // 11.3
+ readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject)
+ } else {
+ bodyReadPromise.resolve(undefined)
+ }
- // step 3: now we have a set, so turn each one into a series of path-portion
- // matching patterns.
- // These will be regexps, except in the case of "**", which is
- // set to the GLOBSTAR object for globstar behavior,
- // and will not contain any / characters
- set = this.globParts = set.map(function (s) {
- return s.split(slashSplit)
- })
+ // 12.
+ /** @type {CacheBatchOperation[]} */
+ const operations = []
- this.debug(this.pattern, set)
+ // 13.
+ /** @type {CacheBatchOperation} */
+ const operation = {
+ type: 'put', // 14.
+ request: innerRequest, // 15.
+ response: clonedResponse // 16.
+ }
- // glob --> regexps
- set = set.map(function (s, si, set) {
- return s.map(this.parse, this)
- }, this)
+ // 17.
+ operations.push(operation)
- this.debug(this.pattern, set)
+ // 19.
+ const bytes = await bodyReadPromise.promise
- // filter out everything that didn't compile properly.
- set = set.filter(function (s) {
- return s.indexOf(false) === -1
- })
+ if (clonedResponse.body != null) {
+ clonedResponse.body.source = bytes
+ }
- this.debug(this.pattern, set)
+ // 19.1
+ const cacheJobPromise = createDeferredPromise()
- this.set = set
-}
+ // 19.2.1
+ let errorData = null
-Minimatch.prototype.parseNegate = parseNegate
-function parseNegate () {
- var pattern = this.pattern
- var negate = false
- var options = this.options
- var negateOffset = 0
+ // 19.2.2
+ try {
+ this.#batchCacheOperations(operations)
+ } catch (e) {
+ errorData = e
+ }
- if (options.nonegate) return
+ // 19.2.3
+ queueMicrotask(() => {
+ // 19.2.3.1
+ if (errorData === null) {
+ cacheJobPromise.resolve()
+ } else { // 19.2.3.2
+ cacheJobPromise.reject(errorData)
+ }
+ })
- for (var i = 0, l = pattern.length
- ; i < l && pattern.charAt(i) === '!'
- ; i++) {
- negate = !negate
- negateOffset++
+ return cacheJobPromise.promise
}
- if (negateOffset) this.pattern = pattern.substr(negateOffset)
- this.negate = negate
-}
+ async delete (request, options = {}) {
+ webidl.brandCheck(this, Cache)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' })
-// Brace expansion:
-// a{b,c}d -> abd acd
-// a{b,}c -> abc ac
-// a{0..3}d -> a0d a1d a2d a3d
-// a{b,c{d,e}f}g -> abg acdfg acefg
-// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
-//
-// Invalid sets are not expanded.
-// a{2..}b -> a{2..}b
-// a{b}c -> a{b}c
-minimatch.braceExpand = function (pattern, options) {
- return braceExpand(pattern, options)
-}
+ request = webidl.converters.RequestInfo(request)
+ options = webidl.converters.CacheQueryOptions(options)
-Minimatch.prototype.braceExpand = braceExpand
+ /**
+ * @type {Request}
+ */
+ let r = null
-function braceExpand (pattern, options) {
- if (!options) {
- if (this instanceof Minimatch) {
- options = this.options
+ if (request instanceof Request) {
+ r = request[kState]
+
+ if (r.method !== 'GET' && !options.ignoreMethod) {
+ return false
+ }
} else {
- options = {}
+ assert(typeof request === 'string')
+
+ r = new Request(request)[kState]
}
- }
- pattern = typeof pattern === 'undefined'
- ? this.pattern : pattern
+ /** @type {CacheBatchOperation[]} */
+ const operations = []
- assertValidPattern(pattern)
+ /** @type {CacheBatchOperation} */
+ const operation = {
+ type: 'delete',
+ request: r,
+ options
+ }
- // Thanks to Yeting Li for
- // improving this regexp to avoid a ReDOS vulnerability.
- if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
- // shortcut. no need to expand.
- return [pattern]
- }
+ operations.push(operation)
- return expand(pattern)
-}
+ const cacheJobPromise = createDeferredPromise()
-var MAX_PATTERN_LENGTH = 1024 * 64
-var assertValidPattern = function (pattern) {
- if (typeof pattern !== 'string') {
- throw new TypeError('invalid pattern')
- }
+ let errorData = null
+ let requestResponses
- if (pattern.length > MAX_PATTERN_LENGTH) {
- throw new TypeError('pattern is too long')
+ try {
+ requestResponses = this.#batchCacheOperations(operations)
+ } catch (e) {
+ errorData = e
+ }
+
+ queueMicrotask(() => {
+ if (errorData === null) {
+ cacheJobPromise.resolve(!!requestResponses?.length)
+ } else {
+ cacheJobPromise.reject(errorData)
+ }
+ })
+
+ return cacheJobPromise.promise
}
-}
-// parse a component of the expanded set.
-// At this point, no pattern may contain "/" in it
-// so we're going to return a 2d array, where each entry is the full
-// pattern, split on '/', and then turned into a regular expression.
-// A regexp is made at the end which joins each array with an
-// escaped /, and another full one which joins each regexp with |.
-//
-// Following the lead of Bash 4.1, note that "**" only has special meaning
-// when it is the *only* thing in a path portion. Otherwise, any series
-// of * is equivalent to a single *. Globstar behavior is enabled by
-// default, and can be disabled by setting options.noglobstar.
-Minimatch.prototype.parse = parse
-var SUBPARSE = {}
-function parse (pattern, isSub) {
- assertValidPattern(pattern)
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys
+ * @param {any} request
+ * @param {import('../../types/cache').CacheQueryOptions} options
+ * @returns {readonly Request[]}
+ */
+ async keys (request = undefined, options = {}) {
+ webidl.brandCheck(this, Cache)
- var options = this.options
+ if (request !== undefined) request = webidl.converters.RequestInfo(request)
+ options = webidl.converters.CacheQueryOptions(options)
- // shortcuts
- if (pattern === '**') {
- if (!options.noglobstar)
- return GLOBSTAR
- else
- pattern = '*'
- }
- if (pattern === '') return ''
+ // 1.
+ let r = null
- var re = ''
- var hasMagic = !!options.nocase
- var escaping = false
- // ? => one single character
- var patternListStack = []
- var negativeLists = []
- var stateChar
- var inClass = false
- var reClassStart = -1
- var classStart = -1
- // . and .. never match anything that doesn't start with .,
- // even when options.dot is set.
- var patternStart = pattern.charAt(0) === '.' ? '' // anything
- // not (start or / followed by . or .. followed by / or end)
- : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
- : '(?!\\.)'
- var self = this
+ // 2.
+ if (request !== undefined) {
+ // 2.1
+ if (request instanceof Request) {
+ // 2.1.1
+ r = request[kState]
- function clearStateChar () {
- if (stateChar) {
- // we had some state-tracking character
- // that wasn't consumed by this pass.
- switch (stateChar) {
- case '*':
- re += star
- hasMagic = true
- break
- case '?':
- re += qmark
- hasMagic = true
- break
- default:
- re += '\\' + stateChar
- break
+ // 2.1.2
+ if (r.method !== 'GET' && !options.ignoreMethod) {
+ return []
+ }
+ } else if (typeof request === 'string') { // 2.2
+ r = new Request(request)[kState]
}
- self.debug('clearStateChar %j %j', stateChar, re)
- stateChar = false
}
- }
- for (var i = 0, len = pattern.length, c
- ; (i < len) && (c = pattern.charAt(i))
- ; i++) {
- this.debug('%s\t%s %s %j', pattern, i, re, c)
+ // 4.
+ const promise = createDeferredPromise()
- // skip over any that are escaped.
- if (escaping && reSpecials[c]) {
- re += '\\' + c
- escaping = false
- continue
- }
+ // 5.
+ // 5.1
+ const requests = []
- switch (c) {
- /* istanbul ignore next */
- case '/': {
- // completely not allowed, even escaped.
- // Should already be path-split by now.
- return false
+ // 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)
- case '\\':
- clearStateChar()
- escaping = true
- continue
-
- // the various stateChar values
- // for the "extglob" stuff.
- case '?':
- case '*':
- case '+':
- case '@':
- case '!':
- this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
-
- // all of those are literals inside a class, except that
- // the glob [!a] means [^a] in regexp
- if (inClass) {
- this.debug(' in class')
- if (c === '!' && i === classStart + 1) c = '^'
- re += c
- continue
- }
+ // 5.3.2
+ for (const requestResponse of requestResponses) {
+ // 5.3.2.1
+ requests.push(requestResponse[0])
+ }
+ }
- // if we already have a stateChar, then it means
- // that there was something like ** or +? in there.
- // Handle the stateChar, then proceed with this one.
- self.debug('call clearStateChar %j', stateChar)
- clearStateChar()
- stateChar = c
- // if extglob is disabled, then +(asdf|foo) isn't a thing.
- // just clear the statechar *now*, rather than even diving into
- // the patternList stuff.
- if (options.noext) clearStateChar()
- continue
+ // 5.4
+ queueMicrotask(() => {
+ // 5.4.1
+ const requestList = []
- case '(':
- if (inClass) {
- re += '('
- continue
- }
+ // 5.4.2
+ for (const request of requests) {
+ const requestObject = new Request('https://a')
+ requestObject[kState] = request
+ requestObject[kHeaders][kHeadersList] = request.headersList
+ requestObject[kHeaders][kGuard] = 'immutable'
+ requestObject[kRealm] = request.client
- if (!stateChar) {
- re += '\\('
- continue
- }
+ // 5.4.2.1
+ requestList.push(requestObject)
+ }
- patternListStack.push({
- type: stateChar,
- start: i - 1,
- reStart: re.length,
- open: plTypes[stateChar].open,
- close: plTypes[stateChar].close
- })
- // negation is (?:(?!js)[^/]*)
- re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
- this.debug('plType %j %j', stateChar, re)
- stateChar = false
- continue
+ // 5.4.3
+ promise.resolve(Object.freeze(requestList))
+ })
- case ')':
- if (inClass || !patternListStack.length) {
- re += '\\)'
- continue
- }
+ return promise.promise
+ }
- clearStateChar()
- hasMagic = true
- var pl = patternListStack.pop()
- // negation is (?:(?!js)[^/]*)
- // The others are (?:)
- re += pl.close
- if (pl.type === '!') {
- negativeLists.push(pl)
- }
- pl.reEnd = re.length
- continue
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm
+ * @param {CacheBatchOperation[]} operations
+ * @returns {requestResponseList}
+ */
+ #batchCacheOperations (operations) {
+ // 1.
+ const cache = this.#relevantRequestResponseList
- case '|':
- if (inClass || !patternListStack.length || escaping) {
- re += '\\|'
- escaping = false
- continue
- }
+ // 2.
+ const backupCache = [...cache]
- clearStateChar()
- re += '|'
- continue
+ // 3.
+ const addedItems = []
- // these are mostly the same in regexp and glob
- case '[':
- // swallow any state-tracking char before the [
- clearStateChar()
+ // 4.1
+ const resultList = []
- if (inClass) {
- re += '\\' + c
- continue
+ 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"'
+ })
}
- inClass = true
- classStart = i
- reClassStart = re.length
- re += c
- continue
-
- case ']':
- // a right bracket shall lose its special
- // meaning and represent itself in
- // a bracket expression if it occurs
- // first in the list. -- POSIX.2 2.8.3.2
- if (i === classStart + 1 || !inClass) {
- re += '\\' + c
- escaping = false
- continue
+ // 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'
+ })
}
- // handle the case where we left a class open.
- // "[z-a]" is valid, equivalent to "\[z-a\]"
- // split where the last [ was, make sure we don't have
- // an invalid re. if so, re-walk the contents of the
- // would-be class to re-translate any characters that
- // were passed through as-is
- // TODO: It would probably be faster to determine this
- // without a try/catch and a new RegExp, but it's tricky
- // to do safely. For now, this is safe and works.
- var cs = pattern.substring(classStart + 1, i)
- try {
- RegExp('[' + cs + ']')
- } catch (er) {
- // not a valid class!
- var sp = this.parse(cs, SUBPARSE)
- re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
- hasMagic = hasMagic || sp[1]
- inClass = false
- continue
+ // 4.2.3
+ if (this.#queryCache(operation.request, operation.options, addedItems).length) {
+ throw new DOMException('???', 'InvalidStateError')
}
- // finish up the class.
- hasMagic = true
- inClass = false
- re += c
- continue
+ // 4.2.4
+ let requestResponses
+
+ // 4.2.5
+ if (operation.type === 'delete') {
+ // 4.2.5.1
+ requestResponses = this.#queryCache(operation.request, operation.options)
- default:
- // swallow any state char that wasn't consumed
- clearStateChar()
+ // TODO: the spec is wrong, this is needed to pass WPTs
+ if (requestResponses.length === 0) {
+ return []
+ }
- if (escaping) {
- // no need
- escaping = false
- } else if (reSpecials[c]
- && !(c === '^' && inClass)) {
- re += '\\'
- }
+ // 4.2.5.2
+ for (const requestResponse of requestResponses) {
+ const idx = cache.indexOf(requestResponse)
+ assert(idx !== -1)
- re += c
+ // 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'
+ })
+ }
- } // switch
- } // for
+ // 4.2.6.2
+ const r = operation.request
- // handle the case where we left a class open.
- // "[abc" is valid, equivalent to "\[abc"
- if (inClass) {
- // split where the last [ was, and escape it
- // this is a huge pita. We now have to re-walk
- // the contents of the would-be class to re-translate
- // any characters that were passed through as-is
- cs = pattern.substr(classStart + 1)
- sp = this.parse(cs, SUBPARSE)
- re = re.substr(0, reClassStart) + '\\[' + sp[0]
- hasMagic = hasMagic || sp[1]
- }
+ // 4.2.6.3
+ if (!urlIsHttpHttpsScheme(r.url)) {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'expected http or https scheme'
+ })
+ }
- // handle the case where we had a +( thing at the *end*
- // of the pattern.
- // each pattern list stack adds 3 chars, and we need to go through
- // and escape any | chars that were passed through as-is for the regexp.
- // Go through and escape them, taking care not to double-escape any
- // | chars that were already escaped.
- for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
- var tail = re.slice(pl.reStart + pl.open.length)
- this.debug('setting tail', re, pl)
- // maybe some even number of \, then maybe 1 \, followed by a |
- tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
- if (!$2) {
- // the | isn't already escaped, so escape it.
- $2 = '\\'
- }
+ // 4.2.6.4
+ if (r.method !== 'GET') {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'not get method'
+ })
+ }
- // need to escape all those slashes *again*, without escaping the
- // one that we need for escaping the | character. As it works out,
- // escaping an even number of slashes can be done by simply repeating
- // it exactly after itself. That's why this trick works.
- //
- // I am sorry that you have to see this.
- return $1 + $1 + $2 + '|'
- })
+ // 4.2.6.5
+ if (operation.options != null) {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'options must not be defined'
+ })
+ }
- this.debug('tail=%j\n %s', tail, tail, pl, re)
- var t = pl.type === '*' ? star
- : pl.type === '?' ? qmark
- : '\\' + pl.type
+ // 4.2.6.6
+ requestResponses = this.#queryCache(operation.request)
- hasMagic = true
- re = re.slice(0, pl.reStart) + t + '\\(' + tail
- }
+ // 4.2.6.7
+ for (const requestResponse of requestResponses) {
+ const idx = cache.indexOf(requestResponse)
+ assert(idx !== -1)
- // handle trailing things that only matter at the very end.
- clearStateChar()
- if (escaping) {
- // trailing \\
- re += '\\\\'
- }
+ // 4.2.6.7.1
+ cache.splice(idx, 1)
+ }
- // only need to apply the nodot start if the re starts with
- // something that could conceivably capture a dot
- var addPatternStart = false
- switch (re.charAt(0)) {
- case '[': case '.': case '(': addPatternStart = true
- }
+ // 4.2.6.8
+ cache.push([operation.request, operation.response])
- // Hack to work around lack of negative lookbehind in JS
- // A pattern like: *.!(x).!(y|z) needs to ensure that a name
- // like 'a.xyz.yz' doesn't match. So, the first negative
- // lookahead, has to look ALL the way ahead, to the end of
- // the pattern.
- for (var n = negativeLists.length - 1; n > -1; n--) {
- var nl = negativeLists[n]
+ // 4.2.6.10
+ addedItems.push([operation.request, operation.response])
+ }
- var nlBefore = re.slice(0, nl.reStart)
- var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
- var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
- var nlAfter = re.slice(nl.reEnd)
+ // 4.2.7
+ resultList.push([operation.request, operation.response])
+ }
- nlLast += nlAfter
+ // 4.3
+ return resultList
+ } catch (e) { // 5.
+ // 5.1
+ this.#relevantRequestResponseList.length = 0
- // Handle nested stuff like *(*.js|!(*.json)), where open parens
- // mean that we should *not* include the ) in the bit that is considered
- // "after" the negated section.
- var openParensBefore = nlBefore.split('(').length - 1
- var cleanAfter = nlAfter
- for (i = 0; i < openParensBefore; i++) {
- cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
- }
- nlAfter = cleanAfter
+ // 5.2
+ this.#relevantRequestResponseList = backupCache
- var dollar = ''
- if (nlAfter === '' && isSub !== SUBPARSE) {
- dollar = '$'
+ // 5.3
+ throw e
}
- var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
- re = newRe
- }
-
- // if the re is not "" at this point, then we need to make sure
- // it doesn't match against an empty path part.
- // Otherwise a/* will match a/, which it should not.
- if (re !== '' && hasMagic) {
- re = '(?=.)' + re
}
- if (addPatternStart) {
- re = patternStart + re
- }
+ /**
+ * @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 = []
- // parsing just a piece of a larger pattern.
- if (isSub === SUBPARSE) {
- return [re, hasMagic]
- }
+ const storage = targetStorage ?? this.#relevantRequestResponseList
- // skip the regexp for non-magical patterns
- // unescape anything in it, though, so that it'll be
- // an exact match against a file etc.
- if (!hasMagic) {
- return globUnescape(pattern)
- }
+ for (const requestResponse of storage) {
+ const [cachedRequest, cachedResponse] = requestResponse
+ if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) {
+ resultList.push(requestResponse)
+ }
+ }
- var flags = options.nocase ? 'i' : ''
- try {
- var regExp = new RegExp('^' + re + '$', flags)
- } catch (er) /* istanbul ignore next - should be impossible */ {
- // If it was an invalid regular expression, then it can't match
- // anything. This trick looks for a character after the end of
- // the string, which is of course impossible, except in multi-line
- // mode, but it's not a /m regex.
- return new RegExp('$.')
+ return resultList
}
- regExp._glob = pattern
- regExp._src = re
+ /**
+ * @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
+ // }
- return regExp
-}
+ const queryURL = new URL(requestQuery.url)
-minimatch.makeRe = function (pattern, options) {
- return new Minimatch(pattern, options || {}).makeRe()
-}
+ const cachedURL = new URL(request.url)
-Minimatch.prototype.makeRe = makeRe
-function makeRe () {
- if (this.regexp || this.regexp === false) return this.regexp
+ if (options?.ignoreSearch) {
+ cachedURL.search = ''
- // at this point, this.set is a 2d array of partial
- // pattern strings, or "**".
- //
- // It's better to use .match(). This function shouldn't
- // be used, really, but it's pretty convenient sometimes,
- // when you just want to work with a regex.
- var set = this.set
+ queryURL.search = ''
+ }
- if (!set.length) {
- this.regexp = false
- return this.regexp
- }
- var options = this.options
+ if (!urlEquals(queryURL, cachedURL, true)) {
+ return false
+ }
- var twoStar = options.noglobstar ? star
- : options.dot ? twoStarDot
- : twoStarNoDot
- var flags = options.nocase ? 'i' : ''
+ if (
+ response == null ||
+ options?.ignoreVary ||
+ !response.headersList.contains('vary')
+ ) {
+ return true
+ }
- var re = set.map(function (pattern) {
- return pattern.map(function (p) {
- return (p === GLOBSTAR) ? twoStar
- : (typeof p === 'string') ? regExpEscape(p)
- : p._src
- }).join('\\\/')
- }).join('|')
+ const fieldValues = getFieldValues(response.headersList.get('vary'))
- // must match entire pattern
- // ending in a * or ** will make it less strict.
- re = '^(?:' + re + ')$'
+ for (const fieldValue of fieldValues) {
+ if (fieldValue === '*') {
+ return false
+ }
- // can match anything, as long as it's not this.
- if (this.negate) re = '^(?!' + re + ').*$'
+ const requestValue = request.headersList.get(fieldValue)
+ const queryValue = requestQuery.headersList.get(fieldValue)
- try {
- this.regexp = new RegExp(re, flags)
- } catch (ex) /* istanbul ignore next - should be impossible */ {
- this.regexp = false
- }
- return this.regexp
-}
+ // 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
+ }
+ }
-minimatch.match = function (list, pattern, options) {
- options = options || {}
- var mm = new Minimatch(pattern, options)
- list = list.filter(function (f) {
- return mm.match(f)
- })
- if (mm.options.nonull && !list.length) {
- list.push(pattern)
+ return true
}
- return list
}
-Minimatch.prototype.match = function match (f, partial) {
- if (typeof partial === 'undefined') partial = this.partial
- this.debug('match', f, this.pattern)
- // short-circuit in the case of busted things.
- // comments, etc.
- if (this.comment) return false
- if (this.empty) return f === ''
-
- if (f === '/' && partial) return true
-
- var options = this.options
+Object.defineProperties(Cache.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'Cache',
+ configurable: true
+ },
+ match: kEnumerableProperty,
+ matchAll: kEnumerableProperty,
+ add: kEnumerableProperty,
+ addAll: kEnumerableProperty,
+ put: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ keys: kEnumerableProperty
+})
- // windows: need to use /, not \
- if (path.sep !== '/') {
- f = f.split(path.sep).join('/')
+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
}
+]
- // treat the test path as a set of pathparts.
- f = f.split(slashSplit)
- this.debug(this.pattern, 'split', f)
-
- // just ONE of the pattern sets in this.set needs to match
- // in order for it to be valid. If negating, then just one
- // match means that we have failed.
- // Either way, return on the first hit.
-
- var set = this.set
- this.debug(this.pattern, 'set', set)
+webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters)
- // Find the basename of the path by looking for the last non-empty segment
- var filename
- var i
- for (i = f.length - 1; i >= 0; i--) {
- filename = f[i]
- if (filename) break
+webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([
+ ...cacheQueryOptionConverters,
+ {
+ key: 'cacheName',
+ converter: webidl.converters.DOMString
}
+])
- for (i = 0; i < set.length; i++) {
- var pattern = set[i]
- var file = f
- if (options.matchBase && pattern.length === 1) {
- file = [filename]
- }
- var hit = this.matchOne(file, pattern, partial)
- if (hit) {
- if (options.flipNegate) return true
- return !this.negate
- }
- }
+webidl.converters.Response = webidl.interfaceConverter(Response)
- // didn't get any hits. this is success if it's a negative
- // pattern, failure otherwise.
- if (options.flipNegate) return false
- return this.negate
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.RequestInfo
+)
+
+module.exports = {
+ Cache
}
-// set partial to true to test if, for example,
-// "/a/b" matches the start of "/*/b/*/d"
-// Partial means, if you run out of file before you run
-// out of pattern, then that's fine, as long as all
-// the parts match.
-Minimatch.prototype.matchOne = function (file, pattern, partial) {
- var options = this.options
- this.debug('matchOne',
- { 'this': this, file: file, pattern: pattern })
+/***/ }),
- this.debug('matchOne', file.length, pattern.length)
+/***/ 44738:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- for (var fi = 0,
- pi = 0,
- fl = file.length,
- pl = pattern.length
- ; (fi < fl) && (pi < pl)
- ; fi++, pi++) {
- this.debug('matchOne loop')
- var p = pattern[pi]
- var f = file[fi]
+"use strict";
- this.debug(pattern, p, f)
- // should be impossible.
- // some invalid regexp stuff in the set.
- /* istanbul ignore if */
- if (p === false) return false
+const { kConstruct } = __nccwpck_require__(80296)
+const { Cache } = __nccwpck_require__(50479)
+const { webidl } = __nccwpck_require__(74222)
+const { kEnumerableProperty } = __nccwpck_require__(3440)
- if (p === GLOBSTAR) {
- this.debug('GLOBSTAR', [pattern, p, f])
+class CacheStorage {
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map
+ * @type {Map no
- // - matchOne(y/z/c, c) -> no
- // - matchOne(z/c, c) -> no
- // - matchOne(c, c) yes, hit
- var fr = fi
- var pr = pi + 1
- if (pr === pl) {
- this.debug('** at the end')
- // a ** at the end will just swallow the rest.
- // We have found a match.
- // however, it will not swallow /.x, unless
- // options.dot is set.
- // . and .. are *never* matched by **, for explosively
- // exponential reasons.
- for (; fi < fl; fi++) {
- if (file[fi] === '.' || file[fi] === '..' ||
- (!options.dot && file[fi].charAt(0) === '.')) return false
- }
- return true
- }
+ constructor () {
+ if (arguments[0] !== kConstruct) {
+ webidl.illegalConstructor()
+ }
+ }
- // ok, let's see if we can swallow whatever we can.
- while (fr < fl) {
- var swallowee = file[fr]
+ async match (request, options = {}) {
+ webidl.brandCheck(this, CacheStorage)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.match' })
- this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
+ request = webidl.converters.RequestInfo(request)
+ options = webidl.converters.MultiCacheQueryOptions(options)
- // XXX remove this slice. Just pass the start index.
- if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
- this.debug('globstar found match!', fr, fl, swallowee)
- // found a match.
- return true
- } else {
- // can't swallow "." or ".." ever.
- // can only swallow ".foo" when explicitly asked.
- if (swallowee === '.' || swallowee === '..' ||
- (!options.dot && swallowee.charAt(0) === '.')) {
- this.debug('dot detected!', file, fr, pattern, pr)
- break
- }
+ // 1.
+ if (options.cacheName != null) {
+ // 1.1.1.1
+ if (this.#caches.has(options.cacheName)) {
+ // 1.1.1.1.1
+ const cacheList = this.#caches.get(options.cacheName)
+ const cache = new Cache(kConstruct, cacheList)
- // ** swallows a segment, and continue.
- this.debug('globstar swallow a segment, and continue')
- fr++
- }
+ return await cache.match(request, options)
}
+ } else { // 2.
+ // 2.2
+ for (const cacheList of this.#caches.values()) {
+ const cache = new Cache(kConstruct, cacheList)
- // no match was found.
- // However, in partial mode, we can't say this is necessarily over.
- // If there's more *pattern* left, then
- /* istanbul ignore if */
- if (partial) {
- // ran out of file
- this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
- if (fr === fl) return true
+ // 2.2.1.2
+ const response = await cache.match(request, options)
+
+ if (response !== undefined) {
+ return response
+ }
}
- return false
}
+ }
- // something other than **
- // non-magic patterns just have to match exactly
- // patterns with magic have been turned into regexps.
- var hit
- if (typeof p === 'string') {
- hit = f === p
- this.debug('string match', p, f, hit)
- } else {
- hit = f.match(p)
- this.debug('pattern match', p, f, hit)
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#cache-storage-has
+ * @param {string} cacheName
+ * @returns {Promise}
+ */
+ async has (cacheName) {
+ webidl.brandCheck(this, CacheStorage)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' })
+
+ cacheName = webidl.converters.DOMString(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)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' })
+
+ cacheName = webidl.converters.DOMString(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)
}
- if (!hit) return false
+ // 2.2
+ const cache = []
+
+ // 2.3
+ this.#caches.set(cacheName, cache)
+
+ // 2.4
+ return new Cache(kConstruct, cache)
}
- // Note: ending in / means that we'll get a final ""
- // at the end of the pattern. This can only match a
- // corresponding "" at the end of the file.
- // If the file ends in /, then it can only match a
- // a pattern that ends in /, unless the pattern just
- // doesn't have any more for it. But, a/b/ should *not*
- // match "a/b/*", even though "" matches against the
- // [^/]*? pattern, except in partial mode, where it might
- // simply not be reached yet.
- // However, a/b/ should still satisfy a/*
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete
+ * @param {string} cacheName
+ * @returns {Promise}
+ */
+ async delete (cacheName) {
+ webidl.brandCheck(this, CacheStorage)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' })
- // now either we fell off the end of the pattern, or we're done.
- if (fi === fl && pi === pl) {
- // ran out of pattern and filename at the same time.
- // an exact hit!
- return true
- } else if (fi === fl) {
- // ran out of file, but still had pattern left.
- // this is ok if we're doing the match as part of
- // a glob fs traversal.
- return partial
- } else /* istanbul ignore else */ if (pi === pl) {
- // ran out of pattern, still have file left.
- // this is only acceptable if we're on the very last
- // empty segment of a file with a trailing slash.
- // a/* should match a/b/
- return (fi === fl - 1) && (file[fi] === '')
+ cacheName = webidl.converters.DOMString(cacheName)
+
+ return this.#caches.delete(cacheName)
}
- // should be unreachable.
- /* istanbul ignore next */
- throw new Error('wtf?')
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys
+ * @returns {string[]}
+ */
+ async keys () {
+ webidl.brandCheck(this, CacheStorage)
+
+ // 2.1
+ const keys = this.#caches.keys()
+
+ // 2.2
+ return [...keys]
+ }
}
-// replace stuff like \* with *
-function globUnescape (s) {
- return s.replace(/\\(.)/g, '$1')
+Object.defineProperties(CacheStorage.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'CacheStorage',
+ configurable: true
+ },
+ match: kEnumerableProperty,
+ has: kEnumerableProperty,
+ open: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ keys: kEnumerableProperty
+})
+
+module.exports = {
+ CacheStorage
}
-function regExpEscape (s) {
- return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
+
+/***/ }),
+
+/***/ 80296:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+module.exports = {
+ kConstruct: (__nccwpck_require__(36443).kConstruct)
}
/***/ }),
-/***/ 744:
-/***/ ((module) => {
+/***/ 23993:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-/**
- * Helpers.
- */
+"use strict";
-var s = 1000;
-var m = s * 60;
-var h = m * 60;
-var d = h * 24;
-var w = d * 7;
-var y = d * 365.25;
+
+const assert = __nccwpck_require__(42613)
+const { URLSerializer } = __nccwpck_require__(94322)
+const { isValidHeaderName } = __nccwpck_require__(15523)
/**
- * Parse or format the given `val`.
- *
- * Options:
- *
- * - `long` verbose formatting [false]
- *
- * @param {String|Number} val
- * @param {Object} [options]
- * @throws {Error} throw an error if val is not a non-empty string or a number
- * @return {String|Number}
- * @api public
+ * @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)
-module.exports = function (val, options) {
- options = options || {};
- var type = typeof val;
- if (type === 'string' && val.length > 0) {
- return parse(val);
- } else if (type === 'number' && isFinite(val)) {
- return options.long ? fmtLong(val) : fmtShort(val);
- }
- throw new Error(
- 'val is not a non-empty string or a valid number. val=' +
- JSON.stringify(val)
- );
-};
+ const serializedB = URLSerializer(B, excludeFragment)
+
+ return serializedA === serializedB
+}
/**
- * Parse the given `str` and return milliseconds.
- *
- * @param {String} str
- * @return {Number}
- * @api private
+ * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262
+ * @param {string} header
*/
+function fieldValues (header) {
+ assert(header !== null)
-function parse(str) {
- str = String(str);
- if (str.length > 100) {
- return;
- }
- var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
- str
- );
- if (!match) {
- return;
- }
- var n = parseFloat(match[1]);
- var type = (match[2] || 'ms').toLowerCase();
- switch (type) {
- case 'years':
- case 'year':
- case 'yrs':
- case 'yr':
- case 'y':
- return n * y;
- case 'weeks':
- case 'week':
- case 'w':
- return n * w;
- case 'days':
- case 'day':
- case 'd':
- return n * d;
- case 'hours':
- case 'hour':
- case 'hrs':
- case 'hr':
- case 'h':
- return n * h;
- case 'minutes':
- case 'minute':
- case 'mins':
- case 'min':
- case 'm':
- return n * m;
- case 'seconds':
- case 'second':
- case 'secs':
- case 'sec':
- case 's':
- return n * s;
- case 'milliseconds':
- case 'millisecond':
- case 'msecs':
- case 'msec':
- case 'ms':
- return n;
- default:
- return undefined;
+ const values = []
+
+ for (let value of header.split(',')) {
+ value = value.trim()
+
+ if (!value.length) {
+ continue
+ } else if (!isValidHeaderName(value)) {
+ continue
+ }
+
+ values.push(value)
}
+
+ return values
}
-/**
- * Short format for `ms`.
- *
- * @param {Number} ms
- * @return {String}
- * @api private
- */
+module.exports = {
+ urlEquals,
+ fieldValues
+}
-function fmtShort(ms) {
- var msAbs = Math.abs(ms);
- if (msAbs >= d) {
- return Math.round(ms / d) + 'd';
- }
- if (msAbs >= h) {
- return Math.round(ms / h) + 'h';
- }
- if (msAbs >= m) {
- return Math.round(ms / m) + 'm';
- }
- if (msAbs >= s) {
- return Math.round(ms / s) + 's';
+
+/***/ }),
+
+/***/ 86197:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+// @ts-check
+
+
+
+/* global WebAssembly */
+
+const assert = __nccwpck_require__(42613)
+const net = __nccwpck_require__(69278)
+const http = __nccwpck_require__(58611)
+const { pipeline } = __nccwpck_require__(2203)
+const util = __nccwpck_require__(3440)
+const timers = __nccwpck_require__(28804)
+const Request = __nccwpck_require__(44655)
+const DispatcherBase = __nccwpck_require__(50001)
+const {
+ RequestContentLengthMismatchError,
+ ResponseContentLengthMismatchError,
+ InvalidArgumentError,
+ RequestAbortedError,
+ HeadersTimeoutError,
+ HeadersOverflowError,
+ SocketError,
+ InformationalError,
+ BodyTimeoutError,
+ HTTPParserError,
+ ResponseExceededMaxSizeError,
+ ClientDestroyedError
+} = __nccwpck_require__(68707)
+const buildConnector = __nccwpck_require__(59136)
+const {
+ kUrl,
+ kReset,
+ kServerName,
+ kClient,
+ kBusy,
+ kParser,
+ kConnect,
+ kBlocking,
+ kResuming,
+ kRunning,
+ kPending,
+ kSize,
+ kWriting,
+ kQueue,
+ kConnected,
+ kConnecting,
+ kNeedDrain,
+ kNoRef,
+ kKeepAliveDefaultTimeout,
+ kHostHeader,
+ kPendingIdx,
+ kRunningIdx,
+ kError,
+ kPipelining,
+ kSocket,
+ kKeepAliveTimeoutValue,
+ kMaxHeadersSize,
+ kKeepAliveMaxTimeout,
+ kKeepAliveTimeoutThreshold,
+ kHeadersTimeout,
+ kBodyTimeout,
+ kStrictContentLength,
+ kConnector,
+ kMaxRedirections,
+ kMaxRequests,
+ kCounter,
+ kClose,
+ kDestroy,
+ kDispatch,
+ kInterceptors,
+ kLocalAddress,
+ kMaxResponseSize,
+ kHTTPConnVersion,
+ // HTTP2
+ kHost,
+ kHTTP2Session,
+ kHTTP2SessionState,
+ kHTTP2BuildRequest,
+ kHTTP2CopyHeaders,
+ kHTTP1BuildRequest
+} = __nccwpck_require__(36443)
+
+/** @type {import('http2')} */
+let http2
+try {
+ http2 = __nccwpck_require__(85675)
+} 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
}
- return ms + 'ms';
+} = http2
+
+// Experimental
+let h2ExperimentalWarned = false
+
+const FastBuffer = Buffer[Symbol.species]
+
+const kClosedResolve = Symbol('kClosedResolve')
+
+const channels = {}
+
+try {
+ const diagnosticsChannel = __nccwpck_require__(31637)
+ channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders')
+ channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect')
+ channels.connectError = diagnosticsChannel.channel('undici:client:connectError')
+ channels.connected = diagnosticsChannel.channel('undici:client:connected')
+} catch {
+ channels.sendHeaders = { hasSubscribers: false }
+ channels.beforeConnect = { hasSubscribers: false }
+ channels.connectError = { hasSubscribers: false }
+ channels.connected = { hasSubscribers: false }
}
/**
- * Long format for `ms`.
- *
- * @param {Number} ms
- * @return {String}
- * @api private
+ * @type {import('../types/client').default}
*/
+class Client extends DispatcherBase {
+ /**
+ *
+ * @param {string|URL} url
+ * @param {import('../types/client').Client.Options} options
+ */
+ constructor (url, {
+ interceptors,
+ maxHeaderSize,
+ headersTimeout,
+ socketTimeout,
+ requestTimeout,
+ connectTimeout,
+ bodyTimeout,
+ idleTimeout,
+ keepAlive,
+ keepAliveTimeout,
+ maxKeepAliveTimeout,
+ keepAliveMaxTimeout,
+ keepAliveTimeoutThreshold,
+ socketPath,
+ pipelining,
+ tls,
+ strictContentLength,
+ maxCachedSessions,
+ maxRedirections,
+ connect,
+ maxRequestsPerClient,
+ localAddress,
+ maxResponseSize,
+ autoSelectFamily,
+ autoSelectFamilyAttemptTimeout,
+ // h2
+ allowH2,
+ maxConcurrentStreams
+ } = {}) {
+ super()
+
+ 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 && !Number.isFinite(maxHeaderSize)) {
+ throw new InvalidArgumentError('invalid maxHeaderSize')
+ }
+
+ 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')
+ }
-function fmtLong(ms) {
- var msAbs = Math.abs(ms);
- if (msAbs >= d) {
- return plural(ms, msAbs, d, 'day');
- }
- if (msAbs >= h) {
- return plural(ms, msAbs, h, 'hour');
- }
- if (msAbs >= m) {
- return plural(ms, msAbs, m, 'minute');
- }
- if (msAbs >= s) {
- return plural(ms, msAbs, s, 'second');
- }
- return ms + ' ms';
-}
+ if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {
+ throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold')
+ }
-/**
- * Pluralization helper.
- */
+ if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {
+ throw new InvalidArgumentError('headersTimeout must be a positive integer or zero')
+ }
-function plural(ms, msAbs, n, name) {
- var isPlural = msAbs >= n * 1.5;
- return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
-}
+ 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 (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
+ throw new InvalidArgumentError('maxRedirections must be a positive number')
+ }
-/***/ 9318:
-/***/ ((module, exports) => {
+ if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
+ throw new InvalidArgumentError('maxRequestsPerClient must be a positive number')
+ }
-exports = module.exports = SemVer
+ if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) {
+ throw new InvalidArgumentError('localAddress must be valid string IP address')
+ }
-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 () {}
-}
+ if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
+ throw new InvalidArgumentError('maxResponseSize must be a positive number')
+ }
-// 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'
+ if (
+ autoSelectFamilyAttemptTimeout != null &&
+ (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)
+ ) {
+ throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number')
+ }
-var MAX_LENGTH = 256
-var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
- /* istanbul ignore next */ 9007199254740991
+ // h2
+ if (allowH2 != null && typeof allowH2 !== 'boolean') {
+ throw new InvalidArgumentError('allowH2 must be a valid boolean value')
+ }
-// Max safe segment length for coercion.
-var MAX_SAFE_COMPONENT_LENGTH = 16
+ if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) {
+ throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0')
+ }
-var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6
+ if (typeof connect !== 'function') {
+ connect = buildConnector({
+ ...tls,
+ maxCachedSessions,
+ allowH2,
+ socketPath,
+ timeout: connectTimeout,
+ ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
+ ...connect
+ })
+ }
-// 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
+ this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client)
+ ? interceptors.Client
+ : [createRedirectInterceptor({ maxRedirections })]
+ this[kUrl] = util.parseOrigin(url)
+ this[kConnector] = connect
+ this[kSocket] = null
+ this[kPipelining] = pipelining != null ? pipelining : 1
+ this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize
+ this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout
+ this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout
+ this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : 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[kMaxRedirections] = maxRedirections
+ this[kMaxRequests] = maxRequestsPerClient
+ this[kClosedResolve] = null
+ this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1
+ this[kHTTPConnVersion] = 'h1'
-function tok (n) {
- t[n] = R++
-}
+ // HTTP/2
+ this[kHTTP2Session] = null
+ this[kHTTP2SessionState] = !allowH2
+ ? null
+ : {
+ // streams: null, // Fixed queue of streams - For future support of `push`
+ openStreams: 0, // Keep track of them to decide wether or not unref the session
+ maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server
+ }
+ this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}`
-var LETTERDASHNUMBER = '[a-zA-Z0-9-]'
+ // 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).
-// 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],
-]
+ this[kQueue] = []
+ this[kRunningIdx] = 0
+ this[kPendingIdx] = 0
+ }
-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 + '}')
+ get pipelining () {
+ return this[kPipelining]
}
- return value
-}
-// The following Regular Expressions can be used for tokenizing,
-// validating, and parsing SemVer version strings.
+ set pipelining (value) {
+ this[kPipelining] = value
+ resume(this, true)
+ }
-// ## Numeric Identifier
-// A single `0`, or a non-zero digit followed by zero or more digits.
+ get [kPending] () {
+ return this[kQueue].length - this[kPendingIdx]
+ }
-tok('NUMERICIDENTIFIER')
-src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*'
-tok('NUMERICIDENTIFIERLOOSE')
-src[t.NUMERICIDENTIFIERLOOSE] = '\\d+'
+ get [kRunning] () {
+ return this[kPendingIdx] - this[kRunningIdx]
+ }
-// ## Non-numeric Identifier
-// Zero or more digits, followed by a letter or hyphen, and then zero or
-// more letters, digits, or hyphens.
+ get [kSize] () {
+ return this[kQueue].length - this[kRunningIdx]
+ }
-tok('NONNUMERICIDENTIFIER')
-src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-]' + LETTERDASHNUMBER + '*'
+ get [kConnected] () {
+ return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed
+ }
-// ## Main Version
-// Three dot-separated numeric identifiers.
+ get [kBusy] () {
+ const socket = this[kSocket]
+ return (
+ (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) ||
+ (this[kSize] >= (this[kPipelining] || 1)) ||
+ this[kPending] > 0
+ )
+ }
-tok('MAINVERSION')
-src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' +
- '(' + src[t.NUMERICIDENTIFIER] + ')\\.' +
- '(' + src[t.NUMERICIDENTIFIER] + ')'
+ /* istanbul ignore: only used for test */
+ [kConnect] (cb) {
+ connect(this)
+ this.once('connect', cb)
+ }
-tok('MAINVERSIONLOOSE')
-src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' +
- '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' +
- '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')'
+ [kDispatch] (opts, handler) {
+ const origin = opts.origin || this[kUrl].origin
-// ## Pre-release Version Identifier
-// A numeric identifier, or a non-numeric identifier.
+ const request = this[kHTTPConnVersion] === 'h2'
+ ? Request[kHTTP2BuildRequest](origin, opts, handler)
+ : Request[kHTTP1BuildRequest](origin, opts, handler)
-tok('PRERELEASEIDENTIFIER')
-src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] +
- '|' + src[t.NONNUMERICIDENTIFIER] + ')'
+ 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
+ process.nextTick(resume, this)
+ } else {
+ resume(this, true)
+ }
-tok('PRERELEASEIDENTIFIERLOOSE')
-src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] +
- '|' + src[t.NONNUMERICIDENTIFIER] + ')'
+ if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
+ this[kNeedDrain] = 2
+ }
-// ## Pre-release Version
-// Hyphen, followed by one or more dot-separated pre-release version
-// identifiers.
+ return this[kNeedDrain] < 2
+ }
-tok('PRERELEASE')
-src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] +
- '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))'
+ 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]) {
+ resolve(null)
+ } else {
+ this[kClosedResolve] = resolve
+ }
+ })
+ }
-tok('PRERELEASELOOSE')
-src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] +
- '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))'
+ 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]
+ errorRequest(this, request, err)
+ }
-// ## Build Metadata Identifier
-// Any combination of digits, letters, or hyphens.
+ const callback = () => {
+ if (this[kClosedResolve]) {
+ // TODO (fix): Should we error here with ClientDestroyedError?
+ this[kClosedResolve]()
+ this[kClosedResolve] = null
+ }
+ resolve()
+ }
-tok('BUILDIDENTIFIER')
-src[t.BUILDIDENTIFIER] = LETTERDASHNUMBER + '+'
+ if (this[kHTTP2Session] != null) {
+ util.destroy(this[kHTTP2Session], err)
+ this[kHTTP2Session] = null
+ this[kHTTP2SessionState] = null
+ }
-// ## Build Metadata
-// Plus sign, followed by one or more period-separated build metadata
-// identifiers.
+ if (!this[kSocket]) {
+ queueMicrotask(callback)
+ } else {
+ util.destroy(this[kSocket].on('close', callback), err)
+ }
-tok('BUILD')
-src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] +
- '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))'
+ resume(this)
+ })
+ }
+}
-// ## Full Version String
-// A main version, followed optionally by a pre-release version and
-// build metadata.
+function onHttp2SessionError (err) {
+ assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
-// 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.
+ this[kSocket][kError] = err
-tok('FULL')
-tok('FULLPLAIN')
-src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] +
- src[t.PRERELEASE] + '?' +
- src[t.BUILD] + '?'
+ onError(this[kClient], err)
+}
-src[t.FULL] = '^' + src[t.FULLPLAIN] + '$'
+function onHttp2FrameError (type, code, id) {
+ const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
-// 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] + '?'
+ if (id === 0) {
+ this[kSocket][kError] = err
+ onError(this[kClient], err)
+ }
+}
-tok('LOOSE')
-src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$'
+function onHttp2SessionEnd () {
+ util.destroy(this, new SocketError('other side closed'))
+ util.destroy(this[kSocket], new SocketError('other side closed'))
+}
-tok('GTLT')
-src[t.GTLT] = '((?:<|>)?=?)'
+function onHTTP2GoAway (code) {
+ const client = this[kClient]
+ const err = new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${code}`)
+ client[kSocket] = null
+ client[kHTTP2Session] = null
-// 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|\\*'
+ if (client.destroyed) {
+ assert(this[kPending] === 0)
-tok('XRANGEPLAIN')
-src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' +
- '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' +
- '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' +
- '(?:' + src[t.PRERELEASE] + ')?' +
- src[t.BUILD] + '?' +
- ')?)?'
+ // Fail entire queue.
+ const requests = client[kQueue].splice(client[kRunningIdx])
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i]
+ errorRequest(this, request, err)
+ }
+ } else if (client[kRunning] > 0) {
+ // Fail head of pipeline.
+ const request = client[kQueue][client[kRunningIdx]]
+ client[kQueue][client[kRunningIdx]++] = null
-tok('XRANGEPLAINLOOSE')
-src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
- '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
- '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
- '(?:' + src[t.PRERELEASELOOSE] + ')?' +
- src[t.BUILD] + '?' +
- ')?)?'
+ errorRequest(client, request, err)
+ }
-tok('XRANGE')
-src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$'
-tok('XRANGELOOSE')
-src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$'
+ client[kPendingIdx] = client[kRunningIdx]
-// 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')
+ assert(client[kRunning] === 0)
-// Tilde ranges.
-// Meaning is "reasonably at or greater than"
-tok('LONETILDE')
-src[t.LONETILDE] = '(?:~>?)'
+ client.emit('disconnect',
+ client[kUrl],
+ [client],
+ err
+ )
-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~'
+ resume(client)
+}
-tok('TILDE')
-src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$'
-tok('TILDELOOSE')
-src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$'
+const constants = __nccwpck_require__(52824)
+const createRedirectInterceptor = __nccwpck_require__(64415)
+const EMPTY_BUF = Buffer.alloc(0)
-// Caret ranges.
-// Meaning is "at least and backwards compatible with"
-tok('LONECARET')
-src[t.LONECARET] = '(?:\\^)'
+async function lazyllhttp () {
+ const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(63870) : undefined
-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^'
+ let mod
+ try {
+ mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(53434), 'base64'))
+ } catch (e) {
+ /* istanbul ignore next */
-tok('CARET')
-src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$'
-tok('CARETLOOSE')
-src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$'
+ // 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 = await WebAssembly.compile(Buffer.from(llhttpWasmData || __nccwpck_require__(63870), 'base64'))
+ }
-// 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] + ')$|^$'
+ return await WebAssembly.instantiate(mod, {
+ env: {
+ /* eslint-disable camelcase */
-// 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] + ')'
+ wasm_on_url: (p, at, len) => {
+ /* istanbul ignore next */
+ return 0
+ },
+ wasm_on_status: (p, at, len) => {
+ assert.strictEqual(currentParser.ptr, p)
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
+ return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
+ },
+ wasm_on_message_begin: (p) => {
+ assert.strictEqual(currentParser.ptr, p)
+ return currentParser.onMessageBegin() || 0
+ },
+ wasm_on_header_field: (p, at, len) => {
+ assert.strictEqual(currentParser.ptr, p)
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
+ return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
+ },
+ wasm_on_header_value: (p, at, len) => {
+ assert.strictEqual(currentParser.ptr, p)
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
+ return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
+ },
+ wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {
+ assert.strictEqual(currentParser.ptr, p)
+ return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0
+ },
+ wasm_on_body: (p, at, len) => {
+ assert.strictEqual(currentParser.ptr, p)
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
+ return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
+ },
+ wasm_on_message_complete: (p) => {
+ assert.strictEqual(currentParser.ptr, p)
+ return currentParser.onMessageComplete() || 0
+ }
+
+ /* eslint-enable camelcase */
+ }
+ })
+}
+
+let llhttpInstance = null
+let llhttpPromise = lazyllhttp()
+llhttpPromise.catch()
-// 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'
+let currentParser = null
+let currentBufferRef = null
+let currentBufferSize = 0
+let currentBufferPtr = null
-// 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*$'
+const TIMEOUT_HEADERS = 1
+const TIMEOUT_BODY = 2
+const TIMEOUT_IDLE = 3
-tok('HYPHENRANGELOOSE')
-src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' +
- '\\s+-\\s+' +
- '(' + src[t.XRANGEPLAINLOOSE] + ')' +
- '\\s*$'
+class Parser {
+ constructor (client, socket, { exports }) {
+ assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0)
-// Star ranges basically just allow anything at all.
-tok('STAR')
-src[t.STAR] = '(<|>)?=?\\s*\\*'
+ this.llhttp = exports
+ this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)
+ this.client = client
+ this.socket = socket
+ this.timeout = null
+ this.timeoutValue = null
+ this.timeoutType = null
+ this.statusCode = null
+ 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)
-// 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])
+ this.bytesRead = 0
- // 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]))
+ this.keepAlive = ''
+ this.contentLength = ''
+ this.connection = ''
+ this.maxResponseSize = client[kMaxResponseSize]
}
-}
-exports.parse = parse
-function parse (version, options) {
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
+ setTimeout (value, type) {
+ this.timeoutType = type
+ if (value !== this.timeoutValue) {
+ timers.clearTimeout(this.timeout)
+ if (value) {
+ this.timeout = timers.setTimeout(onParserTimeout, value, this)
+ // istanbul ignore else: only for jest
+ if (this.timeout.unref) {
+ this.timeout.unref()
+ }
+ } else {
+ this.timeout = null
+ }
+ this.timeoutValue = value
+ } else if (this.timeout) {
+ // istanbul ignore else: only for jest
+ if (this.timeout.refresh) {
+ this.timeout.refresh()
+ }
}
}
- if (version instanceof SemVer) {
- return version
- }
+ resume () {
+ if (this.socket.destroyed || !this.paused) {
+ return
+ }
- if (typeof version !== 'string') {
- return null
- }
+ assert(this.ptr != null)
+ assert(currentParser == null)
- if (version.length > MAX_LENGTH) {
- return null
- }
+ this.llhttp.llhttp_resume(this.ptr)
- var r = options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL]
- if (!r.test(version)) {
- return null
- }
+ assert(this.timeoutType === TIMEOUT_BODY)
+ if (this.timeout) {
+ // istanbul ignore else: only for jest
+ if (this.timeout.refresh) {
+ this.timeout.refresh()
+ }
+ }
- try {
- return new SemVer(version, options)
- } catch (er) {
- return null
+ this.paused = false
+ this.execute(this.socket.read() || EMPTY_BUF) // Flush parser.
+ this.readMore()
}
-}
-exports.valid = valid
-function valid (version, options) {
- var v = parse(version, options)
- return v ? v.version : null
-}
+ readMore () {
+ while (!this.paused && this.ptr) {
+ const chunk = this.socket.read()
+ if (chunk === null) {
+ break
+ }
+ this.execute(chunk)
+ }
+ }
-exports.clean = clean
-function clean (version, options) {
- var s = parse(version.trim().replace(/^[=v]+/, ''), options)
- return s ? s.version : null
-}
+ execute (data) {
+ assert(this.ptr != null)
+ assert(currentParser == null)
+ assert(!this.paused)
-exports.SemVer = SemVer
+ const { socket, llhttp } = this
-function SemVer (version, options) {
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
+ if (data.length > currentBufferSize) {
+ if (currentBufferPtr) {
+ llhttp.free(currentBufferPtr)
+ }
+ currentBufferSize = Math.ceil(data.length / 4096) * 4096
+ currentBufferPtr = llhttp.malloc(currentBufferSize)
}
- }
- if (version instanceof SemVer) {
- if (version.loose === options.loose) {
- return version
- } else {
- version = version.version
+
+ new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data)
+
+ // 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 = data
+ currentParser = this
+ ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.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
+ }
+
+ const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr
+
+ if (ret === constants.ERROR.PAUSED_UPGRADE) {
+ this.onUpgrade(data.slice(offset))
+ } else if (ret === constants.ERROR.PAUSED) {
+ this.paused = true
+ socket.unshift(data.slice(offset))
+ } else if (ret !== constants.ERROR.OK) {
+ 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.slice(offset))
+ }
+ } catch (err) {
+ util.destroy(socket, err)
}
- } 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')
+ destroy () {
+ assert(this.ptr != null)
+ assert(currentParser == null)
+
+ this.llhttp.llhttp_free(this.ptr)
+ this.ptr = null
+
+ timers.clearTimeout(this.timeout)
+ this.timeout = null
+ this.timeoutValue = null
+ this.timeoutType = null
+
+ this.paused = false
}
- if (!(this instanceof SemVer)) {
- return new SemVer(version, options)
+ onStatus (buf) {
+ this.statusText = buf.toString()
}
- debug('SemVer', version, options)
- this.options = options
- this.loose = !!options.loose
+ onMessageBegin () {
+ const { socket, client } = this
- var m = version.trim().match(options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL])
+ /* istanbul ignore next: difficult to make a test case for */
+ if (socket.destroyed) {
+ return -1
+ }
- if (!m) {
- throw new TypeError('Invalid Version: ' + version)
+ const request = client[kQueue][client[kRunningIdx]]
+ if (!request) {
+ return -1
+ }
}
- this.raw = version
+ onHeaderField (buf) {
+ const len = this.headers.length
- // these are actually numbers
- this.major = +m[1]
- this.minor = +m[2]
- this.patch = +m[3]
+ if ((len & 1) === 0) {
+ this.headers.push(buf)
+ } else {
+ this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
+ }
- if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
- throw new TypeError('Invalid major version')
+ this.trackHeader(buf.length)
}
- if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
- throw new TypeError('Invalid minor version')
- }
+ onHeaderValue (buf) {
+ let len = this.headers.length
- if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
- throw new TypeError('Invalid patch version')
+ 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 && key.toString().toLowerCase() === 'keep-alive') {
+ this.keepAlive += buf.toString()
+ } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') {
+ this.connection += buf.toString()
+ } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') {
+ this.contentLength += buf.toString()
+ }
+
+ this.trackHeader(buf.length)
}
- // 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
- })
+ trackHeader (len) {
+ this.headersSize += len
+ if (this.headersSize >= this.headersMaxSize) {
+ util.destroy(this.socket, new HeadersOverflowError())
+ }
}
- this.build = m[5] ? m[5].split('.') : []
- this.format()
-}
+ onUpgrade (head) {
+ const { upgrade, client, socket, headers, statusCode } = this
-SemVer.prototype.format = function () {
- this.version = this.major + '.' + this.minor + '.' + this.patch
- if (this.prerelease.length) {
- this.version += '-' + this.prerelease.join('.')
- }
- return this.version
-}
+ assert(upgrade)
-SemVer.prototype.toString = function () {
- return this.version
-}
+ const request = client[kQueue][client[kRunningIdx]]
+ assert(request)
-SemVer.prototype.compare = function (other) {
- debug('SemVer.compare', this.version, this.options, other)
- if (!(other instanceof SemVer)) {
- other = new SemVer(other, this.options)
- }
+ assert(!socket.destroyed)
+ assert(socket === client[kSocket])
+ assert(!this.paused)
+ assert(request.upgrade || request.method === 'CONNECT')
- return this.compareMain(other) || this.comparePre(other)
-}
+ this.statusCode = null
+ this.statusText = ''
+ this.shouldKeepAlive = null
-SemVer.prototype.compareMain = function (other) {
- if (!(other instanceof SemVer)) {
- other = new SemVer(other, this.options)
- }
+ assert(this.headers.length % 2 === 0)
+ this.headers = []
+ this.headersSize = 0
- return compareIdentifiers(this.major, other.major) ||
- compareIdentifiers(this.minor, other.minor) ||
- compareIdentifiers(this.patch, other.patch)
-}
+ socket.unshift(head)
-SemVer.prototype.comparePre = function (other) {
- if (!(other instanceof SemVer)) {
- other = new SemVer(other, this.options)
- }
+ socket[kParser].destroy()
+ socket[kParser] = null
- // 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
- }
+ socket[kClient] = null
+ socket[kError] = null
+ socket
+ .removeListener('error', onSocketError)
+ .removeListener('readable', onSocketReadable)
+ .removeListener('end', onSocketEnd)
+ .removeListener('close', onSocketClose)
- 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)
+ client[kSocket] = null
+ 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)
}
- } while (++i)
-}
-SemVer.prototype.compareBuild = function (other) {
- if (!(other instanceof SemVer)) {
- other = new SemVer(other, this.options)
+ resume(client)
}
- 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
+ onHeadersComplete (statusCode, upgrade, shouldKeepAlive) {
+ const { client, socket, headers, statusText } = this
- 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)
- }
+ /* 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.strictEqual(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 (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]
- }
+ }
+
+ 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 % 2 === 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 {
- this.prerelease = [identifier, 0]
+ client[kKeepAliveTimeoutValue] = timeout
}
+ } else {
+ client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]
}
- break
+ } else {
+ // Stop more requests from being dispatched.
+ socket[kReset] = true
+ }
- default:
- throw new Error('invalid increment argument: ' + release)
- }
- this.format()
- this.raw = this.version
- return this
-}
+ const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false
-exports.inc = inc
-function inc (version, release, loose, identifier) {
- if (typeof (loose) === 'string') {
- identifier = loose
- loose = undefined
- }
+ if (request.aborted) {
+ return -1
+ }
- try {
- return new SemVer(version, loose).inc(release, identifier).version
- } catch (er) {
- return null
+ if (request.method === 'HEAD') {
+ return 1
+ }
+
+ if (statusCode < 200) {
+ return 1
+ }
+
+ if (socket[kBlocking]) {
+ socket[kBlocking] = false
+ resume(client)
+ }
+
+ return pause ? constants.ERROR.PAUSED : 0
}
-}
-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'
+ onBody (buf) {
+ const { client, socket, statusCode, maxResponseSize } = this
+
+ if (socket.destroyed) {
+ return -1
}
- for (var key in v1) {
- if (key === 'major' || key === 'minor' || key === 'patch') {
- if (v1[key] !== v2[key]) {
- return prefix + key
- }
+
+ const request = client[kQueue][client[kRunningIdx]]
+ assert(request)
+
+ assert.strictEqual(this.timeoutType, TIMEOUT_BODY)
+ if (this.timeout) {
+ // istanbul ignore else: only for jest
+ if (this.timeout.refresh) {
+ this.timeout.refresh()
}
}
- return defaultResult // may be undefined
- }
-}
-exports.compareIdentifiers = compareIdentifiers
+ assert(statusCode >= 200)
-var numeric = /^[0-9]+$/
-function compareIdentifiers (a, b) {
- var anum = numeric.test(a)
- var bnum = numeric.test(b)
+ if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
+ util.destroy(socket, new ResponseExceededMaxSizeError())
+ return -1
+ }
- if (anum && bnum) {
- a = +a
- b = +b
- }
+ this.bytesRead += buf.length
- return a === b ? 0
- : (anum && !bnum) ? -1
- : (bnum && !anum) ? 1
- : a < b ? -1
- : 1
-}
+ if (request.onData(buf) === false) {
+ return constants.ERROR.PAUSED
+ }
+ }
-exports.rcompareIdentifiers = rcompareIdentifiers
-function rcompareIdentifiers (a, b) {
- return compareIdentifiers(b, a)
-}
+ onMessageComplete () {
+ const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this
-exports.major = major
-function major (a, loose) {
- return new SemVer(a, loose).major
-}
+ if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
+ return -1
+ }
-exports.minor = minor
-function minor (a, loose) {
- return new SemVer(a, loose).minor
-}
+ if (upgrade) {
+ return
+ }
-exports.patch = patch
-function patch (a, loose) {
- return new SemVer(a, loose).patch
-}
+ const request = client[kQueue][client[kRunningIdx]]
+ assert(request)
-exports.compare = compare
-function compare (a, b, loose) {
- return new SemVer(a, loose).compare(new SemVer(b, loose))
-}
+ assert(statusCode >= 100)
-exports.compareLoose = compareLoose
-function compareLoose (a, b) {
- return compare(a, b, true)
-}
+ this.statusCode = null
+ this.statusText = ''
+ this.bytesRead = 0
+ this.contentLength = ''
+ this.keepAlive = ''
+ this.connection = ''
-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)
-}
+ assert(this.headers.length % 2 === 0)
+ this.headers = []
+ this.headersSize = 0
-exports.rcompare = rcompare
-function rcompare (a, b, loose) {
- return compare(b, a, loose)
-}
+ if (statusCode < 200) {
+ return
+ }
-exports.sort = sort
-function sort (list, loose) {
- return list.sort(function (a, b) {
- return exports.compareBuild(a, b, loose)
- })
-}
+ /* istanbul ignore next: should be handled by llhttp? */
+ if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) {
+ util.destroy(socket, new ResponseContentLengthMismatchError())
+ return -1
+ }
-exports.rsort = rsort
-function rsort (list, loose) {
- return list.sort(function (a, b) {
- return exports.compareBuild(b, a, loose)
- })
-}
+ request.onComplete(headers)
-exports.gt = gt
-function gt (a, b, loose) {
- return compare(a, b, loose) > 0
-}
+ client[kQueue][client[kRunningIdx]++] = null
-exports.lt = lt
-function lt (a, b, loose) {
- return compare(a, b, loose) < 0
+ if (socket[kWriting]) {
+ assert.strictEqual(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] === 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(resume, client)
+ } else {
+ resume(client)
+ }
+ }
}
-exports.eq = eq
-function eq (a, b, loose) {
- return compare(a, b, loose) === 0
-}
+function onParserTimeout (parser) {
+ const { socket, timeoutType, client } = parser
-exports.neq = neq
-function neq (a, b, loose) {
- return compare(a, b, loose) !== 0
+ /* istanbul ignore else */
+ if (timeoutType === TIMEOUT_HEADERS) {
+ if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
+ assert(!parser.paused, 'cannot be paused while waiting for headers')
+ util.destroy(socket, new HeadersTimeoutError())
+ }
+ } else if (timeoutType === TIMEOUT_BODY) {
+ if (!parser.paused) {
+ util.destroy(socket, new BodyTimeoutError())
+ }
+ } else if (timeoutType === TIMEOUT_IDLE) {
+ assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue])
+ util.destroy(socket, new InformationalError('socket idle timeout'))
+ }
}
-exports.gte = gte
-function gte (a, b, loose) {
- return compare(a, b, loose) >= 0
+function onSocketReadable () {
+ const { [kParser]: parser } = this
+ if (parser) {
+ parser.readMore()
+ }
}
-exports.lte = lte
-function lte (a, b, loose) {
- return compare(a, b, loose) <= 0
-}
+function onSocketError (err) {
+ const { [kClient]: client, [kParser]: parser } = this
-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
+ assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
- case '!==':
- if (typeof a === 'object')
- a = a.version
- if (typeof b === 'object')
- b = b.version
- return a !== b
+ if (client[kHTTPConnVersion] !== 'h2') {
+ // 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
+ }
+ }
- case '':
- case '=':
- case '==':
- return eq(a, b, loose)
+ this[kError] = err
- case '!=':
- return neq(a, b, loose)
+ onError(this[kClient], err)
+}
- case '>':
- return gt(a, b, loose)
+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.
- case '>=':
- return gte(a, b, loose)
+ assert(client[kPendingIdx] === client[kRunningIdx])
- case '<':
- return lt(a, b, loose)
+ const requests = client[kQueue].splice(client[kRunningIdx])
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i]
+ errorRequest(client, request, err)
+ }
+ assert(client[kSize] === 0)
+ }
+}
- case '<=':
- return lte(a, b, loose)
+function onSocketEnd () {
+ const { [kParser]: parser, [kClient]: client } = this
- default:
- throw new TypeError('Invalid operator: ' + op)
+ if (client[kHTTPConnVersion] !== 'h2') {
+ 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)))
}
-exports.Comparator = Comparator
-function Comparator (comp, options) {
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
+function onSocketClose () {
+ const { [kClient]: client, [kParser]: parser } = this
+
+ if (client[kHTTPConnVersion] === 'h1' && 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
}
- if (comp instanceof Comparator) {
- if (comp.loose === !!options.loose) {
- return comp
- } else {
- comp = comp.value
+ const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
+
+ client[kSocket] = 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]
+ 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
- if (!(this instanceof Comparator)) {
- return new Comparator(comp, options)
+ errorRequest(client, request, err)
}
- comp = comp.trim().split(/\s+/).join(' ')
- debug('comparator', comp, options)
- this.options = options
- this.loose = !!options.loose
- this.parse(comp)
+ client[kPendingIdx] = client[kRunningIdx]
- if (this.semver === ANY) {
- this.value = ''
- } else {
- this.value = this.operator + this.semver.version
- }
+ assert(client[kRunning] === 0)
- debug('comp', this)
+ client.emit('disconnect', client[kUrl], [client], err)
+
+ resume(client)
}
-var ANY = {}
-Comparator.prototype.parse = function (comp) {
- var r = this.options.loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR]
- var m = comp.match(r)
+async function connect (client) {
+ assert(!client[kConnecting])
+ assert(!client[kSocket])
- if (!m) {
- throw new TypeError('Invalid comparator: ' + comp)
- }
+ let { host, hostname, protocol, port } = client[kUrl]
- this.operator = m[1] !== undefined ? m[1] : ''
- if (this.operator === '=') {
- this.operator = ''
+ // Resolve ipv6
+ if (hostname[0] === '[') {
+ const idx = hostname.indexOf(']')
+
+ assert(idx !== -1)
+ const ip = hostname.substring(1, idx)
+
+ assert(net.isIP(ip))
+ hostname = ip
}
- // 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)
+ client[kConnecting] = true
+
+ if (channels.beforeConnect.hasSubscribers) {
+ channels.beforeConnect.publish({
+ connectParams: {
+ host,
+ hostname,
+ protocol,
+ port,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ },
+ connector: client[kConnector]
+ })
}
-}
-Comparator.prototype.toString = function () {
- return this.value
-}
+ 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', () => {}), new ClientDestroyedError())
+ return
+ }
-Comparator.prototype.test = function (version) {
- debug('Comparator.test', version, this.options.loose)
+ client[kConnecting] = false
- if (this.semver === ANY || version === ANY) {
- return true
- }
+ assert(socket)
- if (typeof version === 'string') {
- try {
- version = new SemVer(version, this.options)
- } catch (er) {
- return false
- }
- }
+ const isH2 = socket.alpnProtocol === 'h2'
+ if (isH2) {
+ if (!h2ExperimentalWarned) {
+ h2ExperimentalWarned = true
+ process.emitWarning('H2 support is experimental, expect them to change at any time.', {
+ code: 'UNDICI-H2'
+ })
+ }
- return cmp(version, this.operator, this.semver, this.options)
-}
+ const session = http2.connect(client[kUrl], {
+ createConnection: () => socket,
+ peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams
+ })
-Comparator.prototype.intersects = function (comp, options) {
- if (!(comp instanceof Comparator)) {
- throw new TypeError('a Comparator is required')
- }
+ client[kHTTPConnVersion] = 'h2'
+ session[kClient] = client
+ session[kSocket] = socket
+ session.on('error', onHttp2SessionError)
+ session.on('frameError', onHttp2FrameError)
+ session.on('end', onHttp2SessionEnd)
+ session.on('goaway', onHTTP2GoAway)
+ session.on('close', onSocketClose)
+ session.unref()
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
+ client[kHTTP2Session] = session
+ socket[kHTTP2Session] = session
+ } else {
+ if (!llhttpInstance) {
+ llhttpInstance = await llhttpPromise
+ llhttpPromise = null
+ }
+
+ socket[kNoRef] = false
+ socket[kWriting] = false
+ socket[kReset] = false
+ socket[kBlocking] = false
+ socket[kParser] = new Parser(client, socket, llhttpInstance)
}
- }
- var rangeTmp
+ socket[kCounter] = 0
+ socket[kMaxRequests] = client[kMaxRequests]
+ socket[kClient] = client
+ socket[kError] = null
- if (this.operator === '') {
- if (this.value === '') {
- return true
+ socket
+ .on('error', onSocketError)
+ .on('readable', onSocketReadable)
+ .on('end', onSocketEnd)
+ .on('close', onSocketClose)
+
+ client[kSocket] = socket
+
+ if (channels.connected.hasSubscribers) {
+ channels.connected.publish({
+ connectParams: {
+ host,
+ hostname,
+ protocol,
+ port,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ },
+ connector: client[kConnector],
+ socket
+ })
}
- rangeTmp = new Range(comp.value, options)
- return satisfies(this.value, rangeTmp, options)
- } else if (comp.operator === '') {
- if (comp.value === '') {
- return true
+ client.emit('connect', client[kUrl], [client])
+ } catch (err) {
+ if (client.destroyed) {
+ return
}
- 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
-}
+ client[kConnecting] = false
-exports.Range = Range
-function Range (range, options) {
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
+ if (channels.connectError.hasSubscribers) {
+ channels.connectError.publish({
+ connectParams: {
+ host,
+ hostname,
+ protocol,
+ port,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ },
+ connector: client[kConnector],
+ error: err
+ })
}
- }
- if (range instanceof Range) {
- if (range.loose === !!options.loose &&
- range.includePrerelease === !!options.includePrerelease) {
- return range
+ 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]++]
+ errorRequest(client, request, err)
+ }
} else {
- return new Range(range.raw, options)
+ onError(client, err)
}
- }
-
- if (range instanceof Comparator) {
- return new Range(range.value, options)
- }
- if (!(this instanceof Range)) {
- return new Range(range, options)
+ client.emit('connectionError', client[kUrl], [client], err)
}
- 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(' ')
+ resume(client)
+}
- // 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
- })
+function emitDrain (client) {
+ client[kNeedDrain] = 0
+ client.emit('drain', client[kUrl], [client])
+}
- if (!this.set.length) {
- throw new TypeError('Invalid SemVer Range: ' + this.raw)
+function resume (client, sync) {
+ if (client[kResuming] === 2) {
+ return
}
- this.format()
-}
+ client[kResuming] = 2
-Range.prototype.format = function () {
- this.range = this.set.map(function (comps) {
- return comps.join(' ').trim()
- }).join('||').trim()
- return this.range
-}
+ _resume(client, sync)
+ client[kResuming] = 0
-Range.prototype.toString = function () {
- return this.range
+ if (client[kRunningIdx] > 256) {
+ client[kQueue].splice(0, client[kRunningIdx])
+ client[kPendingIdx] -= client[kRunningIdx]
+ client[kRunningIdx] = 0
+ }
}
-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])
+function _resume (client, sync) {
+ while (true) {
+ if (client.destroyed) {
+ assert(client[kPending] === 0)
+ return
+ }
- // `~ 1.2.3` => `~1.2.3`
- range = range.replace(safeRe[t.TILDETRIM], tildeTrimReplace)
+ if (client[kClosedResolve] && !client[kSize]) {
+ client[kClosedResolve]()
+ client[kClosedResolve] = null
+ return
+ }
- // `^ 1.2.3` => `^1.2.3`
- range = range.replace(safeRe[t.CARETTRIM], caretTrimReplace)
+ const socket = client[kSocket]
- // normalize spaces
- range = range.split(/\s+/).join(' ')
+ if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') {
+ 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
+ }
- // At this point, the range is completely trimmed and
- // ready to be split into comparators.
+ if (client[kSize] === 0) {
+ if (socket[kParser].timeoutType !== TIMEOUT_IDLE) {
+ socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE)
+ }
+ } 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)
+ }
+ }
+ }
- 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)
+ if (client[kBusy]) {
+ client[kNeedDrain] = 2
+ } else if (client[kNeedDrain] === 2) {
+ if (sync) {
+ client[kNeedDrain] = 1
+ process.nextTick(emitDrain, client)
+ } else {
+ emitDrain(client)
+ }
+ continue
+ }
- return set
-}
+ if (client[kPending] === 0) {
+ return
+ }
-Range.prototype.intersects = function (range, options) {
- if (!(range instanceof Range)) {
- throw new TypeError('a Range is required')
- }
+ if (client[kRunning] >= (client[kPipelining] || 1)) {
+ return
+ }
- 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)
- })
- })
- )
- })
- )
- })
-}
+ const request = client[kQueue][client[kPendingIdx]]
-// 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()
+ if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {
+ if (client[kRunning] > 0) {
+ return
+ }
- while (result && remainingComparators.length) {
- result = remainingComparators.every(function (otherComparator) {
- return testComparator.intersects(otherComparator, options)
- })
+ client[kServerName] = request.servername
- testComparator = remainingComparators.pop()
- }
+ if (socket && socket.servername !== request.servername) {
+ util.destroy(socket, new InformationalError('servername changed'))
+ return
+ }
+ }
- return result
-}
+ if (client[kConnecting]) {
+ return
+ }
-// 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(' ')
- })
-}
+ if (!socket && !client[kHTTP2Session]) {
+ connect(client)
+ return
+ }
-// 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
-}
+ if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) {
+ return
+ }
-function isX (id) {
- return !id || id.toLowerCase() === 'x' || id === '*'
-}
+ if (client[kRunning] > 0 && !request.idempotent) {
+ // Non-idempotent request cannot be retried.
+ // Ensure that no other requests are inflight and
+ // could cause failure.
+ return
+ }
-// ~, ~> --> * (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(' ')
-}
+ 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
+ }
-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 (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 &&
+ (util.isStream(request.body) || util.isAsyncIterable(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.
- 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'
+ // Request with stream or iterator body cannot be retried.
+ // Ensure that no other requests are inflight and
+ // could cause failure.
+ return
}
- debug('tilde return', ret)
- return ret
- })
+ if (!request.aborted && write(client, request)) {
+ client[kPendingIdx]++
+ } else {
+ client[kQueue].splice(client[kPendingIdx], 1)
+ }
+ }
}
-// ^ --> * (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(' ')
+// 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 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
+function write (client, request) {
+ if (client[kHTTPConnVersion] === 'h2') {
+ writeH2(client, client[kHTTP2Session], request)
+ return
+ }
- 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'
- }
- }
+ const { body, method, path, host, upgrade, headers, blocking, reset } = 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
- debug('caret return', ret)
- return ret
- })
-}
+ // 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.
-function replaceXRanges (comp, options) {
- debug('replaceXRanges', comp, options)
- return comp.split(/\s+/).map(function (comp) {
- return replaceXRange(comp, options)
- }).join(' ')
-}
+ const expectsPayload = (
+ method === 'PUT' ||
+ method === 'POST' ||
+ method === 'PATCH'
+ )
-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 (body && typeof body.read === 'function') {
+ // Try to read EOF in order to get length.
+ body.read(0)
+ }
- if (gtlt === '=' && anyX) {
- gtlt = ''
+ const bodyLength = util.bodyLength(body)
+
+ let contentLength = bodyLength
+
+ 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]) {
+ errorRequest(client, request, new RequestContentLengthMismatchError())
+ return false
}
- // 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' : ''
+ process.emitWarning(new RequestContentLengthMismatchError())
+ }
- 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
+ const socket = client[kSocket]
- 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
- }
+ try {
+ request.onConnect((err) => {
+ if (request.aborted || request.completed) {
+ return
}
- 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
- }
+ errorRequest(client, request, err || new RequestAbortedError())
- debug('xRange return', ret)
+ util.destroy(socket, new InformationalError('aborted'))
+ })
+ } catch (err) {
+ errorRequest(client, request, err)
+ }
- return ret
- })
-}
+ if (request.aborted) {
+ return false
+ }
-// 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], '')
-}
+ 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.
-// 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
+ socket[kReset] = true
}
- 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
+ if (upgrade || method === 'CONNECT') {
+ // On CONNECT or upgrade, block pipeline from dispatching further
+ // requests on this connection.
+
+ socket[kReset] = true
}
- return (from + ' ' + to).trim()
-}
+ if (reset != null) {
+ socket[kReset] = reset
+ }
-// if ANY of the sets match ALL of its comparators, then pass
-Range.prototype.test = function (version) {
- if (!version) {
- return false
+ if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {
+ socket[kReset] = true
}
- if (typeof version === 'string') {
- try {
- version = new SemVer(version, this.options)
- } catch (er) {
- return false
- }
+ if (blocking) {
+ socket[kBlocking] = true
}
- for (var i = 0; i < this.set.length; i++) {
- if (testSet(this.set[i], version, this.options)) {
- return true
- }
+ let header = `${method} ${path} HTTP/1.1\r\n`
+
+ if (typeof host === 'string') {
+ header += `host: ${host}\r\n`
+ } else {
+ header += client[kHostHeader]
}
- return false
-}
-function testSet (set, version, options) {
- for (var i = 0; i < set.length; i++) {
- if (!set[i].test(version)) {
- return false
- }
+ 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 (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 (headers) {
+ header += headers
+ }
- 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
- }
- }
+ if (channels.sendHeaders.hasSubscribers) {
+ channels.sendHeaders.publish({ request, headers: header, socket })
+ }
+
+ /* istanbul ignore else: assertion */
+ if (!body || bodyLength === 0) {
+ 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')
}
+ request.onRequestSent()
+ } else if (util.isBuffer(body)) {
+ assert(contentLength === body.byteLength, 'buffer body must have content length')
- // Version has a -pre, but it's not one of the ones we like.
- return false
+ socket.cork()
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
+ socket.write(body)
+ socket.uncork()
+ request.onBodySent(body)
+ request.onRequestSent()
+ if (!expectsPayload) {
+ socket[kReset] = true
+ }
+ } else if (util.isBlobLike(body)) {
+ if (typeof body.stream === 'function') {
+ writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload })
+ } else {
+ writeBlob({ body, client, request, socket, contentLength, header, expectsPayload })
+ }
+ } else if (util.isStream(body)) {
+ writeStream({ body, client, request, socket, contentLength, header, expectsPayload })
+ } else if (util.isIterable(body)) {
+ writeIterable({ body, client, request, socket, contentLength, header, expectsPayload })
+ } else {
+ assert(false)
}
return true
}
-exports.satisfies = satisfies
-function satisfies (version, range, options) {
- try {
- range = new Range(range, options)
- } catch (er) {
+function writeH2 (client, session, request) {
+ const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request
+
+ let headers
+ if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim())
+ else headers = reqHeaders
+
+ if (upgrade) {
+ errorRequest(client, request, new Error('Upgrade not supported for H2'))
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)
+ // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event?
+ request.onConnect((err) => {
+ if (request.aborted || request.completed) {
+ return
}
- }
- })
- 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
+ errorRequest(client, request, err || new RequestAbortedError())
+ })
+ } catch (err) {
+ errorRequest(client, request, err)
}
- 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
+ if (request.aborted) {
+ return false
}
- minver = new SemVer('0.0.0-0')
- if (range.test(minver)) {
- return minver
- }
+ /** @type {import('node:http2').ClientHttp2Stream} */
+ let stream
+ const h2State = client[kHTTP2SessionState]
- minver = null
- for (var i = 0; i < range.set.length; ++i) {
- var comparators = range.set[i]
+ headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost]
+ headers[HTTP2_HEADER_METHOD] = method
- 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 (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.id && !stream.pending) {
+ request.onUpgrade(null, null, stream)
+ ++h2State.openStreams
+ } else {
+ stream.once('ready', () => {
+ request.onUpgrade(null, null, stream)
+ ++h2State.openStreams
+ })
+ }
+
+ stream.once('close', () => {
+ h2State.openStreams -= 1
+ // TODO(HTTP/2): unref only if current streams count is 0
+ if (h2State.openStreams === 0) session.unref()
})
+
+ return true
}
- if (minver && range.test(minver)) {
- return minver
+ // https://tools.ietf.org/html/rfc7540#section-8.3
+ // :path and :scheme headers must be omited 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)
}
- return null
-}
+ let contentLength = util.bodyLength(body)
-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
+ if (contentLength == null) {
+ contentLength = request.contentLength
}
-}
-// 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)
-}
+ 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.
-// 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)
-}
+ contentLength = null
+ }
-exports.outside = outside
-function outside (version, range, hilo, options) {
- version = new SemVer(version, options)
- range = new Range(range, options)
+ // 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]) {
+ errorRequest(client, request, new RequestContentLengthMismatchError())
+ return false
+ }
- 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 ">"')
+ process.emitWarning(new RequestContentLengthMismatchError())
}
- // If it satisifes the range it is not outside
- if (satisfies(version, range, options)) {
- return false
+ if (contentLength != null) {
+ assert(body, 'no body must not have content length')
+ headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`
+ }
+
+ session.ref()
+
+ const shouldEndStream = method === 'GET' || method === 'HEAD'
+ 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()
}
- // From now on, variable terms are as if we're in "gtr" mode.
- // but note that everything is flipped for the "ltr" function.
+ // Increment counter as we have new several streams open
+ ++h2State.openStreams
- for (var i = 0; i < range.set.length; ++i) {
- var comparators = range.set[i]
+ stream.once('response', headers => {
+ const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers
- var high = null
- var low = null
+ if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) {
+ stream.pause()
+ }
+ })
- 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
- }
- })
+ stream.once('end', () => {
+ request.onComplete([])
+ })
- // If the edge version comparator has a operator then our version
- // isn't outside it
- if (high.operator === comp || high.operator === ecomp) {
- return false
+ stream.on('data', (chunk) => {
+ if (request.onData(chunk) === false) {
+ stream.pause()
}
+ })
- // 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
+ stream.once('close', () => {
+ h2State.openStreams -= 1
+ // TODO(HTTP/2): unref only if current streams count is 0
+ if (h2State.openStreams === 0) {
+ session.unref()
}
- }
- return true
-}
+ })
-exports.prerelease = prerelease
-function prerelease (version, options) {
- var parsed = parse(version, options)
- return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
-}
+ stream.once('error', function (err) {
+ if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {
+ h2State.streams -= 1
+ util.destroy(stream, err)
+ }
+ })
-exports.intersects = intersects
-function intersects (r1, r2, options) {
- r1 = new Range(r1, options)
- r2 = new Range(r2, options)
- return r1.intersects(r2)
-}
+ stream.once('frameError', (type, code) => {
+ const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
+ errorRequest(client, request, err)
-exports.coerce = coerce
-function coerce (version, options) {
- if (version instanceof SemVer) {
- return version
- }
+ if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {
+ h2State.streams -= 1
+ util.destroy(stream, err)
+ }
+ })
- if (typeof version === 'number') {
- version = String(version)
- }
+ // stream.on('aborted', () => {
+ // // TODO(HTTP/2): Support aborted
+ // })
- if (typeof version !== 'string') {
- return null
- }
+ // stream.on('timeout', () => {
+ // // TODO(HTTP/2): Support timeout
+ // })
- options = options || {}
+ // stream.on('push', headers => {
+ // // TODO(HTTP/2): Suppor push
+ // })
- 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
+ // stream.on('trailers', headers => {
+ // // TODO(HTTP/2): Support trailers
+ // })
+
+ return true
+
+ function writeBodyH2 () {
+ /* istanbul ignore else: assertion */
+ if (!body) {
+ request.onRequestSent()
+ } else if (util.isBuffer(body)) {
+ assert(contentLength === body.byteLength, 'buffer body must have content length')
+ stream.cork()
+ stream.write(body)
+ stream.uncork()
+ stream.end()
+ request.onBodySent(body)
+ request.onRequestSent()
+ } else if (util.isBlobLike(body)) {
+ if (typeof body.stream === 'function') {
+ writeIterable({
+ client,
+ request,
+ contentLength,
+ h2stream: stream,
+ expectsPayload,
+ body: body.stream(),
+ socket: client[kSocket],
+ header: ''
+ })
+ } else {
+ writeBlob({
+ body,
+ client,
+ request,
+ contentLength,
+ expectsPayload,
+ h2stream: stream,
+ header: '',
+ socket: client[kSocket]
+ })
}
- safeRe[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length
+ } else if (util.isStream(body)) {
+ writeStream({
+ body,
+ client,
+ request,
+ contentLength,
+ expectsPayload,
+ socket: client[kSocket],
+ h2stream: stream,
+ header: ''
+ })
+ } else if (util.isIterable(body)) {
+ writeIterable({
+ body,
+ client,
+ request,
+ contentLength,
+ expectsPayload,
+ header: '',
+ h2stream: stream,
+ socket: client[kSocket]
+ })
+ } else {
+ assert(false)
}
- // leave it in a clean state
- safeRe[t.COERCERTL].lastIndex = -1
}
+}
- if (match === null) {
- return null
- }
+function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
+ assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
- return parse(match[2] +
- '.' + (match[3] || '0') +
- '.' + (match[4] || '0'), options)
-}
+ if (client[kHTTPConnVersion] === 'h2') {
+ // For HTTP/2, is enough to pipe the stream
+ const pipe = pipeline(
+ body,
+ h2stream,
+ (err) => {
+ if (err) {
+ util.destroy(body, err)
+ util.destroy(h2stream, err)
+ } else {
+ request.onRequestSent()
+ }
+ }
+ )
+ pipe.on('data', onPipeData)
+ pipe.once('end', () => {
+ pipe.removeListener('data', onPipeData)
+ util.destroy(pipe)
+ })
-/***/ }),
+ function onPipeData (chunk) {
+ request.onBodySent(chunk)
+ }
-/***/ 6496:
-/***/ ((module) => {
+ return
+ }
-const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;
-const numRegex = /^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;
-// const octRegex = /0x[a-z0-9]+/;
-// const binRegex = /0x[a-z0-9]+/;
+ let finished = false
+ const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })
-//polyfill
-if (!Number.parseInt && window.parseInt) {
- Number.parseInt = window.parseInt;
-}
-if (!Number.parseFloat && window.parseFloat) {
- Number.parseFloat = window.parseFloat;
-}
+ const onData = function (chunk) {
+ if (finished) {
+ return
+ }
-
-const consider = {
- hex : true,
- leadingZeros: true,
- decimalPoint: "\.",
- eNotation: true
- //skipLike: /regex/
-};
+ try {
+ if (!writer.write(chunk) && this.pause) {
+ this.pause()
+ }
+ } catch (err) {
+ util.destroy(this, err)
+ }
+ }
+ const onDrain = function () {
+ if (finished) {
+ return
+ }
-function toNumber(str, options = {}){
- // const options = Object.assign({}, consider);
- // if(opt.leadingZeros === false){
- // options.leadingZeros = false;
- // }else if(opt.hex === false){
- // options.hex = false;
- // }
+ if (body.resume) {
+ body.resume()
+ }
+ }
+ const onAbort = function () {
+ if (finished) {
+ return
+ }
+ const err = new RequestAbortedError()
+ queueMicrotask(() => onFinished(err))
+ }
+ const onFinished = function (err) {
+ if (finished) {
+ return
+ }
- options = Object.assign({}, consider, options );
- if(!str || typeof str !== "string" ) return str;
-
- let trimmedStr = str.trim();
- // if(trimmedStr === "0.0") return 0;
- // else if(trimmedStr === "+0.0") return 0;
- // else if(trimmedStr === "-0.0") return -0;
+ finished = true
- if(options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str;
- else if (options.hex && hexRegex.test(trimmedStr)) {
- return Number.parseInt(trimmedStr, 16);
- // } else if (options.parseOct && octRegex.test(str)) {
- // return Number.parseInt(val, 8);
- // }else if (options.parseBin && binRegex.test(str)) {
- // return Number.parseInt(val, 2);
- }else{
- //separate negative sign, leading zeros, and rest number
- const match = numRegex.exec(trimmedStr);
- if(match){
- const sign = match[1];
- const leadingZeros = match[2];
- let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros
- //trim ending zeros for floating number
-
- const eNotation = match[4] || match[6];
- if(!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str; //-0123
- else if(!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str; //0123
- else{//no leading zeros or leading zeros are allowed
- const num = Number(trimmedStr);
- const numStr = "" + num;
- if(numStr.search(/[eE]/) !== -1){ //given number is long and parsed to eNotation
- if(options.eNotation) return num;
- else return str;
- }else if(eNotation){ //given number has enotation
- if(options.eNotation) return num;
- else return str;
- }else if(trimmedStr.indexOf(".") !== -1){ //floating number
- // const decimalPart = match[5].substr(1);
- // const intPart = trimmedStr.substr(0,trimmedStr.indexOf("."));
+ assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))
-
- // const p = numStr.indexOf(".");
- // const givenIntPart = numStr.substr(0,p);
- // const givenDecPart = numStr.substr(p+1);
- if(numStr === "0" && (numTrimmedByZeros === "") ) return num; //0.0
- else if(numStr === numTrimmedByZeros) return num; //0.456. 0.79000
- else if( sign && numStr === "-"+numTrimmedByZeros) return num;
- else return str;
- }
-
- if(leadingZeros){
- // if(numTrimmedByZeros === numStr){
- // if(options.leadingZeros) return num;
- // else return str;
- // }else return str;
- if(numTrimmedByZeros === numStr) return num;
- else if(sign+numTrimmedByZeros === numStr) return num;
- else return str;
- }
+ socket
+ .off('drain', onDrain)
+ .off('error', onFinished)
- if(trimmedStr === numStr) return num;
- else if(trimmedStr === sign+numStr) return num;
- // else{
- // //number with +/- sign
- // trimmedStr.test(/[-+][0-9]);
+ body
+ .removeListener('data', onData)
+ .removeListener('end', onFinished)
+ .removeListener('error', onFinished)
+ .removeListener('close', onAbort)
- // }
- return str;
- }
- // else if(!eNotation && trimmedStr && trimmedStr !== Number(trimmedStr) ) return str;
-
- }else{ //non-numeric string
- return str;
- }
+ if (!err) {
+ try {
+ writer.end()
+ } catch (er) {
+ err = er
+ }
}
-}
-/**
- *
- * @param {string} numStr without leading zeros
- * @returns
- */
-function trimZeros(numStr){
- if(numStr && numStr.indexOf(".") !== -1){//float
- numStr = numStr.replace(/0+$/, ""); //remove ending zeros
- if(numStr === ".") numStr = "0";
- else if(numStr[0] === ".") numStr = "0"+numStr;
- else if(numStr[numStr.length-1] === ".") numStr = numStr.substr(0,numStr.length-1);
- return numStr;
+ writer.destroy(err)
+
+ if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {
+ util.destroy(body, err)
+ } else {
+ util.destroy(body)
}
- return numStr;
-}
-module.exports = toNumber
+ }
+ body
+ .on('data', onData)
+ .on('end', onFinished)
+ .on('error', onFinished)
+ .on('close', onAbort)
-/***/ }),
+ if (body.resume) {
+ body.resume()
+ }
-/***/ 1860:
-/***/ ((module) => {
+ socket
+ .on('drain', onDrain)
+ .on('error', onFinished)
+}
-/******************************************************************************
-Copyright (c) Microsoft Corporation.
+async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
+ assert(contentLength === body.size, 'blob body must have content length')
-Permission to use, copy, modify, and/or distribute this software for any
-purpose with or without fee is hereby granted.
+ const isH2 = client[kHTTPConnVersion] === 'h2'
+ try {
+ if (contentLength != null && contentLength !== body.size) {
+ throw new RequestContentLengthMismatchError()
+ }
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
-OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-PERFORMANCE OF THIS SOFTWARE.
-***************************************************************************** */
-/* global global, define, Symbol, Reflect, Promise, SuppressedError, Iterator */
-var __extends;
-var __assign;
-var __rest;
-var __decorate;
-var __param;
-var __esDecorate;
-var __runInitializers;
-var __propKey;
-var __setFunctionName;
-var __metadata;
-var __awaiter;
-var __generator;
-var __exportStar;
-var __values;
-var __read;
-var __spread;
-var __spreadArrays;
-var __spreadArray;
-var __await;
-var __asyncGenerator;
-var __asyncDelegator;
-var __asyncValues;
-var __makeTemplateObject;
-var __importStar;
-var __importDefault;
-var __classPrivateFieldGet;
-var __classPrivateFieldSet;
-var __classPrivateFieldIn;
-var __createBinding;
-var __addDisposableResource;
-var __disposeResources;
-var __rewriteRelativeImportExtension;
-(function (factory) {
- var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {};
- if (typeof define === "function" && define.amd) {
- define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); });
+ const buffer = Buffer.from(await body.arrayBuffer())
+
+ if (isH2) {
+ h2stream.cork()
+ h2stream.write(buffer)
+ h2stream.uncork()
+ } else {
+ socket.cork()
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
+ socket.write(buffer)
+ socket.uncork()
}
- else if ( true && typeof module.exports === "object") {
- factory(createExporter(root, createExporter(module.exports)));
+
+ request.onBodySent(buffer)
+ request.onRequestSent()
+
+ if (!expectsPayload) {
+ socket[kReset] = true
}
- else {
- factory(createExporter(root));
+
+ resume(client)
+ } catch (err) {
+ util.destroy(isH2 ? h2stream : socket, err)
+ }
+}
+
+async function writeIterable ({ h2stream, 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()
}
- function createExporter(exports, previous) {
- if (exports !== root) {
- if (typeof Object.create === "function") {
- Object.defineProperty(exports, "__esModule", { value: true });
- }
- else {
- exports.__esModule = true;
- }
- }
- return function (id, v) { return exports[id] = previous ? previous(id, v) : v; };
+ }
+
+ const waitForDrain = () => new Promise((resolve, reject) => {
+ assert(callback === null)
+
+ if (socket[kError]) {
+ reject(socket[kError])
+ } else {
+ callback = resolve
}
-})
-(function (exporter) {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
+ })
- __extends = function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
+ if (client[kHTTPConnVersion] === 'h2') {
+ h2stream
+ .on('close', onDrain)
+ .on('drain', onDrain)
- __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];
+ 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]
}
- return t;
- };
- __rest = function (s, e) {
- var t = {};
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
- t[p[i]] = s[p[i]];
- }
- return t;
- };
+ const res = h2stream.write(chunk)
+ request.onBodySent(chunk)
+ if (!res) {
+ await waitForDrain()
+ }
+ }
+ } catch (err) {
+ h2stream.destroy(err)
+ } finally {
+ request.onRequestSent()
+ h2stream.end()
+ h2stream
+ .off('close', onDrain)
+ .off('drain', onDrain)
+ }
- __decorate = function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
+ return
+ }
- __param = function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
+ socket
+ .on('close', onDrain)
+ .on('drain', onDrain)
- __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
- function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
- var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
- var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
- var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
- var _, done = false;
- for (var i = decorators.length - 1; i >= 0; i--) {
- var context = {};
- for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
- for (var p in contextIn.access) context.access[p] = contextIn.access[p];
- context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
- var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
- if (kind === "accessor") {
- if (result === void 0) continue;
- if (result === null || typeof result !== "object") throw new TypeError("Object expected");
- if (_ = accept(result.get)) descriptor.get = _;
- if (_ = accept(result.set)) descriptor.set = _;
- if (_ = accept(result.init)) initializers.unshift(_);
- }
- else if (_ = accept(result)) {
- if (kind === "field") initializers.unshift(_);
- else descriptor[key] = _;
- }
- }
- if (target) Object.defineProperty(target, contextIn.name, descriptor);
- done = true;
- };
+ const writer = new AsyncWriter({ 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]
+ }
- __runInitializers = function (thisArg, initializers, value) {
- var useValue = arguments.length > 2;
- for (var i = 0; i < initializers.length; i++) {
- value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
- }
- return useValue ? value : void 0;
- };
+ if (!writer.write(chunk)) {
+ await waitForDrain()
+ }
+ }
- __propKey = function (x) {
- return typeof x === "symbol" ? x : "".concat(x);
- };
+ writer.end()
+ } catch (err) {
+ writer.destroy(err)
+ } finally {
+ socket
+ .off('close', onDrain)
+ .off('drain', onDrain)
+ }
+}
- __setFunctionName = function (f, name, prefix) {
- if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
- return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
- };
+class AsyncWriter {
+ constructor ({ 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
- __metadata = function (metadataKey, metadataValue) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
- };
+ socket[kWriting] = true
+ }
- __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());
- });
- };
+ write (chunk) {
+ const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this
- __generator = function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- };
+ if (socket[kError]) {
+ throw socket[kError]
+ }
- __exportStar = function(m, o) {
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
- };
+ if (socket.destroyed) {
+ return false
+ }
- __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];
- });
+ const len = Buffer.byteLength(chunk)
+ if (!len) {
+ return true
+ }
- __values = function (o) {
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
- if (m) return m.call(o);
- if (o && typeof o.length === "number") return {
- next: function () {
- if (o && i >= o.length) o = void 0;
- return { value: o && o[i++], done: !o };
- }
- };
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
- };
+ // We should defer writing chunks.
+ if (contentLength !== null && bytesWritten + len > contentLength) {
+ if (client[kStrictContentLength]) {
+ throw new RequestContentLengthMismatchError()
+ }
- __read = function (o, n) {
- var m = typeof Symbol === "function" && o[Symbol.iterator];
- if (!m) return o;
- var i = m.call(o), r, ar = [], e;
- try {
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
- }
- catch (error) { e = { error: error }; }
- finally {
- try {
- if (r && !r.done && (m = i["return"])) m.call(i);
- }
- finally { if (e) throw e.error; }
- }
- return ar;
- };
+ process.emitWarning(new RequestContentLengthMismatchError())
+ }
- /** @deprecated */
- __spread = function () {
- for (var ar = [], i = 0; i < arguments.length; i++)
- ar = ar.concat(__read(arguments[i]));
- return ar;
- };
+ socket.cork()
- /** @deprecated */
- __spreadArrays = function () {
- for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
- for (var r = Array(s), k = 0, i = 0; i < il; i++)
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
- r[k] = a[j];
- return r;
- };
+ if (bytesWritten === 0) {
+ if (!expectsPayload) {
+ socket[kReset] = true
+ }
- __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));
- };
+ if (contentLength === null) {
+ socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1')
+ } else {
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
+ }
+ }
- __await = function (v) {
- return this instanceof __await ? (this.v = v, this) : new __await(v);
- };
+ if (contentLength === null) {
+ socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1')
+ }
- __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 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
- function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
- function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
- 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]); }
- };
+ this.bytesWritten += len
- __asyncDelegator = function (o) {
- var i, p;
- return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
- function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
- };
+ const ret = socket.write(chunk)
- __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); }
- };
+ socket.uncork()
- __makeTemplateObject = function (cooked, raw) {
- if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
- return cooked;
- };
+ request.onBodySent(chunk)
- var __setModuleDefault = Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- };
+ 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()
+ }
+ }
+ }
- 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 ret
+ }
- __importStar = 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;
- };
+ end () {
+ const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this
+ request.onRequestSent()
- __importDefault = function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
+ socket[kWriting] = false
- __classPrivateFieldGet = function (receiver, state, kind, f) {
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
- };
+ if (socket[kError]) {
+ throw socket[kError]
+ }
- __classPrivateFieldSet = function (receiver, state, value, kind, f) {
- if (kind === "m") throw new TypeError("Private method is not writable");
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
- };
+ if (socket.destroyed) {
+ return
+ }
- __classPrivateFieldIn = function (state, receiver) {
- if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
- return typeof state === "function" ? receiver === state : state.has(receiver);
- };
+ 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.
- __addDisposableResource = function (env, value, async) {
- if (value !== null && value !== void 0) {
- if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
- var dispose, inner;
- if (async) {
- if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
- dispose = value[Symbol.asyncDispose];
- }
- if (dispose === void 0) {
- if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
- dispose = value[Symbol.dispose];
- if (async) inner = dispose;
- }
- if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
- if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
- env.stack.push({ value: value, dispose: dispose, async: async });
- }
- else if (async) {
- env.stack.push({ async: true });
- }
- return value;
- };
+ 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')
+ }
- var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
- var e = new Error(message);
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
- };
+ if (contentLength !== null && bytesWritten !== contentLength) {
+ if (client[kStrictContentLength]) {
+ throw new RequestContentLengthMismatchError()
+ } else {
+ process.emitWarning(new RequestContentLengthMismatchError())
+ }
+ }
- __disposeResources = function (env) {
- function fail(e) {
- env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
- env.hasError = true;
- }
- var r, s = 0;
- function next() {
- while (r = env.stack.pop()) {
- try {
- if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
- if (r.dispose) {
- var result = r.dispose.call(r.value);
- if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
- }
- else s |= 1;
- }
- catch (e) {
- fail(e);
- }
- }
- if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
- if (env.hasError) throw env.error;
- }
- return next();
- };
+ if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
+ // istanbul ignore else: only for jest
+ if (socket[kParser].timeout.refresh) {
+ socket[kParser].timeout.refresh()
+ }
+ }
- __rewriteRelativeImportExtension = function (path, preserveJsx) {
- if (typeof path === "string" && /^\.\.?\//.test(path)) {
- return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
- return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
- });
- }
- return path;
- };
+ resume(client)
+ }
- exporter("__extends", __extends);
- exporter("__assign", __assign);
- exporter("__rest", __rest);
- exporter("__decorate", __decorate);
- exporter("__param", __param);
- exporter("__esDecorate", __esDecorate);
- exporter("__runInitializers", __runInitializers);
- exporter("__propKey", __propKey);
- exporter("__setFunctionName", __setFunctionName);
- exporter("__metadata", __metadata);
- exporter("__awaiter", __awaiter);
- exporter("__generator", __generator);
- exporter("__exportStar", __exportStar);
- exporter("__createBinding", __createBinding);
- exporter("__values", __values);
- exporter("__read", __read);
- exporter("__spread", __spread);
- exporter("__spreadArrays", __spreadArrays);
- exporter("__spreadArray", __spreadArray);
- exporter("__await", __await);
- exporter("__asyncGenerator", __asyncGenerator);
- exporter("__asyncDelegator", __asyncDelegator);
- exporter("__asyncValues", __asyncValues);
- exporter("__makeTemplateObject", __makeTemplateObject);
- exporter("__importStar", __importStar);
- exporter("__importDefault", __importDefault);
- exporter("__classPrivateFieldGet", __classPrivateFieldGet);
- exporter("__classPrivateFieldSet", __classPrivateFieldSet);
- exporter("__classPrivateFieldIn", __classPrivateFieldIn);
- exporter("__addDisposableResource", __addDisposableResource);
- exporter("__disposeResources", __disposeResources);
- exporter("__rewriteRelativeImportExtension", __rewriteRelativeImportExtension);
-});
+ destroy (err) {
+ const { socket, client } = this
+
+ socket[kWriting] = false
+
+ if (err) {
+ assert(client[kRunning] <= 1, 'pipeline should only contain this request')
+ util.destroy(socket, err)
+ }
+ }
+}
+
+function errorRequest (client, request, err) {
+ try {
+ request.onError(err)
+ assert(request.aborted)
+ } catch (err) {
+ client.emit('error', err)
+ }
+}
-0 && (0);
+module.exports = Client
/***/ }),
-/***/ 770:
+/***/ 13194:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-module.exports = __nccwpck_require__(218);
+"use strict";
+
+
+/* istanbul ignore file: only for Node 12 */
+
+const { kConnected, kSize } = __nccwpck_require__(36443)
+
+class CompatWeakRef {
+ constructor (value) {
+ this.value = value
+ }
+
+ deref () {
+ return this.value[kConnected] === 0 && this.value[kSize] === 0
+ ? undefined
+ : this.value
+ }
+}
+
+class CompatFinalizer {
+ constructor (finalizer) {
+ this.finalizer = finalizer
+ }
+
+ register (dispatcher, key) {
+ if (dispatcher.on) {
+ dispatcher.on('disconnect', () => {
+ if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {
+ this.finalizer(key)
+ }
+ })
+ }
+ }
+}
+
+module.exports = function () {
+ // FIXME: remove workaround when the Node bug is fixed
+ // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
+ if (process.env.NODE_V8_COVERAGE) {
+ return {
+ WeakRef: CompatWeakRef,
+ FinalizationRegistry: CompatFinalizer
+ }
+ }
+ return {
+ WeakRef: global.WeakRef || CompatWeakRef,
+ FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer
+ }
+}
/***/ }),
-/***/ 218:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 19237:
+/***/ ((module) => {
"use strict";
-var net = __nccwpck_require__(9278);
-var tls = __nccwpck_require__(4756);
-var http = __nccwpck_require__(8611);
-var https = __nccwpck_require__(5692);
-var events = __nccwpck_require__(4434);
-var assert = __nccwpck_require__(2613);
-var util = __nccwpck_require__(9023);
+// 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
-exports.httpOverHttp = httpOverHttp;
-exports.httpsOverHttp = httpsOverHttp;
-exports.httpOverHttps = httpOverHttps;
-exports.httpsOverHttps = httpsOverHttps;
+module.exports = {
+ maxAttributeValueSize,
+ maxNameValuePairSize
+}
-function httpOverHttp(options) {
- var agent = new TunnelingAgent(options);
- agent.request = http.request;
- return agent;
-}
+/***/ }),
-function httpsOverHttp(options) {
- var agent = new TunnelingAgent(options);
- agent.request = http.request;
- agent.createSocket = createSecureSocket;
- agent.defaultPort = 443;
- return agent;
-}
+/***/ 53168:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-function httpOverHttps(options) {
- var agent = new TunnelingAgent(options);
- agent.request = https.request;
- return agent;
-}
+"use strict";
-function httpsOverHttps(options) {
- var agent = new TunnelingAgent(options);
- agent.request = https.request;
- agent.createSocket = createSecureSocket;
- agent.defaultPort = 443;
- return agent;
+
+const { parseSetCookie } = __nccwpck_require__(8915)
+const { stringify } = __nccwpck_require__(3834)
+const { webidl } = __nccwpck_require__(74222)
+const { Headers } = __nccwpck_require__(26349)
+
+/**
+ * @typedef {Object} Cookie
+ * @property {string} name
+ * @property {string} value
+ * @property {Date|number|undefined} expires
+ * @property {number|undefined} maxAge
+ * @property {string|undefined} domain
+ * @property {string|undefined} path
+ * @property {boolean|undefined} secure
+ * @property {boolean|undefined} httpOnly
+ * @property {'Strict'|'Lax'|'None'} sameSite
+ * @property {string[]} unparsed
+ */
+
+/**
+ * @param {Headers} headers
+ * @returns {Record}
+ */
+function getCookies (headers) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' })
+
+ webidl.brandCheck(headers, Headers, { strict: false })
+
+ const cookie = headers.get('cookie')
+ 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) {
+ webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' })
-function TunnelingAgent(options) {
- var self = this;
- self.options = options || {};
- self.proxyOptions = self.options.proxy || {};
- self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;
- self.requests = [];
- self.sockets = [];
+ webidl.brandCheck(headers, Headers, { strict: false })
- self.on('free', function onFree(socket, host, port, localAddress) {
- var options = toOptions(host, port, localAddress);
- for (var i = 0, len = self.requests.length; i < len; ++i) {
- var pending = self.requests[i];
- if (pending.host === options.host && pending.port === options.port) {
- // Detect the request to connect same origin server,
- // reuse the connection.
- self.requests.splice(i, 1);
- pending.request.onSocket(socket);
- return;
- }
- }
- socket.destroy();
- self.removeSocket(socket);
- });
+ name = webidl.converters.DOMString(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
+ })
}
-util.inherits(TunnelingAgent, events.EventEmitter);
-TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {
- var self = this;
- var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));
+/**
+ * @param {Headers} headers
+ * @returns {Cookie[]}
+ */
+function getSetCookies (headers) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' })
- if (self.sockets.length >= this.maxSockets) {
- // We are over limit so we'll add it to the queue.
- self.requests.push(options);
- return;
+ webidl.brandCheck(headers, Headers, { strict: false })
+
+ const cookies = headers.getSetCookie()
+
+ if (!cookies) {
+ return []
}
- // If we are under maxSockets create a new one.
- self.createSocket(options, function(socket) {
- socket.on('free', onFree);
- socket.on('close', onCloseOrRemove);
- socket.on('agentRemove', onCloseOrRemove);
- req.onSocket(socket);
+ return cookies.map((pair) => parseSetCookie(pair))
+}
- function onFree() {
- self.emit('free', socket, options);
- }
+/**
+ * @param {Headers} headers
+ * @param {Cookie} cookie
+ * @returns {void}
+ */
+function setCookie (headers, cookie) {
+ webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' })
- function onCloseOrRemove(err) {
- self.removeSocket(socket);
- socket.removeListener('free', onFree);
- socket.removeListener('close', onCloseOrRemove);
- socket.removeListener('agentRemove', onCloseOrRemove);
- }
- });
-};
+ webidl.brandCheck(headers, Headers, { strict: false })
-TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
- var self = this;
- var placeholder = {};
- self.sockets.push(placeholder);
+ cookie = webidl.converters.Cookie(cookie)
- var connectOptions = mergeOptions({}, self.proxyOptions, {
- method: 'CONNECT',
- path: options.host + ':' + options.port,
- agent: false,
- headers: {
- host: options.host + ':' + options.port
- }
- });
- if (options.localAddress) {
- connectOptions.localAddress = options.localAddress;
+ const str = stringify(cookie)
+
+ if (str) {
+ headers.append('Set-Cookie', stringify(cookie))
}
- if (connectOptions.proxyAuth) {
- connectOptions.headers = connectOptions.headers || {};
- connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
- new Buffer(connectOptions.proxyAuth).toString('base64');
+}
+
+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
}
+])
- debug('making CONNECT request');
- var connectReq = self.request(connectOptions);
- connectReq.useChunkedEncodingByDefault = false; // for v0.6
- connectReq.once('response', onResponse); // for v0.6
- connectReq.once('upgrade', onUpgrade); // for v0.6
- connectReq.once('connect', onConnect); // for v0.7 or later
- connectReq.once('error', onError);
- connectReq.end();
+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)
+ }
- function onResponse(res) {
- // Very hacky. This is necessary to avoid http-parser leaks.
- res.upgrade = true;
+ 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: []
}
+])
- function onUpgrade(res, socket, head) {
- // Hacky.
- process.nextTick(function() {
- onConnect(res, socket, head);
- });
- }
+module.exports = {
+ getCookies,
+ deleteCookie,
+ getSetCookies,
+ setCookie
+}
- function onConnect(res, socket, head) {
- connectReq.removeAllListeners();
- socket.removeAllListeners();
- if (res.statusCode !== 200) {
- debug('tunneling socket could not be established, statusCode=%d',
- res.statusCode);
- socket.destroy();
- var error = new Error('tunneling socket could not be established, ' +
- 'statusCode=' + res.statusCode);
- error.code = 'ECONNRESET';
- options.request.emit('error', error);
- self.removeSocket(placeholder);
- return;
- }
- if (head.length > 0) {
- debug('got illegal response body from proxy');
- socket.destroy();
- var error = new Error('got illegal response body from proxy');
- error.code = 'ECONNRESET';
- options.request.emit('error', error);
- self.removeSocket(placeholder);
- return;
- }
- debug('tunneling connection has established');
- self.sockets[self.sockets.indexOf(placeholder)] = socket;
- return cb(socket);
- }
+/***/ }),
- function onError(cause) {
- connectReq.removeAllListeners();
+/***/ 8915:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- debug('tunneling socket could not be established, cause=%s\n',
- cause.message, cause.stack);
- var error = new Error('tunneling socket could not be established, ' +
- 'cause=' + cause.message);
- error.code = 'ECONNRESET';
- options.request.emit('error', error);
- self.removeSocket(placeholder);
- }
-};
+"use strict";
-TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
- var pos = this.sockets.indexOf(socket)
- if (pos === -1) {
- return;
+
+const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(19237)
+const { isCTLExcludingHtab } = __nccwpck_require__(3834)
+const { collectASequenceOfCodePointsFast } = __nccwpck_require__(94322)
+const assert = __nccwpck_require__(42613)
+
+/**
+ * @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 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
}
- this.sockets.splice(pos, 1);
- var pending = this.requests.shift();
- if (pending) {
- // If we have pending requests and a socket gets closed a new one
- // needs to be created to take over in the pool for the one that closed.
- this.createSocket(pending, function(socket) {
- pending.request.onSocket(socket);
- });
+ 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
}
-};
-function createSecureSocket(options, cb) {
- var self = this;
- TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
- var hostHeader = options.request.getHeader('host');
- var tlsOptions = mergeOptions({}, self.options, {
- socket: socket,
- servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host
- });
+ // 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)
+ }
- // 0 is dummy port for v0.6
- var secureSocket = tls.connect(0, tlsOptions);
- self.sockets[self.sockets.indexOf(socket)] = secureSocket;
- cb(secureSocket);
- });
-}
+ // 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
+ }
-function toOptions(host, port, localAddress) {
- if (typeof host === 'string') { // since v0.10
- return {
- host: host,
- port: port,
- localAddress: localAddress
- };
+ // 6. The cookie-name is the name string, and the cookie-value is the
+ // value string.
+ return {
+ name, value, ...parseUnparsedAttributes(unparsedAttributes)
}
- return host; // for v0.11 or later
}
-function mergeOptions(target) {
- for (var i = 1, len = arguments.length; i < len; ++i) {
- var overrides = arguments[i];
- if (typeof overrides === 'object') {
- var keys = Object.keys(overrides);
- for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
- var k = keys[j];
- if (overrides[k] !== undefined) {
- target[k] = overrides[k];
- }
- }
- }
+/**
+ * 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 = ''
}
- return target;
-}
+ // Let the cookie-av string be the characters consumed in this step.
-var debug;
-if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
- debug = function() {
- var args = Array.prototype.slice.call(arguments);
- if (typeof args[0] === 'string') {
- args[0] = 'TUNNEL: ' + args[0];
- } else {
- args.unshift('TUNNEL:');
- }
- console.error.apply(console, args);
- }
-} else {
- debug = function() {};
-}
-exports.debug = debug; // for test
+ 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:
-/***/ 7878:
-/***/ ((__unused_webpack_module, exports) => {
+ // 1. The attribute-name string consists of the entire cookie-av
+ // string, and the attribute-value string is empty.
+ attributeName = cookieAv
+ }
-"use strict";
+ // 5. Remove any leading or trailing WSP characters from the attribute-
+ // name string and the attribute-value string.
+ attributeName = attributeName.trim()
+ attributeValue = attributeValue.trim()
-Object.defineProperty(exports, "__esModule", ({ value: true }));
+ // 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)
-/***/ 3315:
-/***/ ((__unused_webpack_module, exports) => {
+ // 2. If the attribute-value failed to parse as a cookie date, ignore
+ // the cookie-av.
-"use strict";
+ 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.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isValidErrorCode = exports.httpStatusFromErrorCode = exports.TwirpErrorCode = exports.BadRouteError = exports.InternalServerErrorWith = exports.InternalServerError = exports.RequiredArgumentError = exports.InvalidArgumentError = exports.NotFoundError = exports.TwirpError = void 0;
-/**
- * Represents a twirp error
- */
-class TwirpError extends Error {
- constructor(code, msg) {
- super(msg);
- this.code = TwirpErrorCode.Internal;
- this.meta = {};
- this.code = code;
- this.msg = msg;
- Object.setPrototypeOf(this, TwirpError.prototype);
- }
- /**
- * Adds a metadata kv to the error
- * @param key
- * @param value
- */
- withMeta(key, value) {
- this.meta[key] = value;
- return this;
- }
- /**
- * Returns a single metadata value
- * return "" if not found
- * @param key
- */
- getMeta(key) {
- return this.meta[key] || "";
- }
- /**
- * Add the original error cause
- * @param err
- * @param addMeta
- */
- withCause(err, addMeta = false) {
- this._originalCause = err;
- if (addMeta) {
- this.withMeta("cause", err.message);
- }
- return this;
- }
- cause() {
- return this._originalCause;
- }
- /**
- * Returns the error representation to JSON
- */
- toJSON() {
- try {
- return JSON.stringify({
- code: this.code,
- msg: this.msg,
- meta: this.meta,
- });
- }
- catch (e) {
- return `{"code": "internal", "msg": "There was an error but it could not be serialized into JSON"}`;
- }
- }
- /**
- * Create a twirp error from an object
- * @param obj
- */
- static fromObject(obj) {
- const code = obj["code"] || TwirpErrorCode.Unknown;
- const msg = obj["msg"] || "unknown";
- const error = new TwirpError(code, msg);
- if (obj["meta"]) {
- Object.keys(obj["meta"]).forEach((key) => {
- error.withMeta(key, obj["meta"][key]);
- });
- }
- return error;
- }
-}
-exports.TwirpError = TwirpError;
-/**
- * NotFoundError constructor for the common NotFound error.
- */
-class NotFoundError extends TwirpError {
- constructor(msg) {
- super(TwirpErrorCode.NotFound, msg);
- }
-}
-exports.NotFoundError = NotFoundError;
-/**
- * InvalidArgumentError constructor for the common InvalidArgument error. Can be
- * used when an argument has invalid format, is a number out of range, is a bad
- * option, etc).
- */
-class InvalidArgumentError extends TwirpError {
- constructor(argument, validationMsg) {
- super(TwirpErrorCode.InvalidArgument, argument + " " + validationMsg);
- this.withMeta("argument", argument);
- }
-}
-exports.InvalidArgumentError = InvalidArgumentError;
-/**
- * RequiredArgumentError is a more specific constructor for InvalidArgument
- * error. Should be used when the argument is required (expected to have a
- * non-zero value).
- */
-class RequiredArgumentError extends InvalidArgumentError {
- constructor(argument) {
- super(argument, "is required");
- }
-}
-exports.RequiredArgumentError = RequiredArgumentError;
-/**
- * InternalError constructor for the common Internal error. Should be used to
- * specify that something bad or unexpected happened.
- */
-class InternalServerError extends TwirpError {
- constructor(msg) {
- super(TwirpErrorCode.Internal, msg);
- }
-}
-exports.InternalServerError = InternalServerError;
-/**
- * InternalErrorWith makes an internal error, wrapping the original error and using it
- * for the error message, and with metadata "cause" with the original error type.
- * This function is used by Twirp services to wrap non-Twirp errors as internal errors.
- * The wrapped error can be extracted later with err.cause()
- */
-class InternalServerErrorWith extends InternalServerError {
- constructor(err) {
- super(err.message);
- this.withMeta("cause", err.name);
- this.withCause(err);
- }
-}
-exports.InternalServerErrorWith = InternalServerErrorWith;
-/**
- * A standard BadRoute Error
- */
-class BadRouteError extends TwirpError {
- constructor(msg, method, url) {
- super(TwirpErrorCode.BadRoute, msg);
- this.withMeta("twirp_invalid_route", method + " " + url);
- }
-}
-exports.BadRouteError = BadRouteError;
-var TwirpErrorCode;
-(function (TwirpErrorCode) {
- // Canceled indicates the operation was cancelled (typically by the caller).
- TwirpErrorCode["Canceled"] = "canceled";
- // Unknown error. For example when handling errors raised by APIs that do not
- // return enough error information.
- TwirpErrorCode["Unknown"] = "unknown";
- // InvalidArgument indicates client specified an invalid argument. It
- // indicates arguments that are problematic regardless of the state of the
- // system (i.e. a malformed file name, required argument, number out of range,
- // etc.).
- TwirpErrorCode["InvalidArgument"] = "invalid_argument";
- // Malformed indicates an error occurred while decoding the client's request.
- // This may mean that the message was encoded improperly, or that there is a
- // disagreement in message format between the client and server.
- TwirpErrorCode["Malformed"] = "malformed";
- // DeadlineExceeded means operation expired before completion. For operations
- // that change the state of the system, this error may be returned even if the
- // operation has completed successfully (timeout).
- TwirpErrorCode["DeadlineExceeded"] = "deadline_exceeded";
- // NotFound means some requested entity was not found.
- TwirpErrorCode["NotFound"] = "not_found";
- // BadRoute means that the requested URL path wasn't routable to a Twirp
- // service and method. This is returned by the generated server, and usually
- // shouldn't be returned by applications. Instead, applications should use
- // NotFound or Unimplemented.
- TwirpErrorCode["BadRoute"] = "bad_route";
- // AlreadyExists means an attempt to create an entity failed because one
- // already exists.
- TwirpErrorCode["AlreadyExists"] = "already_exists";
- // PermissionDenied indicates the caller does not have permission to execute
- // the specified operation. It must not be used if the caller cannot be
- // identified (Unauthenticated).
- TwirpErrorCode["PermissionDenied"] = "permission_denied";
- // Unauthenticated indicates the request does not have valid authentication
- // credentials for the operation.
- TwirpErrorCode["Unauthenticated"] = "unauthenticated";
- // ResourceExhausted indicates some resource has been exhausted, perhaps a
- // per-user quota, or perhaps the entire file system is out of space.
- TwirpErrorCode["ResourceExhausted"] = "resource_exhausted";
- // FailedPrecondition indicates operation was rejected because the system is
- // not in a state required for the operation's execution. For example, doing
- // an rmdir operation on a directory that is non-empty, or on a non-directory
- // object, or when having conflicting read-modify-write on the same resource.
- TwirpErrorCode["FailedPrecondition"] = "failed_precondition";
- // Aborted indicates the operation was aborted, typically due to a concurrency
- // issue like sequencer check failures, transaction aborts, etc.
- TwirpErrorCode["Aborted"] = "aborted";
- // OutOfRange means operation was attempted past the valid range. For example,
- // seeking or reading past end of a paginated collection.
- //
- // Unlike InvalidArgument, this error indicates a problem that may be fixed if
- // the system state changes (i.e. adding more items to the collection).
- //
- // There is a fair bit of overlap between FailedPrecondition and OutOfRange.
- // We recommend using OutOfRange (the more specific error) when it applies so
- // that callers who are iterating through a space can easily look for an
- // OutOfRange error to detect when they are done.
- TwirpErrorCode["OutOfRange"] = "out_of_range";
- // Unimplemented indicates operation is not implemented or not
- // supported/enabled in this service.
- TwirpErrorCode["Unimplemented"] = "unimplemented";
- // Internal errors. When some invariants expected by the underlying system
- // have been broken. In other words, something bad happened in the library or
- // backend service. Do not confuse with HTTP Internal Server Error; an
- // Internal error could also happen on the client code, i.e. when parsing a
- // server response.
- TwirpErrorCode["Internal"] = "internal";
- // Unavailable indicates the service is currently unavailable. This is a most
- // likely a transient condition and may be corrected by retrying with a
- // backoff.
- TwirpErrorCode["Unavailable"] = "unavailable";
- // DataLoss indicates unrecoverable data loss or corruption.
- TwirpErrorCode["DataLoss"] = "data_loss";
-})(TwirpErrorCode = exports.TwirpErrorCode || (exports.TwirpErrorCode = {}));
-// ServerHTTPStatusFromErrorCode maps a Twirp error type into a similar HTTP
-// response status. It is used by the Twirp server handler to set the HTTP
-// response status code. Returns 0 if the ErrorCode is invalid.
-function httpStatusFromErrorCode(code) {
- switch (code) {
- case TwirpErrorCode.Canceled:
- return 408; // RequestTimeout
- case TwirpErrorCode.Unknown:
- return 500; // Internal Server Error
- case TwirpErrorCode.InvalidArgument:
- return 400; // BadRequest
- case TwirpErrorCode.Malformed:
- return 400; // BadRequest
- case TwirpErrorCode.DeadlineExceeded:
- return 408; // RequestTimeout
- case TwirpErrorCode.NotFound:
- return 404; // Not Found
- case TwirpErrorCode.BadRoute:
- return 404; // Not Found
- case TwirpErrorCode.AlreadyExists:
- return 409; // Conflict
- case TwirpErrorCode.PermissionDenied:
- return 403; // Forbidden
- case TwirpErrorCode.Unauthenticated:
- return 401; // Unauthorized
- case TwirpErrorCode.ResourceExhausted:
- return 429; // Too Many Requests
- case TwirpErrorCode.FailedPrecondition:
- return 412; // Precondition Failed
- case TwirpErrorCode.Aborted:
- return 409; // Conflict
- case TwirpErrorCode.OutOfRange:
- return 400; // Bad Request
- case TwirpErrorCode.Unimplemented:
- return 501; // Not Implemented
- case TwirpErrorCode.Internal:
- return 500; // Internal Server Error
- case TwirpErrorCode.Unavailable:
- return 503; // Service Unavailable
- case TwirpErrorCode.DataLoss:
- return 500; // Internal Server Error
- default:
- return 0; // Invalid!
- }
-}
-exports.httpStatusFromErrorCode = httpStatusFromErrorCode;
-// IsValidErrorCode returns true if is one of the valid predefined constants.
-function isValidErrorCode(code) {
- return httpStatusFromErrorCode(code) != 0;
-}
-exports.isValidErrorCode = isValidErrorCode;
+ // 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)
+ }
-/***/ 9636:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ // 3. Let delta-seconds be the attribute-value converted to an integer.
+ const deltaSeconds = Number(attributeValue)
-"use strict";
+ // 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).
-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.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 __rest = (this && this.__rest) || function (s, e) {
- var t = {};
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
- t[p[i]] = s[p[i]];
- }
- return t;
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Gateway = exports.Pattern = void 0;
-const querystring_1 = __nccwpck_require__(3480);
-const dotObject = __importStar(__nccwpck_require__(5129));
-const request_1 = __nccwpck_require__(9647);
-const errors_1 = __nccwpck_require__(3315);
-const http_client_1 = __nccwpck_require__(5683);
-const server_1 = __nccwpck_require__(1035);
-var Pattern;
-(function (Pattern) {
- Pattern["POST"] = "post";
- Pattern["GET"] = "get";
- Pattern["PATCH"] = "patch";
- Pattern["PUT"] = "put";
- Pattern["DELETE"] = "delete";
-})(Pattern = exports.Pattern || (exports.Pattern = {}));
-/**
- * The Gateway proxies http requests to Twirp Compliant
- * handlers
- */
-class Gateway {
- constructor(routes) {
- this.routes = routes;
- }
- /**
- * Middleware that rewrite the current request
- * to a Twirp compliant request
- */
- twirpRewrite(prefix = "/twirp") {
- return (req, resp, next) => {
- this.rewrite(req, resp, prefix)
- .then(() => next())
- .catch((e) => {
- if (e instanceof errors_1.TwirpError) {
- if (e.code !== errors_1.TwirpErrorCode.NotFound) {
- server_1.writeError(resp, e);
- }
- else {
- next();
- }
- }
- });
- };
- }
- /**
- * Rewrite an incoming request to a Twirp compliant request
- * @param req
- * @param resp
- * @param prefix
- */
- rewrite(req, resp, prefix = "/twirp") {
- return __awaiter(this, void 0, void 0, function* () {
- const [match, route] = this.matchRoute(req);
- const body = yield this.prepareTwirpBody(req, match, route);
- const twirpUrl = `${prefix}/${route.packageName}.${route.serviceName}/${route.methodName}`;
- req.url = twirpUrl;
- req.originalUrl = twirpUrl;
- req.method = "POST";
- req.headers["content-type"] = "application/json";
- req.rawBody = Buffer.from(JSON.stringify(body));
- if (route.responseBodyKey) {
- const endFn = resp.end.bind(resp);
- resp.end = function (chunk) {
- if (resp.statusCode === 200) {
- endFn(`{ "${route.responseBodyKey}": ${chunk} }`);
- }
- else {
- endFn(chunk);
- }
- };
- }
- });
- }
- /**
- * Create a reverse proxy handler to
- * proxy http requests to Twirp Compliant handlers
- * @param httpClientOption
- */
- reverseProxy(httpClientOption) {
- const client = http_client_1.NodeHttpRPC(httpClientOption);
- return (req, res) => __awaiter(this, void 0, void 0, function* () {
- try {
- const [match, route] = this.matchRoute(req);
- const body = yield this.prepareTwirpBody(req, match, route);
- const response = yield client.request(`${route.packageName}.${route.serviceName}`, route.methodName, "application/json", body);
- res.statusCode = 200;
- res.setHeader("content-type", "application/json");
- let jsonResponse;
- if (route.responseBodyKey) {
- jsonResponse = JSON.stringify({ [route.responseBodyKey]: response });
- }
- else {
- jsonResponse = JSON.stringify(response);
- }
- res.end(jsonResponse);
- }
- catch (e) {
- server_1.writeError(res, e);
- }
- });
+ // 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)
}
- /**
- * Prepares twirp body requests using http.google.annotions
- * compliant spec
- *
- * @param req
- * @param match
- * @param route
- * @protected
- */
- prepareTwirpBody(req, match, route) {
- return __awaiter(this, void 0, void 0, function* () {
- const _a = match.params, { query_string } = _a, params = __rest(_a, ["query_string"]);
- let requestBody = Object.assign({}, params);
- if (query_string && route.bodyKey !== "*") {
- const queryParams = this.parseQueryString(query_string);
- requestBody = Object.assign(Object.assign({}, queryParams), requestBody);
- }
- let body = {};
- if (route.bodyKey) {
- const data = yield request_1.getRequestData(req);
- try {
- const jsonBody = JSON.parse(data.toString() || "{}");
- if (route.bodyKey === "*") {
- body = jsonBody;
- }
- else {
- body[route.bodyKey] = jsonBody;
- }
- }
- catch (e) {
- const msg = "the json request could not be decoded";
- throw new errors_1.TwirpError(errors_1.TwirpErrorCode.Malformed, msg).withCause(e, true);
- }
- }
- return Object.assign(Object.assign({}, body), requestBody);
- });
+
+ // 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
}
- /**
- * Matches a route
- * @param req
- */
- matchRoute(req) {
- var _a;
- const httpMethod = (_a = req.method) === null || _a === void 0 ? void 0 : _a.toLowerCase();
- if (!httpMethod) {
- throw new errors_1.BadRouteError(`method not allowed`, req.method || "", req.url || "");
- }
- const routes = this.routes[httpMethod];
- for (const route of routes) {
- const match = route.matcher(req.url || "/");
- if (match) {
- return [match, route];
- }
- }
- throw new errors_1.NotFoundError(`url ${req.url} not found`);
+
+ // 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'
}
- /**
- * Parse query string
- * @param queryString
- */
- parseQueryString(queryString) {
- const queryParams = querystring_1.parse(queryString.replace("?", ""));
- return dotObject.object(queryParams);
+
+ // 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
}
-exports.Gateway = Gateway;
/***/ }),
-/***/ 3898:
-/***/ (function(__unused_webpack_module, exports) {
+/***/ 3834:
+/***/ ((module) => {
"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.isHook = exports.chainHooks = void 0;
-// ChainHooks creates a new ServerHook which chains the callbacks in
-// each of the constituent hooks passed in. Each hook function will be
-// called in the order of the ServerHooks values passed in.
-//
-// For the erroring hooks, RequestReceived and RequestRouted, any returned
-// errors prevent processing by later hooks.
-function chainHooks(...hooks) {
- if (hooks.length === 0) {
- return null;
- }
- if (hooks.length === 1) {
- return hooks[0];
+
+/**
+ * @param {string} value
+ * @returns {boolean}
+ */
+function isCTLExcludingHtab (value) {
+ if (value.length === 0) {
+ return false
+ }
+
+ for (const char of value) {
+ const code = char.charCodeAt(0)
+
+ if (
+ (code >= 0x00 || code <= 0x08) ||
+ (code >= 0x0A || code <= 0x1F) ||
+ code === 0x7F
+ ) {
+ return false
}
- const serverHook = {
- requestReceived(ctx) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.requestReceived) {
- continue;
- }
- yield hook.requestReceived(ctx);
- }
- });
- },
- requestPrepared(ctx) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.requestPrepared) {
- continue;
- }
- console.warn("hook requestPrepared is deprecated and will be removed in the next release. " +
- "Please use responsePrepared instead.");
- yield hook.requestPrepared(ctx);
- }
- });
- },
- responsePrepared(ctx) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.responsePrepared) {
- continue;
- }
- yield hook.responsePrepared(ctx);
- }
- });
- },
- requestSent(ctx) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.requestSent) {
- continue;
- }
- console.warn("hook requestSent is deprecated and will be removed in the next release. " +
- "Please use responseSent instead.");
- yield hook.requestSent(ctx);
- }
- });
- },
- responseSent(ctx) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.responseSent) {
- continue;
- }
- yield hook.responseSent(ctx);
- }
- });
- },
- requestRouted(ctx) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.requestRouted) {
- continue;
- }
- yield hook.requestRouted(ctx);
- }
- });
- },
- error(ctx, err) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.error) {
- continue;
- }
- yield hook.error(ctx, err);
- }
- });
- },
- };
- return serverHook;
+ }
}
-exports.chainHooks = chainHooks;
-function isHook(object) {
- return ("requestReceived" in object ||
- "requestPrepared" in object ||
- "requestSent" in object ||
- "requestRouted" in object ||
- "responsePrepared" in object ||
- "responseSent" in object ||
- "error" in object);
+
+/**
+ CHAR =
+ token = 1*
+ separators = "(" | ")" | "<" | ">" | "@"
+ | "," | ";" | ":" | "\" | <">
+ | "/" | "[" | "]" | "?" | "="
+ | "{" | "}" | SP | HT
+ * @param {string} name
+ */
+function validateCookieName (name) {
+ for (const char of name) {
+ const code = char.charCodeAt(0)
+
+ if (
+ (code <= 0x20 || code > 0x7F) ||
+ char === '(' ||
+ char === ')' ||
+ char === '>' ||
+ char === '<' ||
+ char === '@' ||
+ char === ',' ||
+ char === ';' ||
+ char === ':' ||
+ char === '\\' ||
+ char === '"' ||
+ char === '/' ||
+ char === '[' ||
+ char === ']' ||
+ char === '?' ||
+ char === '=' ||
+ char === '{' ||
+ char === '}'
+ ) {
+ throw new Error('Invalid cookie name')
+ }
+ }
}
-exports.isHook = isHook;
+/**
+ 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) {
+ for (const char of value) {
+ const code = char.charCodeAt(0)
-/***/ }),
+ if (
+ code < 0x21 || // exclude CTLs (0-31)
+ code === 0x22 ||
+ code === 0x2C ||
+ code === 0x3B ||
+ code === 0x5C ||
+ code > 0x7E // non-ascii
+ ) {
+ throw new Error('Invalid header value')
+ }
+ }
+}
-/***/ 5683:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/**
+ * path-value =
+ * @param {string} path
+ */
+function validateCookiePath (path) {
+ for (const char of path) {
+ const code = char.charCodeAt(0)
-"use strict";
+ if (code < 0x21 || char === ';') {
+ throw new Error('Invalid cookie path')
+ }
+ }
+}
-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.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.FetchRPC = exports.wrapErrorResponseToTwirpError = exports.NodeHttpRPC = void 0;
-const http = __importStar(__nccwpck_require__(8611));
-const https = __importStar(__nccwpck_require__(5692));
-const url_1 = __nccwpck_require__(7016);
-const errors_1 = __nccwpck_require__(3315);
/**
- * a node HTTP RPC implementation
- * @param options
- * @constructor
+ * I have no idea why these values aren't allowed to be honest,
+ * but Deno tests these. - Khafra
+ * @param {string} domain
*/
-const NodeHttpRPC = (options) => ({
- request(service, method, contentType, data) {
- let client;
- return new Promise((resolve, rejected) => {
- const responseChunks = [];
- const requestData = contentType === "application/protobuf"
- ? Buffer.from(data)
- : JSON.stringify(data);
- const url = new url_1.URL(options.baseUrl);
- const isHttps = url.protocol === "https:";
- if (isHttps) {
- client = https;
- }
- else {
- client = http;
- }
- const prefix = url.pathname !== "/" ? url.pathname : "";
- const req = client
- .request(Object.assign(Object.assign({}, (options ? options : {})), { method: "POST", protocol: url.protocol, host: url.hostname, port: url.port ? url.port : isHttps ? 443 : 80, path: `${prefix}/${service}/${method}`, headers: Object.assign(Object.assign({}, (options.headers ? options.headers : {})), { "Content-Type": contentType, "Content-Length": contentType === "application/protobuf"
- ? Buffer.byteLength(requestData)
- : Buffer.from(requestData).byteLength }) }), (res) => {
- res.on("data", (chunk) => responseChunks.push(chunk));
- res.on("end", () => {
- const data = Buffer.concat(responseChunks);
- if (res.statusCode != 200) {
- rejected(wrapErrorResponseToTwirpError(data.toString()));
- }
- else {
- if (contentType === "application/json") {
- resolve(JSON.parse(data.toString()));
- }
- else {
- resolve(data);
- }
- }
- });
- res.on("error", (err) => {
- rejected(err);
- });
- })
- .on("error", (err) => {
- rejected(err);
- });
- req.end(requestData);
- });
- },
-});
-exports.NodeHttpRPC = NodeHttpRPC;
-function wrapErrorResponseToTwirpError(errorResponse) {
- return errors_1.TwirpError.fromObject(JSON.parse(errorResponse));
+function validateCookieDomain (domain) {
+ if (
+ domain.startsWith('-') ||
+ domain.endsWith('.') ||
+ domain.endsWith('-')
+ ) {
+ throw new Error('Invalid cookie domain')
+ }
+}
+
+/**
+ * @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)
+ }
+
+ const days = [
+ 'Sun', 'Mon', 'Tue', 'Wed',
+ 'Thu', 'Fri', 'Sat'
+ ]
+
+ const months = [
+ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
+ ]
+
+ const dayName = days[date.getUTCDay()]
+ const day = date.getUTCDate().toString().padStart(2, '0')
+ const month = months[date.getUTCMonth()]
+ const year = date.getUTCFullYear()
+ const hour = date.getUTCHours().toString().padStart(2, '0')
+ const minute = date.getUTCMinutes().toString().padStart(2, '0')
+ const second = date.getUTCSeconds().toString().padStart(2, '0')
+
+ return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT`
}
-exports.wrapErrorResponseToTwirpError = wrapErrorResponseToTwirpError;
+
/**
- * a browser fetch RPC implementation
+ 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
*/
-const FetchRPC = (options) => ({
- request(service, method, contentType, data) {
- return __awaiter(this, void 0, void 0, function* () {
- const headers = new Headers(options.headers);
- headers.set("content-type", contentType);
- const response = yield fetch(`${options.baseUrl}/${service}/${method}`, Object.assign(Object.assign({}, options), { method: "POST", headers, body: data instanceof Uint8Array ? data : JSON.stringify(data) }));
- if (response.status === 200) {
- if (contentType === "application/json") {
- return yield response.json();
- }
- return new Uint8Array(yield response.arrayBuffer());
- }
- throw errors_1.TwirpError.fromObject(yield response.json());
- });
- },
-});
-exports.FetchRPC = FetchRPC;
+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)
-/***/ 430:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ const out = [`${cookie.name}=${cookie.value}`]
-"use strict";
+ // 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
+ }
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __exportStar = (this && this.__exportStar) || function(m, exports) {
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.TwirpContentType = void 0;
-__exportStar(__nccwpck_require__(7878), exports);
-__exportStar(__nccwpck_require__(1035), exports);
-__exportStar(__nccwpck_require__(4036), exports);
-__exportStar(__nccwpck_require__(3898), exports);
-__exportStar(__nccwpck_require__(3315), exports);
-__exportStar(__nccwpck_require__(9636), exports);
-__exportStar(__nccwpck_require__(5683), exports);
-var request_1 = __nccwpck_require__(9647);
-Object.defineProperty(exports, "TwirpContentType", ({ enumerable: true, get: function () { return request_1.TwirpContentType; } }));
+ 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')
+ }
-/***/ 4036:
-/***/ (function(__unused_webpack_module, exports) {
+ if (typeof cookie.maxAge === 'number') {
+ validateCookieMaxAge(cookie.maxAge)
+ out.push(`Max-Age=${cookie.maxAge}`)
+ }
-"use strict";
+ if (cookie.domain) {
+ validateCookieDomain(cookie.domain)
+ out.push(`Domain=${cookie.domain}`)
+ }
-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.chainInterceptors = void 0;
-// chains multiple Interceptors into a single Interceptor.
-// The first interceptor wraps the second one, and so on.
-// Returns null if interceptors is empty.
-function chainInterceptors(...interceptors) {
- if (interceptors.length === 0) {
- return;
- }
- if (interceptors.length === 1) {
- return interceptors[0];
- }
- const first = interceptors[0];
- return (ctx, request, handler) => __awaiter(this, void 0, void 0, function* () {
- let next = handler;
- for (let i = interceptors.length - 1; i > 0; i--) {
- next = ((next) => (ctx, typedRequest) => {
- return interceptors[i](ctx, typedRequest, next);
- })(next);
- }
- return first(ctx, request, next);
- });
-}
-exports.chainInterceptors = chainInterceptors;
+ 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}`)
+ }
-/***/ 9647:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ for (const part of cookie.unparsed) {
+ if (!part.includes('=')) {
+ throw new Error('Invalid unparsed')
+ }
-"use strict";
+ const [key, ...value] = part.split('=')
-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.parseTwirpPath = exports.getRequestData = exports.validateRequest = exports.getContentType = exports.TwirpContentType = void 0;
-const errors_1 = __nccwpck_require__(3315);
-/**
- * Supported Twirp Content-Type
- */
-var TwirpContentType;
-(function (TwirpContentType) {
- TwirpContentType[TwirpContentType["Protobuf"] = 0] = "Protobuf";
- TwirpContentType[TwirpContentType["JSON"] = 1] = "JSON";
- TwirpContentType[TwirpContentType["Unknown"] = 2] = "Unknown";
-})(TwirpContentType = exports.TwirpContentType || (exports.TwirpContentType = {}));
-/**
- * Get supported content-type
- * @param mimeType
- */
-function getContentType(mimeType) {
- switch (mimeType) {
- case "application/protobuf":
- return TwirpContentType.Protobuf;
- case "application/json":
- return TwirpContentType.JSON;
- default:
- return TwirpContentType.Unknown;
- }
-}
-exports.getContentType = getContentType;
-/**
- * Validate a twirp request
- * @param ctx
- * @param request
- * @param pathPrefix
- */
-function validateRequest(ctx, request, pathPrefix) {
- if (request.method !== "POST") {
- const msg = `unsupported method ${request.method} (only POST is allowed)`;
- throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
- }
- const path = parseTwirpPath(request.url || "");
- if (path.pkgService !==
- (ctx.packageName ? ctx.packageName + "." : "") + ctx.serviceName) {
- const msg = `no handler for path ${request.url}`;
- throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
- }
- if (path.prefix !== pathPrefix) {
- const msg = `invalid path prefix ${path.prefix}, expected ${pathPrefix}, on path ${request.url}`;
- throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
- }
- const mimeContentType = request.headers["content-type"] || "";
- if (ctx.contentType === TwirpContentType.Unknown) {
- const msg = `unexpected Content-Type: ${request.headers["content-type"]}`;
- throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
- }
- return Object.assign(Object.assign({}, path), { mimeContentType, contentType: ctx.contentType });
-}
-exports.validateRequest = validateRequest;
-/**
- * Get request data from the body
- * @param req
- */
-function getRequestData(req) {
- return new Promise((resolve, reject) => {
- const reqWithRawBody = req;
- if (reqWithRawBody.rawBody instanceof Buffer) {
- resolve(reqWithRawBody.rawBody);
- return;
- }
- const chunks = [];
- req.on("data", (chunk) => chunks.push(chunk));
- req.on("end", () => __awaiter(this, void 0, void 0, function* () {
- const data = Buffer.concat(chunks);
- resolve(data);
- }));
- req.on("error", (err) => {
- if (req.aborted) {
- reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.DeadlineExceeded, "failed to read request: deadline exceeded"));
- }
- else {
- reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.Malformed, err.message).withCause(err));
- }
- });
- req.on("close", () => {
- reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.Canceled, "failed to read request: context canceled"));
- });
- });
+ out.push(`${key.trim()}=${value.join('=')}`)
+ }
+
+ return out.join('; ')
}
-exports.getRequestData = getRequestData;
-/**
- * Parses twirp url path
- * @param path
- */
-function parseTwirpPath(path) {
- const parts = path.split("/");
- if (parts.length < 2) {
- return {
- pkgService: "",
- method: "",
- prefix: "",
- };
- }
- return {
- method: parts[parts.length - 1],
- pkgService: parts[parts.length - 2],
- prefix: parts.slice(0, parts.length - 2).join("/"),
- };
+
+module.exports = {
+ isCTLExcludingHtab,
+ validateCookieName,
+ validateCookiePath,
+ validateCookieValue,
+ toIMFDate,
+ stringify
}
-exports.parseTwirpPath = parseTwirpPath;
/***/ }),
-/***/ 1035:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ 59136:
+/***/ ((module, __unused_webpack_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.writeError = exports.TwirpServer = void 0;
-const hooks_1 = __nccwpck_require__(3898);
-const request_1 = __nccwpck_require__(9647);
-const errors_1 = __nccwpck_require__(3315);
-/**
- * Runtime server implementation of a TwirpServer
- */
-class TwirpServer {
- constructor(options) {
- this.pathPrefix = "/twirp";
- this.hooks = [];
- this.interceptors = [];
- this.packageName = options.packageName;
- this.serviceName = options.serviceName;
- this.methodList = options.methodList;
- this.matchRoute = options.matchRoute;
- this.service = options.service;
- }
- /**
- * Returns the prefix for this server
- */
- get prefix() {
- return this.pathPrefix;
- }
- /**
- * The http handler for twirp complaint endpoints
- * @param options
- */
- httpHandler(options) {
- return (req, resp) => {
- // setup prefix
- if ((options === null || options === void 0 ? void 0 : options.prefix) !== undefined) {
- this.withPrefix(options.prefix);
- }
- return this._httpHandler(req, resp);
- };
- }
- /**
- * Adds interceptors or hooks to the request stack
- * @param middlewares
- */
- use(...middlewares) {
- middlewares.forEach((middleware) => {
- if (hooks_1.isHook(middleware)) {
- this.hooks.push(middleware);
- return this;
- }
- this.interceptors.push(middleware);
- });
- return this;
- }
- /**
- * Adds a prefix to the service url path
- * @param prefix
- */
- withPrefix(prefix) {
- if (prefix === false) {
- this.pathPrefix = "";
+
+const net = __nccwpck_require__(69278)
+const assert = __nccwpck_require__(42613)
+const util = __nccwpck_require__(3440)
+const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(68707)
+
+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.
+
+let SessionCache
+// FIXME: remove workaround when the Node bug is fixed
+// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
+if (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) {
+ SessionCache = class WeakSessionCache {
+ constructor (maxCachedSessions) {
+ this._maxCachedSessions = maxCachedSessions
+ this._sessionCache = new Map()
+ this._sessionRegistry = new global.FinalizationRegistry((key) => {
+ if (this._sessionCache.size < this._maxCachedSessions) {
+ return
}
- else {
- this.pathPrefix = prefix;
+
+ const ref = this._sessionCache.get(key)
+ if (ref !== undefined && ref.deref() === undefined) {
+ this._sessionCache.delete(key)
}
- return this;
+ })
}
- /**
- * Returns the regex matching path for this twirp server
- */
- matchingPath() {
- const baseRegex = this.baseURI().replace(/\./g, "\\.");
- return new RegExp(`${baseRegex}\/(${this.methodList.join("|")})`);
+
+ get (sessionKey) {
+ const ref = this._sessionCache.get(sessionKey)
+ return ref ? ref.deref() : null
}
- /**
- * Returns the base URI for this twirp server
- */
- baseURI() {
- return `${this.pathPrefix}/${this.packageName ? this.packageName + "." : ""}${this.serviceName}`;
+
+ set (sessionKey, session) {
+ if (this._maxCachedSessions === 0) {
+ return
+ }
+
+ this._sessionCache.set(sessionKey, new WeakRef(session))
+ this._sessionRegistry.register(session, sessionKey)
}
- /**
- * Create a twirp context
- * @param req
- * @param res
- * @private
- */
- createContext(req, res) {
- return {
- packageName: this.packageName,
- serviceName: this.serviceName,
- methodName: "",
- contentType: request_1.getContentType(req.headers["content-type"]),
- req: req,
- res: res,
- };
+ }
+} else {
+ SessionCache = class SimpleSessionCache {
+ constructor (maxCachedSessions) {
+ this._maxCachedSessions = maxCachedSessions
+ this._sessionCache = new Map()
}
- /**
- * Twrip server http handler implementation
- * @param req
- * @param resp
- * @private
- */
- _httpHandler(req, resp) {
- return __awaiter(this, void 0, void 0, function* () {
- const ctx = this.createContext(req, resp);
- try {
- yield this.invokeHook("requestReceived", ctx);
- const { method, mimeContentType } = request_1.validateRequest(ctx, req, this.pathPrefix || "");
- const handler = this.matchRoute(method, {
- onMatch: (ctx) => {
- return this.invokeHook("requestRouted", ctx);
- },
- onNotFound: () => {
- const msg = `no handler for path ${req.url}`;
- throw new errors_1.BadRouteError(msg, req.method || "", req.url || "");
- },
- });
- const body = yield request_1.getRequestData(req);
- const response = yield handler(ctx, this.service, body, this.interceptors);
- yield Promise.all([
- this.invokeHook("responsePrepared", ctx),
- // keep backwards compatibility till next release
- this.invokeHook("requestPrepared", ctx),
- ]);
- resp.statusCode = 200;
- resp.setHeader("Content-Type", mimeContentType);
- resp.end(response);
- }
- catch (e) {
- yield this.invokeHook("error", ctx, mustBeTwirpError(e));
- if (!resp.headersSent) {
- writeError(resp, e);
- }
- }
- finally {
- yield Promise.all([
- this.invokeHook("responseSent", ctx),
- // keep backwards compatibility till next release
- this.invokeHook("requestSent", ctx),
- ]);
- }
- });
+
+ get (sessionKey) {
+ return this._sessionCache.get(sessionKey)
+ }
+
+ set (sessionKey, session) {
+ if (this._maxCachedSessions === 0) {
+ return
+ }
+
+ if (this._sessionCache.size >= this._maxCachedSessions) {
+ // remove the oldest session
+ const { value: oldestKey } = this._sessionCache.keys().next()
+ this._sessionCache.delete(oldestKey)
+ }
+
+ this._sessionCache.set(sessionKey, session)
+ }
+ }
+}
+
+function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...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__(64756)
+ }
+ servername = servername || options.servername || util.getServerName(host) || null
+
+ const sessionKey = servername || hostname
+ const session = sessionCache.get(sessionKey) || null
+
+ assert(sessionKey)
+
+ socket = tls.connect({
+ highWaterMark: 16384, // TLS in node can't have bigger HWM anyway...
+ ...options,
+ servername,
+ session,
+ localAddress,
+ // TODO(HTTP/2): Add support for h2c
+ ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'],
+ socket: httpSocket, // upgrade socket connection
+ port: port || 443,
+ 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')
+ socket = net.connect({
+ highWaterMark: 64 * 1024, // Same as nodejs fs streams.
+ ...options,
+ localAddress,
+ port: port || 80,
+ host: hostname
+ })
}
- /**
- * Invoke a hook
- * @param hookName
- * @param ctx
- * @param err
- * @protected
- */
- invokeHook(hookName, ctx, err) {
- return __awaiter(this, void 0, void 0, function* () {
- if (this.hooks.length === 0) {
- return;
- }
- const chainedHooks = hooks_1.chainHooks(...this.hooks);
- const hook = chainedHooks === null || chainedHooks === void 0 ? void 0 : chainedHooks[hookName];
- if (hook) {
- yield hook(ctx, err || new errors_1.InternalServerError("internal server error"));
- }
- });
+
+ // 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 cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout)
+
+ socket
+ .setNoDelay(true)
+ .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () {
+ cancelTimeout()
+
+ if (callback) {
+ const cb = callback
+ callback = null
+ cb(null, this)
+ }
+ })
+ .on('error', function (err) {
+ cancelTimeout()
+
+ if (callback) {
+ const cb = callback
+ callback = null
+ cb(err)
+ }
+ })
+
+ return socket
+ }
}
-exports.TwirpServer = TwirpServer;
-/**
- * Write http error response
- * @param res
- * @param error
- */
-function writeError(res, error) {
- const twirpError = mustBeTwirpError(error);
- res.setHeader("Content-Type", "application/json");
- res.statusCode = errors_1.httpStatusFromErrorCode(twirpError.code);
- res.end(twirpError.toJSON());
+
+function setupTimeout (onConnectTimeout, timeout) {
+ if (!timeout) {
+ return () => {}
+ }
+
+ let s1 = null
+ let s2 = null
+ const timeoutId = setTimeout(() => {
+ // setImmediate is added to make sure that we priotorise socket error events over timeouts
+ s1 = setImmediate(() => {
+ if (process.platform === 'win32') {
+ // Windows needs an extra setImmediate probably due to implementation differences in the socket logic
+ s2 = setImmediate(() => onConnectTimeout())
+ } else {
+ onConnectTimeout()
+ }
+ })
+ }, timeout)
+ return () => {
+ clearTimeout(timeoutId)
+ clearImmediate(s1)
+ clearImmediate(s2)
+ }
}
-exports.writeError = writeError;
-/**
- * Make sure that the error passed is a TwirpError
- * otherwise it will wrap it into an InternalError
- * @param err
- */
-function mustBeTwirpError(err) {
- if (err instanceof errors_1.TwirpError) {
- return err;
- }
- return new errors_1.InternalServerErrorWith(err);
+
+function onConnectTimeout (socket) {
+ util.destroy(socket, new ConnectTimeoutError())
}
+module.exports = buildConnector
+
/***/ }),
-/***/ 6752:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 10735:
+/***/ ((module) => {
"use strict";
-const Client = __nccwpck_require__(6197)
-const Dispatcher = __nccwpck_require__(992)
-const errors = __nccwpck_require__(8707)
-const Pool = __nccwpck_require__(5076)
-const BalancedPool = __nccwpck_require__(1093)
-const Agent = __nccwpck_require__(9965)
-const util = __nccwpck_require__(3440)
-const { InvalidArgumentError } = errors
-const api = __nccwpck_require__(6615)
-const buildConnector = __nccwpck_require__(9136)
-const MockClient = __nccwpck_require__(7365)
-const MockAgent = __nccwpck_require__(7501)
-const MockPool = __nccwpck_require__(4004)
-const mockErrors = __nccwpck_require__(2429)
-const ProxyAgent = __nccwpck_require__(2720)
-const RetryHandler = __nccwpck_require__(3573)
-const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(2581)
-const DecoratorHandler = __nccwpck_require__(8840)
-const RedirectHandler = __nccwpck_require__(8299)
-const createRedirectInterceptor = __nccwpck_require__(4415)
+/** @type {Record} */
+const headerNameLowerCasedRecord = {}
-let hasCrypto
-try {
- __nccwpck_require__(6982)
- hasCrypto = true
-} catch {
- hasCrypto = false
+// https://developer.mozilla.org/docs/Web/HTTP/Headers
+const wellknownHeaderNames = [
+ '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'
+]
+
+for (let i = 0; i < wellknownHeaderNames.length; ++i) {
+ const key = wellknownHeaderNames[i]
+ const lowerCasedKey = key.toLowerCase()
+ headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] =
+ lowerCasedKey
}
-Object.assign(Dispatcher.prototype, api)
+// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
+Object.setPrototypeOf(headerNameLowerCasedRecord, null)
-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.RetryHandler = RetryHandler
+module.exports = {
+ wellknownHeaderNames,
+ headerNameLowerCasedRecord
+}
-module.exports.DecoratorHandler = DecoratorHandler
-module.exports.RedirectHandler = RedirectHandler
-module.exports.createRedirectInterceptor = createRedirectInterceptor
-module.exports.buildConnector = buildConnector
-module.exports.errors = errors
+/***/ }),
-function makeDispatcher (fn) {
- return (url, opts, handler) => {
- if (typeof opts === 'function') {
- handler = opts
- opts = null
- }
+/***/ 68707:
+/***/ ((module) => {
- if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) {
- throw new InvalidArgumentError('invalid url')
- }
+"use strict";
- 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')
- }
+class UndiciError extends Error {
+ constructor (message) {
+ super(message)
+ this.name = 'UndiciError'
+ this.code = 'UND_ERR'
+ }
+}
- let path = opts.path
- if (!opts.path.startsWith('/')) {
- path = `/${path}`
- }
+class ConnectTimeoutError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, ConnectTimeoutError)
+ this.name = 'ConnectTimeoutError'
+ this.message = message || 'Connect Timeout Error'
+ this.code = 'UND_ERR_CONNECT_TIMEOUT'
+ }
+}
- url = new URL(util.parseOrigin(url).origin + path)
- } else {
- if (!opts) {
- opts = typeof url === 'object' ? url : {}
- }
+class HeadersTimeoutError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, HeadersTimeoutError)
+ this.name = 'HeadersTimeoutError'
+ this.message = message || 'Headers Timeout Error'
+ this.code = 'UND_ERR_HEADERS_TIMEOUT'
+ }
+}
- url = util.parseURL(url)
- }
+class HeadersOverflowError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, HeadersOverflowError)
+ this.name = 'HeadersOverflowError'
+ this.message = message || 'Headers Overflow Error'
+ this.code = 'UND_ERR_HEADERS_OVERFLOW'
+ }
+}
- const { agent, dispatcher = getGlobalDispatcher() } = opts
+class BodyTimeoutError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, BodyTimeoutError)
+ this.name = 'BodyTimeoutError'
+ this.message = message || 'Body Timeout Error'
+ this.code = 'UND_ERR_BODY_TIMEOUT'
+ }
+}
- if (agent) {
- throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?')
- }
+class ResponseStatusCodeError extends UndiciError {
+ constructor (message, statusCode, headers, body) {
+ super(message)
+ Error.captureStackTrace(this, ResponseStatusCodeError)
+ 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
+ }
+}
- 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)
+class InvalidArgumentError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, InvalidArgumentError)
+ this.name = 'InvalidArgumentError'
+ this.message = message || 'Invalid Argument Error'
+ this.code = 'UND_ERR_INVALID_ARG'
}
}
-module.exports.setGlobalDispatcher = setGlobalDispatcher
-module.exports.getGlobalDispatcher = getGlobalDispatcher
+class InvalidReturnValueError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, InvalidReturnValueError)
+ this.name = 'InvalidReturnValueError'
+ this.message = message || 'Invalid Return Value Error'
+ this.code = 'UND_ERR_INVALID_RETURN_VALUE'
+ }
+}
-if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) {
- let fetchImpl = null
- module.exports.fetch = async function fetch (resource) {
- if (!fetchImpl) {
- fetchImpl = (__nccwpck_require__(2315).fetch)
- }
+class RequestAbortedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, RequestAbortedError)
+ this.name = 'AbortError'
+ this.message = message || 'Request aborted'
+ this.code = 'UND_ERR_ABORTED'
+ }
+}
- try {
- return await fetchImpl(...arguments)
- } catch (err) {
- if (typeof err === 'object') {
- Error.captureStackTrace(err, this)
- }
+class InformationalError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, InformationalError)
+ this.name = 'InformationalError'
+ this.message = message || 'Request information'
+ this.code = 'UND_ERR_INFO'
+ }
+}
- throw err
- }
+class RequestContentLengthMismatchError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, RequestContentLengthMismatchError)
+ this.name = 'RequestContentLengthMismatchError'
+ this.message = message || 'Request body length does not match content-length header'
+ this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
}
- module.exports.Headers = __nccwpck_require__(6349).Headers
- module.exports.Response = __nccwpck_require__(8676).Response
- module.exports.Request = __nccwpck_require__(5194).Request
- module.exports.FormData = __nccwpck_require__(3073).FormData
- module.exports.File = __nccwpck_require__(3041).File
- module.exports.FileReader = __nccwpck_require__(2160).FileReader
+}
- const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(5628)
+class ResponseContentLengthMismatchError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, ResponseContentLengthMismatchError)
+ this.name = 'ResponseContentLengthMismatchError'
+ this.message = message || 'Response body length does not match content-length header'
+ this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'
+ }
+}
- module.exports.setGlobalOrigin = setGlobalOrigin
- module.exports.getGlobalOrigin = getGlobalOrigin
+class ClientDestroyedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, ClientDestroyedError)
+ this.name = 'ClientDestroyedError'
+ this.message = message || 'The client is destroyed'
+ this.code = 'UND_ERR_DESTROYED'
+ }
+}
+
+class ClientClosedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, ClientClosedError)
+ this.name = 'ClientClosedError'
+ this.message = message || 'The client is closed'
+ this.code = 'UND_ERR_CLOSED'
+ }
+}
- const { CacheStorage } = __nccwpck_require__(4738)
- const { kConstruct } = __nccwpck_require__(296)
+class SocketError extends UndiciError {
+ constructor (message, socket) {
+ super(message)
+ Error.captureStackTrace(this, SocketError)
+ this.name = 'SocketError'
+ this.message = message || 'Socket error'
+ this.code = 'UND_ERR_SOCKET'
+ this.socket = socket
+ }
+}
- // 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)
+class NotSupportedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, NotSupportedError)
+ this.name = 'NotSupportedError'
+ this.message = message || 'Not supported error'
+ this.code = 'UND_ERR_NOT_SUPPORTED'
+ }
}
-if (util.nodeMajor >= 16) {
- const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(3168)
+class BalancedPoolMissingUpstreamError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, NotSupportedError)
+ this.name = 'MissingUpstreamError'
+ this.message = message || 'No upstream has been added to the BalancedPool'
+ this.code = 'UND_ERR_BPL_MISSING_UPSTREAM'
+ }
+}
- module.exports.deleteCookie = deleteCookie
- module.exports.getCookies = getCookies
- module.exports.getSetCookies = getSetCookies
- module.exports.setCookie = setCookie
+class HTTPParserError extends Error {
+ constructor (message, code, data) {
+ super(message)
+ Error.captureStackTrace(this, HTTPParserError)
+ this.name = 'HTTPParserError'
+ this.code = code ? `HPE_${code}` : undefined
+ this.data = data ? data.toString() : undefined
+ }
+}
- const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322)
+class ResponseExceededMaxSizeError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, ResponseExceededMaxSizeError)
+ this.name = 'ResponseExceededMaxSizeError'
+ this.message = message || 'Response content exceeded max size'
+ this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE'
+ }
+}
- module.exports.parseMIMEType = parseMIMEType
- module.exports.serializeAMimeType = serializeAMimeType
+class RequestRetryError extends UndiciError {
+ constructor (message, code, { headers, data }) {
+ super(message)
+ Error.captureStackTrace(this, RequestRetryError)
+ this.name = 'RequestRetryError'
+ this.message = message || 'Request retry error'
+ this.code = 'UND_ERR_REQ_RETRY'
+ this.statusCode = code
+ this.data = data
+ this.headers = headers
+ }
}
-if (util.nodeMajor >= 18 && hasCrypto) {
- const { WebSocket } = __nccwpck_require__(5171)
-
- module.exports.WebSocket = WebSocket
+module.exports = {
+ HTTPParserError,
+ UndiciError,
+ HeadersTimeoutError,
+ HeadersOverflowError,
+ BodyTimeoutError,
+ RequestContentLengthMismatchError,
+ ConnectTimeoutError,
+ ResponseStatusCodeError,
+ InvalidArgumentError,
+ InvalidReturnValueError,
+ RequestAbortedError,
+ ClientDestroyedError,
+ ClientClosedError,
+ InformationalError,
+ SocketError,
+ NotSupportedError,
+ ResponseContentLengthMismatchError,
+ BalancedPoolMissingUpstreamError,
+ ResponseExceededMaxSizeError,
+ RequestRetryError
}
-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.MockPool = MockPool
-module.exports.MockAgent = MockAgent
-module.exports.mockErrors = mockErrors
-
/***/ }),
-/***/ 9965:
+/***/ 44655:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-const { InvalidArgumentError } = __nccwpck_require__(8707)
-const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(6443)
-const DispatcherBase = __nccwpck_require__(1)
-const Pool = __nccwpck_require__(5076)
-const Client = __nccwpck_require__(6197)
+const {
+ InvalidArgumentError,
+ NotSupportedError
+} = __nccwpck_require__(68707)
+const assert = __nccwpck_require__(42613)
+const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(36443)
const util = __nccwpck_require__(3440)
-const createRedirectInterceptor = __nccwpck_require__(4415)
-const { WeakRef, FinalizationRegistry } = __nccwpck_require__(3194)()
-
-const kOnConnect = Symbol('onConnect')
-const kOnDisconnect = Symbol('onDisconnect')
-const kOnConnectionError = Symbol('onConnectionError')
-const kMaxRedirections = Symbol('maxRedirections')
-const kOnDrain = Symbol('onDrain')
-const kFactory = Symbol('factory')
-const kFinalizer = Symbol('finalizer')
-const kOptions = Symbol('options')
-function defaultFactory (origin, opts) {
- return opts && opts.connections === 1
- ? new Client(origin, opts)
- : new Pool(origin, opts)
-}
+// tokenRegExp and headerCharRegex have been lifted from
+// https://github.com/nodejs/node/blob/main/lib/_http_common.js
-class Agent extends DispatcherBase {
- constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {
- super()
+/**
+ * Verifies that the given val is a valid HTTP token
+ * per the rules defined in RFC 7230
+ * See https://tools.ietf.org/html/rfc7230#section-3.2.6
+ */
+const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/
- if (typeof factory !== 'function') {
- throw new InvalidArgumentError('factory must be a function.')
- }
+/**
+ * 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]/
- if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
- throw new InvalidArgumentError('connect must be a function or an object')
- }
+// Verifies that a given path is valid does not contain control chars \x00 to \x20
+const invalidPathRegex = /[^\u0021-\u00ff]/
- if (!Number.isInteger(maxRedirections) || maxRedirections < 0) {
- throw new InvalidArgumentError('maxRedirections must be a positive number')
- }
+const kHandler = Symbol('handler')
- if (connect && typeof connect !== 'function') {
- connect = { ...connect }
- }
+const channels = {}
- this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent)
- ? options.interceptors.Agent
- : [createRedirectInterceptor({ maxRedirections })]
+let extractBody
- this[kOptions] = { ...util.deepClone(options), connect }
- this[kOptions].interceptors = options.interceptors
- ? { ...options.interceptors }
- : undefined
- this[kMaxRedirections] = maxRedirections
- this[kFactory] = factory
- this[kClients] = new Map()
- this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => {
- const ref = this[kClients].get(key)
- if (ref !== undefined && ref.deref() === undefined) {
- this[kClients].delete(key)
- }
- })
+try {
+ const diagnosticsChannel = __nccwpck_require__(31637)
+ channels.create = diagnosticsChannel.channel('undici:request:create')
+ channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent')
+ channels.headers = diagnosticsChannel.channel('undici:request:headers')
+ channels.trailers = diagnosticsChannel.channel('undici:request:trailers')
+ channels.error = diagnosticsChannel.channel('undici:request:error')
+} catch {
+ channels.create = { hasSubscribers: false }
+ channels.bodySent = { hasSubscribers: false }
+ channels.headers = { hasSubscribers: false }
+ channels.trailers = { hasSubscribers: false }
+ channels.error = { hasSubscribers: false }
+}
- const agent = this
+class Request {
+ constructor (origin, {
+ path,
+ method,
+ body,
+ headers,
+ query,
+ idempotent,
+ blocking,
+ upgrade,
+ headersTimeout,
+ bodyTimeout,
+ reset,
+ throwOnError,
+ expectContinue
+ }, 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.exec(path) !== null) {
+ throw new InvalidArgumentError('invalid request path')
+ }
- this[kOnDrain] = (origin, targets) => {
- agent.emit('drain', origin, [agent, ...targets])
+ if (typeof method !== 'string') {
+ throw new InvalidArgumentError('method must be a string')
+ } else if (tokenRegExp.exec(method) === null) {
+ throw new InvalidArgumentError('invalid request method')
}
- this[kOnConnect] = (origin, targets) => {
- agent.emit('connect', origin, [agent, ...targets])
+ if (upgrade && typeof upgrade !== 'string') {
+ throw new InvalidArgumentError('upgrade must be a string')
}
- this[kOnDisconnect] = (origin, targets, err) => {
- agent.emit('disconnect', origin, [agent, ...targets], err)
+ if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
+ throw new InvalidArgumentError('invalid headersTimeout')
}
- this[kOnConnectionError] = (origin, targets, err) => {
- agent.emit('connectionError', origin, [agent, ...targets], err)
+ if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
+ throw new InvalidArgumentError('invalid bodyTimeout')
}
- }
- get [kRunning] () {
- let ret = 0
- for (const ref of this[kClients].values()) {
- const client = ref.deref()
- /* istanbul ignore next: gc is undeterministic */
- if (client) {
- ret += client[kRunning]
- }
+ if (reset != null && typeof reset !== 'boolean') {
+ throw new InvalidArgumentError('invalid reset')
}
- 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.')
+ if (expectContinue != null && typeof expectContinue !== 'boolean') {
+ throw new InvalidArgumentError('invalid expectContinue')
}
- const ref = this[kClients].get(key)
+ this.headersTimeout = headersTimeout
- let dispatcher = ref ? ref.deref() : null
- 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.bodyTimeout = bodyTimeout
- this[kClients].set(key, new WeakRef(dispatcher))
- this[kFinalizer].register(dispatcher, key)
- }
+ this.throwOnError = throwOnError === true
- return dispatcher.dispatch(opts, handler)
- }
+ this.method = method
- async [kClose] () {
- const closePromises = []
- for (const ref of this[kClients].values()) {
- const client = ref.deref()
- /* istanbul ignore else: gc is undeterministic */
- if (client) {
- closePromises.push(client.close())
- }
- }
+ this.abort = null
- await Promise.all(closePromises)
- }
+ if (body == null) {
+ this.body = null
+ } else if (util.isStream(body)) {
+ this.body = body
- async [kDestroy] (err) {
- const destroyPromises = []
- for (const ref of this[kClients].values()) {
- const client = ref.deref()
- /* istanbul ignore else: gc is undeterministic */
- if (client) {
- destroyPromises.push(client.destroy(err))
+ const rState = this.body._readableState
+ if (!rState || !rState.autoDestroy) {
+ this.endHandler = function autoDestroy () {
+ util.destroy(this)
+ }
+ this.body.on('end', this.endHandler)
}
- }
- await Promise.all(destroyPromises)
- }
-}
+ this.errorHandler = err => {
+ if (this.abort) {
+ this.abort(err)
+ } else {
+ this.error = err
+ }
+ }
+ this.body.on('error', this.errorHandler)
+ } else if (util.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 (util.isFormDataLike(body) || util.isIterable(body) || util.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')
+ }
-module.exports = Agent
+ this.completed = false
+ this.aborted = false
-/***/ }),
+ this.upgrade = upgrade || null
-/***/ 158:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ this.path = query ? util.buildURL(path, query) : path
-const { addAbortListener } = __nccwpck_require__(3440)
-const { RequestAbortedError } = __nccwpck_require__(8707)
+ this.origin = origin
-const kListener = Symbol('kListener')
-const kSignal = Symbol('kSignal')
+ this.idempotent = idempotent == null
+ ? method === 'HEAD' || method === 'GET'
+ : idempotent
-function abort (self) {
- if (self.abort) {
- self.abort()
- } else {
- self.onError(new RequestAbortedError())
- }
-}
+ this.blocking = blocking == null ? false : blocking
-function addSignal (self, signal) {
- self[kSignal] = null
- self[kListener] = null
+ this.reset = reset == null ? null : reset
- if (!signal) {
- return
- }
+ this.host = null
- if (signal.aborted) {
- abort(self)
- return
- }
+ this.contentLength = null
- self[kSignal] = signal
- self[kListener] = () => {
- abort(self)
- }
+ this.contentType = null
- addAbortListener(self[kSignal], self[kListener])
-}
+ this.headers = ''
-function removeSignal (self) {
- if (!self[kSignal]) {
- return
- }
+ // Only for H2
+ this.expectContinue = expectContinue != null ? expectContinue : false
- if ('removeEventListener' in self[kSignal]) {
- self[kSignal].removeEventListener('abort', self[kListener])
- } else {
- self[kSignal].removeListener('abort', self[kListener])
- }
+ 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') {
+ const keys = Object.keys(headers)
+ for (let i = 0; i < keys.length; i++) {
+ const key = keys[i]
+ processHeader(this, key, headers[key])
+ }
+ } else if (headers != null) {
+ throw new InvalidArgumentError('headers must be an object or an array')
+ }
- self[kSignal] = null
- self[kListener] = null
-}
+ if (util.isFormDataLike(this.body)) {
+ if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) {
+ throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.')
+ }
-module.exports = {
- addSignal,
- removeSignal
-}
+ if (!extractBody) {
+ extractBody = (__nccwpck_require__(8923).extractBody)
+ }
+ const [bodyStream, contentType] = extractBody(body)
+ if (this.contentType == null) {
+ this.contentType = contentType
+ this.headers += `content-type: ${contentType}\r\n`
+ }
+ this.body = bodyStream.stream
+ this.contentLength = bodyStream.length
+ } else if (util.isBlobLike(body) && this.contentType == null && body.type) {
+ this.contentType = body.type
+ this.headers += `content-type: ${body.type}\r\n`
+ }
-/***/ }),
+ util.validateHandler(handler, method, upgrade)
-/***/ 4660:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ this.servername = util.getServerName(this.host)
-"use strict";
+ this[kHandler] = handler
+ if (channels.create.hasSubscribers) {
+ channels.create.publish({ request: this })
+ }
+ }
-const { AsyncResource } = __nccwpck_require__(290)
-const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8707)
-const util = __nccwpck_require__(3440)
-const { addSignal, removeSignal } = __nccwpck_require__(158)
+ onBodySent (chunk) {
+ if (this[kHandler].onBodySent) {
+ try {
+ return this[kHandler].onBodySent(chunk)
+ } catch (err) {
+ this.abort(err)
+ }
+ }
+ }
-class ConnectHandler extends AsyncResource {
- constructor (opts, callback) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
+ onRequestSent () {
+ if (channels.bodySent.hasSubscribers) {
+ channels.bodySent.publish({ request: this })
}
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
+ if (this[kHandler].onRequestSent) {
+ try {
+ return this[kHandler].onRequestSent()
+ } catch (err) {
+ this.abort(err)
+ }
}
+ }
- const { signal, opaque, responseHeaders } = opts
+ onConnect (abort) {
+ assert(!this.aborted)
+ assert(!this.completed)
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ if (this.error) {
+ abort(this.error)
+ } else {
+ this.abort = abort
+ return this[kHandler].onConnect(abort)
}
+ }
- super('UNDICI_CONNECT')
+ onHeaders (statusCode, headers, resume, statusText) {
+ assert(!this.aborted)
+ assert(!this.completed)
- this.opaque = opaque || null
- this.responseHeaders = responseHeaders || null
- this.callback = callback
- this.abort = null
+ if (channels.headers.hasSubscribers) {
+ channels.headers.publish({ request: this, response: { statusCode, headers, statusText } })
+ }
- addSignal(this, signal)
+ try {
+ return this[kHandler].onHeaders(statusCode, headers, resume, statusText)
+ } catch (err) {
+ this.abort(err)
+ }
}
- onConnect (abort, context) {
- if (!this.callback) {
- throw new RequestAbortedError()
- }
+ onData (chunk) {
+ assert(!this.aborted)
+ assert(!this.completed)
- this.abort = abort
- this.context = context
+ try {
+ return this[kHandler].onData(chunk)
+ } catch (err) {
+ this.abort(err)
+ return false
+ }
}
- onHeaders () {
- throw new SocketError('bad connect', null)
- }
+ onUpgrade (statusCode, headers, socket) {
+ assert(!this.aborted)
+ assert(!this.completed)
- onUpgrade (statusCode, rawHeaders, socket) {
- const { callback, opaque, context } = this
+ return this[kHandler].onUpgrade(statusCode, headers, socket)
+ }
- removeSignal(this)
+ onComplete (trailers) {
+ this.onFinally()
- this.callback = null
+ assert(!this.aborted)
- let headers = rawHeaders
- // Indicates is an HTTP2Session
- if (headers != null) {
- headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ this.completed = true
+ if (channels.trailers.hasSubscribers) {
+ channels.trailers.publish({ request: this, trailers })
}
- this.runInAsyncScope(callback, null, null, {
- statusCode,
- headers,
- socket,
- opaque,
- context
- })
+ try {
+ return this[kHandler].onComplete(trailers)
+ } catch (err) {
+ // TODO (fix): This might be a bad idea?
+ this.onError(err)
+ }
}
- onError (err) {
- const { callback, opaque } = this
+ onError (error) {
+ this.onFinally()
- removeSignal(this)
+ if (channels.error.hasSubscribers) {
+ channels.error.publish({ request: this, error })
+ }
- if (callback) {
- this.callback = null
- queueMicrotask(() => {
- this.runInAsyncScope(callback, null, err, { opaque })
- })
+ if (this.aborted) {
+ return
}
- }
-}
+ this.aborted = true
-function connect (opts, callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- connect.call(this, opts, (err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
+ return this[kHandler].onError(error)
}
- try {
- const connectHandler = new ConnectHandler(opts, callback)
- this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler)
- } catch (err) {
- if (typeof callback !== 'function') {
- throw err
+ onFinally () {
+ if (this.errorHandler) {
+ this.body.off('error', this.errorHandler)
+ this.errorHandler = null
}
- const opaque = opts && opts.opaque
- queueMicrotask(() => callback(err, { opaque }))
- }
-}
-module.exports = connect
+ if (this.endHandler) {
+ this.body.off('end', this.endHandler)
+ this.endHandler = null
+ }
+ }
+ // TODO: adjust to support H2
+ addHeader (key, value) {
+ processHeader(this, key, value)
+ return this
+ }
-/***/ }),
+ static [kHTTP1BuildRequest] (origin, opts, handler) {
+ // TODO: Migrate header parsing here, to make Requests
+ // HTTP agnostic
+ return new Request(origin, opts, handler)
+ }
-/***/ 6862:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ static [kHTTP2BuildRequest] (origin, opts, handler) {
+ const headers = opts.headers
+ opts = { ...opts, headers: null }
-"use strict";
+ const request = new Request(origin, opts, handler)
+ request.headers = {}
-const {
- Readable,
- Duplex,
- PassThrough
-} = __nccwpck_require__(2203)
-const {
- InvalidArgumentError,
- InvalidReturnValueError,
- RequestAbortedError
-} = __nccwpck_require__(8707)
-const util = __nccwpck_require__(3440)
-const { AsyncResource } = __nccwpck_require__(290)
-const { addSignal, removeSignal } = __nccwpck_require__(158)
-const assert = __nccwpck_require__(2613)
+ 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(request, headers[i], headers[i + 1], true)
+ }
+ } else if (headers && typeof headers === 'object') {
+ const keys = Object.keys(headers)
+ for (let i = 0; i < keys.length; i++) {
+ const key = keys[i]
+ processHeader(request, key, headers[key], true)
+ }
+ } else if (headers != null) {
+ throw new InvalidArgumentError('headers must be an object or an array')
+ }
-const kResume = Symbol('resume')
+ return request
+ }
-class PipelineRequest extends Readable {
- constructor () {
- super({ autoDestroy: true })
+ static [kHTTP2CopyHeaders] (raw) {
+ const rawHeaders = raw.split('\r\n')
+ const headers = {}
- this[kResume] = null
- }
+ for (const header of rawHeaders) {
+ const [key, value] = header.split(': ')
- _read () {
- const { [kResume]: resume } = this
+ if (value == null || value.length === 0) continue
- if (resume) {
- this[kResume] = null
- resume()
+ if (headers[key]) headers[key] += `,${value}`
+ else headers[key] = value
}
- }
-
- _destroy (err, callback) {
- this._read()
- callback(err)
+ return headers
}
}
-class PipelineResponse extends Readable {
- constructor (resume) {
- super({ autoDestroy: true })
- this[kResume] = resume
+function processHeaderValue (key, val, skipAppend) {
+ if (val && typeof val === 'object') {
+ throw new InvalidArgumentError(`invalid ${key} header`)
}
- _read () {
- this[kResume]()
+ val = val != null ? `${val}` : ''
+
+ if (headerCharRegex.exec(val) !== null) {
+ throw new InvalidArgumentError(`invalid ${key} header`)
}
- _destroy (err, callback) {
- if (!err && !this._readableState.endEmitted) {
- err = new RequestAbortedError()
- }
+ return skipAppend ? val : `${key}: ${val}\r\n`
+}
- callback(err)
+function processHeader (request, key, val, skipAppend = false) {
+ if (val && (typeof val === 'object' && !Array.isArray(val))) {
+ throw new InvalidArgumentError(`invalid ${key} header`)
+ } else if (val === undefined) {
+ return
}
-}
-class PipelineHandler extends AsyncResource {
- constructor (opts, handler) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
+ if (
+ request.host === null &&
+ key.length === 4 &&
+ key.toLowerCase() === 'host'
+ ) {
+ if (headerCharRegex.exec(val) !== null) {
+ throw new InvalidArgumentError(`invalid ${key} header`)
}
-
- if (typeof handler !== 'function') {
- throw new InvalidArgumentError('invalid handler')
+ // Consumed by Client
+ request.host = val
+ } else if (
+ request.contentLength === null &&
+ key.length === 14 &&
+ key.toLowerCase() === 'content-length'
+ ) {
+ request.contentLength = parseInt(val, 10)
+ if (!Number.isFinite(request.contentLength)) {
+ throw new InvalidArgumentError('invalid content-length header')
+ }
+ } else if (
+ request.contentType === null &&
+ key.length === 12 &&
+ key.toLowerCase() === 'content-type'
+ ) {
+ request.contentType = val
+ if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)
+ else request.headers += processHeaderValue(key, val)
+ } else if (
+ key.length === 17 &&
+ key.toLowerCase() === 'transfer-encoding'
+ ) {
+ throw new InvalidArgumentError('invalid transfer-encoding header')
+ } else if (
+ key.length === 10 &&
+ key.toLowerCase() === 'connection'
+ ) {
+ const value = typeof val === 'string' ? val.toLowerCase() : null
+ if (value !== 'close' && value !== 'keep-alive') {
+ throw new InvalidArgumentError('invalid connection header')
+ } else if (value === 'close') {
+ request.reset = true
+ }
+ } else if (
+ key.length === 10 &&
+ key.toLowerCase() === 'keep-alive'
+ ) {
+ throw new InvalidArgumentError('invalid keep-alive header')
+ } else if (
+ key.length === 7 &&
+ key.toLowerCase() === 'upgrade'
+ ) {
+ throw new InvalidArgumentError('invalid upgrade header')
+ } else if (
+ key.length === 6 &&
+ key.toLowerCase() === 'expect'
+ ) {
+ throw new NotSupportedError('expect header not supported')
+ } else if (tokenRegExp.exec(key) === null) {
+ throw new InvalidArgumentError('invalid header key')
+ } else {
+ if (Array.isArray(val)) {
+ for (let i = 0; i < val.length; i++) {
+ if (skipAppend) {
+ if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}`
+ else request.headers[key] = processHeaderValue(key, val[i], skipAppend)
+ } else {
+ request.headers += processHeaderValue(key, val[i])
+ }
+ }
+ } else {
+ if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)
+ else request.headers += processHeaderValue(key, val)
}
+ }
+}
- const { signal, method, opaque, onInfo, responseHeaders } = opts
+module.exports = Request
- 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')
- }
+/***/ 36443:
+/***/ ((module) => {
- super('UNDICI_PIPELINE')
+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'),
+ kHeadersList: Symbol('headers list'),
+ 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'),
+ 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'),
+ 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'),
+ kInterceptors: Symbol('dispatch interceptors'),
+ kMaxResponseSize: Symbol('max response size'),
+ kHTTP2Session: Symbol('http2Session'),
+ kHTTP2SessionState: Symbol('http2Session state'),
+ kHTTP2BuildRequest: Symbol('http2 build request'),
+ kHTTP1BuildRequest: Symbol('http1 build request'),
+ kHTTP2CopyHeaders: Symbol('http2 copy headers'),
+ kHTTPConnVersion: Symbol('http connection version'),
+ kRetryHandlerDefaultRetry: Symbol('retry agent default retry'),
+ kConstruct: Symbol('constructable')
+}
- 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', util.nop)
+/***/ }),
- this.ret = new Duplex({
- readableObjectMode: opts.objectMode,
- autoDestroy: true,
- read: () => {
- const { body } = this
+/***/ 3440:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (body && body.resume) {
- body.resume()
- }
- },
- write: (chunk, encoding, callback) => {
- const { req } = this
+"use strict";
- 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()
- }
+const assert = __nccwpck_require__(42613)
+const { kDestroyed, kBodyUsed } = __nccwpck_require__(36443)
+const { IncomingMessage } = __nccwpck_require__(58611)
+const stream = __nccwpck_require__(2203)
+const net = __nccwpck_require__(69278)
+const { InvalidArgumentError } = __nccwpck_require__(68707)
+const { Blob } = __nccwpck_require__(20181)
+const nodeUtil = __nccwpck_require__(39023)
+const { stringify } = __nccwpck_require__(83480)
+const { headerNameLowerCasedRecord } = __nccwpck_require__(10735)
- if (abort && err) {
- abort()
- }
+const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v))
- util.destroy(body, err)
- util.destroy(req, err)
- util.destroy(res, err)
+function nop () {}
- removeSignal(this)
+function isStream (obj) {
+ return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function'
+}
- callback(err)
- }
- }).on('prefinish', () => {
- const { req } = this
+// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License)
+function isBlobLike (object) {
+ return (Blob && object instanceof Blob) || (
+ object &&
+ typeof object === 'object' &&
+ (typeof object.stream === 'function' ||
+ typeof object.arrayBuffer === 'function') &&
+ /^(Blob|File)$/.test(object[Symbol.toStringTag])
+ )
+}
- // Node < 15 does not call _final in same tick.
- req.push(null)
- })
+function buildURL (url, queryParams) {
+ if (url.includes('?') || url.includes('#')) {
+ throw new Error('Query params cannot be passed when url already contains "?" or "#".')
+ }
- this.res = null
+ const stringified = stringify(queryParams)
- addSignal(this, signal)
+ if (stringified) {
+ url += '?' + stringified
}
- onConnect (abort, context) {
- const { ret, res } = this
+ return url
+}
- assert(!res, 'pipeline cannot be retried')
+function parseURL (url) {
+ if (typeof url === 'string') {
+ url = new URL(url)
- if (ret.destroyed) {
- throw new RequestAbortedError()
+ if (!/^https?:/.test(url.origin || url.protocol)) {
+ throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
}
- this.abort = abort
- this.context = context
+ return url
}
- 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
- }
+ if (!url || typeof url !== 'object') {
+ throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')
+ }
- this.res = new PipelineResponse(resume)
+ if (!/^https?:/.test(url.origin || url.protocol)) {
+ throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
+ }
- 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', util.nop)
- throw err
+ if (!(url instanceof URL)) {
+ if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) {
+ throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')
}
- if (!body || typeof body.on !== 'function') {
- throw new InvalidReturnValueError('expected Readable')
+ if (url.path != null && typeof url.path !== 'string') {
+ throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.')
}
- body
- .on('data', (chunk) => {
- const { ret, body } = this
+ if (url.pathname != null && typeof url.pathname !== 'string') {
+ throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.')
+ }
- if (!ret.push(chunk) && body.pause) {
- body.pause()
- }
- })
- .on('error', (err) => {
- const { ret } = this
+ if (url.hostname != null && typeof url.hostname !== 'string') {
+ throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.')
+ }
- util.destroy(ret, err)
- })
- .on('end', () => {
- const { ret } = this
+ if (url.origin != null && typeof url.origin !== 'string') {
+ throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.')
+ }
- ret.push(null)
- })
- .on('close', () => {
- const { ret } = this
+ 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 (!ret._readableState.ended) {
- util.destroy(ret, new RequestAbortedError())
- }
- })
+ if (origin.endsWith('/')) {
+ origin = origin.substring(0, origin.length - 1)
+ }
- this.body = body
+ if (path && !path.startsWith('/')) {
+ 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.
+ url = new URL(origin + path)
}
- onData (chunk) {
- const { res } = this
- return res.push(chunk)
- }
+ return url
+}
- onComplete (trailers) {
- const { res } = this
- res.push(null)
- }
+function parseOrigin (url) {
+ url = parseURL(url)
- onError (err) {
- const { ret } = this
- this.handler = null
- util.destroy(ret, err)
+ if (url.pathname !== '/' || url.search || url.hash) {
+ throw new InvalidArgumentError('invalid url')
}
-}
-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)
- }
+ return url
}
-module.exports = pipeline
-
-
-/***/ }),
-
-/***/ 4043:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+function getHostname (host) {
+ if (host[0] === '[') {
+ const idx = host.indexOf(']')
-"use strict";
+ assert(idx !== -1)
+ return host.substring(1, idx)
+ }
+ const idx = host.indexOf(':')
+ if (idx === -1) return host
-const Readable = __nccwpck_require__(9927)
-const {
- InvalidArgumentError,
- RequestAbortedError
-} = __nccwpck_require__(8707)
-const util = __nccwpck_require__(3440)
-const { getResolveErrorBodyCallback } = __nccwpck_require__(7655)
-const { AsyncResource } = __nccwpck_require__(290)
-const { addSignal, removeSignal } = __nccwpck_require__(158)
+ return host.substring(0, idx)
+}
-class RequestHandler extends AsyncResource {
- constructor (opts, callback) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
- }
+// IP addresses are not valid server names per RFC6066
+// > Currently, the only server names supported are DNS hostnames
+function getServerName (host) {
+ if (!host) {
+ return null
+ }
- const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts
+ assert.strictEqual(typeof host, 'string')
- try {
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
+ const servername = getHostname(host)
+ if (net.isIP(servername)) {
+ return ''
+ }
- if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) {
- throw new InvalidArgumentError('invalid highWaterMark')
- }
+ return servername
+}
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
- }
+function deepClone (obj) {
+ return JSON.parse(JSON.stringify(obj))
+}
- if (method === 'CONNECT') {
- throw new InvalidArgumentError('invalid method')
- }
+function isAsyncIterable (obj) {
+ return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function')
+}
- if (onInfo && typeof onInfo !== 'function') {
- throw new InvalidArgumentError('invalid onInfo callback')
- }
+function isIterable (obj) {
+ return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function'))
+}
- super('UNDICI_REQUEST')
- } catch (err) {
- if (util.isStream(body)) {
- util.destroy(body.on('error', util.nop), err)
- }
- throw err
- }
+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
+ }
- 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.throwOnError = throwOnError
- this.highWaterMark = highWaterMark
+ return null
+}
- if (util.isStream(body)) {
- body.on('error', (err) => {
- this.onError(err)
- })
- }
+function isDestroyed (stream) {
+ return !stream || !!(stream.destroyed || stream[kDestroyed])
+}
- addSignal(this, signal)
+function isReadableAborted (stream) {
+ const state = stream && stream._readableState
+ return isDestroyed(stream) && state && !state.endEmitted
+}
+
+function destroy (stream, err) {
+ if (stream == null || !isStream(stream) || isDestroyed(stream)) {
+ return
}
- onConnect (abort, context) {
- if (!this.callback) {
- throw new RequestAbortedError()
+ if (typeof stream.destroy === 'function') {
+ if (Object.getPrototypeOf(stream).constructor === IncomingMessage) {
+ // See: https://github.com/nodejs/node/pull/38505/files
+ stream.socket = null
}
- this.abort = abort
- this.context = context
+ stream.destroy(err)
+ } else if (err) {
+ process.nextTick((stream, err) => {
+ stream.emit('error', err)
+ }, stream, err)
}
- onHeaders (statusCode, rawHeaders, resume, statusMessage) {
- const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this
+ if (stream.destroyed !== true) {
+ stream[kDestroyed] = true
+ }
+}
- const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/
+function parseKeepAliveTimeout (val) {
+ const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR)
+ return m ? parseInt(m[1], 10) * 1000 : null
+}
- if (statusCode < 200) {
- if (this.onInfo) {
- this.onInfo({ statusCode, headers })
- }
- return
- }
+/**
+ * Retrieves a header name and returns its lowercase value.
+ * @param {string | Buffer} value Header name
+ * @returns {string}
+ */
+function headerNameToString (value) {
+ return headerNameLowerCasedRecord[value] || value.toLowerCase()
+}
- const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
- const contentType = parsedHeaders['content-type']
- const body = new Readable({ resume, abort, contentType, highWaterMark })
+function parseHeaders (headers, obj = {}) {
+ // For H2 support
+ if (!Array.isArray(headers)) return headers
- this.callback = null
- this.res = body
- if (callback !== null) {
- if (this.throwOnError && statusCode >= 400) {
- this.runInAsyncScope(getResolveErrorBodyCallback, null,
- { callback, body, contentType, statusCode, statusMessage, headers }
- )
+ for (let i = 0; i < headers.length; i += 2) {
+ const key = headers[i].toString().toLowerCase()
+ let val = obj[key]
+
+ if (!val) {
+ if (Array.isArray(headers[i + 1])) {
+ obj[key] = headers[i + 1].map(x => x.toString('utf8'))
} else {
- this.runInAsyncScope(callback, null, null, {
- statusCode,
- headers,
- trailers: this.trailers,
- opaque,
- body,
- context
- })
+ obj[key] = headers[i + 1].toString('utf8')
+ }
+ } else {
+ if (!Array.isArray(val)) {
+ val = [val]
+ obj[key] = val
}
+ val.push(headers[i + 1].toString('utf8'))
}
}
- onData (chunk) {
- const { res } = this
- return res.push(chunk)
+ // 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')
}
- onComplete (trailers) {
- const { res } = this
+ return obj
+}
- removeSignal(this)
+function parseRawHeaders (headers) {
+ const ret = []
+ let hasContentLength = false
+ let contentDispositionIdx = -1
- util.parseHeaders(trailers, this.trailers)
+ for (let n = 0; n < headers.length; n += 2) {
+ const key = headers[n + 0].toString()
+ const val = headers[n + 1].toString('utf8')
- res.push(null)
+ if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) {
+ ret.push(key, val)
+ hasContentLength = true
+ } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) {
+ contentDispositionIdx = ret.push(key, val) - 1
+ } else {
+ ret.push(key, val)
+ }
}
- onError (err) {
- const { res, callback, body, opaque } = this
-
- removeSignal(this)
-
- if (callback) {
- // TODO: Does this need queueMicrotask?
- this.callback = null
- queueMicrotask(() => {
- this.runInAsyncScope(callback, null, err, { opaque })
- })
- }
+ // See https://github.com/nodejs/node/pull/46528
+ if (hasContentLength && contentDispositionIdx !== -1) {
+ ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1')
+ }
- if (res) {
- this.res = null
- // Ensure all queued handlers are invoked before destroying res.
- queueMicrotask(() => {
- util.destroy(res, err)
- })
- }
+ return ret
+}
- if (body) {
- this.body = null
- util.destroy(body, err)
- }
- }
+function isBuffer (buffer) {
+ // See, https://github.com/mcollina/undici/pull/319
+ return buffer instanceof Uint8Array || Buffer.isBuffer(buffer)
}
-function request (opts, callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- request.call(this, opts, (err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
+function validateHandler (handler, method, upgrade) {
+ if (!handler || typeof handler !== 'object') {
+ throw new InvalidArgumentError('handler must be an object')
}
- try {
- this.dispatch(opts, new RequestHandler(opts, callback))
- } catch (err) {
- if (typeof callback !== 'function') {
- throw err
- }
- const opaque = opts && opts.opaque
- queueMicrotask(() => callback(err, { opaque }))
+ if (typeof handler.onConnect !== 'function') {
+ throw new InvalidArgumentError('invalid onConnect method')
}
-}
-module.exports = request
-module.exports.RequestHandler = RequestHandler
+ 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')
+ }
-/***/ 3560:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (typeof handler.onData !== 'function') {
+ throw new InvalidArgumentError('invalid onData method')
+ }
-"use strict";
+ 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.
+function isDisturbed (body) {
+ return !!(body && (
+ stream.isDisturbed
+ ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed?
+ : body[kBodyUsed] ||
+ body.readableDidRead ||
+ (body._readableState && body._readableState.dataEmitted) ||
+ isReadableAborted(body)
+ ))
+}
-const { finished, PassThrough } = __nccwpck_require__(2203)
-const {
- InvalidArgumentError,
- InvalidReturnValueError,
- RequestAbortedError
-} = __nccwpck_require__(8707)
-const util = __nccwpck_require__(3440)
-const { getResolveErrorBodyCallback } = __nccwpck_require__(7655)
-const { AsyncResource } = __nccwpck_require__(290)
-const { addSignal, removeSignal } = __nccwpck_require__(158)
+function isErrored (body) {
+ return !!(body && (
+ stream.isErrored
+ ? stream.isErrored(body)
+ : /state: 'errored'/.test(nodeUtil.inspect(body)
+ )))
+}
-class StreamHandler extends AsyncResource {
- constructor (opts, factory, callback) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
- }
+function isReadable (body) {
+ return !!(body && (
+ stream.isReadable
+ ? stream.isReadable(body)
+ : /state: 'readable'/.test(nodeUtil.inspect(body)
+ )))
+}
- const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts
+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
+ }
+}
- try {
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
+async function * convertIterableToBuffer (iterable) {
+ for await (const chunk of iterable) {
+ yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
+ }
+}
- if (typeof factory !== 'function') {
- throw new InvalidArgumentError('invalid factory')
- }
+let ReadableStream
+function ReadableStreamFrom (iterable) {
+ if (!ReadableStream) {
+ ReadableStream = (__nccwpck_require__(63774).ReadableStream)
+ }
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
- }
+ if (ReadableStream.from) {
+ return ReadableStream.from(convertIterableToBuffer(iterable))
+ }
- if (method === 'CONNECT') {
- throw new InvalidArgumentError('invalid method')
+ let iterator
+ return new ReadableStream(
+ {
+ async start () {
+ iterator = iterable[Symbol.asyncIterator]()
+ },
+ async pull (controller) {
+ const { done, value } = await iterator.next()
+ if (done) {
+ queueMicrotask(() => {
+ controller.close()
+ })
+ } else {
+ const buf = Buffer.isBuffer(value) ? value : Buffer.from(value)
+ controller.enqueue(new Uint8Array(buf))
+ }
+ return controller.desiredSize > 0
+ },
+ async cancel (reason) {
+ await iterator.return()
}
+ },
+ 0
+ )
+}
- if (onInfo && typeof onInfo !== 'function') {
- throw new InvalidArgumentError('invalid onInfo callback')
- }
+// The chunk should be a FormData instance and contains
+// all the required methods.
+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'
+ )
+}
- super('UNDICI_STREAM')
- } catch (err) {
- if (util.isStream(body)) {
- util.destroy(body.on('error', util.nop), err)
- }
+function throwIfAborted (signal) {
+ if (!signal) { return }
+ if (typeof signal.throwIfAborted === 'function') {
+ signal.throwIfAborted()
+ } else {
+ if (signal.aborted) {
+ // DOMException not available < v17.0.0
+ const err = new Error('The operation was aborted')
+ err.name = 'AbortError'
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
- this.throwOnError = throwOnError || false
-
- if (util.isStream(body)) {
- body.on('error', (err) => {
- this.onError(err)
- })
- }
-
- addSignal(this, signal)
}
+}
- onConnect (abort, context) {
- if (!this.callback) {
- throw new RequestAbortedError()
- }
-
- this.abort = abort
- this.context = context
+function addAbortListener (signal, listener) {
+ if ('addEventListener' in signal) {
+ signal.addEventListener('abort', listener, { once: true })
+ return () => signal.removeEventListener('abort', listener)
}
+ signal.addListener('abort', listener)
+ return () => signal.removeListener('abort', listener)
+}
- onHeaders (statusCode, rawHeaders, resume, statusMessage) {
- const { factory, opaque, context, callback, responseHeaders } = this
-
- const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
-
- if (statusCode < 200) {
- if (this.onInfo) {
- this.onInfo({ statusCode, headers })
- }
- return
- }
+const hasToWellFormed = !!String.prototype.toWellFormed
- this.factory = null
+/**
+ * @param {string} val
+ */
+function toUSVString (val) {
+ if (hasToWellFormed) {
+ return `${val}`.toWellFormed()
+ } else if (nodeUtil.toUSVString) {
+ return nodeUtil.toUSVString(val)
+ }
- let res
+ return `${val}`
+}
- if (this.throwOnError && statusCode >= 400) {
- const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
- const contentType = parsedHeaders['content-type']
- res = new PassThrough()
+// Parsed accordingly to RFC 9110
+// https://www.rfc-editor.org/rfc/rfc9110#field.content-range
+function parseRangeHeader (range) {
+ if (range == null || range === '') return { start: 0, end: null, size: null }
- this.callback = null
- this.runInAsyncScope(getResolveErrorBodyCallback, null,
- { callback, body: res, contentType, statusCode, statusMessage, headers }
- )
- } else {
- if (factory === null) {
- return
+ const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null
+ return m
+ ? {
+ start: parseInt(m[1]),
+ end: m[2] ? parseInt(m[2]) : null,
+ size: m[3] ? parseInt(m[3]) : null
}
+ : null
+}
- 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')
- }
+const kEnumerableProperty = Object.create(null)
+kEnumerableProperty.enumerable = true
- // TODO: Avoid finished. It registers an unnecessary amount of listeners.
- finished(res, { readable: false }, (err) => {
- const { callback, res, opaque, trailers, abort } = this
+module.exports = {
+ kEnumerableProperty,
+ nop,
+ isDisturbed,
+ isErrored,
+ isReadable,
+ toUSVString,
+ isReadableAborted,
+ isBlobLike,
+ parseOrigin,
+ parseURL,
+ getServerName,
+ isStream,
+ isIterable,
+ isAsyncIterable,
+ isDestroyed,
+ headerNameToString,
+ parseRawHeaders,
+ parseHeaders,
+ parseKeepAliveTimeout,
+ destroy,
+ bodyLength,
+ deepClone,
+ ReadableStreamFrom,
+ isBuffer,
+ validateHandler,
+ getSocketInfo,
+ isFormDataLike,
+ buildURL,
+ throwIfAborted,
+ addAbortListener,
+ parseRangeHeader,
+ nodeMajor,
+ nodeMinor,
+ nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13),
+ safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE']
+}
- 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()
- }
- })
- }
+/***/ 50001:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- res.on('drain', resume)
+"use strict";
- this.res = res
- const needDrain = res.writableNeedDrain !== undefined
- ? res.writableNeedDrain
- : res._writableState && res._writableState.needDrain
+const Dispatcher = __nccwpck_require__(28611)
+const {
+ ClientDestroyedError,
+ ClientClosedError,
+ InvalidArgumentError
+} = __nccwpck_require__(68707)
+const { kDestroy, kClose, kDispatch, kInterceptors } = __nccwpck_require__(36443)
- return needDrain !== true
- }
+const kDestroyed = Symbol('destroyed')
+const kClosed = Symbol('closed')
+const kOnDestroyed = Symbol('onDestroyed')
+const kOnClosed = Symbol('onClosed')
+const kInterceptedDispatch = Symbol('Intercepted Dispatch')
- onData (chunk) {
- const { res } = this
+class DispatcherBase extends Dispatcher {
+ constructor () {
+ super()
- return res ? res.write(chunk) : true
+ this[kDestroyed] = false
+ this[kOnDestroyed] = null
+ this[kClosed] = false
+ this[kOnClosed] = []
}
- onComplete (trailers) {
- const { res } = this
-
- removeSignal(this)
-
- if (!res) {
- return
- }
-
- this.trailers = util.parseHeaders(trailers)
-
- res.end()
+ get destroyed () {
+ return this[kDestroyed]
}
- onError (err) {
- const { res, callback, opaque, body } = this
-
- removeSignal(this)
+ get closed () {
+ return this[kClosed]
+ }
- this.factory = null
+ get interceptors () {
+ return this[kInterceptors]
+ }
- if (res) {
- this.res = null
- util.destroy(res, err)
- } else if (callback) {
- this.callback = null
- queueMicrotask(() => {
- this.runInAsyncScope(callback, null, err, { opaque })
- })
+ set interceptors (newInterceptors) {
+ if (newInterceptors) {
+ for (let i = newInterceptors.length - 1; i >= 0; i--) {
+ const interceptor = this[kInterceptors][i]
+ if (typeof interceptor !== 'function') {
+ throw new InvalidArgumentError('interceptor must be an function')
+ }
+ }
}
- if (body) {
- this.body = null
- util.destroy(body, err)
- }
+ this[kInterceptors] = newInterceptors
}
-}
-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)
+ close (callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ this.close((err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
})
- })
- }
+ }
- try {
- this.dispatch(opts, new StreamHandler(opts, factory, callback))
- } catch (err) {
if (typeof callback !== 'function') {
- throw err
+ throw new InvalidArgumentError('invalid callback')
}
- const opaque = opts && opts.opaque
- queueMicrotask(() => callback(err, { opaque }))
- }
-}
-
-module.exports = stream
+ 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
+ }
-/***/ 1882:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ this[kClosed] = true
+ this[kOnClosed].push(callback)
-"use strict";
+ 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)
+ })
+ }
-const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8707)
-const { AsyncResource } = __nccwpck_require__(290)
-const util = __nccwpck_require__(3440)
-const { addSignal, removeSignal } = __nccwpck_require__(158)
-const assert = __nccwpck_require__(2613)
+ destroy (err, callback) {
+ if (typeof err === 'function') {
+ callback = err
+ err = null
+ }
-class UpgradeHandler extends AsyncResource {
- constructor (opts, callback) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
+ 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')
}
- const { signal, opaque, responseHeaders } = opts
+ if (this[kDestroyed]) {
+ if (this[kOnDestroyed]) {
+ this[kOnDestroyed].push(callback)
+ } else {
+ queueMicrotask(() => callback(null, null))
+ }
+ return
+ }
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ if (!err) {
+ err = new ClientDestroyedError()
}
- super('UNDICI_UPGRADE')
+ this[kDestroyed] = true
+ this[kOnDestroyed] = this[kOnDestroyed] || []
+ this[kOnDestroyed].push(callback)
- this.responseHeaders = responseHeaders || null
- this.opaque = opaque || null
- this.callback = callback
- this.abort = null
- this.context = null
+ const onDestroyed = () => {
+ const callbacks = this[kOnDestroyed]
+ this[kOnDestroyed] = null
+ for (let i = 0; i < callbacks.length; i++) {
+ callbacks[i](null, null)
+ }
+ }
- addSignal(this, signal)
+ // Should not error.
+ this[kDestroy](err).then(() => {
+ queueMicrotask(onDestroyed)
+ })
}
- onConnect (abort, context) {
- if (!this.callback) {
- throw new RequestAbortedError()
+ [kInterceptedDispatch] (opts, handler) {
+ if (!this[kInterceptors] || this[kInterceptors].length === 0) {
+ this[kInterceptedDispatch] = this[kDispatch]
+ return this[kDispatch](opts, handler)
}
- this.abort = abort
- this.context = null
- }
-
- onHeaders () {
- throw new SocketError('bad upgrade', null)
+ let dispatch = this[kDispatch].bind(this)
+ for (let i = this[kInterceptors].length - 1; i >= 0; i--) {
+ dispatch = this[kInterceptors][i](dispatch)
+ }
+ this[kInterceptedDispatch] = dispatch
+ return dispatch(opts, handler)
}
- onUpgrade (statusCode, rawHeaders, socket) {
- const { callback, opaque, context } = this
-
- assert.strictEqual(statusCode, 101)
-
- removeSignal(this)
+ dispatch (opts, handler) {
+ if (!handler || typeof handler !== 'object') {
+ throw new InvalidArgumentError('handler must be an object')
+ }
- this.callback = null
- const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
- this.runInAsyncScope(callback, null, null, {
- headers,
- socket,
- opaque,
- context
- })
- }
+ try {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('opts must be an object.')
+ }
- onError (err) {
- const { callback, opaque } = this
+ if (this[kDestroyed] || this[kOnDestroyed]) {
+ throw new ClientDestroyedError()
+ }
- removeSignal(this)
+ if (this[kClosed]) {
+ throw new ClientClosedError()
+ }
- if (callback) {
- this.callback = null
- queueMicrotask(() => {
- this.runInAsyncScope(callback, null, err, { opaque })
- })
- }
- }
-}
+ return this[kInterceptedDispatch](opts, handler)
+ } catch (err) {
+ if (typeof handler.onError !== 'function') {
+ throw new InvalidArgumentError('invalid onError method')
+ }
-function upgrade (opts, callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- upgrade.call(this, opts, (err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
- }
+ handler.onError(err)
- try {
- const upgradeHandler = new UpgradeHandler(opts, callback)
- this.dispatch({
- ...opts,
- method: opts.method || 'GET',
- upgrade: opts.protocol || 'Websocket'
- }, upgradeHandler)
- } catch (err) {
- if (typeof callback !== 'function') {
- throw err
+ return false
}
- const opaque = opts && opts.opaque
- queueMicrotask(() => callback(err, { opaque }))
}
}
-module.exports = upgrade
+module.exports = DispatcherBase
/***/ }),
-/***/ 6615:
+/***/ 28611:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-module.exports.request = __nccwpck_require__(4043)
-module.exports.stream = __nccwpck_require__(3560)
-module.exports.pipeline = __nccwpck_require__(6862)
-module.exports.upgrade = __nccwpck_require__(1882)
-module.exports.connect = __nccwpck_require__(4660)
+const EventEmitter = __nccwpck_require__(24434)
+
+class Dispatcher extends EventEmitter {
+ dispatch () {
+ throw new Error('not implemented')
+ }
+
+ close () {
+ throw new Error('not implemented')
+ }
+
+ destroy () {
+ throw new Error('not implemented')
+ }
+}
+
+module.exports = Dispatcher
/***/ }),
-/***/ 9927:
+/***/ 8923:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-// Ported from https://github.com/nodejs/undici/pull/907
-
-const assert = __nccwpck_require__(2613)
-const { Readable } = __nccwpck_require__(2203)
-const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = __nccwpck_require__(8707)
+const Busboy = __nccwpck_require__(89581)
const util = __nccwpck_require__(3440)
-const { ReadableStreamFrom, toUSVString } = __nccwpck_require__(3440)
-
-let Blob
-
-const kConsume = Symbol('kConsume')
-const kReading = Symbol('kReading')
-const kBody = Symbol('kBody')
-const kAbort = Symbol('abort')
-const kContentType = Symbol('kContentType')
-
-const noop = () => {}
+const {
+ ReadableStreamFrom,
+ isBlobLike,
+ isReadableStreamLike,
+ readableStreamClose,
+ createDeferredPromise,
+ fullyReadBody
+} = __nccwpck_require__(15523)
+const { FormData } = __nccwpck_require__(43073)
+const { kState } = __nccwpck_require__(89710)
+const { webidl } = __nccwpck_require__(74222)
+const { DOMException, structuredClone } = __nccwpck_require__(87326)
+const { Blob, File: NativeFile } = __nccwpck_require__(20181)
+const { kBodyUsed } = __nccwpck_require__(36443)
+const assert = __nccwpck_require__(42613)
+const { isErrored } = __nccwpck_require__(3440)
+const { isUint8Array, isArrayBuffer } = __nccwpck_require__(98253)
+const { File: UndiciFile } = __nccwpck_require__(63041)
+const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(94322)
-module.exports = class BodyReadable extends Readable {
- constructor ({
- resume,
- abort,
- contentType = '',
- highWaterMark = 64 * 1024 // Same as nodejs fs streams.
- }) {
- super({
- autoDestroy: true,
- read: resume,
- highWaterMark
- })
+let random
+try {
+ const crypto = __nccwpck_require__(77598)
+ random = (max) => crypto.randomInt(0, max)
+} catch {
+ random = (max) => Math.floor(Math.random(max))
+}
- this._readableState.dataEmitted = false
+let ReadableStream = globalThis.ReadableStream
- this[kAbort] = abort
- this[kConsume] = null
- this[kBody] = null
- this[kContentType] = contentType
+/** @type {globalThis['File']} */
+const File = NativeFile ?? UndiciFile
+const textEncoder = new TextEncoder()
+const textDecoder = new TextDecoder()
- // 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
+// https://fetch.spec.whatwg.org/#concept-bodyinit-extract
+function extractBody (object, keepalive = false) {
+ if (!ReadableStream) {
+ ReadableStream = (__nccwpck_require__(63774).ReadableStream)
}
- destroy (err) {
- if (this.destroyed) {
- // Node < 16
- return this
- }
-
- if (!err && !this._readableState.endEmitted) {
- err = new RequestAbortedError()
- }
-
- if (err) {
- this[kAbort]()
- }
+ // 1. Let stream be null.
+ let stream = null
- return super.destroy(err)
+ // 2. If object is a ReadableStream object, then set stream to object.
+ if (object instanceof ReadableStream) {
+ stream = object
+ } else if (isBlobLike(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.
+ stream = new ReadableStream({
+ async pull (controller) {
+ controller.enqueue(
+ typeof source === 'string' ? textEncoder.encode(source) : source
+ )
+ queueMicrotask(() => readableStreamClose(controller))
+ },
+ start () {},
+ type: undefined
+ })
}
- emit (ev, ...args) {
- if (ev === 'data') {
- // Node < 16.7
- this._readableState.dataEmitted = true
- } else if (ev === 'error') {
- // Node < 16
- this._readableState.errorEmitted = true
- }
- return super.emit(ev, ...args)
- }
+ // 5. Assert: stream is a ReadableStream object.
+ assert(isReadableStreamLike(stream))
- on (ev, ...args) {
- if (ev === 'data' || ev === 'readable') {
- this[kReading] = true
- }
- return super.on(ev, ...args)
- }
+ // 6. Let action be null.
+ let action = null
- addListener (ev, ...args) {
- return this.on(ev, ...args)
- }
+ // 7. Let source be null.
+ let source = null
- off (ev, ...args) {
- const ret = super.off(ev, ...args)
- if (ev === 'data' || ev === 'readable') {
- this[kReading] = (
- this.listenerCount('data') > 0 ||
- this.listenerCount('readable') > 0
- )
- }
- return ret
- }
+ // 8. Let length be null.
+ let length = null
- removeListener (ev, ...args) {
- return this.off(ev, ...args)
- }
+ // 9. Let type be null.
+ let type = null
- push (chunk) {
- if (this[kConsume] && chunk !== null && this.readableLength === 0) {
- consumePush(this[kConsume], chunk)
- return this[kReading] ? super.push(chunk) : true
- }
- return super.push(chunk)
- }
+ // 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
- // https://fetch.spec.whatwg.org/#dom-body-text
- async text () {
- return consume(this, 'text')
- }
+ // Set type to `text/plain;charset=UTF-8`.
+ type = 'text/plain;charset=UTF-8'
+ } else if (object instanceof URLSearchParams) {
+ // URLSearchParams
- // https://fetch.spec.whatwg.org/#dom-body-json
- async json () {
- return consume(this, 'json')
- }
+ // 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
- // https://fetch.spec.whatwg.org/#dom-body-blob
- async blob () {
- return consume(this, 'blob')
- }
+ // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list.
+ source = object.toString()
- // https://fetch.spec.whatwg.org/#dom-body-arraybuffer
- async arrayBuffer () {
- return consume(this, 'arrayBuffer')
- }
+ // 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
- // https://fetch.spec.whatwg.org/#dom-body-formdata
- async formData () {
- // TODO: Implement.
- throw new NotSupportedError()
- }
+ // Set source to a copy of the bytes held by object.
+ source = new Uint8Array(object.slice())
+ } else if (ArrayBuffer.isView(object)) {
+ // BufferSource/ArrayBufferView
- // https://fetch.spec.whatwg.org/#dom-body-bodyused
- get bodyUsed () {
- return util.isDisturbed(this)
- }
+ // 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 (util.isFormDataLike(object)) {
+ const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}`
+ const prefix = `--${boundary}\r\nContent-Disposition: form-data`
- // https://fetch.spec.whatwg.org/#dom-body-body
- 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]
- }
+ /*! 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')
- dump (opts) {
- let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144
- const signal = opts && opts.signal
+ // 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.
- if (signal) {
- try {
- if (typeof signal !== 'object' || !('aborted' in signal)) {
- throw new InvalidArgumentError('signal must be an AbortSignal')
+ 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
}
- util.throwIfAborted(signal)
- } catch (err) {
- return Promise.reject(err)
}
}
- if (this.closed) {
- return Promise.resolve(null)
+ const chunk = textEncoder.encode(`--${boundary}--`)
+ blobParts.push(chunk)
+ length += chunk.byteLength
+ if (hasUnknownSizeValue) {
+ length = null
}
- return new Promise((resolve, reject) => {
- const signalListenerCleanup = signal
- ? util.addAbortListener(signal, () => {
- this.destroy()
- })
- : noop
-
- this
- .on('close', function () {
- signalListenerCleanup()
- if (signal && signal.aborted) {
- reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }))
- } else {
- resolve(null)
- }
- })
- .on('error', noop)
- .on('data', function (chunk) {
- limit -= chunk.length
- if (limit <= 0) {
- this.destroy()
- }
- })
- .resume()
- })
- }
-}
+ // Set source to object.
+ source = object
-// https://streams.spec.whatwg.org/#readablestream-locked
-function isLocked (self) {
- // Consume is an implicit lock.
- return (self[kBody] && self[kBody].locked === true) || self[kConsume]
-}
+ action = async function * () {
+ for (const part of blobParts) {
+ if (part.stream) {
+ yield * part.stream()
+ } else {
+ yield part
+ }
+ }
+ }
-// https://fetch.spec.whatwg.org/#body-unusable
-function isUnusable (self) {
- return util.isDisturbed(self) || isLocked(self)
-}
+ // 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 (isBlobLike(object)) {
+ // Blob
-async function consume (stream, type) {
- if (isUnusable(stream)) {
- throw new TypeError('unusable')
- }
+ // Set source to object.
+ source = object
- assert(!stream[kConsume])
+ // Set length to object’s size.
+ length = object.size
- return new Promise((resolve, reject) => {
- stream[kConsume] = {
- type,
- stream,
- resolve,
- reject,
- length: 0,
- body: []
+ // 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')
}
- stream
- .on('error', function (err) {
- consumeFinish(this[kConsume], err)
- })
- .on('close', function () {
- if (this[kConsume].body !== null) {
- consumeFinish(this[kConsume], new RequestAbortedError())
- }
- })
-
- process.nextTick(consumeStart, stream[kConsume])
- })
-}
+ // 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'
+ )
+ }
-function consumeStart (consume) {
- if (consume.body === null) {
- return
+ stream =
+ object instanceof ReadableStream ? object : ReadableStreamFrom(object)
}
- const { _readableState: state } = consume.stream
-
- for (const chunk of state.buffer) {
- consumePush(consume, chunk)
+ // 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)
}
- if (state.endEmitted) {
- consumeEnd(this[kConsume])
- } else {
- consume.stream.on('end', function () {
- consumeEnd(this[kConsume])
+ // 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()
+ })
+ } 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)) {
+ controller.enqueue(new Uint8Array(value))
+ }
+ }
+ return controller.desiredSize > 0
+ },
+ async cancel (reason) {
+ await iterator.return()
+ },
+ type: undefined
})
}
- consume.stream.resume()
+ // 13. Let body be a body whose stream is stream, source is source,
+ // and length is length.
+ const body = { stream, source, length }
- while (consume.stream.read() != null) {
- // Loop
- }
+ // 14. Return (body, type).
+ return [body, type]
}
-function consumeEnd (consume) {
- const { type, body, resolve, stream, length } = consume
-
- try {
- if (type === 'text') {
- resolve(toUSVString(Buffer.concat(body)))
- } else if (type === 'json') {
- resolve(JSON.parse(Buffer.concat(body)))
- } else if (type === 'arrayBuffer') {
- const dst = new Uint8Array(length)
-
- let pos = 0
- for (const buf of body) {
- dst.set(buf, pos)
- pos += buf.byteLength
- }
+// https://fetch.spec.whatwg.org/#bodyinit-safely-extract
+function safelyExtractBody (object, keepalive = false) {
+ if (!ReadableStream) {
+ // istanbul ignore next
+ ReadableStream = (__nccwpck_require__(63774).ReadableStream)
+ }
- resolve(dst.buffer)
- } else if (type === 'blob') {
- if (!Blob) {
- Blob = (__nccwpck_require__(181).Blob)
- }
- resolve(new Blob(body, { type: stream[kContentType] }))
- }
+ // To safely extract a body and a `Content-Type` value from
+ // a byte sequence or BodyInit object object, run these steps:
- consumeFinish(consume)
- } catch (err) {
- stream.destroy(err)
+ // 1. If object is a ReadableStream object, then:
+ if (object instanceof ReadableStream) {
+ // Assert: object is neither disturbed nor locked.
+ // istanbul ignore next
+ assert(!util.isDisturbed(object), 'The body has already been consumed.')
+ // istanbul ignore next
+ assert(!object.locked, 'The stream is locked.')
}
-}
-function consumePush (consume, chunk) {
- consume.length += chunk.length
- consume.body.push(chunk)
+ // 2. Return the results of extracting object.
+ return extractBody(object, keepalive)
}
-function consumeFinish (consume, err) {
- if (consume.body === null) {
- return
- }
+function cloneBody (body) {
+ // To clone a body body, run these steps:
- if (err) {
- consume.reject(err)
- } else {
- consume.resolve()
- }
+ // https://fetch.spec.whatwg.org/#concept-body-clone
- consume.type = null
- consume.stream = null
- consume.resolve = null
- consume.reject = null
- consume.length = 0
- consume.body = null
-}
+ // 1. Let « out1, out2 » be the result of teeing body’s stream.
+ const [out1, out2] = body.stream.tee()
+ const out2Clone = structuredClone(out2, { transfer: [out2] })
+ // This, for whatever reasons, unrefs out2Clone which allows
+ // the process to exit by itself.
+ const [, finalClone] = out2Clone.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: finalClone,
+ length: body.length,
+ source: body.source
+ }
+}
-/***/ 7655:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+async function * consumeBody (body) {
+ if (body) {
+ if (isUint8Array(body)) {
+ yield body
+ } else {
+ const stream = body.stream
-const assert = __nccwpck_require__(2613)
-const {
- ResponseStatusCodeError
-} = __nccwpck_require__(8707)
-const { toUSVString } = __nccwpck_require__(3440)
+ if (util.isDisturbed(stream)) {
+ throw new TypeError('The body has already been consumed.')
+ }
-async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) {
- assert(body)
+ if (stream.locked) {
+ throw new TypeError('The stream is locked.')
+ }
- let chunks = []
- let limit = 0
+ // Compat.
+ stream[kBodyUsed] = true
- for await (const chunk of body) {
- chunks.push(chunk)
- limit += chunk.length
- if (limit > 128 * 1024) {
- chunks = null
- break
+ yield * stream
}
}
+}
- if (statusCode === 204 || !contentType || !chunks) {
- process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
- return
+function throwIfAborted (state) {
+ if (state.aborted) {
+ throw new DOMException('The operation was aborted.', 'AbortError')
}
+}
- try {
- if (contentType.startsWith('application/json')) {
- const payload = JSON.parse(toUSVString(Buffer.concat(chunks)))
- process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
- return
- }
+function bodyMixinMethods (instance) {
+ 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 specConsumeBody(this, (bytes) => {
+ let mimeType = bodyMimeType(this)
- if (contentType.startsWith('text/')) {
- const payload = toUSVString(Buffer.concat(chunks))
- process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
- return
- }
- } catch (err) {
- // Process in a fallback if error
- }
+ if (mimeType === 'failure') {
+ mimeType = ''
+ } else if (mimeType) {
+ mimeType = serializeAMimeType(mimeType)
+ }
- process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
-}
+ // Return a Blob whose contents are bytes and type attribute
+ // is mimeType.
+ return new Blob([bytes], { type: mimeType })
+ }, instance)
+ },
-module.exports = { getResolveErrorBodyCallback }
+ 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 specConsumeBody(this, (bytes) => {
+ return new Uint8Array(bytes).buffer
+ }, instance)
+ },
+ text () {
+ // The text() method steps are to return the result of running
+ // consume body with this and UTF-8 decode.
+ return specConsumeBody(this, utf8DecodeBytes, instance)
+ },
-/***/ }),
+ json () {
+ // The json() method steps are to return the result of running
+ // consume body with this and parse JSON from bytes.
+ return specConsumeBody(this, parseJSONFromBytes, instance)
+ },
-/***/ 1093:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ async formData () {
+ webidl.brandCheck(this, instance)
-"use strict";
+ throwIfAborted(this[kState])
+ const contentType = this.headers.get('Content-Type')
-const {
- BalancedPoolMissingUpstreamError,
- InvalidArgumentError
-} = __nccwpck_require__(8707)
-const {
- PoolBase,
- kClients,
- kNeedDrain,
- kAddClient,
- kRemoveClient,
- kGetDispatcher
-} = __nccwpck_require__(8640)
-const Pool = __nccwpck_require__(5076)
-const { kUrl, kInterceptors } = __nccwpck_require__(6443)
-const { parseOrigin } = __nccwpck_require__(3440)
-const kFactory = Symbol('factory')
+ // If mimeType’s essence is "multipart/form-data", then:
+ if (/multipart\/form-data/.test(contentType)) {
+ const headers = {}
+ for (const [key, value] of this.headers) headers[key.toLowerCase()] = value
-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')
+ const responseFormData = new FormData()
-function getGreatestCommonDivisor (a, b) {
- if (b === 0) return a
- return getGreatestCommonDivisor(b, a % b)
-}
+ let busboy
-function defaultFactory (origin, opts) {
- return new Pool(origin, opts)
-}
+ try {
+ busboy = new Busboy({
+ headers,
+ preservePath: true
+ })
+ } catch (err) {
+ throw new DOMException(`${err}`, 'AbortError')
+ }
-class BalancedPool extends PoolBase {
- constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) {
- super()
+ busboy.on('field', (name, value) => {
+ responseFormData.append(name, value)
+ })
+ busboy.on('file', (name, value, filename, encoding, mimeType) => {
+ const chunks = []
- this[kOptions] = opts
- this[kIndex] = -1
- this[kCurrentWeight] = 0
+ if (encoding === 'base64' || encoding.toLowerCase() === 'base64') {
+ let base64chunk = ''
- this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100
- this[kErrorPenalty] = this[kOptions].errorPenalty || 15
+ value.on('data', (chunk) => {
+ base64chunk += chunk.toString().replace(/[\r\n]/gm, '')
- if (!Array.isArray(upstreams)) {
- upstreams = [upstreams]
- }
+ const end = base64chunk.length - base64chunk.length % 4
+ chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64'))
- if (typeof factory !== 'function') {
- throw new InvalidArgumentError('factory must be a function.')
- }
+ base64chunk = base64chunk.slice(end)
+ })
+ value.on('end', () => {
+ chunks.push(Buffer.from(base64chunk, 'base64'))
+ responseFormData.append(name, new File(chunks, filename, { type: mimeType }))
+ })
+ } else {
+ value.on('data', (chunk) => {
+ chunks.push(chunk)
+ })
+ value.on('end', () => {
+ responseFormData.append(name, new File(chunks, filename, { type: mimeType }))
+ })
+ }
+ })
- this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool)
- ? opts.interceptors.BalancedPool
- : []
- this[kFactory] = factory
+ const busboyResolve = new Promise((resolve, reject) => {
+ busboy.on('finish', resolve)
+ busboy.on('error', (err) => reject(new TypeError(err)))
+ })
- for (const upstream of upstreams) {
- this.addUpstream(upstream)
- }
- this._updateBalancedPoolStats()
- }
+ if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk)
+ busboy.end()
+ await busboyResolve
- addUpstream (upstream) {
- const upstreamOrigin = parseOrigin(upstream).origin
+ return responseFormData
+ } else if (/application\/x-www-form-urlencoded/.test(contentType)) {
+ // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then:
- 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]))
+ // 1. Let entries be the result of parsing bytes.
+ let entries
+ try {
+ let text = ''
+ // application/x-www-form-urlencoded parser will keep the BOM.
+ // https://url.spec.whatwg.org/#concept-urlencoded-parser
+ // Note that streaming decoder is stateful and cannot be reused
+ const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true })
- this[kAddClient](pool)
- pool.on('connect', () => {
- pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty])
- })
+ for await (const chunk of consumeBody(this[kState].body)) {
+ if (!isUint8Array(chunk)) {
+ throw new TypeError('Expected Uint8Array chunk')
+ }
+ text += streamingDecoder.decode(chunk, { stream: true })
+ }
+ text += streamingDecoder.decode()
+ entries = new URLSearchParams(text)
+ } catch (err) {
+ // istanbul ignore next: Unclear when new URLSearchParams can fail on a string.
+ // 2. If entries is failure, then throw a TypeError.
+ throw Object.assign(new TypeError(), { cause: err })
+ }
- pool.on('connectionError', () => {
- pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
- this._updateBalancedPoolStats()
- })
+ // 3. Return a new FormData object whose entries are entries.
+ const formData = new FormData()
+ for (const [name, value] of entries) {
+ formData.append(name, value)
+ }
+ return formData
+ } else {
+ // Wait a tick before checking if the request has been aborted.
+ // Otherwise, a TypeError can be thrown when an AbortError should.
+ await Promise.resolve()
- 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()
- }
- })
+ throwIfAborted(this[kState])
- for (const client of this[kClients]) {
- client[kWeight] = this[kMaxWeightPerServer]
+ // Otherwise, throw a TypeError.
+ throw webidl.errors.exception({
+ header: `${instance.name}.formData`,
+ message: 'Could not parse content as FormData.'
+ })
+ }
}
+ }
- this._updateBalancedPoolStats()
+ return methods
+}
- return this
- }
+function mixinBody (prototype) {
+ Object.assign(prototype.prototype, bodyMixinMethods(prototype))
+}
- _updateBalancedPoolStats () {
- this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0)
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-body-consume-body
+ * @param {Response|Request} object
+ * @param {(value: unknown) => unknown} convertBytesToJSValue
+ * @param {Response|Request} instance
+ */
+async function specConsumeBody (object, convertBytesToJSValue, instance) {
+ webidl.brandCheck(object, instance)
+
+ throwIfAborted(object[kState])
+
+ // 1. If object is unusable, then return a promise rejected
+ // with a TypeError.
+ if (bodyUnusable(object[kState].body)) {
+ throw new TypeError('Body is unusable')
}
- removeUpstream (upstream) {
- const upstreamOrigin = parseOrigin(upstream).origin
+ // 2. Let promise be a new promise.
+ const promise = createDeferredPromise()
- const pool = this[kClients].find((pool) => (
- pool[kUrl].origin === upstreamOrigin &&
- pool.closed !== true &&
- pool.destroyed !== true
- ))
+ // 3. Let errorSteps given error be to reject promise with error.
+ const errorSteps = (error) => promise.reject(error)
- if (pool) {
- this[kRemoveClient](pool)
+ // 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)
}
-
- return this
}
- get upstreams () {
- return this[kClients]
- .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true)
- .map((p) => p[kUrl].origin)
+ // 5. If object’s body is null, then run successSteps with an
+ // empty byte sequence.
+ if (object[kState].body == null) {
+ successSteps(new Uint8Array())
+ return promise.promise
}
- [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
- ))
+ // 6. Otherwise, fully read object’s body given successSteps,
+ // errorSteps, and object’s relevant global object.
+ await fullyReadBody(object[kState].body, successSteps, errorSteps)
- if (!dispatcher) {
- return
- }
+ // 7. Return promise.
+ return promise.promise
+}
- const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true)
+// https://fetch.spec.whatwg.org/#body-unusable
+function bodyUnusable (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))
+}
- if (allClientsBusy) {
- return
- }
+/**
+ * @see https://encoding.spec.whatwg.org/#utf-8-decode
+ * @param {Buffer} buffer
+ */
+function utf8DecodeBytes (buffer) {
+ if (buffer.length === 0) {
+ return ''
+ }
- let counter = 0
+ // 1. Let buffer be the result of peeking three bytes from
+ // ioQueue, converted to a byte sequence.
- let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain])
+ // 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)
+ }
- while (counter++ < this[kClients].length) {
- this[kIndex] = (this[kIndex] + 1) % this[kClients].length
- const pool = this[kClients][this[kIndex]]
+ // 3. Process a queue with an instance of UTF-8’s
+ // decoder, ioQueue, output, and "replacement".
+ const output = textDecoder.decode(buffer)
- // find pool index with the largest weight
- if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {
- maxWeightIndex = this[kIndex]
- }
+ // 4. Return output.
+ return output
+}
- // 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]
+/**
+ * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value
+ * @param {Uint8Array} bytes
+ */
+function parseJSONFromBytes (bytes) {
+ return JSON.parse(utf8DecodeBytes(bytes))
+}
- if (this[kCurrentWeight] <= 0) {
- this[kCurrentWeight] = this[kMaxWeightPerServer]
- }
- }
- if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) {
- return pool
- }
- }
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-body-mime-type
+ * @param {import('./response').Response|import('./request').Request} object
+ */
+function bodyMimeType (object) {
+ const { headersList } = object[kState]
+ const contentType = headersList.get('content-type')
- this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight]
- this[kIndex] = maxWeightIndex
- return this[kClients][maxWeightIndex]
+ if (contentType === null) {
+ return 'failure'
}
+
+ return parseMIMEType(contentType)
}
-module.exports = BalancedPool
+module.exports = {
+ extractBody,
+ safelyExtractBody,
+ cloneBody,
+ mixinBody
+}
/***/ }),
-/***/ 479:
+/***/ 87326:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-const { kConstruct } = __nccwpck_require__(296)
-const { urlEquals, fieldValues: getFieldValues } = __nccwpck_require__(3993)
-const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(3440)
-const { kHeadersList } = __nccwpck_require__(6443)
-const { webidl } = __nccwpck_require__(4222)
-const { Response, cloneResponse } = __nccwpck_require__(8676)
-const { Request } = __nccwpck_require__(5194)
-const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710)
-const { fetching } = __nccwpck_require__(2315)
-const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(5523)
-const assert = __nccwpck_require__(2613)
-const { getGlobalDispatcher } = __nccwpck_require__(2581)
+const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(28167)
-/**
- * @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
- */
+const corsSafeListedMethods = ['GET', 'HEAD', 'POST']
+const corsSafeListedMethodsSet = new Set(corsSafeListedMethods)
-/**
- * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list
- * @typedef {[any, any][]} requestResponseList
- */
+const nullBodyStatus = [101, 204, 205, 304]
-class Cache {
- /**
- * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list
- * @type {requestResponseList}
- */
- #relevantRequestResponseList
+const redirectStatus = [301, 302, 303, 307, 308]
+const redirectStatusSet = new Set(redirectStatus)
- constructor () {
- if (arguments[0] !== kConstruct) {
- webidl.illegalConstructor()
- }
+// https://fetch.spec.whatwg.org/#block-bad-port
+const badPorts = [
+ '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', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697',
+ '10080'
+]
- this.#relevantRequestResponseList = arguments[1]
- }
+const badPortsSet = new Set(badPorts)
- async match (request, options = {}) {
- webidl.brandCheck(this, Cache)
- webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' })
+// https://w3c.github.io/webappsec-referrer-policy/#referrer-policies
+const referrerPolicy = [
+ '',
+ 'no-referrer',
+ 'no-referrer-when-downgrade',
+ 'same-origin',
+ 'origin',
+ 'strict-origin',
+ 'origin-when-cross-origin',
+ 'strict-origin-when-cross-origin',
+ 'unsafe-url'
+]
+const referrerPolicySet = new Set(referrerPolicy)
- request = webidl.converters.RequestInfo(request)
- options = webidl.converters.CacheQueryOptions(options)
+const requestRedirect = ['follow', 'manual', 'error']
- const p = await this.matchAll(request, options)
+const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE']
+const safeMethodsSet = new Set(safeMethods)
- if (p.length === 0) {
- return
- }
+const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors']
- return p[0]
- }
+const requestCredentials = ['omit', 'same-origin', 'include']
- async matchAll (request = undefined, options = {}) {
- webidl.brandCheck(this, Cache)
+const requestCache = [
+ 'default',
+ 'no-store',
+ 'reload',
+ 'no-cache',
+ 'force-cache',
+ 'only-if-cached'
+]
- if (request !== undefined) request = webidl.converters.RequestInfo(request)
- options = webidl.converters.CacheQueryOptions(options)
+// https://fetch.spec.whatwg.org/#request-body-header-name
+const requestBodyHeader = [
+ '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'
+]
- // 1.
- let r = null
+// https://fetch.spec.whatwg.org/#enumdef-requestduplex
+const requestDuplex = [
+ 'half'
+]
- // 2.
- if (request !== undefined) {
- if (request instanceof Request) {
- // 2.1.1
- r = request[kState]
+// http://fetch.spec.whatwg.org/#forbidden-method
+const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK']
+const forbiddenMethodsSet = new Set(forbiddenMethods)
- // 2.1.2
- if (r.method !== 'GET' && !options.ignoreMethod) {
- return []
- }
- } else if (typeof request === 'string') {
- // 2.2.1
- r = new Request(request)[kState]
- }
- }
+const subresource = [
+ 'audio',
+ 'audioworklet',
+ 'font',
+ 'image',
+ 'manifest',
+ 'paintworklet',
+ 'script',
+ 'style',
+ 'track',
+ 'video',
+ 'xslt',
+ ''
+]
+const subresourceSet = new Set(subresource)
- // 5.
- // 5.1
- const responses = []
+/** @type {globalThis['DOMException']} */
+const DOMException = globalThis.DOMException ?? (() => {
+ // DOMException was only made a global in Node v17.0.0,
+ // but fetch supports >= v16.8.
+ try {
+ atob('~')
+ } catch (err) {
+ return Object.getPrototypeOf(err).constructor
+ }
+})()
- // 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)
+let channel
- // 5.3.2
- for (const requestResponse of requestResponses) {
- responses.push(requestResponse[1])
- }
+/** @type {globalThis['structuredClone']} */
+const structuredClone =
+ globalThis.structuredClone ??
+ // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js
+ // structuredClone was added in v17.0.0, but fetch supports v16.8
+ function structuredClone (value, options = undefined) {
+ if (arguments.length === 0) {
+ throw new TypeError('missing argument')
}
- // 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 = new Response(response.body?.source ?? null)
- const body = responseObject[kState].body
- responseObject[kState] = response
- responseObject[kState].body = body
- responseObject[kHeaders][kHeadersList] = response.headersList
- responseObject[kHeaders][kGuard] = 'immutable'
-
- responseList.push(responseObject)
+ if (!channel) {
+ channel = new MessageChannel()
}
-
- // 6.
- return Object.freeze(responseList)
+ channel.port1.unref()
+ channel.port2.unref()
+ channel.port1.postMessage(value, options?.transfer)
+ return receiveMessageOnPort(channel.port2).message
}
- async add (request) {
- webidl.brandCheck(this, Cache)
- webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' })
-
- request = webidl.converters.RequestInfo(request)
-
- // 1.
- const requests = [request]
-
- // 2.
- const responseArrayPromise = this.addAll(requests)
-
- // 3.
- return await responseArrayPromise
- }
+module.exports = {
+ DOMException,
+ structuredClone,
+ subresource,
+ forbiddenMethods,
+ requestBodyHeader,
+ referrerPolicy,
+ requestRedirect,
+ requestMode,
+ requestCredentials,
+ requestCache,
+ redirectStatus,
+ corsSafeListedMethods,
+ nullBodyStatus,
+ safeMethods,
+ badPorts,
+ requestDuplex,
+ subresourceSet,
+ badPortsSet,
+ redirectStatusSet,
+ corsSafeListedMethodsSet,
+ safeMethodsSet,
+ forbiddenMethodsSet,
+ referrerPolicySet
+}
- async addAll (requests) {
- webidl.brandCheck(this, Cache)
- webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' })
- requests = webidl.converters['sequence'](requests)
+/***/ }),
- // 1.
- const responsePromises = []
+/***/ 94322:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2.
- const requestList = []
+const assert = __nccwpck_require__(42613)
+const { atob } = __nccwpck_require__(20181)
+const { isomorphicDecode } = __nccwpck_require__(15523)
- // 3.
- for (const request of requests) {
- if (typeof request === 'string') {
- continue
- }
+const encoder = new TextEncoder()
- // 3.1
- const r = request[kState]
+/**
+ * @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
+/**
+ * @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
- // 3.2
- if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') {
- throw webidl.errors.exception({
- header: 'Cache.addAll',
- message: 'Expected http/s scheme when method is not GET.'
- })
- }
- }
+// 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:')
- // 4.
- /** @type {ReturnType[]} */
- const fetchControllers = []
+ // 2. Let input be the result of running the URL
+ // serializer on dataURL with exclude fragment
+ // set to true.
+ let input = URLSerializer(dataURL, true)
- // 5.
- for (const request of requests) {
- // 5.1
- const r = new Request(request)[kState]
+ // 3. Remove the leading "data:" string from input.
+ input = input.slice(5)
- // 5.2
- if (!urlIsHttpHttpsScheme(r.url)) {
- throw webidl.errors.exception({
- header: 'Cache.addAll',
- message: 'Expected http/s scheme.'
- })
- }
+ // 4. Let position point at the start of input.
+ const position = { position: 0 }
- // 5.4
- r.initiator = 'fetch'
- r.destination = 'subresource'
+ // 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
+ )
- // 5.5
- requestList.push(r)
+ // 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)
- // 5.6
- const responsePromise = createDeferredPromise()
+ // 7. If position is past the end of input, then
+ // return failure
+ if (position.position >= input.length) {
+ return 'failure'
+ }
- // 5.7
- fetchControllers.push(fetching({
- request: r,
- dispatcher: getGlobalDispatcher(),
- 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'))
+ // 8. Advance position by 1.
+ position.position++
- // 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'
- }))
+ // 9. Let encodedBody be the remainder of input.
+ const encodedBody = input.slice(mimeTypeLength + 1)
- for (const controller of fetchControllers) {
- controller.abort()
- }
+ // 10. Let body be the percent-decoding of encodedBody.
+ let body = stringPercentDecode(encodedBody)
- return
- }
- }
- }
- },
- processResponseEndOfBody (response) {
- // 1.
- if (response.aborted) {
- responsePromise.reject(new DOMException('aborted', 'AbortError'))
- return
- }
+ // 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.
- responsePromise.resolve(response)
- }
- }))
+ // 2. Set body to the forgiving-base64 decode of
+ // stringBody.
+ body = forgivingBase64(stringBody)
- // 5.8
- responsePromises.push(responsePromise.promise)
+ // 3. If body is failure, then return failure.
+ if (body === 'failure') {
+ return 'failure'
}
- // 6.
- const p = Promise.all(responsePromises)
+ // 4. Remove the last 6 code points from mimeType.
+ mimeType = mimeType.slice(0, -6)
- // 7.
- const responses = await p
+ // 5. Remove trailing U+0020 SPACE code points from mimeType,
+ // if any.
+ mimeType = mimeType.replace(/(\u0020)+$/, '')
- // 7.1
- const operations = []
+ // 6. Remove the last U+003B (;) code point from mimeType.
+ mimeType = mimeType.slice(0, -1)
+ }
- // 7.2
- let index = 0
+ // 12. If mimeType starts with U+003B (;), then prepend
+ // "text/plain" to mimeType.
+ if (mimeType.startsWith(';')) {
+ mimeType = 'text/plain' + mimeType
+ }
- // 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
- }
+ // 13. Let mimeTypeRecord be the result of parsing
+ // mimeType.
+ let mimeTypeRecord = parseMIMEType(mimeType)
- operations.push(operation) // 7.3.5
+ // 14. If mimeTypeRecord is failure, then set
+ // mimeTypeRecord to text/plain;charset=US-ASCII.
+ if (mimeTypeRecord === 'failure') {
+ mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII')
+ }
- index++ // 7.3.6
- }
+ // 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 }
+}
- // 7.5
- const cacheJobPromise = createDeferredPromise()
+// https://url.spec.whatwg.org/#concept-url-serializer
+/**
+ * @param {URL} url
+ * @param {boolean} excludeFragment
+ */
+function URLSerializer (url, excludeFragment = false) {
+ if (!excludeFragment) {
+ return url.href
+ }
- // 7.6.1
- let errorData = null
+ const href = url.href
+ const hashLength = url.hash.length
- // 7.6.2
- try {
- this.#batchCacheOperations(operations)
- } catch (e) {
- errorData = e
- }
+ return hashLength === 0 ? href : href.substring(0, href.length - hashLength)
+}
- // 7.6.3
- queueMicrotask(() => {
- // 7.6.3.1
- if (errorData === null) {
- cacheJobPromise.resolve(undefined)
- } else {
- // 7.6.3.2
- cacheJobPromise.reject(errorData)
- }
- })
+// 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 = ''
- // 7.7
- return cacheJobPromise.promise
+ // 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++
}
- async put (request, response) {
- webidl.brandCheck(this, Cache)
- webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' })
+ // 3. Return result.
+ return result
+}
- request = webidl.converters.RequestInfo(request)
- response = webidl.converters.Response(response)
+/**
+ * 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
- // 1.
- let innerRequest = null
+ if (idx === -1) {
+ position.position = input.length
+ return input.slice(start)
+ }
- // 2.
- if (request instanceof Request) {
- innerRequest = request[kState]
- } else { // 3.
- innerRequest = new Request(request)[kState]
- }
+ position.position = idx
+ return input.slice(start, position.position)
+}
- // 4.
- if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') {
- throw webidl.errors.exception({
- header: 'Cache.put',
- message: 'Expected an http/s scheme when method is not GET'
- })
- }
+// 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)
- // 5.
- const innerResponse = response[kState]
+ // 2. Return the percent-decoding of bytes.
+ return percentDecode(bytes)
+}
- // 6.
- if (innerResponse.status === 206) {
- throw webidl.errors.exception({
- header: 'Cache.put',
- message: 'Got 206 status'
- })
- }
+// https://url.spec.whatwg.org/#percent-decode
+/** @param {Uint8Array} input */
+function percentDecode (input) {
+ // 1. Let output be an empty byte sequence.
+ /** @type {number[]} */
+ const output = []
- // 7.
- if (innerResponse.headersList.contains('vary')) {
- // 7.1.
- const fieldValues = getFieldValues(innerResponse.headersList.get('vary'))
+ // 2. For each byte byte in input:
+ for (let i = 0; i < input.length; i++) {
+ const byte = input[i]
- // 7.2.
- for (const fieldValue of fieldValues) {
- // 7.2.1
- if (fieldValue === '*') {
- throw webidl.errors.exception({
- header: 'Cache.put',
- message: 'Got * vary field value'
- })
- }
- }
- }
+ // 1. If byte is not 0x25 (%), then append byte to output.
+ if (byte !== 0x25) {
+ output.push(byte)
- // 8.
- if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) {
- throw webidl.errors.exception({
- header: 'Cache.put',
- message: 'Response body is locked or disturbed'
- })
- }
+ // 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 &&
+ !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2]))
+ ) {
+ output.push(0x25)
- // 9.
- const clonedResponse = cloneResponse(innerResponse)
+ // 3. Otherwise:
+ } else {
+ // 1. Let bytePoint be the two bytes after byte in input,
+ // decoded, and then interpreted as hexadecimal number.
+ const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2])
+ const bytePoint = Number.parseInt(nextTwoBytes, 16)
- // 10.
- const bodyReadPromise = createDeferredPromise()
+ // 2. Append a byte whose value is bytePoint to output.
+ output.push(bytePoint)
- // 11.
- if (innerResponse.body != null) {
- // 11.1
- const stream = innerResponse.body.stream
+ // 3. Skip the next two bytes in input.
+ i += 2
+ }
+ }
- // 11.2
- const reader = stream.getReader()
+ // 3. Return output.
+ return Uint8Array.from(output)
+}
- // 11.3
- readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject)
- } else {
- bodyReadPromise.resolve(undefined)
- }
+// 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)
- // 12.
- /** @type {CacheBatchOperation[]} */
- const operations = []
+ // 2. Let position be a position variable for input,
+ // initially pointing at the start of input.
+ const position = { position: 0 }
- // 13.
- /** @type {CacheBatchOperation} */
- const operation = {
- type: 'put', // 14.
- request: innerRequest, // 15.
- response: clonedResponse // 16.
- }
+ // 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
+ )
- // 17.
- operations.push(operation)
+ // 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'
+ }
- // 19.
- const bytes = await bodyReadPromise.promise
+ // 5. If position is past the end of input, then return
+ // failure
+ if (position.position > input.length) {
+ return 'failure'
+ }
- if (clonedResponse.body != null) {
- clonedResponse.body.source = bytes
- }
+ // 6. Advance position by 1. (This skips past U+002F (/).)
+ position.position++
- // 19.1
- const cacheJobPromise = createDeferredPromise()
+ // 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
+ )
- // 19.2.1
- let errorData = null
+ // 8. Remove any trailing HTTP whitespace from subtype.
+ subtype = removeHTTPWhitespace(subtype, false, true)
- // 19.2.2
- try {
- this.#batchCacheOperations(operations)
- } catch (e) {
- errorData = e
- }
+ // 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'
+ }
- // 19.2.3
- queueMicrotask(() => {
- // 19.2.3.1
- if (errorData === null) {
- cacheJobPromise.resolve()
- } else { // 19.2.3.2
- cacheJobPromise.reject(errorData)
- }
- })
+ const typeLowercase = type.toLowerCase()
+ const subtypeLowercase = subtype.toLowerCase()
- return cacheJobPromise.promise
+ // 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}`
}
- async delete (request, options = {}) {
- webidl.brandCheck(this, Cache)
- webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' })
+ // 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++
- request = webidl.converters.RequestInfo(request)
- options = webidl.converters.CacheQueryOptions(options)
+ // 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
+ )
- /**
- * @type {Request}
- */
- let r = null
+ // 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
+ )
- if (request instanceof Request) {
- r = request[kState]
+ // 4. Set parameterName to parameterName, in ASCII
+ // lowercase.
+ parameterName = parameterName.toLowerCase()
- if (r.method !== 'GET' && !options.ignoreMethod) {
- return false
+ // 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
}
- } else {
- assert(typeof request === 'string')
- r = new Request(request)[kState]
+ // 2. Advance position by 1. (This skips past U+003D (=).)
+ position.position++
}
- /** @type {CacheBatchOperation[]} */
- const operations = []
-
- /** @type {CacheBatchOperation} */
- const operation = {
- type: 'delete',
- request: r,
- options
+ // 6. If position is past the end of input, then break.
+ if (position.position > input.length) {
+ break
}
- operations.push(operation)
+ // 7. Let parameterValue be null.
+ let parameterValue = null
- const cacheJobPromise = createDeferredPromise()
+ // 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)
- let errorData = null
- let requestResponses
+ // 2. Collect a sequence of code points that are not
+ // U+003B (;) from input, given position.
+ collectASequenceOfCodePointsFast(
+ ';',
+ input,
+ position
+ )
- try {
- requestResponses = this.#batchCacheOperations(operations)
- } catch (e) {
- errorData = e
+ // 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(/[\u0009\u000A\u000C\u000D\u0020]/g, '') // eslint-disable-line
- queueMicrotask(() => {
- if (errorData === null) {
- cacheJobPromise.resolve(!!requestResponses?.length)
- } else {
- cacheJobPromise.reject(errorData)
- }
- })
+ // 2. If data’s code point length divides by 4 leaving
+ // no remainder, then:
+ if (data.length % 4 === 0) {
+ // 1. If data ends with one or two U+003D (=) code points,
+ // then remove them from data.
+ data = data.replace(/=?=$/, '')
+ }
- return cacheJobPromise.promise
+ // 3. If data’s code point length divides by 4 leaving
+ // a remainder of 1, then return failure.
+ if (data.length % 4 === 1) {
+ return 'failure'
}
- /**
- * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys
- * @param {any} request
- * @param {import('../../types/cache').CacheQueryOptions} options
- * @returns {readonly Request[]}
- */
- async keys (request = undefined, options = {}) {
- webidl.brandCheck(this, Cache)
+ // 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)) {
+ return 'failure'
+ }
- if (request !== undefined) request = webidl.converters.RequestInfo(request)
- options = webidl.converters.CacheQueryOptions(options)
+ const binary = atob(data)
+ const bytes = new Uint8Array(binary.length)
- // 1.
- let r = null
+ for (let byte = 0; byte < binary.length; byte++) {
+ bytes[byte] = binary.charCodeAt(byte)
+ }
- // 2.
- if (request !== undefined) {
- // 2.1
- if (request instanceof Request) {
- // 2.1.1
- r = request[kState]
+ return bytes
+}
- // 2.1.2
- if (r.method !== 'GET' && !options.ignoreMethod) {
- return []
- }
- } else if (typeof request === 'string') { // 2.2
- r = new Request(request)[kState]
- }
- }
+// 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
+ */
+function collectAnHTTPQuotedString (input, position, extractValue) {
+ // 1. Let positionStart be position.
+ const positionStart = position.position
- // 4.
- const promise = createDeferredPromise()
+ // 2. Let value be the empty string.
+ let value = ''
- // 5.
- // 5.1
- const requests = []
+ // 3. Assert: the code point at position within input
+ // is U+0022 (").
+ assert(input[position.position] === '"')
- // 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)
+ // 4. Advance position by 1.
+ position.position++
- // 5.3.2
- for (const requestResponse of requestResponses) {
- // 5.3.2.1
- requests.push(requestResponse[0])
- }
+ // 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
}
- // 5.4
- queueMicrotask(() => {
- // 5.4.1
- const requestList = []
+ // 3. Let quoteOrBackslash be the code point at position within
+ // input.
+ const quoteOrBackslash = input[position.position]
- // 5.4.2
- for (const request of requests) {
- const requestObject = new Request('https://a')
- requestObject[kState] = request
- requestObject[kHeaders][kHeadersList] = request.headersList
- requestObject[kHeaders][kGuard] = 'immutable'
- requestObject[kRealm] = request.client
+ // 4. Advance position by 1.
+ position.position++
- // 5.4.2.1
- requestList.push(requestObject)
+ // 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
}
- // 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]
+ // 2. Append the code point at position within input to value.
+ value += input[position.position]
- // 3.
- const addedItems = []
+ // 3. Advance position by 1.
+ position.position++
- // 4.1
- const resultList = []
+ // 6. Otherwise:
+ } else {
+ // 1. Assert: quoteOrBackslash is U+0022 (").
+ assert(quoteOrBackslash === '"')
- 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"'
- })
- }
+ // 2. Break.
+ break
+ }
+ }
- // 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'
- })
- }
+ // 6. If the extract-value flag is set, then return value.
+ if (extractValue) {
+ return value
+ }
- // 4.2.3
- if (this.#queryCache(operation.request, operation.options, addedItems).length) {
- throw new DOMException('???', 'InvalidStateError')
- }
+ // 7. Return the code points from positionStart to position,
+ // inclusive, within input.
+ return input.slice(positionStart, position.position)
+}
- // 4.2.4
- let requestResponses
+/**
+ * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type
+ */
+function serializeAMimeType (mimeType) {
+ assert(mimeType !== 'failure')
+ const { parameters, essence } = mimeType
- // 4.2.5
- if (operation.type === 'delete') {
- // 4.2.5.1
- requestResponses = this.#queryCache(operation.request, operation.options)
+ // 1. Let serialization be the concatenation of mimeType’s
+ // type, U+002F (/), and mimeType’s subtype.
+ let serialization = essence
- // TODO: the spec is wrong, this is needed to pass WPTs
- if (requestResponses.length === 0) {
- return []
- }
+ // 2. For each name → value of mimeType’s parameters:
+ for (let [name, value] of parameters.entries()) {
+ // 1. Append U+003B (;) to serialization.
+ serialization += ';'
- // 4.2.5.2
- for (const requestResponse of requestResponses) {
- const idx = cache.indexOf(requestResponse)
- assert(idx !== -1)
+ // 2. Append name to serialization.
+ serialization += name
- // 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'
- })
- }
+ // 3. Append U+003D (=) to serialization.
+ serialization += '='
- // 4.2.6.2
- const r = operation.request
+ // 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 occurence of U+0022 (") or
+ // U+005C (\) in value with U+005C (\).
+ value = value.replace(/(\\|")/g, '\\$1')
- // 4.2.6.3
- if (!urlIsHttpHttpsScheme(r.url)) {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'expected http or https scheme'
- })
- }
+ // 2. Prepend U+0022 (") to value.
+ value = '"' + value
- // 4.2.6.4
- if (r.method !== 'GET') {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'not get method'
- })
- }
+ // 3. Append U+0022 (") to value.
+ value += '"'
+ }
- // 4.2.6.5
- if (operation.options != null) {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'options must not be defined'
- })
- }
+ // 5. Append value to serialization.
+ serialization += value
+ }
- // 4.2.6.6
- requestResponses = this.#queryCache(operation.request)
+ // 3. Return serialization.
+ return serialization
+}
- // 4.2.6.7
- for (const requestResponse of requestResponses) {
- const idx = cache.indexOf(requestResponse)
- assert(idx !== -1)
+/**
+ * @see https://fetch.spec.whatwg.org/#http-whitespace
+ * @param {string} char
+ */
+function isHTTPWhiteSpace (char) {
+ return char === '\r' || char === '\n' || char === '\t' || char === ' '
+}
- // 4.2.6.7.1
- cache.splice(idx, 1)
- }
+/**
+ * @see https://fetch.spec.whatwg.org/#http-whitespace
+ * @param {string} str
+ */
+function removeHTTPWhitespace (str, leading = true, trailing = true) {
+ let lead = 0
+ let trail = str.length - 1
- // 4.2.6.8
- cache.push([operation.request, operation.response])
+ if (leading) {
+ for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++);
+ }
- // 4.2.6.10
- addedItems.push([operation.request, operation.response])
- }
+ if (trailing) {
+ for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--);
+ }
- // 4.2.7
- resultList.push([operation.request, operation.response])
- }
+ return str.slice(lead, trail + 1)
+}
- // 4.3
- return resultList
- } catch (e) { // 5.
- // 5.1
- this.#relevantRequestResponseList.length = 0
+/**
+ * @see https://infra.spec.whatwg.org/#ascii-whitespace
+ * @param {string} char
+ */
+function isASCIIWhitespace (char) {
+ return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' '
+}
- // 5.2
- this.#relevantRequestResponseList = backupCache
+/**
+ * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace
+ */
+function removeASCIIWhitespace (str, leading = true, trailing = true) {
+ let lead = 0
+ let trail = str.length - 1
- // 5.3
- throw e
- }
+ if (leading) {
+ for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++);
}
- /**
- * @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 = []
+ if (trailing) {
+ for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--);
+ }
- const storage = targetStorage ?? this.#relevantRequestResponseList
+ return str.slice(lead, trail + 1)
+}
- for (const requestResponse of storage) {
- const [cachedRequest, cachedResponse] = requestResponse
- if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) {
- resultList.push(requestResponse)
- }
- }
+module.exports = {
+ dataURLProcessor,
+ URLSerializer,
+ collectASequenceOfCodePoints,
+ collectASequenceOfCodePointsFast,
+ stringPercentDecode,
+ parseMIMEType,
+ collectAnHTTPQuotedString,
+ serializeAMimeType
+}
- 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)
+/***/ 63041:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- const cachedURL = new URL(request.url)
+"use strict";
- if (options?.ignoreSearch) {
- cachedURL.search = ''
- queryURL.search = ''
- }
+const { Blob, File: NativeFile } = __nccwpck_require__(20181)
+const { types } = __nccwpck_require__(39023)
+const { kState } = __nccwpck_require__(89710)
+const { isBlobLike } = __nccwpck_require__(15523)
+const { webidl } = __nccwpck_require__(74222)
+const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(94322)
+const { kEnumerableProperty } = __nccwpck_require__(3440)
+const encoder = new TextEncoder()
- if (!urlEquals(queryURL, cachedURL, true)) {
- return false
- }
+class File extends Blob {
+ constructor (fileBits, fileName, options = {}) {
+ // The File constructor is invoked with two or three parameters, depending
+ // on whether the optional dictionary parameter is used. When the File()
+ // constructor is invoked, user agents must run the following steps:
+ webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' })
- if (
- response == null ||
- options?.ignoreVary ||
- !response.headersList.contains('vary')
- ) {
- return true
- }
+ fileBits = webidl.converters['sequence'](fileBits)
+ fileName = webidl.converters.USVString(fileName)
+ options = webidl.converters.FilePropertyBag(options)
- const fieldValues = getFieldValues(response.headersList.get('vary'))
+ // 1. Let bytes be the result of processing blob parts given fileBits and
+ // options.
+ // Note: Blob handles this for us
- for (const fieldValue of fieldValues) {
- if (fieldValue === '*') {
- return false
- }
+ // 2. Let n be the fileName argument to the constructor.
+ const n = fileName
- const requestValue = request.headersList.get(fieldValue)
- const queryValue = requestQuery.headersList.get(fieldValue)
+ // 3. Process FilePropertyBag dictionary argument by running the following
+ // substeps:
- // 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
- }
- }
+ // 1. If the type member is provided and is not the empty string, let t
+ // be set to the type dictionary member. If t contains any characters
+ // outside the range U+0020 to U+007E, then set t to the empty string
+ // and return from these substeps.
+ // 2. Convert every character in t to ASCII lowercase.
+ let t = options.type
+ let d
- return true
- }
-}
+ // eslint-disable-next-line no-labels
+ substep: {
+ if (t) {
+ t = parseMIMEType(t)
-Object.defineProperties(Cache.prototype, {
- [Symbol.toStringTag]: {
- value: 'Cache',
- configurable: true
- },
- match: kEnumerableProperty,
- matchAll: kEnumerableProperty,
- add: kEnumerableProperty,
- addAll: kEnumerableProperty,
- put: kEnumerableProperty,
- delete: kEnumerableProperty,
- keys: kEnumerableProperty
-})
+ if (t === 'failure') {
+ t = ''
+ // eslint-disable-next-line no-labels
+ break substep
+ }
-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
- }
-]
+ t = serializeAMimeType(t).toLowerCase()
+ }
-webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters)
+ // 3. If the lastModified member is provided, let d be set to the
+ // lastModified dictionary member. If it is not provided, set d to the
+ // current date and time represented as the number of milliseconds since
+ // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
+ d = options.lastModified
+ }
-webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([
- ...cacheQueryOptionConverters,
- {
- key: 'cacheName',
- converter: webidl.converters.DOMString
- }
-])
+ // 4. Return a new File object F such that:
+ // F refers to the bytes byte sequence.
+ // F.size is set to the number of total bytes in bytes.
+ // F.name is set to n.
+ // F.type is set to t.
+ // F.lastModified is set to d.
-webidl.converters.Response = webidl.interfaceConverter(Response)
+ super(processBlobParts(fileBits, options), { type: t })
+ this[kState] = {
+ name: n,
+ lastModified: d,
+ type: t
+ }
+ }
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.RequestInfo
-)
+ get name () {
+ webidl.brandCheck(this, File)
-module.exports = {
- Cache
-}
+ return this[kState].name
+ }
+ get lastModified () {
+ webidl.brandCheck(this, File)
-/***/ }),
+ return this[kState].lastModified
+ }
-/***/ 4738:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ get type () {
+ webidl.brandCheck(this, File)
-"use strict";
+ return this[kState].type
+ }
+}
+class FileLike {
+ constructor (blobLike, fileName, options = {}) {
+ // TODO: argument idl type check
-const { kConstruct } = __nccwpck_require__(296)
-const { Cache } = __nccwpck_require__(479)
-const { webidl } = __nccwpck_require__(4222)
-const { kEnumerableProperty } = __nccwpck_require__(3440)
+ // The File constructor is invoked with two or three parameters, depending
+ // on whether the optional dictionary parameter is used. When the File()
+ // constructor is invoked, user agents must run the following steps:
-class CacheStorage {
- /**
- * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map
- * @type {Map}
- */
- async has (cacheName) {
- webidl.brandCheck(this, CacheStorage)
- webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' })
-
- cacheName = webidl.converters.DOMString(cacheName)
+ stream (...args) {
+ webidl.brandCheck(this, FileLike)
- // 2.1.1
- // 2.2
- return this.#caches.has(cacheName)
+ return this[kState].blobLike.stream(...args)
}
- /**
- * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open
- * @param {string} cacheName
- * @returns {Promise}
- */
- async open (cacheName) {
- webidl.brandCheck(this, CacheStorage)
- webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' })
+ arrayBuffer (...args) {
+ webidl.brandCheck(this, FileLike)
- cacheName = webidl.converters.DOMString(cacheName)
+ return this[kState].blobLike.arrayBuffer(...args)
+ }
- // 2.1
- if (this.#caches.has(cacheName)) {
- // await caches.open('v1') !== await caches.open('v1')
+ slice (...args) {
+ webidl.brandCheck(this, FileLike)
- // 2.1.1
- const cache = this.#caches.get(cacheName)
+ return this[kState].blobLike.slice(...args)
+ }
- // 2.1.1.1
- return new Cache(kConstruct, cache)
- }
+ text (...args) {
+ webidl.brandCheck(this, FileLike)
- // 2.2
- const cache = []
+ return this[kState].blobLike.text(...args)
+ }
- // 2.3
- this.#caches.set(cacheName, cache)
+ get size () {
+ webidl.brandCheck(this, FileLike)
- // 2.4
- return new Cache(kConstruct, cache)
+ return this[kState].blobLike.size
}
- /**
- * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete
- * @param {string} cacheName
- * @returns {Promise}
- */
- async delete (cacheName) {
- webidl.brandCheck(this, CacheStorage)
- webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' })
+ get type () {
+ webidl.brandCheck(this, FileLike)
- cacheName = webidl.converters.DOMString(cacheName)
+ return this[kState].blobLike.type
+ }
- return this.#caches.delete(cacheName)
+ get name () {
+ webidl.brandCheck(this, FileLike)
+
+ return this[kState].name
}
- /**
- * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys
- * @returns {string[]}
- */
- async keys () {
- webidl.brandCheck(this, CacheStorage)
+ get lastModified () {
+ webidl.brandCheck(this, FileLike)
- // 2.1
- const keys = this.#caches.keys()
+ return this[kState].lastModified
+ }
- // 2.2
- return [...keys]
+ get [Symbol.toStringTag] () {
+ return 'File'
}
}
-Object.defineProperties(CacheStorage.prototype, {
+Object.defineProperties(File.prototype, {
[Symbol.toStringTag]: {
- value: 'CacheStorage',
+ value: 'File',
configurable: true
},
- match: kEnumerableProperty,
- has: kEnumerableProperty,
- open: kEnumerableProperty,
- delete: kEnumerableProperty,
- keys: kEnumerableProperty
+ name: kEnumerableProperty,
+ lastModified: kEnumerableProperty
})
-module.exports = {
- CacheStorage
-}
-
-
-/***/ }),
-
-/***/ 296:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+webidl.converters.Blob = webidl.interfaceConverter(Blob)
-"use strict";
+webidl.converters.BlobPart = function (V, opts) {
+ if (webidl.util.Type(V) === 'Object') {
+ if (isBlobLike(V)) {
+ return webidl.converters.Blob(V, { strict: false })
+ }
+ if (
+ ArrayBuffer.isView(V) ||
+ types.isAnyArrayBuffer(V)
+ ) {
+ return webidl.converters.BufferSource(V, opts)
+ }
+ }
-module.exports = {
- kConstruct: (__nccwpck_require__(6443).kConstruct)
+ return webidl.converters.USVString(V, opts)
}
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.BlobPart
+)
-/***/ }),
-
-/***/ 3993:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-const assert = __nccwpck_require__(2613)
-const { URLSerializer } = __nccwpck_require__(4322)
-const { isValidHeaderName } = __nccwpck_require__(5523)
-
-/**
- * @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)
+// https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag
+webidl.converters.FilePropertyBag = webidl.dictionaryConverter([
+ {
+ key: 'lastModified',
+ converter: webidl.converters['long long'],
+ get defaultValue () {
+ return Date.now()
+ }
+ },
+ {
+ key: 'type',
+ converter: webidl.converters.DOMString,
+ defaultValue: ''
+ },
+ {
+ key: 'endings',
+ converter: (value) => {
+ value = webidl.converters.DOMString(value)
+ value = value.toLowerCase()
- const serializedB = URLSerializer(B, excludeFragment)
+ if (value !== 'native') {
+ value = 'transparent'
+ }
- return serializedA === serializedB
-}
+ return value
+ },
+ defaultValue: 'transparent'
+ }
+])
/**
- * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262
- * @param {string} header
+ * @see https://www.w3.org/TR/FileAPI/#process-blob-parts
+ * @param {(NodeJS.TypedArray|Blob|string)[]} parts
+ * @param {{ type: string, endings: string }} options
*/
-function fieldValues (header) {
- assert(header !== null)
+function processBlobParts (parts, options) {
+ // 1. Let bytes be an empty sequence of bytes.
+ /** @type {NodeJS.TypedArray[]} */
+ const bytes = []
- const values = []
+ // 2. For each element in parts:
+ for (const element of parts) {
+ // 1. If element is a USVString, run the following substeps:
+ if (typeof element === 'string') {
+ // 1. Let s be element.
+ let s = element
- for (let value of header.split(',')) {
- value = value.trim()
+ // 2. If the endings member of options is "native", set s
+ // to the result of converting line endings to native
+ // of element.
+ if (options.endings === 'native') {
+ s = convertLineEndingsNative(s)
+ }
- if (!value.length) {
- continue
- } else if (!isValidHeaderName(value)) {
- continue
+ // 3. Append the result of UTF-8 encoding s to bytes.
+ bytes.push(encoder.encode(s))
+ } else if (
+ types.isAnyArrayBuffer(element) ||
+ types.isTypedArray(element)
+ ) {
+ // 2. If element is a BufferSource, get a copy of the
+ // bytes held by the buffer source, and append those
+ // bytes to bytes.
+ if (!element.buffer) { // ArrayBuffer
+ bytes.push(new Uint8Array(element))
+ } else {
+ bytes.push(
+ new Uint8Array(element.buffer, element.byteOffset, element.byteLength)
+ )
+ }
+ } else if (isBlobLike(element)) {
+ // 3. If element is a Blob, append the bytes it represents
+ // to bytes.
+ bytes.push(element)
}
-
- values.push(value)
}
- return values
-}
-
-module.exports = {
- urlEquals,
- fieldValues
+ // 3. Return bytes.
+ return bytes
}
+/**
+ * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native
+ * @param {string} s
+ */
+function convertLineEndingsNative (s) {
+ // 1. Let native line ending be be the code point U+000A LF.
+ let nativeLineEnding = '\n'
-/***/ }),
-
-/***/ 6197:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-// @ts-check
-
-
-
-/* global WebAssembly */
-
-const assert = __nccwpck_require__(2613)
-const net = __nccwpck_require__(9278)
-const http = __nccwpck_require__(8611)
-const { pipeline } = __nccwpck_require__(2203)
-const util = __nccwpck_require__(3440)
-const timers = __nccwpck_require__(8804)
-const Request = __nccwpck_require__(4655)
-const DispatcherBase = __nccwpck_require__(1)
-const {
- RequestContentLengthMismatchError,
- ResponseContentLengthMismatchError,
- InvalidArgumentError,
- RequestAbortedError,
- HeadersTimeoutError,
- HeadersOverflowError,
- SocketError,
- InformationalError,
- BodyTimeoutError,
- HTTPParserError,
- ResponseExceededMaxSizeError,
- ClientDestroyedError
-} = __nccwpck_require__(8707)
-const buildConnector = __nccwpck_require__(9136)
-const {
- kUrl,
- kReset,
- kServerName,
- kClient,
- kBusy,
- kParser,
- kConnect,
- kBlocking,
- kResuming,
- kRunning,
- kPending,
- kSize,
- kWriting,
- kQueue,
- kConnected,
- kConnecting,
- kNeedDrain,
- kNoRef,
- kKeepAliveDefaultTimeout,
- kHostHeader,
- kPendingIdx,
- kRunningIdx,
- kError,
- kPipelining,
- kSocket,
- kKeepAliveTimeoutValue,
- kMaxHeadersSize,
- kKeepAliveMaxTimeout,
- kKeepAliveTimeoutThreshold,
- kHeadersTimeout,
- kBodyTimeout,
- kStrictContentLength,
- kConnector,
- kMaxRedirections,
- kMaxRequests,
- kCounter,
- kClose,
- kDestroy,
- kDispatch,
- kInterceptors,
- kLocalAddress,
- kMaxResponseSize,
- kHTTPConnVersion,
- // HTTP2
- kHost,
- kHTTP2Session,
- kHTTP2SessionState,
- kHTTP2BuildRequest,
- kHTTP2CopyHeaders,
- kHTTP1BuildRequest
-} = __nccwpck_require__(6443)
-
-/** @type {import('http2')} */
-let http2
-try {
- http2 = __nccwpck_require__(5675)
-} 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
+ // 2. If the underlying platform’s conventions are to
+ // represent newlines as a carriage return and line feed
+ // sequence, set native line ending to the code point
+ // U+000D CR followed by the code point U+000A LF.
+ if (process.platform === 'win32') {
+ nativeLineEnding = '\r\n'
}
-} = http2
-
-// Experimental
-let h2ExperimentalWarned = false
-const FastBuffer = Buffer[Symbol.species]
-
-const kClosedResolve = Symbol('kClosedResolve')
-
-const channels = {}
-
-try {
- const diagnosticsChannel = __nccwpck_require__(1637)
- channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders')
- channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect')
- channels.connectError = diagnosticsChannel.channel('undici:client:connectError')
- channels.connected = diagnosticsChannel.channel('undici:client:connected')
-} catch {
- channels.sendHeaders = { hasSubscribers: false }
- channels.beforeConnect = { hasSubscribers: false }
- channels.connectError = { hasSubscribers: false }
- channels.connected = { hasSubscribers: false }
+ return s.replace(/\r?\n/g, nativeLineEnding)
}
-/**
- * @type {import('../types/client').default}
- */
-class Client extends DispatcherBase {
- /**
- *
- * @param {string|URL} url
- * @param {import('../types/client').Client.Options} options
- */
- constructor (url, {
- interceptors,
- maxHeaderSize,
- headersTimeout,
- socketTimeout,
- requestTimeout,
- connectTimeout,
- bodyTimeout,
- idleTimeout,
- keepAlive,
- keepAliveTimeout,
- maxKeepAliveTimeout,
- keepAliveMaxTimeout,
- keepAliveTimeoutThreshold,
- socketPath,
- pipelining,
- tls,
- strictContentLength,
- maxCachedSessions,
- maxRedirections,
- connect,
- maxRequestsPerClient,
- localAddress,
- maxResponseSize,
- autoSelectFamily,
- autoSelectFamilyAttemptTimeout,
- // h2
- allowH2,
- maxConcurrentStreams
- } = {}) {
- super()
+// If this function is moved to ./util.js, some tools (such as
+// rollup) will warn about circular dependencies. See:
+// https://github.com/nodejs/undici/issues/1629
+function isFileLike (object) {
+ return (
+ (NativeFile && object instanceof NativeFile) ||
+ object instanceof File || (
+ object &&
+ (typeof object.stream === 'function' ||
+ typeof object.arrayBuffer === 'function') &&
+ object[Symbol.toStringTag] === 'File'
+ )
+ )
+}
- if (keepAlive !== undefined) {
- throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead')
- }
+module.exports = { File, FileLike, isFileLike }
- 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')
- }
+/***/ 43073:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (maxKeepAliveTimeout !== undefined) {
- throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead')
- }
+"use strict";
- if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) {
- throw new InvalidArgumentError('invalid maxHeaderSize')
- }
- if (socketPath != null && typeof socketPath !== 'string') {
- throw new InvalidArgumentError('invalid socketPath')
- }
+const { isBlobLike, toUSVString, makeIterator } = __nccwpck_require__(15523)
+const { kState } = __nccwpck_require__(89710)
+const { File: UndiciFile, FileLike, isFileLike } = __nccwpck_require__(63041)
+const { webidl } = __nccwpck_require__(74222)
+const { Blob, File: NativeFile } = __nccwpck_require__(20181)
- if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {
- throw new InvalidArgumentError('invalid connectTimeout')
- }
+/** @type {globalThis['File']} */
+const File = NativeFile ?? UndiciFile
- if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {
- throw new InvalidArgumentError('invalid keepAliveTimeout')
+// https://xhr.spec.whatwg.org/#formdata
+class FormData {
+ constructor (form) {
+ if (form !== undefined) {
+ throw webidl.errors.conversionFailed({
+ prefix: 'FormData constructor',
+ argument: 'Argument 1',
+ types: ['undefined']
+ })
}
- if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {
- throw new InvalidArgumentError('invalid keepAliveMaxTimeout')
- }
+ this[kState] = []
+ }
- if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {
- throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold')
- }
+ append (name, value, filename = undefined) {
+ webidl.brandCheck(this, FormData)
- if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {
- throw new InvalidArgumentError('headersTimeout must be a positive integer or zero')
- }
+ webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' })
- if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {
- throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero')
+ if (arguments.length === 3 && !isBlobLike(value)) {
+ throw new TypeError(
+ "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'"
+ )
}
- if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
- throw new InvalidArgumentError('connect must be a function or an object')
- }
+ // 1. Let value be value if given; otherwise blobValue.
- if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
- throw new InvalidArgumentError('maxRedirections must be a positive number')
- }
+ name = webidl.converters.USVString(name)
+ value = isBlobLike(value)
+ ? webidl.converters.Blob(value, { strict: false })
+ : webidl.converters.USVString(value)
+ filename = arguments.length === 3
+ ? webidl.converters.USVString(filename)
+ : undefined
- if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
- throw new InvalidArgumentError('maxRequestsPerClient must be a positive number')
- }
+ // 2. Let entry be the result of creating an entry with
+ // name, value, and filename if given.
+ const entry = makeEntry(name, value, filename)
- if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) {
- throw new InvalidArgumentError('localAddress must be valid string IP address')
- }
+ // 3. Append entry to this’s entry list.
+ this[kState].push(entry)
+ }
- if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
- throw new InvalidArgumentError('maxResponseSize must be a positive number')
- }
+ delete (name) {
+ webidl.brandCheck(this, FormData)
- if (
- autoSelectFamilyAttemptTimeout != null &&
- (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)
- ) {
- throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number')
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' })
- // h2
- if (allowH2 != null && typeof allowH2 !== 'boolean') {
- throw new InvalidArgumentError('allowH2 must be a valid boolean value')
- }
+ name = webidl.converters.USVString(name)
- if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) {
- throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0')
- }
+ // The delete(name) method steps are to remove all entries whose name
+ // is name from this’s entry list.
+ this[kState] = this[kState].filter(entry => entry.name !== name)
+ }
- if (typeof connect !== 'function') {
- connect = buildConnector({
- ...tls,
- maxCachedSessions,
- allowH2,
- socketPath,
- timeout: connectTimeout,
- ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
- ...connect
- })
- }
+ get (name) {
+ webidl.brandCheck(this, FormData)
- this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client)
- ? interceptors.Client
- : [createRedirectInterceptor({ maxRedirections })]
- this[kUrl] = util.parseOrigin(url)
- this[kConnector] = connect
- this[kSocket] = null
- this[kPipelining] = pipelining != null ? pipelining : 1
- this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize
- this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout
- this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout
- this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : 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[kMaxRedirections] = maxRedirections
- this[kMaxRequests] = maxRequestsPerClient
- this[kClosedResolve] = null
- this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1
- this[kHTTPConnVersion] = 'h1'
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' })
- // HTTP/2
- this[kHTTP2Session] = null
- this[kHTTP2SessionState] = !allowH2
- ? null
- : {
- // streams: null, // Fixed queue of streams - For future support of `push`
- openStreams: 0, // Keep track of them to decide wether or not unref the session
- maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server
- }
- this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}`
+ name = webidl.converters.USVString(name)
- // 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).
+ // 1. If there is no entry whose name is name in this’s entry list,
+ // then return null.
+ const idx = this[kState].findIndex((entry) => entry.name === name)
+ if (idx === -1) {
+ return null
+ }
- this[kQueue] = []
- this[kRunningIdx] = 0
- this[kPendingIdx] = 0
+ // 2. Return the value of the first entry whose name is name from
+ // this’s entry list.
+ return this[kState][idx].value
}
- get pipelining () {
- return this[kPipelining]
- }
+ getAll (name) {
+ webidl.brandCheck(this, FormData)
- set pipelining (value) {
- this[kPipelining] = value
- resume(this, true)
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' })
- get [kPending] () {
- return this[kQueue].length - this[kPendingIdx]
- }
+ name = webidl.converters.USVString(name)
- get [kRunning] () {
- return this[kPendingIdx] - this[kRunningIdx]
+ // 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[kState]
+ .filter((entry) => entry.name === name)
+ .map((entry) => entry.value)
}
- get [kSize] () {
- return this[kQueue].length - this[kRunningIdx]
- }
+ has (name) {
+ webidl.brandCheck(this, FormData)
- get [kConnected] () {
- return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' })
- get [kBusy] () {
- const socket = this[kSocket]
- return (
- (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) ||
- (this[kSize] >= (this[kPipelining] || 1)) ||
- this[kPending] > 0
- )
- }
+ name = webidl.converters.USVString(name)
- /* istanbul ignore: only used for test */
- [kConnect] (cb) {
- connect(this)
- this.once('connect', cb)
+ // 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[kState].findIndex((entry) => entry.name === name) !== -1
}
- [kDispatch] (opts, handler) {
- const origin = opts.origin || this[kUrl].origin
-
- const request = this[kHTTPConnVersion] === 'h2'
- ? Request[kHTTP2BuildRequest](origin, opts, handler)
- : Request[kHTTP1BuildRequest](origin, opts, handler)
+ set (name, value, filename = undefined) {
+ webidl.brandCheck(this, FormData)
- 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
- process.nextTick(resume, this)
- } else {
- resume(this, true)
- }
+ webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' })
- if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
- this[kNeedDrain] = 2
+ if (arguments.length === 3 && !isBlobLike(value)) {
+ throw new TypeError(
+ "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'"
+ )
}
- return this[kNeedDrain] < 2
- }
+ // The set(name, value) and set(name, blobValue, filename) method steps
+ // are:
- 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]) {
- resolve(null)
- } else {
- this[kClosedResolve] = resolve
- }
- })
- }
+ // 1. Let value be value if given; otherwise blobValue.
- 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]
- errorRequest(this, request, err)
- }
+ name = webidl.converters.USVString(name)
+ value = isBlobLike(value)
+ ? webidl.converters.Blob(value, { strict: false })
+ : webidl.converters.USVString(value)
+ filename = arguments.length === 3
+ ? toUSVString(filename)
+ : undefined
- const callback = () => {
- if (this[kClosedResolve]) {
- // TODO (fix): Should we error here with ClientDestroyedError?
- this[kClosedResolve]()
- this[kClosedResolve] = null
- }
- resolve()
- }
+ // 2. Let entry be the result of creating an entry with name, value, and
+ // filename if given.
+ const entry = makeEntry(name, value, filename)
- if (this[kHTTP2Session] != null) {
- util.destroy(this[kHTTP2Session], err)
- this[kHTTP2Session] = null
- this[kHTTP2SessionState] = null
- }
+ // 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[kState].findIndex((entry) => entry.name === name)
+ if (idx !== -1) {
+ this[kState] = [
+ ...this[kState].slice(0, idx),
+ entry,
+ ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name)
+ ]
+ } else {
+ // 4. Otherwise, append entry to this’s entry list.
+ this[kState].push(entry)
+ }
+ }
- if (!this[kSocket]) {
- queueMicrotask(callback)
- } else {
- util.destroy(this[kSocket].on('close', callback), err)
- }
+ entries () {
+ webidl.brandCheck(this, FormData)
- resume(this)
- })
+ return makeIterator(
+ () => this[kState].map(pair => [pair.name, pair.value]),
+ 'FormData',
+ 'key+value'
+ )
}
-}
-function onHttp2SessionError (err) {
- assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
-
- this[kSocket][kError] = err
+ keys () {
+ webidl.brandCheck(this, FormData)
- onError(this[kClient], err)
-}
+ return makeIterator(
+ () => this[kState].map(pair => [pair.name, pair.value]),
+ 'FormData',
+ 'key'
+ )
+ }
-function onHttp2FrameError (type, code, id) {
- const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
+ values () {
+ webidl.brandCheck(this, FormData)
- if (id === 0) {
- this[kSocket][kError] = err
- onError(this[kClient], err)
+ return makeIterator(
+ () => this[kState].map(pair => [pair.name, pair.value]),
+ 'FormData',
+ 'value'
+ )
}
-}
-function onHttp2SessionEnd () {
- util.destroy(this, new SocketError('other side closed'))
- util.destroy(this[kSocket], new SocketError('other side closed'))
-}
+ /**
+ * @param {(value: string, key: string, self: FormData) => void} callbackFn
+ * @param {unknown} thisArg
+ */
+ forEach (callbackFn, thisArg = globalThis) {
+ webidl.brandCheck(this, FormData)
-function onHTTP2GoAway (code) {
- const client = this[kClient]
- const err = new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${code}`)
- client[kSocket] = null
- client[kHTTP2Session] = null
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' })
- if (client.destroyed) {
- assert(this[kPending] === 0)
+ if (typeof callbackFn !== 'function') {
+ throw new TypeError(
+ "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'."
+ )
+ }
- // Fail entire queue.
- const requests = client[kQueue].splice(client[kRunningIdx])
- for (let i = 0; i < requests.length; i++) {
- const request = requests[i]
- errorRequest(this, request, err)
+ for (const [key, value] of this) {
+ callbackFn.apply(thisArg, [value, key, this])
}
- } else if (client[kRunning] > 0) {
- // Fail head of pipeline.
- const request = client[kQueue][client[kRunningIdx]]
- client[kQueue][client[kRunningIdx]++] = null
+ }
+}
- errorRequest(client, request, err)
+FormData.prototype[Symbol.iterator] = FormData.prototype.entries
+
+Object.defineProperties(FormData.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'FormData',
+ configurable: true
}
+})
- client[kPendingIdx] = client[kRunningIdx]
+/**
+ * @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.
+ // "To convert a string into a scalar value string, replace any surrogates
+ // with U+FFFD."
+ // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end
+ name = Buffer.from(name).toString('utf8')
- assert(client[kRunning] === 0)
+ // 2. If value is a string, then set value to the result of converting
+ // value into a scalar value string.
+ if (typeof value === 'string') {
+ value = Buffer.from(value).toString('utf8')
+ } else {
+ // 3. Otherwise:
- client.emit('disconnect',
- client[kUrl],
- [client],
- err
- )
+ // 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 (!isFileLike(value)) {
+ value = value instanceof Blob
+ ? new File([value], 'blob', { type: value.type })
+ : new FileLike(value, 'blob', { type: value.type })
+ }
- resume(client)
+ // 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 = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile
+ ? new File([value], filename, options)
+ : new FileLike(value, filename, options)
+ }
+ }
+
+ // 4. Return an entry whose name is name and whose value is value.
+ return { name, value }
}
-const constants = __nccwpck_require__(2824)
-const createRedirectInterceptor = __nccwpck_require__(4415)
-const EMPTY_BUF = Buffer.alloc(0)
+module.exports = { FormData }
-async function lazyllhttp () {
- const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(3870) : undefined
- let mod
- try {
- mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(3434), 'base64'))
- } 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 = await WebAssembly.compile(Buffer.from(llhttpWasmData || __nccwpck_require__(3870), 'base64'))
- }
+/***/ 75628:
+/***/ ((module) => {
- return await WebAssembly.instantiate(mod, {
- env: {
- /* eslint-disable camelcase */
+"use strict";
- wasm_on_url: (p, at, len) => {
- /* istanbul ignore next */
- return 0
- },
- wasm_on_status: (p, at, len) => {
- assert.strictEqual(currentParser.ptr, p)
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
- return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
- },
- wasm_on_message_begin: (p) => {
- assert.strictEqual(currentParser.ptr, p)
- return currentParser.onMessageBegin() || 0
- },
- wasm_on_header_field: (p, at, len) => {
- assert.strictEqual(currentParser.ptr, p)
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
- return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
- },
- wasm_on_header_value: (p, at, len) => {
- assert.strictEqual(currentParser.ptr, p)
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
- return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
- },
- wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {
- assert.strictEqual(currentParser.ptr, p)
- return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0
- },
- wasm_on_body: (p, at, len) => {
- assert.strictEqual(currentParser.ptr, p)
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
- return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
- },
- wasm_on_message_complete: (p) => {
- assert.strictEqual(currentParser.ptr, p)
- return currentParser.onMessageComplete() || 0
- }
- /* eslint-enable camelcase */
- }
+// 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
})
}
-let llhttpInstance = null
-let llhttpPromise = lazyllhttp()
-llhttpPromise.catch()
+module.exports = {
+ getGlobalOrigin,
+ setGlobalOrigin
+}
-let currentParser = null
-let currentBufferRef = null
-let currentBufferSize = 0
-let currentBufferPtr = null
-const TIMEOUT_HEADERS = 1
-const TIMEOUT_BODY = 2
-const TIMEOUT_IDLE = 3
+/***/ }),
-class Parser {
- constructor (client, socket, { exports }) {
- assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0)
+/***/ 26349:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- this.llhttp = exports
- this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)
- this.client = client
- this.socket = socket
- this.timeout = null
- this.timeoutValue = null
- this.timeoutType = null
- this.statusCode = null
- 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)
+"use strict";
+// https://github.com/Ethan-Arrowood/undici-fetch
- this.bytesRead = 0
- this.keepAlive = ''
- this.contentLength = ''
- this.connection = ''
- this.maxResponseSize = client[kMaxResponseSize]
- }
- setTimeout (value, type) {
- this.timeoutType = type
- if (value !== this.timeoutValue) {
- timers.clearTimeout(this.timeout)
- if (value) {
- this.timeout = timers.setTimeout(onParserTimeout, value, this)
- // istanbul ignore else: only for jest
- if (this.timeout.unref) {
- this.timeout.unref()
- }
- } else {
- this.timeout = null
- }
- this.timeoutValue = value
- } else if (this.timeout) {
- // istanbul ignore else: only for jest
- if (this.timeout.refresh) {
- this.timeout.refresh()
- }
- }
- }
+const { kHeadersList, kConstruct } = __nccwpck_require__(36443)
+const { kGuard } = __nccwpck_require__(89710)
+const { kEnumerableProperty } = __nccwpck_require__(3440)
+const {
+ makeIterator,
+ isValidHeaderName,
+ isValidHeaderValue
+} = __nccwpck_require__(15523)
+const util = __nccwpck_require__(39023)
+const { webidl } = __nccwpck_require__(74222)
+const assert = __nccwpck_require__(42613)
- resume () {
- if (this.socket.destroyed || !this.paused) {
- return
- }
+const kHeadersMap = Symbol('headers map')
+const kHeadersSortedMap = Symbol('headers map sorted')
- assert(this.ptr != null)
- assert(currentParser == null)
+/**
+ * @param {number} code
+ */
+function isHTTPWhiteSpaceCharCode (code) {
+ return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020
+}
- this.llhttp.llhttp_resume(this.ptr)
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize
+ * @param {string} potentialValue
+ */
+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
- assert(this.timeoutType === TIMEOUT_BODY)
- if (this.timeout) {
- // istanbul ignore else: only for jest
- if (this.timeout.refresh) {
- this.timeout.refresh()
- }
- }
+ while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j
+ while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i
- this.paused = false
- this.execute(this.socket.read() || EMPTY_BUF) // Flush parser.
- this.readMore()
- }
+ return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j)
+}
- readMore () {
- while (!this.paused && this.ptr) {
- const chunk = this.socket.read()
- if (chunk === null) {
- break
+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}.`
+ })
}
- this.execute(chunk)
+
+ // 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']
+ })
}
+}
- execute (data) {
- assert(this.ptr != null)
- assert(currentParser == null)
- assert(!this.paused)
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-headers-append
+ */
+function appendHeader (headers, name, value) {
+ // 1. Normalize value.
+ value = headerValueNormalize(value)
- const { socket, llhttp } = this
+ // 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'
+ })
+ }
- if (data.length > currentBufferSize) {
- if (currentBufferPtr) {
- llhttp.free(currentBufferPtr)
- }
- currentBufferSize = Math.ceil(data.length / 4096) * 4096
- currentBufferPtr = llhttp.malloc(currentBufferSize)
- }
+ // 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.
+ // Note: undici does not implement forbidden header names
+ if (headers[kGuard] === 'immutable') {
+ throw new TypeError('immutable')
+ } else if (headers[kGuard] === 'request-no-cors') {
+ // 5. Otherwise, if headers’s guard is "request-no-cors":
+ // TODO
+ }
- new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data)
+ // 6. Otherwise, if headers’s guard is "response" and name is a
+ // forbidden response-header name, return.
- // 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
+ // 7. Append (name, value) to headers’s header list.
+ return headers[kHeadersList].append(name, value)
- try {
- currentBufferRef = data
- currentParser = this
- ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.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
- }
+ // 8. If headers’s guard is "request-no-cors", then remove
+ // privileged no-CORS request headers from headers
+}
- const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr
+class HeadersList {
+ /** @type {[string, string][]|null} */
+ cookies = null
- if (ret === constants.ERROR.PAUSED_UPGRADE) {
- this.onUpgrade(data.slice(offset))
- } else if (ret === constants.ERROR.PAUSED) {
- this.paused = true
- socket.unshift(data.slice(offset))
- } else if (ret !== constants.ERROR.OK) {
- 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.slice(offset))
- }
- } catch (err) {
- util.destroy(socket, err)
+ constructor (init) {
+ if (init instanceof HeadersList) {
+ this[kHeadersMap] = new Map(init[kHeadersMap])
+ this[kHeadersSortedMap] = init[kHeadersSortedMap]
+ this.cookies = init.cookies === null ? null : [...init.cookies]
+ } else {
+ this[kHeadersMap] = new Map(init)
+ this[kHeadersSortedMap] = null
}
}
- destroy () {
- assert(this.ptr != null)
- assert(currentParser == null)
-
- this.llhttp.llhttp_free(this.ptr)
- this.ptr = null
-
- timers.clearTimeout(this.timeout)
- this.timeout = null
- this.timeoutValue = null
- this.timeoutType = null
+ // https://fetch.spec.whatwg.org/#header-list-contains
+ contains (name) {
+ // A header list list contains a header name name if list
+ // contains a header whose name is a byte-case-insensitive
+ // match for name.
+ name = name.toLowerCase()
- this.paused = false
+ return this[kHeadersMap].has(name)
}
- onStatus (buf) {
- this.statusText = buf.toString()
+ clear () {
+ this[kHeadersMap].clear()
+ this[kHeadersSortedMap] = null
+ this.cookies = null
}
- onMessageBegin () {
- const { socket, client } = this
+ // https://fetch.spec.whatwg.org/#concept-header-list-append
+ append (name, value) {
+ this[kHeadersSortedMap] = null
- /* istanbul ignore next: difficult to make a test case for */
- if (socket.destroyed) {
- return -1
+ // 1. If list contains name, then set name to the first such
+ // header’s name.
+ const lowercaseName = name.toLowerCase()
+ const exists = this[kHeadersMap].get(lowercaseName)
+
+ // 2. Append (name, value) to list.
+ if (exists) {
+ const delimiter = lowercaseName === 'cookie' ? '; ' : ', '
+ this[kHeadersMap].set(lowercaseName, {
+ name: exists.name,
+ value: `${exists.value}${delimiter}${value}`
+ })
+ } else {
+ this[kHeadersMap].set(lowercaseName, { name, value })
}
- const request = client[kQueue][client[kRunningIdx]]
- if (!request) {
- return -1
+ if (lowercaseName === 'set-cookie') {
+ this.cookies ??= []
+ this.cookies.push(value)
}
}
- onHeaderField (buf) {
- const len = this.headers.length
+ // https://fetch.spec.whatwg.org/#concept-header-list-set
+ set (name, value) {
+ this[kHeadersSortedMap] = null
+ const lowercaseName = name.toLowerCase()
- if ((len & 1) === 0) {
- this.headers.push(buf)
- } else {
- this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
+ if (lowercaseName === 'set-cookie') {
+ this.cookies = [value]
}
- this.trackHeader(buf.length)
+ // 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[kHeadersMap].set(lowercaseName, { name, value })
}
- onHeaderValue (buf) {
- let len = this.headers.length
+ // https://fetch.spec.whatwg.org/#concept-header-list-delete
+ delete (name) {
+ this[kHeadersSortedMap] = null
- if ((len & 1) === 1) {
- this.headers.push(buf)
- len += 1
- } else {
- this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
- }
+ name = name.toLowerCase()
- const key = this.headers[len - 2]
- if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') {
- this.keepAlive += buf.toString()
- } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') {
- this.connection += buf.toString()
- } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') {
- this.contentLength += buf.toString()
+ if (name === 'set-cookie') {
+ this.cookies = null
}
- this.trackHeader(buf.length)
+ this[kHeadersMap].delete(name)
}
- trackHeader (len) {
- this.headersSize += len
- if (this.headersSize >= this.headersMaxSize) {
- util.destroy(this.socket, new HeadersOverflowError())
- }
+ // https://fetch.spec.whatwg.org/#concept-header-list-get
+ get (name) {
+ const value = this[kHeadersMap].get(name.toLowerCase())
+
+ // 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 value === undefined ? null : value.value
}
- onUpgrade (head) {
- const { upgrade, client, socket, headers, statusCode } = this
+ * [Symbol.iterator] () {
+ // use the lowercased name
+ for (const [name, { value }] of this[kHeadersMap]) {
+ yield [name, value]
+ }
+ }
- assert(upgrade)
+ get entries () {
+ const headers = {}
- const request = client[kQueue][client[kRunningIdx]]
- assert(request)
+ if (this[kHeadersMap].size) {
+ for (const { name, value } of this[kHeadersMap].values()) {
+ headers[name] = value
+ }
+ }
- assert(!socket.destroyed)
- assert(socket === client[kSocket])
- assert(!this.paused)
- assert(request.upgrade || request.method === 'CONNECT')
+ return headers
+ }
+}
- this.statusCode = null
- this.statusText = ''
- this.shouldKeepAlive = null
+// https://fetch.spec.whatwg.org/#headers-class
+class Headers {
+ constructor (init = undefined) {
+ if (init === kConstruct) {
+ return
+ }
+ this[kHeadersList] = new HeadersList()
- assert(this.headers.length % 2 === 0)
- this.headers = []
- this.headersSize = 0
+ // The new Headers(init) constructor steps are:
- socket.unshift(head)
+ // 1. Set this’s guard to "none".
+ this[kGuard] = 'none'
- socket[kParser].destroy()
- socket[kParser] = null
+ // 2. If init is given, then fill this with init.
+ if (init !== undefined) {
+ init = webidl.converters.HeadersInit(init)
+ fill(this, init)
+ }
+ }
- socket[kClient] = null
- socket[kError] = null
- socket
- .removeListener('error', onSocketError)
- .removeListener('readable', onSocketReadable)
- .removeListener('end', onSocketEnd)
- .removeListener('close', onSocketClose)
+ // https://fetch.spec.whatwg.org/#dom-headers-append
+ append (name, value) {
+ webidl.brandCheck(this, Headers)
- client[kSocket] = null
- client[kQueue][client[kRunningIdx]++] = null
- client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))
+ webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' })
- try {
- request.onUpgrade(statusCode, headers, socket)
- } catch (err) {
- util.destroy(socket, err)
- }
+ name = webidl.converters.ByteString(name)
+ value = webidl.converters.ByteString(value)
- resume(client)
+ return appendHeader(this, name, value)
}
- onHeadersComplete (statusCode, upgrade, shouldKeepAlive) {
- const { client, socket, headers, statusText } = this
+ // https://fetch.spec.whatwg.org/#dom-headers-delete
+ delete (name) {
+ webidl.brandCheck(this, Headers)
- /* istanbul ignore next: difficult to make a test case for */
- if (socket.destroyed) {
- return -1
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' })
- const request = client[kQueue][client[kRunningIdx]]
+ name = webidl.converters.ByteString(name)
- /* istanbul ignore next: difficult to make a test case for */
- if (!request) {
- return -1
+ // 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'
+ })
}
- assert(!this.upgrade)
- assert(this.statusCode < 200)
-
- if (statusCode === 100) {
- util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
- return -1
+ // 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[kGuard] === 'immutable') {
+ throw new TypeError('immutable')
+ } else if (this[kGuard] === 'request-no-cors') {
+ // TODO
}
- /* this can only happen if server is misbehaving */
- if (upgrade && !request.upgrade) {
- util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket)))
- return -1
+ // 6. If this’s header list does not contain name, then
+ // return.
+ if (!this[kHeadersList].contains(name)) {
+ return
}
- assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS)
+ // 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[kHeadersList].delete(name)
+ }
- 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')
- )
+ // https://fetch.spec.whatwg.org/#dom-headers-get
+ get (name) {
+ webidl.brandCheck(this, Headers)
- 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()
- }
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' })
- if (request.method === 'CONNECT') {
- assert(client[kRunning] === 1)
- this.upgrade = true
- return 2
- }
+ name = webidl.converters.ByteString(name)
- if (upgrade) {
- assert(client[kRunning] === 1)
- this.upgrade = true
- return 2
+ // 1. If name is not a header name, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.get',
+ value: name,
+ type: 'header name'
+ })
}
- assert(this.headers.length % 2 === 0)
- this.headers = []
- this.headersSize = 0
+ // 2. Return the result of getting name from this’s header
+ // list.
+ return this[kHeadersList].get(name)
+ }
- if (this.shouldKeepAlive && client[kPipelining]) {
- const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null
+ // https://fetch.spec.whatwg.org/#dom-headers-has
+ has (name) {
+ webidl.brandCheck(this, Headers)
- 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
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' })
- const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false
+ name = webidl.converters.ByteString(name)
- if (request.aborted) {
- return -1
+ // 1. If name is not a header name, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.has',
+ value: name,
+ type: 'header name'
+ })
}
- if (request.method === 'HEAD') {
- return 1
- }
+ // 2. Return true if this’s header list contains name;
+ // otherwise false.
+ return this[kHeadersList].contains(name)
+ }
- if (statusCode < 200) {
- return 1
- }
+ // https://fetch.spec.whatwg.org/#dom-headers-set
+ set (name, value) {
+ webidl.brandCheck(this, Headers)
- if (socket[kBlocking]) {
- socket[kBlocking] = false
- resume(client)
- }
+ webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' })
- return pause ? constants.ERROR.PAUSED : 0
- }
+ name = webidl.converters.ByteString(name)
+ value = webidl.converters.ByteString(value)
- onBody (buf) {
- const { client, socket, statusCode, maxResponseSize } = this
+ // 1. Normalize value.
+ value = headerValueNormalize(value)
- if (socket.destroyed) {
- return -1
+ // 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.set',
+ value: name,
+ type: 'header name'
+ })
+ } else if (!isValidHeaderValue(value)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.set',
+ value,
+ type: 'header value'
+ })
}
- const request = client[kQueue][client[kRunningIdx]]
- assert(request)
-
- assert.strictEqual(this.timeoutType, TIMEOUT_BODY)
- if (this.timeout) {
- // istanbul ignore else: only for jest
- if (this.timeout.refresh) {
- this.timeout.refresh()
- }
+ // 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[kGuard] === 'immutable') {
+ throw new TypeError('immutable')
+ } else if (this[kGuard] === 'request-no-cors') {
+ // TODO
}
- assert(statusCode >= 200)
+ // 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[kHeadersList].set(name, value)
+ }
- if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
- util.destroy(socket, new ResponseExceededMaxSizeError())
- return -1
- }
+ // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie
+ getSetCookie () {
+ webidl.brandCheck(this, Headers)
- this.bytesRead += buf.length
+ // 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.
- if (request.onData(buf) === false) {
- return constants.ERROR.PAUSED
+ const list = this[kHeadersList].cookies
+
+ if (list) {
+ return [...list]
}
- }
- onMessageComplete () {
- const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this
+ return []
+ }
- if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
- return -1
+ // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
+ get [kHeadersSortedMap] () {
+ if (this[kHeadersList][kHeadersSortedMap]) {
+ return this[kHeadersList][kHeadersSortedMap]
}
- if (upgrade) {
- return
- }
+ // 1. Let headers be an empty list of headers with the key being the name
+ // and value the value.
+ const headers = []
- const request = client[kQueue][client[kRunningIdx]]
- assert(request)
+ // 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 = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1)
+ const cookies = this[kHeadersList].cookies
- assert(statusCode >= 100)
+ // 3. For each name of names:
+ for (let i = 0; i < names.length; ++i) {
+ const [name, 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.
- this.statusCode = null
- this.statusText = ''
- this.bytesRead = 0
- this.contentLength = ''
- this.keepAlive = ''
- this.connection = ''
+ // 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:
- assert(this.headers.length % 2 === 0)
- this.headers = []
- this.headersSize = 0
+ // 1. Let value be the result of getting name from list.
- if (statusCode < 200) {
- return
- }
+ // 2. Assert: value is non-null.
+ assert(value !== null)
- /* istanbul ignore next: should be handled by llhttp? */
- if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) {
- util.destroy(socket, new ResponseContentLengthMismatchError())
- return -1
+ // 3. Append (name, value) to headers.
+ headers.push([name, value])
+ }
}
- request.onComplete(headers)
+ this[kHeadersList][kHeadersSortedMap] = headers
- client[kQueue][client[kRunningIdx]++] = null
+ // 4. Return headers.
+ return headers
+ }
- if (socket[kWriting]) {
- assert.strictEqual(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] === 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(resume, client)
- } else {
- resume(client)
+ keys () {
+ webidl.brandCheck(this, Headers)
+
+ if (this[kGuard] === 'immutable') {
+ const value = this[kHeadersSortedMap]
+ return makeIterator(() => value, 'Headers',
+ 'key')
}
+
+ return makeIterator(
+ () => [...this[kHeadersSortedMap].values()],
+ 'Headers',
+ 'key'
+ )
}
-}
-function onParserTimeout (parser) {
- const { socket, timeoutType, client } = parser
+ values () {
+ webidl.brandCheck(this, Headers)
- /* istanbul ignore else */
- if (timeoutType === TIMEOUT_HEADERS) {
- if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
- assert(!parser.paused, 'cannot be paused while waiting for headers')
- util.destroy(socket, new HeadersTimeoutError())
- }
- } else if (timeoutType === TIMEOUT_BODY) {
- if (!parser.paused) {
- util.destroy(socket, new BodyTimeoutError())
+ if (this[kGuard] === 'immutable') {
+ const value = this[kHeadersSortedMap]
+ return makeIterator(() => value, 'Headers',
+ 'value')
}
- } else if (timeoutType === TIMEOUT_IDLE) {
- assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue])
- util.destroy(socket, new InformationalError('socket idle timeout'))
- }
-}
-function onSocketReadable () {
- const { [kParser]: parser } = this
- if (parser) {
- parser.readMore()
+ return makeIterator(
+ () => [...this[kHeadersSortedMap].values()],
+ 'Headers',
+ 'value'
+ )
}
-}
-
-function onSocketError (err) {
- const { [kClient]: client, [kParser]: parser } = this
- assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
+ entries () {
+ webidl.brandCheck(this, Headers)
- if (client[kHTTPConnVersion] !== 'h2') {
- // 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
+ if (this[kGuard] === 'immutable') {
+ const value = this[kHeadersSortedMap]
+ return makeIterator(() => value, 'Headers',
+ 'key+value')
}
- }
- this[kError] = err
+ return makeIterator(
+ () => [...this[kHeadersSortedMap].values()],
+ 'Headers',
+ 'key+value'
+ )
+ }
- onError(this[kClient], err)
-}
+ /**
+ * @param {(value: string, key: string, self: Headers) => void} callbackFn
+ * @param {unknown} thisArg
+ */
+ forEach (callbackFn, thisArg = globalThis) {
+ webidl.brandCheck(this, Headers)
-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.
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' })
- assert(client[kPendingIdx] === client[kRunningIdx])
+ if (typeof callbackFn !== 'function') {
+ throw new TypeError(
+ "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'."
+ )
+ }
- const requests = client[kQueue].splice(client[kRunningIdx])
- for (let i = 0; i < requests.length; i++) {
- const request = requests[i]
- errorRequest(client, request, err)
+ for (const [key, value] of this) {
+ callbackFn.apply(thisArg, [value, key, this])
}
- assert(client[kSize] === 0)
}
-}
-function onSocketEnd () {
- const { [kParser]: parser, [kClient]: client } = this
+ [Symbol.for('nodejs.util.inspect.custom')] () {
+ webidl.brandCheck(this, Headers)
- if (client[kHTTPConnVersion] !== 'h2') {
- if (parser.statusCode && !parser.shouldKeepAlive) {
- // We treat all incoming data so far as a valid response.
- parser.onMessageComplete()
- return
- }
+ return this[kHeadersList]
}
-
- util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
}
-function onSocketClose () {
- const { [kClient]: client, [kParser]: parser } = this
-
- if (client[kHTTPConnVersion] === 'h1' && parser) {
- if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
- // We treat all incoming data so far as a valid response.
- parser.onMessageComplete()
- }
+Headers.prototype[Symbol.iterator] = Headers.prototype.entries
- this[kParser].destroy()
- this[kParser] = null
+Object.defineProperties(Headers.prototype, {
+ append: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ get: kEnumerableProperty,
+ has: kEnumerableProperty,
+ set: kEnumerableProperty,
+ getSetCookie: kEnumerableProperty,
+ keys: kEnumerableProperty,
+ values: kEnumerableProperty,
+ entries: kEnumerableProperty,
+ forEach: kEnumerableProperty,
+ [Symbol.iterator]: { enumerable: false },
+ [Symbol.toStringTag]: {
+ value: 'Headers',
+ configurable: true
+ },
+ [util.inspect.custom]: {
+ enumerable: false
}
+})
- const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
+webidl.converters.HeadersInit = function (V) {
+ if (webidl.util.Type(V) === 'Object') {
+ if (V[Symbol.iterator]) {
+ return webidl.converters['sequence>'](V)
+ }
- client[kSocket] = null
+ return webidl.converters['record'](V)
+ }
- if (client.destroyed) {
- assert(client[kPending] === 0)
+ throw webidl.errors.conversionFailed({
+ prefix: 'Headers constructor',
+ argument: 'Argument 1',
+ types: ['sequence>', 'record']
+ })
+}
- // Fail entire queue.
- const requests = client[kQueue].splice(client[kRunningIdx])
- for (let i = 0; i < requests.length; i++) {
- const request = requests[i]
- 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
+module.exports = {
+ fill,
+ Headers,
+ HeadersList
+}
- errorRequest(client, request, err)
- }
- client[kPendingIdx] = client[kRunningIdx]
+/***/ }),
- assert(client[kRunning] === 0)
+/***/ 12315:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- client.emit('disconnect', client[kUrl], [client], err)
+"use strict";
+// https://github.com/Ethan-Arrowood/undici-fetch
- resume(client)
-}
-async function connect (client) {
- assert(!client[kConnecting])
- assert(!client[kSocket])
- let { host, hostname, protocol, port } = client[kUrl]
+const {
+ Response,
+ makeNetworkError,
+ makeAppropriateNetworkError,
+ filterResponse,
+ makeResponse
+} = __nccwpck_require__(48676)
+const { Headers } = __nccwpck_require__(26349)
+const { Request, makeRequest } = __nccwpck_require__(25194)
+const zlib = __nccwpck_require__(43106)
+const {
+ bytesMatch,
+ makePolicyContainer,
+ clonePolicyContainer,
+ requestBadPort,
+ TAOCheck,
+ appendRequestOriginHeader,
+ responseLocationURL,
+ requestCurrentURL,
+ setRequestReferrerPolicyOnRedirect,
+ tryUpgradeRequestToAPotentiallyTrustworthyURL,
+ createOpaqueTimingInfo,
+ appendFetchMetadata,
+ corsCheck,
+ crossOriginResourcePolicyCheck,
+ determineRequestsReferrer,
+ coarsenedSharedCurrentTime,
+ createDeferredPromise,
+ isBlobLike,
+ sameOrigin,
+ isCancelled,
+ isAborted,
+ isErrorLike,
+ fullyReadBody,
+ readableStreamClose,
+ isomorphicEncode,
+ urlIsLocal,
+ urlIsHttpHttpsScheme,
+ urlHasHttpsScheme
+} = __nccwpck_require__(15523)
+const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(89710)
+const assert = __nccwpck_require__(42613)
+const { safelyExtractBody } = __nccwpck_require__(8923)
+const {
+ redirectStatusSet,
+ nullBodyStatus,
+ safeMethodsSet,
+ requestBodyHeader,
+ subresourceSet,
+ DOMException
+} = __nccwpck_require__(87326)
+const { kHeadersList } = __nccwpck_require__(36443)
+const EE = __nccwpck_require__(24434)
+const { Readable, pipeline } = __nccwpck_require__(2203)
+const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = __nccwpck_require__(3440)
+const { dataURLProcessor, serializeAMimeType } = __nccwpck_require__(94322)
+const { TransformStream } = __nccwpck_require__(63774)
+const { getGlobalDispatcher } = __nccwpck_require__(32581)
+const { webidl } = __nccwpck_require__(74222)
+const { STATUS_CODES } = __nccwpck_require__(58611)
+const GET_OR_HEAD = ['GET', 'HEAD']
- // Resolve ipv6
- if (hostname[0] === '[') {
- const idx = hostname.indexOf(']')
+/** @type {import('buffer').resolveObjectURL} */
+let resolveObjectURL
+let ReadableStream = globalThis.ReadableStream
- assert(idx !== -1)
- const ip = hostname.substring(1, idx)
+class Fetch extends EE {
+ constructor (dispatcher) {
+ super()
- assert(net.isIP(ip))
- hostname = ip
+ this.dispatcher = dispatcher
+ this.connection = null
+ this.dump = false
+ this.state = 'ongoing'
+ // 2 terminated listeners get added per request,
+ // but only 1 gets removed. If there are 20 redirects,
+ // 21 listeners will be added.
+ // See https://github.com/nodejs/undici/issues/1711
+ // TODO (fix): Find and fix root cause for leaked listener.
+ this.setMaxListeners(21)
}
- client[kConnecting] = true
+ terminate (reason) {
+ if (this.state !== 'ongoing') {
+ return
+ }
- if (channels.beforeConnect.hasSubscribers) {
- channels.beforeConnect.publish({
- connectParams: {
- host,
- hostname,
- protocol,
- port,
- servername: client[kServerName],
- localAddress: client[kLocalAddress]
- },
- connector: client[kConnector]
- })
+ this.state = 'terminated'
+ this.connection?.destroy(reason)
+ this.emit('terminated', reason)
}
- 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', () => {}), new ClientDestroyedError())
+ // https://fetch.spec.whatwg.org/#fetch-controller-abort
+ abort (error) {
+ if (this.state !== 'ongoing') {
return
}
- client[kConnecting] = false
-
- assert(socket)
+ // 1. Set controller’s state to "aborted".
+ this.state = 'aborted'
- const isH2 = socket.alpnProtocol === 'h2'
- if (isH2) {
- if (!h2ExperimentalWarned) {
- h2ExperimentalWarned = true
- process.emitWarning('H2 support is experimental, expect them to change at any time.', {
- code: 'UNDICI-H2'
- })
- }
+ // 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')
+ }
- const session = http2.connect(client[kUrl], {
- createConnection: () => socket,
- peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams
- })
+ // 4. Let serializedError be StructuredSerialize(error).
+ // If that threw an exception, catch it, and let
+ // serializedError be StructuredSerialize(fallbackError).
- client[kHTTPConnVersion] = 'h2'
- session[kClient] = client
- session[kSocket] = socket
- session.on('error', onHttp2SessionError)
- session.on('frameError', onHttp2FrameError)
- session.on('end', onHttp2SessionEnd)
- session.on('goaway', onHTTP2GoAway)
- session.on('close', onSocketClose)
- session.unref()
+ // 5. Set controller’s serialized abort reason to serializedError.
+ this.serializedAbortReason = error
- client[kHTTP2Session] = session
- socket[kHTTP2Session] = session
- } else {
- if (!llhttpInstance) {
- llhttpInstance = await llhttpPromise
- llhttpPromise = null
- }
+ this.connection?.destroy(error)
+ this.emit('terminated', error)
+ }
+}
- socket[kNoRef] = false
- socket[kWriting] = false
- socket[kReset] = false
- socket[kBlocking] = false
- socket[kParser] = new Parser(client, socket, llhttpInstance)
- }
+// https://fetch.spec.whatwg.org/#fetch-method
+function fetch (input, init = {}) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' })
- socket[kCounter] = 0
- socket[kMaxRequests] = client[kMaxRequests]
- socket[kClient] = client
- socket[kError] = null
+ // 1. Let p be a new promise.
+ const p = createDeferredPromise()
- socket
- .on('error', onSocketError)
- .on('readable', onSocketReadable)
- .on('end', onSocketEnd)
- .on('close', onSocketClose)
+ // 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
- client[kSocket] = socket
+ try {
+ requestObject = new Request(input, init)
+ } catch (e) {
+ p.reject(e)
+ return p.promise
+ }
- if (channels.connected.hasSubscribers) {
- channels.connected.publish({
- connectParams: {
- host,
- hostname,
- protocol,
- port,
- servername: client[kServerName],
- localAddress: client[kLocalAddress]
- },
- connector: client[kConnector],
- socket
- })
- }
- client.emit('connect', client[kUrl], [client])
- } catch (err) {
- if (client.destroyed) {
- return
- }
+ // 3. Let request be requestObject’s request.
+ const request = requestObject[kState]
- client[kConnecting] = false
+ // 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)
- if (channels.connectError.hasSubscribers) {
- channels.connectError.publish({
- connectParams: {
- host,
- hostname,
- protocol,
- port,
- servername: client[kServerName],
- localAddress: client[kLocalAddress]
- },
- connector: client[kConnector],
- error: err
- })
- }
+ // 2. Return p.
+ return p.promise
+ }
- 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]++]
- errorRequest(client, request, err)
- }
- } else {
- onError(client, err)
- }
+ // 5. Let globalObject be request’s client’s global object.
+ const globalObject = request.client.globalObject
- client.emit('connectionError', client[kUrl], [client], err)
+ // 6. If globalObject is a ServiceWorkerGlobalScope object, then set
+ // request’s service-workers mode to "none".
+ if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') {
+ request.serviceWorkers = 'none'
}
- resume(client)
-}
+ // 7. Let responseObject be null.
+ let responseObject = null
-function emitDrain (client) {
- client[kNeedDrain] = 0
- client.emit('drain', client[kUrl], [client])
-}
+ // 8. Let relevantRealm be this’s relevant Realm.
+ const relevantRealm = null
-function resume (client, sync) {
- if (client[kResuming] === 2) {
- return
- }
+ // 9. Let locallyAborted be false.
+ let locallyAborted = false
- client[kResuming] = 2
+ // 10. Let controller be null.
+ let controller = null
- _resume(client, sync)
- client[kResuming] = 0
+ // 11. Add the following abort steps to requestObject’s signal:
+ addAbortListener(
+ requestObject.signal,
+ () => {
+ // 1. Set locallyAborted to true.
+ locallyAborted = true
- if (client[kRunningIdx] > 256) {
- client[kQueue].splice(0, client[kRunningIdx])
- client[kPendingIdx] -= client[kRunningIdx]
- client[kRunningIdx] = 0
- }
-}
+ // 2. Assert: controller is non-null.
+ assert(controller != null)
-function _resume (client, sync) {
- while (true) {
- if (client.destroyed) {
- assert(client[kPending] === 0)
- return
- }
+ // 3. Abort controller with requestObject’s signal’s abort reason.
+ controller.abort(requestObject.signal.reason)
- if (client[kClosedResolve] && !client[kSize]) {
- client[kClosedResolve]()
- client[kClosedResolve] = null
- return
+ // 4. Abort the fetch() call with p, request, responseObject,
+ // and requestObject’s signal’s abort reason.
+ abortFetch(p, request, responseObject, requestObject.signal.reason)
}
+ )
- const socket = client[kSocket]
+ // 12. Let handleFetchDone given response response be to finalize and
+ // report timing with response, globalObject, and "fetch".
+ const handleFetchDone = (response) =>
+ finalizeAndReportTiming(response, 'fetch')
- if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') {
- 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
- }
+ // 13. Set controller to the result of calling fetch given request,
+ // with processResponseEndOfBody set to handleFetchDone, and processResponse
+ // given response being these substeps:
- if (client[kSize] === 0) {
- if (socket[kParser].timeoutType !== TIMEOUT_IDLE) {
- socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE)
- }
- } 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)
- }
- }
+ const processResponse = (response) => {
+ // 1. If locallyAborted is true, terminate these substeps.
+ if (locallyAborted) {
+ return Promise.resolve()
}
- if (client[kBusy]) {
- client[kNeedDrain] = 2
- } else if (client[kNeedDrain] === 2) {
- if (sync) {
- client[kNeedDrain] = 1
- process.nextTick(emitDrain, client)
- } else {
- emitDrain(client)
- }
- continue
- }
+ // 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.
- if (client[kPending] === 0) {
- return
- }
+ // 2. Abort the fetch() call with p, request, responseObject, and
+ // deserializedError.
- if (client[kRunning] >= (client[kPipelining] || 1)) {
- return
+ abortFetch(p, request, responseObject, controller.serializedAbortReason)
+ return Promise.resolve()
}
- const request = client[kQueue][client[kPendingIdx]]
-
- if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {
- if (client[kRunning] > 0) {
- return
- }
+ // 3. If response is a network error, then reject p with a TypeError
+ // and terminate these substeps.
+ if (response.type === 'error') {
+ p.reject(
+ Object.assign(new TypeError('fetch failed'), { cause: response.error })
+ )
+ return Promise.resolve()
+ }
- client[kServerName] = request.servername
+ // 4. Set responseObject to the result of creating a Response object,
+ // given response, "immutable", and relevantRealm.
+ responseObject = new Response()
+ responseObject[kState] = response
+ responseObject[kRealm] = relevantRealm
+ responseObject[kHeaders][kHeadersList] = response.headersList
+ responseObject[kHeaders][kGuard] = 'immutable'
+ responseObject[kHeaders][kRealm] = relevantRealm
- if (socket && socket.servername !== request.servername) {
- util.destroy(socket, new InformationalError('servername changed'))
- return
- }
- }
+ // 5. Resolve p with responseObject.
+ p.resolve(responseObject)
+ }
- if (client[kConnecting]) {
- return
- }
+ controller = fetching({
+ request,
+ processResponseEndOfBody: handleFetchDone,
+ processResponse,
+ dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici
+ })
- if (!socket && !client[kHTTP2Session]) {
- connect(client)
- return
- }
+ // 14. Return p.
+ return p.promise
+}
- if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) {
- return
- }
+// 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
+ }
- if (client[kRunning] > 0 && !request.idempotent) {
- // Non-idempotent request cannot be retried.
- // Ensure that no other requests are inflight and
- // could cause failure.
- return
- }
+ // 2. If response’s URL list is null or empty, then return.
+ if (!response.urlList?.length) {
+ return
+ }
- 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
- }
+ // 3. Let originalURL be response’s URL list[0].
+ const originalURL = response.urlList[0]
- if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 &&
- (util.isStream(request.body) || util.isAsyncIterable(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.
+ // 4. Let timingInfo be response’s timing info.
+ let timingInfo = response.timingInfo
- // Request with stream or iterator body cannot be retried.
- // Ensure that no other requests are inflight and
- // could cause failure.
- return
- }
+ // 5. Let cacheState be response’s cache state.
+ let cacheState = response.cacheState
- if (!request.aborted && write(client, request)) {
- client[kPendingIdx]++
- } else {
- client[kQueue].splice(client[kPendingIdx], 1)
- }
+ // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return.
+ if (!urlIsHttpHttpsScheme(originalURL)) {
+ return
}
-}
-
-// 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 write (client, request) {
- if (client[kHTTPConnVersion] === 'h2') {
- writeH2(client, client[kHTTP2Session], request)
+ // 7. If timingInfo is null, then return.
+ if (timingInfo === null) {
return
}
- const { body, method, path, host, upgrade, headers, blocking, reset } = request
+ // 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
+ })
- // 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
+ // 2. Set cacheState to the empty string.
+ cacheState = ''
+ }
- // 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.
+ // 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()
- const expectsPayload = (
- method === 'PUT' ||
- method === 'POST' ||
- method === 'PATCH'
+ // 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,
+ initiatorType,
+ globalThis,
+ cacheState
)
+}
- if (body && typeof body.read === 'function') {
- // Try to read EOF in order to get length.
- body.read(0)
+// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing
+function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) {
+ if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) {
+ performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState)
}
+}
- const bodyLength = util.bodyLength(body)
+// https://fetch.spec.whatwg.org/#abort-fetch
+function abortFetch (p, request, responseObject, error) {
+ // Note: AbortSignal.reason was added in node v17.2.0
+ // which would give us an undefined error to reject with.
+ // Remove this once node v16 is no longer supported.
+ if (!error) {
+ error = new DOMException('The operation was aborted.', 'AbortError')
+ }
- let contentLength = bodyLength
+ // 1. Reject promise with error.
+ p.reject(error)
- if (contentLength === null) {
- contentLength = request.contentLength
+ // 2. If request’s body is not null and is readable, then cancel request’s
+ // body with error.
+ if (request.body != null && isReadable(request.body?.stream)) {
+ request.body.stream.cancel(error).catch((err) => {
+ if (err.code === 'ERR_INVALID_STATE') {
+ // Node bug?
+ return
+ }
+ throw err
+ })
}
- 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
+ // 3. If responseObject is null, then return.
+ if (responseObject == null) {
+ return
}
- // 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]) {
- errorRequest(client, request, new RequestContentLengthMismatchError())
- return false
- }
+ // 4. Let response be responseObject’s response.
+ const response = responseObject[kState]
- process.emitWarning(new RequestContentLengthMismatchError())
+ // 5. If response’s body is not null and is readable, then error response’s
+ // body with error.
+ if (response.body != null && isReadable(response.body?.stream)) {
+ response.body.stream.cancel(error).catch((err) => {
+ if (err.code === 'ERR_INVALID_STATE') {
+ // Node bug?
+ return
+ }
+ throw err
+ })
}
+}
- const socket = client[kSocket]
+// https://fetch.spec.whatwg.org/#fetching
+function fetching ({
+ request,
+ processRequestBodyChunkLength,
+ processRequestEndOfBody,
+ processResponse,
+ processResponseEndOfBody,
+ processResponseConsumeBody,
+ useParallelQueue = false,
+ dispatcher // undici
+}) {
+ // 1. Let taskDestination be null.
+ let taskDestination = null
- try {
- request.onConnect((err) => {
- if (request.aborted || request.completed) {
- return
- }
+ // 2. Let crossOriginIsolatedCapability be false.
+ let crossOriginIsolatedCapability = false
- errorRequest(client, request, err || new RequestAbortedError())
+ // 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
- util.destroy(socket, new InformationalError('aborted'))
- })
- } catch (err) {
- errorRequest(client, request, err)
+ // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin
+ // isolated capability.
+ crossOriginIsolatedCapability =
+ request.client.crossOriginIsolatedCapability
}
- if (request.aborted) {
- return false
- }
+ // 4. If useParallelQueue is true, then set taskDestination to the result of
+ // starting a new parallel queue.
+ // TODO
- 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.
+ // 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 currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability)
+ const timingInfo = createOpaqueTimingInfo({
+ startTime: currenTime
+ })
- socket[kReset] = true
+ // 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
}
- if (upgrade || method === 'CONNECT') {
- // On CONNECT or upgrade, block pipeline from dispatching further
- // requests on this connection.
+ // 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)
- socket[kReset] = true
+ // 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'
}
- if (reset != null) {
- socket[kReset] = reset
+ // 9. If request’s origin is "client", then set request’s origin to request’s
+ // client’s origin.
+ if (request.origin === 'client') {
+ // TODO: What if request.client is null?
+ request.origin = request.client?.origin
}
- if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {
- socket[kReset] = true
- }
+ // 10. If all of the following conditions are true:
+ // TODO
- if (blocking) {
- socket[kBlocking] = true
+ // 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()
+ }
}
- let header = `${method} ${path} HTTP/1.1\r\n`
+ // 12. If request’s header list does not contain `Accept`, then:
+ if (!request.headersList.contains('accept')) {
+ // 1. Let value be `*/*`.
+ const value = '*/*'
- if (typeof host === 'string') {
- header += `host: ${host}\r\n`
- } else {
- header += client[kHostHeader]
- }
+ // 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
- 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'
+ // 3. Append `Accept`/value to request’s header list.
+ request.headersList.append('accept', value)
}
- if (headers) {
- header += headers
+ // 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')) {
+ request.headersList.append('accept-language', '*')
}
- if (channels.sendHeaders.hasSubscribers) {
- channels.sendHeaders.publish({ request, headers: header, socket })
+ // 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
}
- /* istanbul ignore else: assertion */
- if (!body || bodyLength === 0) {
- 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')
- }
- request.onRequestSent()
- } 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)
- request.onRequestSent()
- if (!expectsPayload) {
- socket[kReset] = true
- }
- } else if (util.isBlobLike(body)) {
- if (typeof body.stream === 'function') {
- writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload })
- } else {
- writeBlob({ body, client, request, socket, contentLength, header, expectsPayload })
- }
- } else if (util.isStream(body)) {
- writeStream({ body, client, request, socket, contentLength, header, expectsPayload })
- } else if (util.isIterable(body)) {
- writeIterable({ body, client, request, socket, contentLength, header, expectsPayload })
- } else {
- assert(false)
+ // 15. If request is a subresource request, then:
+ if (subresourceSet.has(request.destination)) {
+ // TODO
}
- return true
+ // 16. Run main fetch given fetchParams.
+ mainFetch(fetchParams)
+ .catch(err => {
+ fetchParams.controller.terminate(err)
+ })
+
+ // 17. Return fetchParam's controller
+ return fetchParams.controller
}
-function writeH2 (client, session, request) {
- const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request
+// https://fetch.spec.whatwg.org/#concept-main-fetch
+async function mainFetch (fetchParams, recursive = false) {
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
- let headers
- if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim())
- else headers = reqHeaders
+ // 2. Let response be null.
+ let response = null
- if (upgrade) {
- errorRequest(client, request, new Error('Upgrade not supported for H2'))
- return false
+ // 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')
}
- try {
- // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event?
- request.onConnect((err) => {
- if (request.aborted || request.completed) {
- return
- }
+ // 4. Run report Content Security Policy violations for request.
+ // TODO
- errorRequest(client, request, err || new RequestAbortedError())
- })
- } catch (err) {
- errorRequest(client, request, err)
+ // 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?
- if (request.aborted) {
- return false
+ // 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
}
- /** @type {import('node:http2').ClientHttp2Stream} */
- let stream
- const h2State = client[kHTTP2SessionState]
+ // 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)
+ }
- headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost]
- headers[HTTP2_HEADER_METHOD] = method
+ // 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
- 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 })
+ // 10. If recursive is false, then run the remaining steps in parallel.
+ // TODO
- if (stream.id && !stream.pending) {
- request.onUpgrade(null, null, stream)
- ++h2State.openStreams
- } else {
- stream.once('ready', () => {
- request.onUpgrade(null, null, stream)
- ++h2State.openStreams
- })
- }
+ // 11. If response is null, then set response to the result of running
+ // the steps corresponding to the first matching statement:
+ if (response === null) {
+ response = await (async () => {
+ const currentURL = requestCurrentURL(request)
- stream.once('close', () => {
- h2State.openStreams -= 1
- // TODO(HTTP/2): unref only if current streams count is 0
- if (h2State.openStreams === 0) session.unref()
- })
+ 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'
- return true
- }
+ // 2. Return the result of running scheme fetch given fetchParams.
+ return await schemeFetch(fetchParams)
+ }
- // https://tools.ietf.org/html/rfc7540#section-8.3
- // :path and :scheme headers must be omited when sending CONNECT
+ // request’s mode is "same-origin"
+ if (request.mode === 'same-origin') {
+ // 1. Return a network error.
+ return makeNetworkError('request mode cannot be "same-origin"')
+ }
- headers[HTTP2_HEADER_PATH] = path
- headers[HTTP2_HEADER_SCHEME] = 'https'
+ // request’s mode is "no-cors"
+ if (request.mode === 'no-cors') {
+ // 1. If request’s redirect mode is not "follow", then return a network
+ // error.
+ if (request.redirect !== 'follow') {
+ return makeNetworkError(
+ 'redirect mode cannot be "follow" for "no-cors" 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
+ // 2. Set request’s response tainting to "opaque".
+ request.responseTainting = 'opaque'
- // 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.
+ // 3. Return the result of running scheme fetch given fetchParams.
+ return await schemeFetch(fetchParams)
+ }
- const expectsPayload = (
- method === 'PUT' ||
- method === 'POST' ||
- method === 'PATCH'
- )
+ // request’s current URL’s scheme is not an HTTP(S) scheme
+ if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {
+ // Return a network error.
+ return makeNetworkError('URL scheme must be a HTTP(S) scheme')
+ }
- if (body && typeof body.read === 'function') {
- // Try to read EOF in order to get length.
- body.read(0)
- }
+ // - 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
- let contentLength = util.bodyLength(body)
+ // Otherwise
+ // 1. Set request’s response tainting to "cors".
+ request.responseTainting = 'cors'
- if (contentLength == null) {
- contentLength = request.contentLength
+ // 2. Return the result of running HTTP fetch given fetchParams.
+ return await httpFetch(fetchParams)
+ })()
}
- 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
+ // 12. If recursive is true, then return response.
+ if (recursive) {
+ return response
}
- // 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]) {
- errorRequest(client, request, new RequestContentLengthMismatchError())
- return false
+ // 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
}
- process.emitWarning(new RequestContentLengthMismatchError())
+ // 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)
+ }
}
- if (contentLength != null) {
- assert(body, 'no body must not have content length')
- headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`
+ // 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)
}
- session.ref()
+ // 16. If request’s timing allow failed flag is unset, then set
+ // internalResponse’s timing allow passed flag.
+ if (!request.timingAllowFailed) {
+ response.timingAllowPassed = true
+ }
- const shouldEndStream = method === 'GET' || method === 'HEAD'
- if (expectContinue) {
- headers[HTTP2_HEADER_EXPECT] = '100-continue'
- stream = session.request(headers, { endStream: shouldEndStream, signal })
+ // 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
- stream.once('continue', writeBodyH2)
- } else {
- stream = session.request(headers, {
- endStream: shouldEndStream,
- signal
- })
- writeBodyH2()
+ // 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')
+ ) {
+ response = internalResponse = makeNetworkError()
}
- // Increment counter as we have new several streams open
- ++h2State.openStreams
+ // 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
+ }
- stream.once('response', headers => {
- const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers
+ // 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))
- if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) {
- stream.pause()
+ // 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
}
- })
-
- stream.once('end', () => {
- request.onComplete([])
- })
- stream.on('data', (chunk) => {
- if (request.onData(chunk) === false) {
- stream.pause()
- }
- })
+ // 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
+ }
- stream.once('close', () => {
- h2State.openStreams -= 1
- // TODO(HTTP/2): unref only if current streams count is 0
- if (h2State.openStreams === 0) {
- session.unref()
- }
- })
+ // 2. Set response’s body to bytes as a body.
+ response.body = safelyExtractBody(bytes)[0]
- stream.once('error', function (err) {
- if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {
- h2State.streams -= 1
- util.destroy(stream, err)
+ // 3. Run fetch finale given fetchParams and response.
+ fetchFinale(fetchParams, response)
}
- })
- stream.once('frameError', (type, code) => {
- const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
- errorRequest(client, request, err)
+ // 4. Fully read response’s body given processBody and processBodyError.
+ await fullyReadBody(response.body, processBody, processBodyError)
+ } else {
+ // 21. Otherwise, run fetch finale given fetchParams and response.
+ fetchFinale(fetchParams, response)
+ }
+}
- if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {
- h2State.streams -= 1
- util.destroy(stream, 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))
+ }
- // stream.on('aborted', () => {
- // // TODO(HTTP/2): Support aborted
- // })
+ // 2. Let request be fetchParams’s request.
+ const { request } = fetchParams
- // stream.on('timeout', () => {
- // // TODO(HTTP/2): Support timeout
- // })
+ const { protocol: scheme } = requestCurrentURL(request)
- // stream.on('push', headers => {
- // // TODO(HTTP/2): Suppor push
- // })
+ // 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.
- // stream.on('trailers', headers => {
- // // TODO(HTTP/2): Support trailers
- // })
+ // Otherwise, return a network error.
+ return Promise.resolve(makeNetworkError('about scheme is not supported'))
+ }
+ case 'blob:': {
+ if (!resolveObjectURL) {
+ resolveObjectURL = (__nccwpck_require__(20181).resolveObjectURL)
+ }
- return true
+ // 1. Let blobURLEntry be request’s current URL’s blob URL entry.
+ const blobURLEntry = requestCurrentURL(request)
- function writeBodyH2 () {
- /* istanbul ignore else: assertion */
- if (!body) {
- request.onRequestSent()
- } else if (util.isBuffer(body)) {
- assert(contentLength === body.byteLength, 'buffer body must have content length')
- stream.cork()
- stream.write(body)
- stream.uncork()
- stream.end()
- request.onBodySent(body)
- request.onRequestSent()
- } else if (util.isBlobLike(body)) {
- if (typeof body.stream === 'function') {
- writeIterable({
- client,
- request,
- contentLength,
- h2stream: stream,
- expectsPayload,
- body: body.stream(),
- socket: client[kSocket],
- header: ''
- })
- } else {
- writeBlob({
- body,
- client,
- request,
- contentLength,
- expectsPayload,
- h2stream: stream,
- header: '',
- socket: client[kSocket]
- })
+ // 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.'))
}
- } else if (util.isStream(body)) {
- writeStream({
- body,
- client,
- request,
- contentLength,
- expectsPayload,
- socket: client[kSocket],
- h2stream: stream,
- header: ''
- })
- } else if (util.isIterable(body)) {
- writeIterable({
- body,
- client,
- request,
- contentLength,
- expectsPayload,
- header: '',
- h2stream: stream,
- socket: client[kSocket]
- })
- } else {
- assert(false)
- }
- }
-}
-function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
- assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
+ const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString())
- if (client[kHTTPConnVersion] === 'h2') {
- // For HTTP/2, is enough to pipe the stream
- const pipe = pipeline(
- body,
- h2stream,
- (err) => {
- if (err) {
- util.destroy(body, err)
- util.destroy(h2stream, err)
- } else {
- request.onRequestSent()
- }
+ // 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' || !isBlobLike(blobURLEntryObject)) {
+ return Promise.resolve(makeNetworkError('invalid method'))
}
- )
- pipe.on('data', onPipeData)
- pipe.once('end', () => {
- pipe.removeListener('data', onPipeData)
- util.destroy(pipe)
- })
+ // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object.
+ const bodyWithType = safelyExtractBody(blobURLEntryObject)
- function onPipeData (chunk) {
- request.onBodySent(chunk)
- }
+ // 4. Let body be bodyWithType’s body.
+ const body = bodyWithType[0]
- return
- }
+ // 5. Let length be body’s length, serialized and isomorphic encoded.
+ const length = isomorphicEncode(`${body.length}`)
- let finished = false
+ // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence.
+ const type = bodyWithType[1] ?? ''
- const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })
+ // 7. Return a new response whose status message is `OK`, header list is
+ // « (`Content-Length`, length), (`Content-Type`, type) », and body is body.
+ const response = makeResponse({
+ statusText: 'OK',
+ headersList: [
+ ['content-length', { name: 'Content-Length', value: length }],
+ ['content-type', { name: 'Content-Type', value: type }]
+ ]
+ })
- const onData = function (chunk) {
- if (finished) {
- return
+ response.body = body
+
+ 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)
- try {
- if (!writer.write(chunk) && this.pause) {
- this.pause()
+ // 2. If dataURLStruct is failure, then return a
+ // network error.
+ if (dataURLStruct === 'failure') {
+ return Promise.resolve(makeNetworkError('failed to fetch the data URL'))
}
- } catch (err) {
- util.destroy(this, err)
+
+ // 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]
+ }))
}
- }
- const onDrain = function () {
- if (finished) {
- return
+ 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.
- if (body.resume) {
- body.resume()
+ return httpFetch(fetchParams)
+ .catch((err) => makeNetworkError(err))
}
- }
- const onAbort = function () {
- if (finished) {
- return
+ default: {
+ return Promise.resolve(makeNetworkError('unknown scheme'))
}
- const err = new RequestAbortedError()
- queueMicrotask(() => onFinished(err))
}
- const onFinished = function (err) {
- if (finished) {
- return
- }
-
- finished = true
+}
- assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))
+// https://fetch.spec.whatwg.org/#finalize-response
+function finalizeResponse (fetchParams, response) {
+ // 1. Set fetchParams’s request’s done flag.
+ fetchParams.request.done = true
- socket
- .off('drain', onDrain)
- .off('error', onFinished)
+ // 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))
+ }
+}
- body
- .removeListener('data', onData)
- .removeListener('end', onFinished)
- .removeListener('error', onFinished)
- .removeListener('close', onAbort)
+// https://fetch.spec.whatwg.org/#fetch-finale
+function fetchFinale (fetchParams, response) {
+ // 1. If response is a network error, then:
+ if (response.type === 'error') {
+ // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ».
+ response.urlList = [fetchParams.request.urlList[0]]
- if (!err) {
- try {
- writer.end()
- } catch (er) {
- err = er
- }
- }
+ // 2. Set response’s timing info to the result of creating an opaque timing
+ // info for fetchParams’s timing info.
+ response.timingInfo = createOpaqueTimingInfo({
+ startTime: fetchParams.timingInfo.startTime
+ })
+ }
- writer.destroy(err)
+ // 2. Let processResponseEndOfBody be the following steps:
+ const processResponseEndOfBody = () => {
+ // 1. Set fetchParams’s request’s done flag.
+ fetchParams.request.done = true
- if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {
- util.destroy(body, err)
- } else {
- util.destroy(body)
+ // If fetchParams’s process response end-of-body is not null,
+ // then queue a fetch task to run fetchParams’s process response
+ // end-of-body given response with fetchParams’s task destination.
+ if (fetchParams.processResponseEndOfBody != null) {
+ queueMicrotask(() => fetchParams.processResponseEndOfBody(response))
}
}
- body
- .on('data', onData)
- .on('end', onFinished)
- .on('error', onFinished)
- .on('close', onAbort)
-
- if (body.resume) {
- body.resume()
+ // 3. 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))
}
- socket
- .on('drain', onDrain)
- .on('error', onFinished)
-}
+ // 4. If response’s body is null, then run processResponseEndOfBody.
+ if (response.body == null) {
+ processResponseEndOfBody()
+ } else {
+ // 5. Otherwise:
-async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
- assert(contentLength === body.size, 'blob body must have content length')
+ // 1. Let transformStream be a new a TransformStream.
- const isH2 = client[kHTTPConnVersion] === 'h2'
- try {
- if (contentLength != null && contentLength !== body.size) {
- throw new RequestContentLengthMismatchError()
+ // 2. Let identityTransformAlgorithm be an algorithm which, given chunk,
+ // enqueues chunk in transformStream.
+ const identityTransformAlgorithm = (chunk, controller) => {
+ controller.enqueue(chunk)
}
- const buffer = Buffer.from(await body.arrayBuffer())
+ // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm
+ // and flushAlgorithm set to processResponseEndOfBody.
+ const transformStream = new TransformStream({
+ start () {},
+ transform: identityTransformAlgorithm,
+ flush: processResponseEndOfBody
+ }, {
+ size () {
+ return 1
+ }
+ }, {
+ size () {
+ return 1
+ }
+ })
- if (isH2) {
- h2stream.cork()
- h2stream.write(buffer)
- h2stream.uncork()
+ // 4. Set response’s body to the result of piping response’s body through transformStream.
+ response.body = { stream: response.body.stream.pipeThrough(transformStream) }
+ }
+
+ // 6. If fetchParams’s process response consume body is non-null, then:
+ if (fetchParams.processResponseConsumeBody != null) {
+ // 1. Let processBody given nullOrBytes be this step: run fetchParams’s
+ // process response consume body given response and nullOrBytes.
+ const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes)
+
+ // 2. Let processBodyError be this step: run fetchParams’s process
+ // response consume body given response and failure.
+ const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure)
+
+ // 3. If response’s body is null, then queue a fetch task to run processBody
+ // given null, with fetchParams’s task destination.
+ if (response.body == null) {
+ queueMicrotask(() => processBody(null))
} else {
- socket.cork()
- socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
- socket.write(buffer)
- socket.uncork()
+ // 4. Otherwise, fully read response’s body given processBody, processBodyError,
+ // and fetchParams’s task destination.
+ return fullyReadBody(response.body, processBody, processBodyError)
}
+ return Promise.resolve()
+ }
+}
- request.onBodySent(buffer)
- request.onRequestSent()
+// https://fetch.spec.whatwg.org/#http-fetch
+async function httpFetch (fetchParams) {
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
- if (!expectsPayload) {
- socket[kReset] = true
- }
+ // 2. Let response be null.
+ let response = null
- resume(client)
- } catch (err) {
- util.destroy(isH2 ? h2stream : socket, err)
+ // 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
}
-}
-async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
- assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')
+ // 6. If response is null, then:
+ if (response === null) {
+ // 1. If makeCORSPreflight is true and one of these conditions is true:
+ // TODO
- let callback = null
- function onDrain () {
- if (callback) {
- const cb = callback
- callback = null
- cb()
+ // 2. If request’s redirect mode is "follow", then set request’s
+ // service-workers mode to "none".
+ if (request.redirect === 'follow') {
+ request.serviceWorkers = 'none'
}
- }
- const waitForDrain = () => new Promise((resolve, reject) => {
- assert(callback === null)
+ // 3. Set response and actualResponse to the result of running
+ // HTTP-network-or-cache fetch given fetchParams.
+ actualResponse = response = await httpNetworkOrCacheFetch(fetchParams)
- if (socket[kError]) {
- reject(socket[kError])
- } else {
- callback = resolve
+ // 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')
}
- })
- if (client[kHTTPConnVersion] === 'h2') {
- h2stream
- .on('close', onDrain)
- .on('drain', onDrain)
+ // 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
+ }
+ }
- 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]
- }
+ // 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')
+ }
- const res = h2stream.write(chunk)
- request.onBodySent(chunk)
- if (!res) {
- await waitForDrain()
- }
- }
- } catch (err) {
- h2stream.destroy(err)
- } finally {
- request.onRequestSent()
- h2stream.end()
- h2stream
- .off('close', onDrain)
- .off('drain', onDrain)
+ // 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()
+ }
+
+ // 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)
}
-
- return
}
- socket
- .on('close', onDrain)
- .on('drain', onDrain)
+ // 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
- const writer = new AsyncWriter({ 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]
- }
+ locationURL = responseLocationURL(
+ actualResponse,
+ requestCurrentURL(request).hash
+ )
- if (!writer.write(chunk)) {
- await waitForDrain()
- }
+ // 4. If locationURL is null, then return response.
+ if (locationURL == null) {
+ return response
}
-
- writer.end()
} catch (err) {
- writer.destroy(err)
- } finally {
- socket
- .off('close', onDrain)
- .off('drain', onDrain)
+ // 5. If locationURL is failure, then return a network error.
+ return Promise.resolve(makeNetworkError(err))
}
-}
-class AsyncWriter {
- constructor ({ 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
+ // 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'))
+ }
- socket[kWriting] = true
+ // 7. If request’s redirect count is 20, then return a network error.
+ if (request.redirectCount === 20) {
+ return Promise.resolve(makeNetworkError('redirect count exceeded'))
}
- write (chunk) {
- const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this
+ // 8. Increase request’s redirect count by 1.
+ request.redirectCount += 1
- if (socket[kError]) {
- throw socket[kError]
- }
+ // 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"'))
+ }
- if (socket.destroyed) {
- return false
- }
+ // 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"'
+ ))
+ }
- const len = Buffer.byteLength(chunk)
- if (!len) {
- return true
- }
+ // 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())
+ }
- // We should defer writing chunks.
- if (contentLength !== null && bytesWritten + len > contentLength) {
- if (client[kStrictContentLength]) {
- throw new RequestContentLengthMismatchError()
- }
+ // 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
- process.emitWarning(new RequestContentLengthMismatchError())
+ // 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)
}
+ }
- socket.cork()
+ // 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')
- if (bytesWritten === 0) {
- if (!expectsPayload) {
- socket[kReset] = true
- }
+ // https://fetch.spec.whatwg.org/#authentication-entries
+ request.headersList.delete('proxy-authorization', 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')
- }
- }
+ // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement.
+ request.headersList.delete('cookie')
+ request.headersList.delete('host')
+ }
- if (contentLength === null) {
- socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1')
- }
+ // 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]
+ }
- this.bytesWritten += len
+ // 15. Let timingInfo be fetchParams’s timing info.
+ const timingInfo = fetchParams.timingInfo
- const ret = socket.write(chunk)
+ // 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)
- socket.uncork()
+ // 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
+ }
- request.onBodySent(chunk)
+ // 18. Append locationURL to request’s URL list.
+ request.urlList.push(locationURL)
- 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()
- }
- }
- }
+ // 19. Invoke set request’s referrer policy on redirect on request and
+ // actualResponse.
+ setRequestReferrerPolicyOnRedirect(request, actualResponse)
- return ret
- }
+ // 20. Return the result of running main fetch given fetchParams and true.
+ return mainFetch(fetchParams, true)
+}
- end () {
- const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this
- request.onRequestSent()
+// 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
- socket[kWriting] = false
+ // 2. Let httpFetchParams be null.
+ let httpFetchParams = null
- if (socket[kError]) {
- throw socket[kError]
- }
+ // 3. Let httpRequest be null.
+ let httpRequest = null
- if (socket.destroyed) {
- return
- }
+ // 4. Let response be null.
+ let response = null
- 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.
+ // 5. Let storedResponse be null.
+ // TODO: cache
- 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')
- }
+ // 6. Let httpCache be null.
+ const httpCache = null
- if (contentLength !== null && bytesWritten !== contentLength) {
- if (client[kStrictContentLength]) {
- throw new RequestContentLengthMismatchError()
- } else {
- process.emitWarning(new RequestContentLengthMismatchError())
- }
- }
+ // 7. Let the revalidatingFlag be unset.
+ const revalidatingFlag = false
- if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
- // istanbul ignore else: only for jest
- if (socket[kParser].timeout.refresh) {
- socket[kParser].timeout.refresh()
- }
- }
+ // 8. Run these steps, but abort when the ongoing fetch is terminated:
- resume(client)
- }
+ // 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:
- destroy (err) {
- const { socket, client } = this
+ // 1. Set httpRequest to a clone of request.
+ httpRequest = makeRequest(request)
- socket[kWriting] = false
+ // 2. Set httpFetchParams to a copy of fetchParams.
+ httpFetchParams = { ...fetchParams }
- if (err) {
- assert(client[kRunning] <= 1, 'pipeline should only contain this request')
- util.destroy(socket, err)
- }
+ // 3. Set httpFetchParams’s request to httpRequest.
+ httpFetchParams.request = httpRequest
}
-}
-function errorRequest (client, request, err) {
- try {
- request.onError(err)
- assert(request.aborted)
- } catch (err) {
- client.emit('error', err)
- }
-}
+ // 3. Let includeCredentials be true if one of
+ const includeCredentials =
+ request.credentials === 'include' ||
+ (request.credentials === 'same-origin' &&
+ request.responseTainting === 'basic')
-module.exports = Client
+ // 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'
+ }
-/***/ 3194:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 7. If contentLength is non-null, then set contentLengthHeaderValue to
+ // contentLength, serialized and isomorphic encoded.
+ if (contentLength != null) {
+ contentLengthHeaderValue = isomorphicEncode(`${contentLength}`)
+ }
-"use strict";
+ // 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)
+ }
+ // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`,
+ // contentLengthHeaderValue) to httpRequest’s header list.
-/* istanbul ignore file: only for Node 12 */
+ // 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.
+ }
-const { kConnected, kSize } = __nccwpck_require__(6443)
+ // 11. If httpRequest’s referrer is a URL, then append
+ // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded,
+ // to httpRequest’s header list.
+ if (httpRequest.referrer instanceof URL) {
+ httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href))
+ }
-class CompatWeakRef {
- constructor (value) {
- this.value = value
+ // 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')) {
+ httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node')
}
- deref () {
- return this.value[kConnected] === 0 && this.value[kSize] === 0
- ? undefined
- : this.value
+ // 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') ||
+ httpRequest.headersList.contains('if-none-match') ||
+ httpRequest.headersList.contains('if-unmodified-since') ||
+ httpRequest.headersList.contains('if-match') ||
+ httpRequest.headersList.contains('if-range'))
+ ) {
+ httpRequest.cache = 'no-store'
}
-}
-class CompatFinalizer {
- constructor (finalizer) {
- this.finalizer = finalizer
+ // 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')
+ ) {
+ httpRequest.headersList.append('cache-control', 'max-age=0')
}
- register (dispatcher, key) {
- if (dispatcher.on) {
- dispatcher.on('disconnect', () => {
- if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {
- this.finalizer(key)
- }
- })
+ // 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')) {
+ httpRequest.headersList.append('pragma', 'no-cache')
}
- }
-}
-module.exports = function () {
- // FIXME: remove workaround when the Node bug is fixed
- // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
- if (process.env.NODE_V8_COVERAGE) {
- return {
- WeakRef: CompatWeakRef,
- FinalizationRegistry: CompatFinalizer
+ // 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')) {
+ httpRequest.headersList.append('cache-control', 'no-cache')
}
}
- return {
- WeakRef: global.WeakRef || CompatWeakRef,
- FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer
- }
-}
-
-
-/***/ }),
-
-/***/ 9237:
-/***/ ((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
+ // 18. If httpRequest’s header list contains `Range`, then append
+ // `Accept-Encoding`/`identity` to httpRequest’s header list.
+ if (httpRequest.headersList.contains('range')) {
+ httpRequest.headersList.append('accept-encoding', 'identity')
+ }
-module.exports = {
- maxAttributeValueSize,
- maxNameValuePairSize
-}
+ // 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')) {
+ if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
+ httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate')
+ } else {
+ httpRequest.headersList.append('accept-encoding', 'gzip, deflate')
+ }
+ }
+ httpRequest.headersList.delete('host')
-/***/ }),
+ // 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
+ }
-/***/ 3168:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 21. If there’s a proxy-authentication entry, use it as appropriate.
+ // TODO: proxy-authentication
-"use strict";
+ // 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'
+ }
-const { parseSetCookie } = __nccwpck_require__(8915)
-const { stringify, getHeadersList } = __nccwpck_require__(3834)
-const { webidl } = __nccwpck_require__(4222)
-const { Headers } = __nccwpck_require__(6349)
+ // 24. If httpRequest’s cache mode is neither "no-store" nor "reload",
+ // then:
+ if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') {
+ // TODO: cache
+ }
-/**
- * @typedef {Object} Cookie
- * @property {string} name
- * @property {string} value
- * @property {Date|number|undefined} expires
- * @property {number|undefined} maxAge
- * @property {string|undefined} domain
- * @property {string|undefined} path
- * @property {boolean|undefined} secure
- * @property {boolean|undefined} httpOnly
- * @property {'Strict'|'Lax'|'None'} sameSite
- * @property {string[]} unparsed
- */
+ // 9. If aborted, then return the appropriate network error for fetchParams.
+ // TODO
-/**
- * @param {Headers} headers
- * @returns {Record}
- */
-function getCookies (headers) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' })
+ // 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.mode === 'only-if-cached') {
+ return makeNetworkError('only if cached')
+ }
- webidl.brandCheck(headers, Headers, { strict: false })
+ // 2. Let forwardResponse be the result of running HTTP-network fetch
+ // given httpFetchParams, includeCredentials, and isNewConnectionFetch.
+ const forwardResponse = await httpNetworkFetch(
+ httpFetchParams,
+ includeCredentials,
+ isNewConnectionFetch
+ )
- const cookie = headers.get('cookie')
- const out = {}
+ // 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
+ }
- if (!cookie) {
- return out
- }
+ // 4. If the revalidatingFlag is set and forwardResponse’s status is 304,
+ // then:
+ if (revalidatingFlag && forwardResponse.status === 304) {
+ // TODO: cache
+ }
- for (const piece of cookie.split(';')) {
- const [name, ...value] = piece.split('=')
+ // 5. If response is null, then:
+ if (response == null) {
+ // 1. Set response to forwardResponse.
+ response = forwardResponse
- out[name.trim()] = value.join('=')
+ // 2. Store httpRequest and forwardResponse in httpCache, as per the
+ // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING]
+ // TODO: cache
+ }
}
- return out
-}
+ // 11. Set response’s URL list to a clone of httpRequest’s URL list.
+ response.urlList = [...httpRequest.urlList]
-/**
- * @param {Headers} headers
- * @param {string} name
- * @param {{ path?: string, domain?: string }|undefined} attributes
- * @returns {void}
- */
-function deleteCookie (headers, name, attributes) {
- webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' })
+ // 12. If httpRequest’s header list contains `Range`, then set response’s
+ // range-requested flag.
+ if (httpRequest.headersList.contains('range')) {
+ response.rangeRequested = true
+ }
- webidl.brandCheck(headers, Headers, { strict: false })
+ // 13. Set response’s request-includes-credentials to includeCredentials.
+ response.requestIncludesCredentials = includeCredentials
- name = webidl.converters.DOMString(name)
- attributes = webidl.converters.DeleteCookieAttributes(attributes)
+ // 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
- // Matches behavior of
- // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278
- setCookie(headers, {
- name,
- value: '',
- expires: new Date(0),
- ...attributes
- })
-}
+ // 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()
+ }
-/**
- * @param {Headers} headers
- * @returns {Cookie[]}
- */
-function getSetCookies (headers) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' })
+ // 2. ???
- webidl.brandCheck(headers, Headers, { strict: false })
+ // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.
+ if (isCancelled(fetchParams)) {
+ return makeAppropriateNetworkError(fetchParams)
+ }
- const cookies = getHeadersList(headers).cookies
+ // 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?
- if (!cookies) {
- return []
+ // 5. Set response to the result of running HTTP-network-or-cache fetch given
+ // fetchParams.
+ // TODO
+ return makeNetworkError('proxy authentication required')
}
- // In older versions of undici, cookies is a list of name:value.
- return cookies.map((pair) => parseSetCookie(Array.isArray(pair) ? pair[1] : pair))
-}
-
-/**
- * @param {Headers} headers
- * @param {Cookie} cookie
- * @returns {void}
- */
-function setCookie (headers, cookie) {
- webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' })
-
- webidl.brandCheck(headers, Headers, { strict: false })
+ // 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:
- cookie = webidl.converters.Cookie(cookie)
+ // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
+ if (isCancelled(fetchParams)) {
+ return makeAppropriateNetworkError(fetchParams)
+ }
- const str = stringify(cookie)
+ // 2. Set response to the result of running HTTP-network-or-cache
+ // fetch given fetchParams, isAuthenticationFetch, and true.
- if (str) {
- headers.append('Set-Cookie', stringify(cookie))
- }
-}
+ // 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()
-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
+ response = await httpNetworkOrCacheFetch(
+ fetchParams,
+ isAuthenticationFetch,
+ true
+ )
}
-])
-
-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: []
+ // 17. If isAuthenticationFetch is true, then create an authentication entry
+ if (isAuthenticationFetch) {
+ // TODO
}
-])
-module.exports = {
- getCookies,
- deleteCookie,
- getSetCookies,
- setCookie
+ // 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) {
+ if (!this.destroyed) {
+ this.destroyed = true
+ this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError'))
+ }
+ }
+ }
-/***/ 8915:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
-"use strict";
+ // 2. Let response be null.
+ let response = null
+ // 3. Let timingInfo be fetchParams’s timing info.
+ const timingInfo = fetchParams.timingInfo
-const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(9237)
-const { isCTLExcludingHtab } = __nccwpck_require__(3834)
-const { collectASequenceOfCodePointsFast } = __nccwpck_require__(4322)
-const assert = __nccwpck_require__(2613)
+ // 4. Let httpCache be the result of determining the HTTP cache partition,
+ // given request.
+ // TODO: cache
+ const httpCache = null
-/**
- * @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 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
+ // 5. If httpCache is null, then set request’s cache mode to "no-store".
+ if (httpCache == null) {
+ request.cache = 'no-store'
}
- 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:
+ // 6. Let networkPartitionKey be the result of determining the network
+ // partition key given request.
+ // TODO
- // 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
- }
+ // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise
+ // "no".
+ const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars
- // 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
+ // 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 {
- // 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)
+ // Let connection be the result of obtaining a connection, given
+ // networkPartitionKey, request’s current URL’s origin,
+ // includeCredentials, and forceNewConnection.
+ // TODO
}
- // 4. Remove any leading or trailing WSP characters from the name
- // string and the value string.
- name = name.trim()
- value = value.trim()
+ // 9. Run these steps, but abort when the ongoing fetch is terminated:
- // 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
- }
+ // 1. If connection is failure, then return a network error.
- // 6. The cookie-name is the name string, and the cookie-value is the
- // value string.
- return {
- name, value, ...parseUnparsedAttributes(unparsedAttributes)
- }
-}
+ // 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.
-/**
- * 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
- }
+ // 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.
- // 2. Discard the first character of the unparsed-attributes (which
- // will be a %x3B (";") character).
- assert(unparsedAttributes[0] === ';')
- unparsedAttributes = unparsedAttributes.slice(1)
+ // 4. Set timingInfo’s final network-request start time to the coarsened
+ // shared current time given fetchParams’s cross-origin isolated
+ // capability.
- let cookieAv = ''
+ // 5. Set response to the result of making an HTTP request over connection
+ // using request with the following caveats:
- // 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:
+ // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS]
+ // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH]
- // 1. Consume the remainder of the unparsed-attributes.
- cookieAv = unparsedAttributes
- unparsedAttributes = ''
- }
+ // - 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.
- // Let the cookie-av string be the characters consumed in this step.
+ // - 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).
- let attributeName = ''
- let attributeValue = ''
+ // - Wait until all the headers are transmitted.
- // 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 }
+ // - 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.
- attributeName = collectASequenceOfCodePointsFast(
- '=',
- cookieAv,
- position
- )
- attributeValue = cookieAv.slice(position.position + 1)
- } else {
- // Otherwise:
+ // - If request’s header list contains `Transfer-Encoding`/`chunked` and
+ // response is transferred via HTTP/1.0 or older, then return a network
+ // error.
- // 1. The attribute-name string consists of the entire cookie-av
- // string, and the attribute-value string is empty.
- attributeName = cookieAv
- }
+ // - If the HTTP request results in a TLS client certificate dialog, then:
- // 5. Remove any leading or trailing WSP characters from the attribute-
- // name string and the attribute-value string.
- attributeName = attributeName.trim()
- attributeValue = attributeValue.trim()
+ // 1. If request’s window is an environment settings object, make the
+ // dialog available in request’s window.
- // 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)
- }
+ // 2. Otherwise, return a network error.
- // 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()
+ // 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:
- // 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)
+ // 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. If the attribute-value failed to parse as a cookie date, ignore
- // the cookie-av.
+ // 2. Run this step in parallel: transmit bytes.
+ yield bytes
- 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.
+ // 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)
+ }
- // 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)
+ // 2. Let processEndOfBody be these steps:
+ const processEndOfBody = () => {
+ // 1. If fetchParams is canceled, then abort these steps.
+ if (isCancelled(fetchParams)) {
+ return
+ }
- if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') {
- return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
+ // 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()
+ }
}
- // 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 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)
+ }
}
- // 3. Let delta-seconds be the attribute-value converted to an integer.
- const deltaSeconds = Number(attributeValue)
+ // 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 })
- // 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).
+ if (socket) {
+ response = makeResponse({ status, statusText, headersList, socket })
+ } else {
+ const iterator = body[Symbol.asyncIterator]()
+ fetchParams.controller.next = () => iterator.next()
- // 5. Set delta-seconds to the smaller of its present value and cookie-
- // age-limit.
- // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs)
+ 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()
- // 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
+ // 2. Return the appropriate network error for fetchParams.
+ return makeAppropriateNetworkError(fetchParams, err)
+ }
- // 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.
+ return makeNetworkError(err)
+ }
- // 1. Let cookie-domain be the attribute-value.
- let cookieDomain = attributeValue
+ // 11. Let pullAlgorithm be an action that resumes the ongoing fetch
+ // if it is suspended.
+ const pullAlgorithm = () => {
+ fetchParams.controller.resume()
+ }
- // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be
- // cookie-domain without its leading %x2E (".").
- if (cookieDomain[0] === '.') {
- cookieDomain = cookieDomain.slice(1)
- }
+ // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s
+ // controller with reason, given reason.
+ const cancelAlgorithm = (reason) => {
+ fetchParams.controller.abort(reason)
+ }
- // 3. Convert the cookie-domain to lower case.
- cookieDomain = cookieDomain.toLowerCase()
+ // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by
+ // the user agent.
+ // TODO
- // 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.
+ // 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
- // 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:
+ // 15. Let stream be a new ReadableStream.
+ // 16. Set up stream with pullAlgorithm set to pullAlgorithm,
+ // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to
+ // highWaterMark, and sizeAlgorithm set to sizeAlgorithm.
+ if (!ReadableStream) {
+ ReadableStream = (__nccwpck_require__(63774).ReadableStream)
+ }
- // 1. Let cookie-path be the attribute-value.
- cookiePath = attributeValue
+ const stream = new ReadableStream(
+ {
+ async start (controller) {
+ fetchParams.controller.controller = controller
+ },
+ async pull (controller) {
+ await pullAlgorithm(controller)
+ },
+ async cancel (reason) {
+ await cancelAlgorithm(reason)
+ }
+ },
+ {
+ highWaterMark: 0,
+ size () {
+ return 1
+ }
}
+ )
- // 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.
+ // 17. Run these steps, but abort when the ongoing fetch is terminated:
- 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. Set response’s body to a new body whose stream is stream.
+ response.body = { stream }
- // 1. Let enforcement be "Default".
- let enforcement = 'Default'
+ // 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
- 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 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
- // 3. If cookie-av's attribute-value is a case-insensitive match for
- // "Strict", set enforcement to "Strict".
- if (attributeValueLowercase.includes('strict')) {
- enforcement = 'Strict'
- }
+ // 18. If aborted, then:
+ // TODO
- // 4. If cookie-av's attribute-value is a case-insensitive match for
- // "Lax", set enforcement to "Lax".
- if (attributeValueLowercase.includes('lax')) {
- enforcement = 'Lax'
- }
+ // 19. Run these steps in parallel:
- // 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 ??= []
+ // 1. Run these steps, but abort when fetchParams is canceled:
+ fetchParams.controller.on('terminated', onAborted)
+ fetchParams.controller.resume = async () => {
+ // 1. While true
+ while (true) {
+ // 1-3. See onData...
- cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`)
- }
+ // 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()
- // 8. Return to Step 1 of this algorithm.
- return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
-}
+ if (isAborted(fetchParams)) {
+ break
+ }
-module.exports = {
- parseSetCookie,
- parseUnparsedAttributes
-}
+ 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)
-/***/ 3834:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ finalizeResponse(fetchParams, response)
-"use strict";
+ return
+ }
+ // 5. Increase timingInfo’s decoded body size by bytes’s length.
+ timingInfo.decodedBodySize += bytes?.byteLength ?? 0
-const assert = __nccwpck_require__(2613)
-const { kHeadersList } = __nccwpck_require__(6443)
+ // 6. If bytes is failure, then terminate fetchParams’s controller.
+ if (isFailure) {
+ fetchParams.controller.terminate(bytes)
+ return
+ }
-function isCTLExcludingHtab (value) {
- if (value.length === 0) {
- return false
- }
+ // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes
+ // into stream.
+ fetchParams.controller.controller.enqueue(new Uint8Array(bytes))
- for (const char of value) {
- const code = char.charCodeAt(0)
+ // 8. If stream is errored, then terminate the ongoing fetch.
+ if (isErrored(stream)) {
+ fetchParams.controller.terminate()
+ return
+ }
- if (
- (code >= 0x00 || code <= 0x08) ||
- (code >= 0x0A || code <= 0x1F) ||
- code === 0x7F
- ) {
- return false
+ // 9. If stream doesn’t need more data ask the user agent to suspend
+ // the ongoing fetch.
+ if (!fetchParams.controller.controller.desiredSize) {
+ return
+ }
}
}
-}
-/**
- CHAR =
- token = 1*
- separators = "(" | ")" | "<" | ">" | "@"
- | "," | ";" | ":" | "\" | <">
- | "/" | "[" | "]" | "?" | "="
- | "{" | "}" | SP | HT
- * @param {string} name
- */
-function validateCookieName (name) {
- for (const char of name) {
- const code = char.charCodeAt(0)
+ // 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
- if (
- (code <= 0x20 || code > 0x7F) ||
- char === '(' ||
- char === ')' ||
- char === '>' ||
- char === '<' ||
- char === '@' ||
- char === ',' ||
- char === ';' ||
- char === ':' ||
- char === '\\' ||
- char === '"' ||
- char === '/' ||
- char === '[' ||
- char === ']' ||
- char === '?' ||
- char === '=' ||
- char === '{' ||
- char === '}'
- ) {
- throw new Error('Invalid cookie name')
+ // 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()
}
-}
-/**
- 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) {
- for (const char of value) {
- const code = char.charCodeAt(0)
+ // 20. Return response.
+ return response
- if (
- code < 0x21 || // exclude CTLs (0-31)
- code === 0x22 ||
- code === 0x2C ||
- code === 0x3B ||
- code === 0x5C ||
- code > 0x7E // non-ascii
- ) {
- throw new Error('Invalid header value')
- }
- }
-}
+ async function dispatch ({ body }) {
+ const url = requestCurrentURL(request)
+ /** @type {import('../..').Agent} */
+ const agent = fetchParams.controller.dispatcher
-/**
- * path-value =
- * @param {string} path
- */
-function validateCookiePath (path) {
- for (const char of path) {
- const code = char.charCodeAt(0)
+ return new Promise((resolve, reject) => agent.dispatch(
+ {
+ path: url.pathname + url.search,
+ origin: url.origin,
+ method: request.method,
+ body: fetchParams.controller.dispatcher.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,
- if (code < 0x21 || char === ';') {
- throw new Error('Invalid cookie path')
- }
- }
-}
+ onConnect (abort) {
+ // TODO (fix): Do we need connection here?
+ const { connection } = fetchParams.controller
-/**
- * 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')
- }
-}
+ if (connection.destroyed) {
+ abort(new DOMException('The operation was aborted.', 'AbortError'))
+ } else {
+ fetchParams.controller.on('terminated', abort)
+ this.abort = connection.abort = abort
+ }
+ },
-/**
- * @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]
+ onHeaders (status, headersList, resume, statusText) {
+ if (status < 200) {
+ return
+ }
- 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
+ let codings = []
+ let location = ''
- 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
+ const headers = new Headers()
- GMT = %x47.4D.54 ; "GMT", case-sensitive
+ // For H2, the headers are a plain JS object
+ // We distinguish between them and iterate accordingly
+ if (Array.isArray(headersList)) {
+ for (let n = 0; n < headersList.length; n += 2) {
+ const key = headersList[n + 0].toString('latin1')
+ const val = headersList[n + 1].toString('latin1')
+ if (key.toLowerCase() === 'content-encoding') {
+ // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
+ // "All content-coding values are case-insensitive..."
+ codings = val.toLowerCase().split(',').map((x) => x.trim())
+ } else if (key.toLowerCase() === 'location') {
+ location = val
+ }
- time-of-day = hour ":" minute ":" second
- ; 00:00:00 - 23:59:60 (leap second)
+ headers[kHeadersList].append(key, val)
+ }
+ } else {
+ const keys = Object.keys(headersList)
+ for (const key of keys) {
+ const val = headersList[key]
+ if (key.toLowerCase() === 'content-encoding') {
+ // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
+ // "All content-coding values are case-insensitive..."
+ codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse()
+ } else if (key.toLowerCase() === 'location') {
+ location = val
+ }
- hour = 2DIGIT
- minute = 2DIGIT
- second = 2DIGIT
- */
-function toIMFDate (date) {
- if (typeof date === 'number') {
- date = new Date(date)
- }
+ headers[kHeadersList].append(key, val)
+ }
+ }
- const days = [
- 'Sun', 'Mon', 'Tue', 'Wed',
- 'Thu', 'Fri', 'Sat'
- ]
+ this.body = new Readable({ read: resume })
- const months = [
- 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
- 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
- ]
+ const decoders = []
- const dayName = days[date.getUTCDay()]
- const day = date.getUTCDate().toString().padStart(2, '0')
- const month = months[date.getUTCMonth()]
- const year = date.getUTCFullYear()
- const hour = date.getUTCHours().toString().padStart(2, '0')
- const minute = date.getUTCMinutes().toString().padStart(2, '0')
- const second = date.getUTCSeconds().toString().padStart(2, '0')
+ const willFollow = request.redirect === 'follow' &&
+ location &&
+ redirectStatusSet.has(status)
+
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
+ if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {
+ for (const coding of codings) {
+ // 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(zlib.createInflate())
+ } else if (coding === 'br') {
+ decoders.push(zlib.createBrotliDecompress())
+ } else {
+ decoders.length = 0
+ break
+ }
+ }
+ }
- return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT`
-}
+ resolve({
+ status,
+ statusText,
+ headersList: headers[kHeadersList],
+ body: decoders.length
+ ? pipeline(this.body, ...decoders, () => { })
+ : this.body.on('error', () => {})
+ })
-/**
- 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')
- }
-}
+ return true
+ },
-/**
- * @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
- }
+ onData (chunk) {
+ if (fetchParams.controller.dump) {
+ return
+ }
- validateCookieName(cookie.name)
- validateCookieValue(cookie.value)
+ // 1. If one or more bytes have been transmitted from response’s
+ // message body, then:
- const out = [`${cookie.name}=${cookie.value}`]
+ // 1. Let bytes be the transmitted bytes.
+ const bytes = chunk
- // 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
- }
+ // 2. Let codings be the result of extracting header list values
+ // given `Content-Encoding` and response’s header list.
+ // See pullAlgorithm.
- if (cookie.name.startsWith('__Host-')) {
- cookie.secure = true
- cookie.domain = null
- cookie.path = '/'
- }
+ // 3. Increase timingInfo’s encoded body size by bytes’s length.
+ timingInfo.encodedBodySize += bytes.byteLength
- if (cookie.secure) {
- out.push('Secure')
- }
+ // 4. See pullAlgorithm...
- if (cookie.httpOnly) {
- out.push('HttpOnly')
- }
+ return this.body.push(bytes)
+ },
- if (typeof cookie.maxAge === 'number') {
- validateCookieMaxAge(cookie.maxAge)
- out.push(`Max-Age=${cookie.maxAge}`)
- }
+ onComplete () {
+ if (this.abort) {
+ fetchParams.controller.off('terminated', this.abort)
+ }
- if (cookie.domain) {
- validateCookieDomain(cookie.domain)
- out.push(`Domain=${cookie.domain}`)
- }
+ fetchParams.controller.ended = true
- if (cookie.path) {
- validateCookiePath(cookie.path)
- out.push(`Path=${cookie.path}`)
- }
+ this.body.push(null)
+ },
- if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') {
- out.push(`Expires=${toIMFDate(cookie.expires)}`)
- }
+ onError (error) {
+ if (this.abort) {
+ fetchParams.controller.off('terminated', this.abort)
+ }
- if (cookie.sameSite) {
- out.push(`SameSite=${cookie.sameSite}`)
- }
+ this.body?.destroy(error)
- for (const part of cookie.unparsed) {
- if (!part.includes('=')) {
- throw new Error('Invalid unparsed')
- }
+ fetchParams.controller.terminate(error)
- const [key, ...value] = part.split('=')
+ reject(error)
+ },
- out.push(`${key.trim()}=${value.join('=')}`)
- }
+ onUpgrade (status, headersList, socket) {
+ if (status !== 101) {
+ return
+ }
- return out.join('; ')
-}
+ const headers = new Headers()
-let kHeadersListNode
+ for (let n = 0; n < headersList.length; n += 2) {
+ const key = headersList[n + 0].toString('latin1')
+ const val = headersList[n + 1].toString('latin1')
-function getHeadersList (headers) {
- if (headers[kHeadersList]) {
- return headers[kHeadersList]
- }
+ headers[kHeadersList].append(key, val)
+ }
- if (!kHeadersListNode) {
- kHeadersListNode = Object.getOwnPropertySymbols(headers).find(
- (symbol) => symbol.description === 'headers list'
- )
+ resolve({
+ status,
+ statusText: STATUS_CODES[status],
+ headersList: headers[kHeadersList],
+ socket
+ })
- assert(kHeadersListNode, 'Headers cannot be parsed')
+ return true
+ }
+ }
+ ))
}
-
- const headersList = headers[kHeadersListNode]
- assert(headersList)
-
- return headersList
}
module.exports = {
- isCTLExcludingHtab,
- stringify,
- getHeadersList
+ fetch,
+ Fetch,
+ fetching,
+ finalizeAndReportTiming
}
/***/ }),
-/***/ 9136:
+/***/ 25194:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
+/* globals AbortController */
+
-const net = __nccwpck_require__(9278)
-const assert = __nccwpck_require__(2613)
+const { extractBody, mixinBody, cloneBody } = __nccwpck_require__(8923)
+const { Headers, fill: fillHeaders, HeadersList } = __nccwpck_require__(26349)
+const { FinalizationRegistry } = __nccwpck_require__(13194)()
const util = __nccwpck_require__(3440)
-const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(8707)
+const {
+ isValidHTTPToken,
+ sameOrigin,
+ normalizeMethod,
+ makePolicyContainer,
+ normalizeMethodRecord
+} = __nccwpck_require__(15523)
+const {
+ forbiddenMethodsSet,
+ corsSafeListedMethodsSet,
+ referrerPolicy,
+ requestRedirect,
+ requestMode,
+ requestCredentials,
+ requestCache,
+ requestDuplex
+} = __nccwpck_require__(87326)
+const { kEnumerableProperty } = util
+const { kHeaders, kSignal, kState, kGuard, kRealm } = __nccwpck_require__(89710)
+const { webidl } = __nccwpck_require__(74222)
+const { getGlobalOrigin } = __nccwpck_require__(75628)
+const { URLSerializer } = __nccwpck_require__(94322)
+const { kHeadersList, kConstruct } = __nccwpck_require__(36443)
+const assert = __nccwpck_require__(42613)
+const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(24434)
-let tls // include tls conditionally since it is not always available
+let TransformStream = globalThis.TransformStream
-// 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 kAbortController = Symbol('abortController')
-let SessionCache
-// FIXME: remove workaround when the Node bug is fixed
-// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
-if (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) {
- SessionCache = class WeakSessionCache {
- constructor (maxCachedSessions) {
- this._maxCachedSessions = maxCachedSessions
- this._sessionCache = new Map()
- this._sessionRegistry = new global.FinalizationRegistry((key) => {
- if (this._sessionCache.size < this._maxCachedSessions) {
- return
- }
+const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {
+ signal.removeEventListener('abort', abort)
+})
- const ref = this._sessionCache.get(key)
- if (ref !== undefined && ref.deref() === undefined) {
- this._sessionCache.delete(key)
- }
- })
+// https://fetch.spec.whatwg.org/#request-class
+class Request {
+ // https://fetch.spec.whatwg.org/#dom-request
+ constructor (input, init = {}) {
+ if (input === kConstruct) {
+ return
}
- get (sessionKey) {
- const ref = this._sessionCache.get(sessionKey)
- return ref ? ref.deref() : null
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' })
+
+ input = webidl.converters.RequestInfo(input)
+ init = webidl.converters.RequestInit(init)
+
+ // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object
+ this[kRealm] = {
+ settingsObject: {
+ baseUrl: getGlobalOrigin(),
+ get origin () {
+ return this.baseUrl?.origin
+ },
+ policyContainer: makePolicyContainer()
+ }
}
- set (sessionKey, session) {
- if (this._maxCachedSessions === 0) {
- return
+ // 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 = this[kRealm].settingsObject.baseUrl
+
+ // 4. Let signal be null.
+ let signal = null
+
+ // 5. If input is a string, then:
+ if (typeof input === 'string') {
+ // 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 })
}
- this._sessionCache.set(sessionKey, new WeakRef(session))
- this._sessionRegistry.register(session, sessionKey)
+ // 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(input instanceof Request)
+
+ // 8. Set request to input’s request.
+ request = input[kState]
+
+ // 9. Set signal to input’s signal.
+ signal = input[kSignal]
}
- }
-} else {
- SessionCache = class SimpleSessionCache {
- constructor (maxCachedSessions) {
- this._maxCachedSessions = maxCachedSessions
- this._sessionCache = new Map()
+
+ // 7. Let origin be this’s relevant settings object’s origin.
+ const origin = this[kRealm].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
}
- get (sessionKey) {
- return this._sessionCache.get(sessionKey)
+ // 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`)
}
- set (sessionKey, session) {
- if (this._maxCachedSessions === 0) {
- return
- }
+ // 11. If init["window"] exists, then set window to "no-window".
+ if ('window' in init) {
+ window = 'no-window'
+ }
- if (this._sessionCache.size >= this._maxCachedSessions) {
- // remove the oldest session
- const { value: oldestKey } = this._sessionCache.keys().next()
- this._sessionCache.delete(oldestKey)
+ // 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: this[kRealm].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'
}
- this._sessionCache.set(sessionKey, session)
+ // 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]
}
- }
-}
-function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) {
- if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {
- throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero')
- }
+ // 14. If init["referrer"] exists, then:
+ if (init.referrer !== undefined) {
+ // 1. Let referrer be init["referrer"].
+ const referrer = init.referrer
- 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__(4756)
+ // 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, this[kRealm].settingsObject.baseUrl))
+ ) {
+ request.referrer = 'client'
+ } else {
+ // 4. Otherwise, set request’s referrer to parsedReferrer.
+ request.referrer = parsedReferrer
+ }
}
- servername = servername || options.servername || util.getServerName(host) || null
+ }
- const sessionKey = servername || hostname
- const session = sessionCache.get(sessionKey) || null
+ // 15. If init["referrerPolicy"] exists, then set request’s referrer policy
+ // to it.
+ if (init.referrerPolicy !== undefined) {
+ request.referrerPolicy = init.referrerPolicy
+ }
- assert(sessionKey)
+ // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise.
+ let mode
+ if (init.mode !== undefined) {
+ mode = init.mode
+ } else {
+ mode = fallbackMode
+ }
- socket = tls.connect({
- highWaterMark: 16384, // TLS in node can't have bigger HWM anyway...
- ...options,
- servername,
- session,
- localAddress,
- // TODO(HTTP/2): Add support for h2c
- ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'],
- socket: httpSocket, // upgrade socket connection
- port: port || 443,
- host: hostname
+ // 17. If mode is "navigate", then throw a TypeError.
+ if (mode === 'navigate') {
+ throw webidl.errors.exception({
+ header: 'Request constructor',
+ message: 'invalid request mode navigate.'
})
+ }
- 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')
- socket = net.connect({
- highWaterMark: 64 * 1024, // Same as nodejs fs streams.
- ...options,
- localAddress,
- port: port || 80,
- host: hostname
- })
+ // 18. If mode is non-null, set request’s mode to mode.
+ if (mode != null) {
+ request.mode = mode
}
- // 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)
+ // 19. If init["credentials"] exists, then set request’s credentials mode
+ // to it.
+ if (init.credentials !== undefined) {
+ request.credentials = init.credentials
}
- const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout)
+ // 18. If init["cache"] exists, then set request’s cache mode to it.
+ if (init.cache !== undefined) {
+ request.cache = init.cache
+ }
- socket
- .setNoDelay(true)
- .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () {
- cancelTimeout()
+ // 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"
+ )
+ }
- if (callback) {
- const cb = callback
- callback = null
- cb(null, this)
- }
- })
- .on('error', function (err) {
- cancelTimeout()
+ // 22. If init["redirect"] exists, then set request’s redirect mode to it.
+ if (init.redirect !== undefined) {
+ request.redirect = init.redirect
+ }
- if (callback) {
- const cb = callback
- callback = null
- cb(err)
- }
- })
+ // 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)
+ }
- return socket
- }
-}
+ // 25. If init["method"] exists, then:
+ if (init.method !== undefined) {
+ // 1. Let method be init["method"].
+ let method = init.method
-function setupTimeout (onConnectTimeout, timeout) {
- if (!timeout) {
- return () => {}
- }
+ // 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.`)
+ }
- let s1 = null
- let s2 = null
- const timeoutId = setTimeout(() => {
- // setImmediate is added to make sure that we priotorise socket error events over timeouts
- s1 = setImmediate(() => {
- if (process.platform === 'win32') {
- // Windows needs an extra setImmediate probably due to implementation differences in the socket logic
- s2 = setImmediate(() => onConnectTimeout())
- } else {
- onConnectTimeout()
+ if (forbiddenMethodsSet.has(method.toUpperCase())) {
+ throw new TypeError(`'${method}' HTTP method is unsupported.`)
}
- })
- }, timeout)
- return () => {
- clearTimeout(timeoutId)
- clearImmediate(s1)
- clearImmediate(s2)
- }
-}
-function onConnectTimeout (socket) {
- util.destroy(socket, new ConnectTimeoutError())
-}
+ // 3. Normalize method.
+ method = normalizeMethodRecord[method] ?? normalizeMethod(method)
-module.exports = buildConnector
+ // 4. Set request’s method to method.
+ request.method = method
+ }
+ // 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[kState] = request
-/***/ 735:
-/***/ ((module) => {
+ // 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[kSignal] = ac.signal
+ this[kSignal][kRealm] = this[kRealm]
-"use strict";
+ // 29. If signal is not null, then make this’s signal follow signal.
+ if (signal != null) {
+ if (
+ !signal ||
+ typeof signal.aborted !== 'boolean' ||
+ typeof signal.addEventListener !== 'function'
+ ) {
+ throw new TypeError(
+ "Failed to construct 'Request': member signal is not of type AbortSignal."
+ )
+ }
+ 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
-/** @type {Record} */
-const headerNameLowerCasedRecord = {}
+ const acRef = new WeakRef(ac)
+ const abort = function () {
+ const ac = acRef.deref()
+ if (ac !== undefined) {
+ ac.abort(this.reason)
+ }
+ }
-// https://developer.mozilla.org/docs/Web/HTTP/Headers
-const wellknownHeaderNames = [
- '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'
-]
+ // Third-party AbortControllers may not work with these.
+ // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619.
+ try {
+ // If the max amount of listeners is equal to the default, increase it
+ // This is only available in node >= v19.9.0
+ if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) {
+ setMaxListeners(100, signal)
+ } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) {
+ setMaxListeners(100, signal)
+ }
+ } catch {}
-for (let i = 0; i < wellknownHeaderNames.length; ++i) {
- const key = wellknownHeaderNames[i]
- const lowerCasedKey = key.toLowerCase()
- headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] =
- lowerCasedKey
-}
+ util.addAbortListener(signal, abort)
+ requestFinalizer.register(ac, { signal, abort })
+ }
+ }
-// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
-Object.setPrototypeOf(headerNameLowerCasedRecord, null)
+ // 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[kHeaders] = new Headers(kConstruct)
+ this[kHeaders][kHeadersList] = request.headersList
+ this[kHeaders][kGuard] = 'request'
+ this[kHeaders][kRealm] = this[kRealm]
-module.exports = {
- wellknownHeaderNames,
- headerNameLowerCasedRecord
-}
+ // 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".
+ this[kHeaders][kGuard] = 'request-no-cors'
+ }
-/***/ }),
+ // 32. If init is not empty, then:
+ if (initHasKey) {
+ /** @type {HeadersList} */
+ const headersList = this[kHeaders][kHeadersList]
+ // 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)
-/***/ 8707:
-/***/ ((module) => {
+ // 3. Empty this’s headers’s header list.
+ headersList.clear()
-"use strict";
+ // 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 [key, val] of headers) {
+ headersList.append(key, val)
+ }
+ // Note: Copy the `set-cookie` meta-data.
+ headersList.cookies = headers.cookies
+ } else {
+ // 5. Otherwise, fill this’s headers with headers.
+ fillHeaders(this[kHeaders], headers)
+ }
+ }
+ // 33. Let inputBody be input’s request’s body if input is a Request
+ // object; otherwise null.
+ const inputBody = input instanceof Request ? input[kState].body : null
-class UndiciError extends Error {
- constructor (message) {
- super(message)
- this.name = 'UndiciError'
- this.code = 'UND_ERR'
- }
-}
+ // 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.')
+ }
-class ConnectTimeoutError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, ConnectTimeoutError)
- this.name = 'ConnectTimeoutError'
- this.message = message || 'Connect Timeout Error'
- this.code = 'UND_ERR_CONNECT_TIMEOUT'
- }
-}
+ // 35. Let initBody be null.
+ let initBody = null
-class HeadersTimeoutError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, HeadersTimeoutError)
- this.name = 'HeadersTimeoutError'
- this.message = message || 'Headers Timeout Error'
- this.code = 'UND_ERR_HEADERS_TIMEOUT'
- }
-}
+ // 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
-class HeadersOverflowError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, HeadersOverflowError)
- this.name = 'HeadersOverflowError'
- this.message = message || 'Headers Overflow Error'
- this.code = 'UND_ERR_HEADERS_OVERFLOW'
- }
-}
+ // 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 && !this[kHeaders][kHeadersList].contains('content-type')) {
+ this[kHeaders].append('content-type', contentType)
+ }
+ }
-class BodyTimeoutError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, BodyTimeoutError)
- this.name = 'BodyTimeoutError'
- this.message = message || 'Body Timeout Error'
- this.code = 'UND_ERR_BODY_TIMEOUT'
- }
-}
+ // 37. Let inputOrInitBody be initBody if it is non-null; otherwise
+ // inputBody.
+ const inputOrInitBody = initBody ?? inputBody
-class ResponseStatusCodeError extends UndiciError {
- constructor (message, statusCode, headers, body) {
- super(message)
- Error.captureStackTrace(this, ResponseStatusCodeError)
- 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
- }
-}
+ // 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.')
+ }
-class InvalidArgumentError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, InvalidArgumentError)
- this.name = 'InvalidArgumentError'
- this.message = message || 'Invalid Argument Error'
- this.code = 'UND_ERR_INVALID_ARG'
- }
-}
+ // 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"'
+ )
+ }
-class InvalidReturnValueError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, InvalidReturnValueError)
- this.name = 'InvalidReturnValueError'
- this.message = message || 'Invalid Return Value Error'
- this.code = 'UND_ERR_INVALID_RETURN_VALUE'
- }
-}
+ // 3. Set this’s request’s use-CORS-preflight flag.
+ request.useCORSPreflightFlag = true
+ }
-class RequestAbortedError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, RequestAbortedError)
- this.name = 'AbortError'
- this.message = message || 'Request aborted'
- this.code = 'UND_ERR_ABORTED'
- }
-}
+ // 39. Let finalBody be inputOrInitBody.
+ let finalBody = inputOrInitBody
-class InformationalError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, InformationalError)
- this.name = 'InformationalError'
- this.message = message || 'Request information'
- this.code = 'UND_ERR_INFO'
- }
-}
+ // 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 (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) {
+ throw new TypeError(
+ 'Cannot construct a Request with a Request object that has already been used.'
+ )
+ }
-class RequestContentLengthMismatchError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, RequestContentLengthMismatchError)
- this.name = 'RequestContentLengthMismatchError'
- this.message = message || 'Request body length does not match content-length header'
- this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
- }
-}
+ // 2. Set finalBody to the result of creating a proxy for inputBody.
+ if (!TransformStream) {
+ TransformStream = (__nccwpck_require__(63774).TransformStream)
+ }
-class ResponseContentLengthMismatchError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, ResponseContentLengthMismatchError)
- this.name = 'ResponseContentLengthMismatchError'
- this.message = message || 'Response body length does not match content-length header'
- this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'
- }
-}
+ // 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
+ }
+ }
-class ClientDestroyedError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, ClientDestroyedError)
- this.name = 'ClientDestroyedError'
- this.message = message || 'The client is destroyed'
- this.code = 'UND_ERR_DESTROYED'
+ // 41. Set this’s request’s body to finalBody.
+ this[kState].body = finalBody
}
-}
-class ClientClosedError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, ClientClosedError)
- this.name = 'ClientClosedError'
- this.message = message || 'The client is closed'
- this.code = 'UND_ERR_CLOSED'
- }
-}
+ // Returns request’s HTTP method, which is "GET" by default.
+ get method () {
+ webidl.brandCheck(this, Request)
-class SocketError extends UndiciError {
- constructor (message, socket) {
- super(message)
- Error.captureStackTrace(this, SocketError)
- this.name = 'SocketError'
- this.message = message || 'Socket error'
- this.code = 'UND_ERR_SOCKET'
- this.socket = socket
+ // The method getter steps are to return this’s request’s method.
+ return this[kState].method
}
-}
-class NotSupportedError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, NotSupportedError)
- this.name = 'NotSupportedError'
- this.message = message || 'Not supported error'
- this.code = 'UND_ERR_NOT_SUPPORTED'
- }
-}
+ // Returns the URL of request as a string.
+ get url () {
+ webidl.brandCheck(this, Request)
-class BalancedPoolMissingUpstreamError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, NotSupportedError)
- this.name = 'MissingUpstreamError'
- this.message = message || 'No upstream has been added to the BalancedPool'
- this.code = 'UND_ERR_BPL_MISSING_UPSTREAM'
+ // The url getter steps are to return this’s request’s URL, serialized.
+ return URLSerializer(this[kState].url)
}
-}
-class HTTPParserError extends Error {
- constructor (message, code, data) {
- super(message)
- Error.captureStackTrace(this, HTTPParserError)
- this.name = 'HTTPParserError'
- this.code = code ? `HPE_${code}` : undefined
- this.data = data ? data.toString() : undefined
- }
-}
+ // 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)
-class ResponseExceededMaxSizeError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, ResponseExceededMaxSizeError)
- this.name = 'ResponseExceededMaxSizeError'
- this.message = message || 'Response content exceeded max size'
- this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE'
+ // The headers getter steps are to return this’s headers.
+ return this[kHeaders]
}
-}
-class RequestRetryError extends UndiciError {
- constructor (message, code, { headers, data }) {
- super(message)
- Error.captureStackTrace(this, RequestRetryError)
- this.name = 'RequestRetryError'
- this.message = message || 'Request retry error'
- this.code = 'UND_ERR_REQ_RETRY'
- this.statusCode = code
- this.data = data
- this.headers = 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[kState].destination
}
-}
-module.exports = {
- HTTPParserError,
- UndiciError,
- HeadersTimeoutError,
- HeadersOverflowError,
- BodyTimeoutError,
- RequestContentLengthMismatchError,
- ConnectTimeoutError,
- ResponseStatusCodeError,
- InvalidArgumentError,
- InvalidReturnValueError,
- RequestAbortedError,
- ClientDestroyedError,
- ClientClosedError,
- InformationalError,
- SocketError,
- NotSupportedError,
- ResponseContentLengthMismatchError,
- BalancedPoolMissingUpstreamError,
- ResponseExceededMaxSizeError,
- RequestRetryError
-}
+ // 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[kState].referrer === 'no-referrer') {
+ return ''
+ }
-/***/ }),
+ // 2. If this’s request’s referrer is "client", then return
+ // "about:client".
+ if (this[kState].referrer === 'client') {
+ return 'about:client'
+ }
-/***/ 4655:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // Return this’s request’s referrer, serialized.
+ return this[kState].referrer.toString()
+ }
-"use strict";
+ // 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[kState].referrerPolicy
+ }
-const {
- InvalidArgumentError,
- NotSupportedError
-} = __nccwpck_require__(8707)
-const assert = __nccwpck_require__(2613)
-const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(6443)
-const util = __nccwpck_require__(3440)
+ // 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)
-// tokenRegExp and headerCharRegex have been lifted from
-// https://github.com/nodejs/node/blob/main/lib/_http_common.js
+ // The mode getter steps are to return this’s request’s mode.
+ return this[kState].mode
+ }
-/**
- * Verifies that the given val is a valid HTTP token
- * per the rules defined in RFC 7230
- * See https://tools.ietf.org/html/rfc7230#section-3.2.6
- */
-const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/
+ // 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 () {
+ // The credentials getter steps are to return this’s request’s credentials mode.
+ return this[kState].credentials
+ }
-/**
- * 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]/
+ // 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)
-// Verifies that a given path is valid does not contain control chars \x00 to \x20
-const invalidPathRegex = /[^\u0021-\u00ff]/
+ // The cache getter steps are to return this’s request’s cache mode.
+ return this[kState].cache
+ }
-const kHandler = Symbol('handler')
+ // 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)
-const channels = {}
+ // The redirect getter steps are to return this’s request’s redirect mode.
+ return this[kState].redirect
+ }
-let extractBody
+ // 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)
-try {
- const diagnosticsChannel = __nccwpck_require__(1637)
- channels.create = diagnosticsChannel.channel('undici:request:create')
- channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent')
- channels.headers = diagnosticsChannel.channel('undici:request:headers')
- channels.trailers = diagnosticsChannel.channel('undici:request:trailers')
- channels.error = diagnosticsChannel.channel('undici:request:error')
-} catch {
- channels.create = { hasSubscribers: false }
- channels.bodySent = { hasSubscribers: false }
- channels.headers = { hasSubscribers: false }
- channels.trailers = { hasSubscribers: false }
- channels.error = { hasSubscribers: false }
-}
+ // The integrity getter steps are to return this’s request’s integrity
+ // metadata.
+ return this[kState].integrity
+ }
-class Request {
- constructor (origin, {
- path,
- method,
- body,
- headers,
- query,
- idempotent,
- blocking,
- upgrade,
- headersTimeout,
- bodyTimeout,
- reset,
- throwOnError,
- expectContinue
- }, 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.exec(path) !== null) {
- throw new InvalidArgumentError('invalid request path')
- }
+ // Returns a boolean indicating whether or not request can outlive the
+ // global in which it was created.
+ get keepalive () {
+ webidl.brandCheck(this, Request)
- if (typeof method !== 'string') {
- throw new InvalidArgumentError('method must be a string')
- } else if (tokenRegExp.exec(method) === null) {
- throw new InvalidArgumentError('invalid request method')
- }
+ // The keepalive getter steps are to return this’s request’s keepalive.
+ return this[kState].keepalive
+ }
- if (upgrade && typeof upgrade !== 'string') {
- throw new InvalidArgumentError('upgrade must be a string')
- }
+ // Returns a boolean indicating whether or not request is for a reload
+ // navigation.
+ get isReloadNavigation () {
+ webidl.brandCheck(this, Request)
- if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
- throw new InvalidArgumentError('invalid headersTimeout')
- }
+ // The isReloadNavigation getter steps are to return true if this’s
+ // request’s reload-navigation flag is set; otherwise false.
+ return this[kState].reloadNavigation
+ }
- if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
- throw new InvalidArgumentError('invalid bodyTimeout')
- }
+ // Returns a boolean indicating whether or not request is for a history
+ // navigation (a.k.a. back-foward navigation).
+ get isHistoryNavigation () {
+ webidl.brandCheck(this, Request)
- if (reset != null && typeof reset !== 'boolean') {
- throw new InvalidArgumentError('invalid reset')
- }
+ // The isHistoryNavigation getter steps are to return true if this’s request’s
+ // history-navigation flag is set; otherwise false.
+ return this[kState].historyNavigation
+ }
- if (expectContinue != null && typeof expectContinue !== 'boolean') {
- throw new InvalidArgumentError('invalid expectContinue')
- }
+ // 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)
- this.headersTimeout = headersTimeout
+ // The signal getter steps are to return this’s signal.
+ return this[kSignal]
+ }
- this.bodyTimeout = bodyTimeout
+ get body () {
+ webidl.brandCheck(this, Request)
- this.throwOnError = throwOnError === true
+ return this[kState].body ? this[kState].body.stream : null
+ }
- this.method = method
+ get bodyUsed () {
+ webidl.brandCheck(this, Request)
- this.abort = null
+ return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
+ }
- if (body == null) {
- this.body = null
- } else if (util.isStream(body)) {
- this.body = body
+ get duplex () {
+ webidl.brandCheck(this, Request)
- const rState = this.body._readableState
- if (!rState || !rState.autoDestroy) {
- this.endHandler = function autoDestroy () {
- util.destroy(this)
- }
- this.body.on('end', this.endHandler)
- }
+ return 'half'
+ }
- this.errorHandler = err => {
- if (this.abort) {
- this.abort(err)
- } else {
- this.error = err
- }
- }
- this.body.on('error', this.errorHandler)
- } else if (util.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 (util.isFormDataLike(body) || util.isIterable(body) || util.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')
+ // Returns a clone of request.
+ clone () {
+ webidl.brandCheck(this, Request)
+
+ // 1. If this is unusable, then throw a TypeError.
+ if (this.bodyUsed || this.body?.locked) {
+ throw new TypeError('unusable')
}
- this.completed = false
+ // 2. Let clonedRequest be the result of cloning this’s request.
+ const clonedRequest = cloneRequest(this[kState])
- this.aborted = false
+ // 3. Let clonedRequestObject be the result of creating a Request object,
+ // given clonedRequest, this’s headers’s guard, and this’s relevant Realm.
+ const clonedRequestObject = new Request(kConstruct)
+ clonedRequestObject[kState] = clonedRequest
+ clonedRequestObject[kRealm] = this[kRealm]
+ clonedRequestObject[kHeaders] = new Headers(kConstruct)
+ clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList
+ clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard]
+ clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm]
- this.upgrade = upgrade || null
+ // 4. Make clonedRequestObject’s signal follow this’s signal.
+ const ac = new AbortController()
+ if (this.signal.aborted) {
+ ac.abort(this.signal.reason)
+ } else {
+ util.addAbortListener(
+ this.signal,
+ () => {
+ ac.abort(this.signal.reason)
+ }
+ )
+ }
+ clonedRequestObject[kSignal] = ac.signal
- this.path = query ? util.buildURL(path, query) : path
+ // 4. Return clonedRequestObject.
+ return clonedRequestObject
+ }
+}
- this.origin = origin
+mixinBody(Request)
- this.idempotent = idempotent == null
- ? method === 'HEAD' || method === 'GET'
- : idempotent
+function makeRequest (init) {
+ // https://fetch.spec.whatwg.org/#requests
+ const request = {
+ method: 'GET',
+ localURLsOnly: false,
+ unsafeRequest: false,
+ body: null,
+ client: null,
+ reservedClient: null,
+ replacesClientId: '',
+ window: 'client',
+ keepalive: false,
+ serviceWorkers: 'all',
+ initiator: '',
+ destination: '',
+ priority: null,
+ origin: 'client',
+ policyContainer: 'client',
+ referrer: 'client',
+ referrerPolicy: '',
+ mode: 'no-cors',
+ useCORSPreflightFlag: false,
+ credentials: 'same-origin',
+ useCredentials: false,
+ cache: 'default',
+ redirect: 'follow',
+ integrity: '',
+ cryptoGraphicsNonceMetadata: '',
+ parserMetadata: '',
+ reloadNavigation: false,
+ historyNavigation: false,
+ userActivation: false,
+ taintedOrigin: false,
+ redirectCount: 0,
+ responseTainting: 'basic',
+ preventNoCacheCacheControlHeaderModification: false,
+ done: false,
+ timingAllowFailed: false,
+ ...init,
+ headersList: init.headersList
+ ? new HeadersList(init.headersList)
+ : new HeadersList()
+ }
+ request.url = request.urlList[0]
+ return request
+}
- this.blocking = blocking == null ? false : blocking
+// https://fetch.spec.whatwg.org/#concept-request-clone
+function cloneRequest (request) {
+ // To clone a request request, run these steps:
- this.reset = reset == null ? null : reset
+ // 1. Let newRequest be a copy of request, except for its body.
+ const newRequest = makeRequest({ ...request, body: null })
- this.host = 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)
+ }
- this.contentLength = null
+ // 3. Return newRequest.
+ return newRequest
+}
- this.contentType = null
+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
+ }
+})
- this.headers = ''
+webidl.converters.Request = webidl.interfaceConverter(
+ Request
+)
- // Only for H2
- this.expectContinue = expectContinue != null ? expectContinue : false
+// https://fetch.spec.whatwg.org/#requestinfo
+webidl.converters.RequestInfo = function (V) {
+ if (typeof V === 'string') {
+ return webidl.converters.USVString(V)
+ }
- 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') {
- const keys = Object.keys(headers)
- for (let i = 0; i < keys.length; i++) {
- const key = keys[i]
- processHeader(this, key, headers[key])
- }
- } else if (headers != null) {
- throw new InvalidArgumentError('headers must be an object or an array')
- }
+ if (V instanceof Request) {
+ return webidl.converters.Request(V)
+ }
- if (util.isFormDataLike(this.body)) {
- if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) {
- throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.')
- }
+ return webidl.converters.USVString(V)
+}
- if (!extractBody) {
- extractBody = (__nccwpck_require__(8923).extractBody)
- }
+webidl.converters.AbortSignal = webidl.interfaceConverter(
+ AbortSignal
+)
- const [bodyStream, contentType] = extractBody(body)
- if (this.contentType == null) {
- this.contentType = contentType
- this.headers += `content-type: ${contentType}\r\n`
- }
- this.body = bodyStream.stream
- this.contentLength = bodyStream.length
- } else if (util.isBlobLike(body) && this.contentType == null && body.type) {
- this.contentType = body.type
- this.headers += `content-type: ${body.type}\r\n`
- }
+// 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,
+ { strict: false }
+ )
+ )
+ },
+ {
+ key: 'window',
+ converter: webidl.converters.any
+ },
+ {
+ key: 'duplex',
+ converter: webidl.converters.DOMString,
+ allowedValues: requestDuplex
+ }
+])
- util.validateHandler(handler, method, upgrade)
+module.exports = { Request, makeRequest }
- this.servername = util.getServerName(this.host)
- this[kHandler] = handler
+/***/ }),
- if (channels.create.hasSubscribers) {
- channels.create.publish({ request: this })
- }
- }
+/***/ 48676:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- onBodySent (chunk) {
- if (this[kHandler].onBodySent) {
- try {
- return this[kHandler].onBodySent(chunk)
- } catch (err) {
- this.abort(err)
- }
- }
- }
+"use strict";
- onRequestSent () {
- if (channels.bodySent.hasSubscribers) {
- channels.bodySent.publish({ request: this })
- }
- if (this[kHandler].onRequestSent) {
- try {
- return this[kHandler].onRequestSent()
- } catch (err) {
- this.abort(err)
- }
- }
- }
+const { Headers, HeadersList, fill } = __nccwpck_require__(26349)
+const { extractBody, cloneBody, mixinBody } = __nccwpck_require__(8923)
+const util = __nccwpck_require__(3440)
+const { kEnumerableProperty } = util
+const {
+ isValidReasonPhrase,
+ isCancelled,
+ isAborted,
+ isBlobLike,
+ serializeJavascriptValueToJSONString,
+ isErrorLike,
+ isomorphicEncode
+} = __nccwpck_require__(15523)
+const {
+ redirectStatusSet,
+ nullBodyStatus,
+ DOMException
+} = __nccwpck_require__(87326)
+const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(89710)
+const { webidl } = __nccwpck_require__(74222)
+const { FormData } = __nccwpck_require__(43073)
+const { getGlobalOrigin } = __nccwpck_require__(75628)
+const { URLSerializer } = __nccwpck_require__(94322)
+const { kHeadersList, kConstruct } = __nccwpck_require__(36443)
+const assert = __nccwpck_require__(42613)
+const { types } = __nccwpck_require__(39023)
+
+const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(63774).ReadableStream)
+const textEncoder = new TextEncoder('utf-8')
- onConnect (abort) {
- assert(!this.aborted)
- assert(!this.completed)
+// https://fetch.spec.whatwg.org/#response-class
+class Response {
+ // Creates network error Response.
+ static error () {
+ // TODO
+ const relevantRealm = { settingsObject: {} }
- if (this.error) {
- abort(this.error)
- } else {
- this.abort = abort
- return this[kHandler].onConnect(abort)
- }
+ // 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 = new Response()
+ responseObject[kState] = makeNetworkError()
+ responseObject[kRealm] = relevantRealm
+ responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList
+ responseObject[kHeaders][kGuard] = 'immutable'
+ responseObject[kHeaders][kRealm] = relevantRealm
+ return responseObject
}
- onHeaders (statusCode, headers, resume, statusText) {
- assert(!this.aborted)
- assert(!this.completed)
+ // https://fetch.spec.whatwg.org/#dom-response-json
+ static json (data, init = {}) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' })
- if (channels.headers.hasSubscribers) {
- channels.headers.publish({ request: this, response: { statusCode, headers, statusText } })
+ if (init !== null) {
+ init = webidl.converters.ResponseInit(init)
}
- try {
- return this[kHandler].onHeaders(statusCode, headers, resume, statusText)
- } catch (err) {
- this.abort(err)
- }
- }
+ // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data.
+ const bytes = textEncoder.encode(
+ serializeJavascriptValueToJSONString(data)
+ )
- onData (chunk) {
- assert(!this.aborted)
- assert(!this.completed)
+ // 2. Let body be the result of extracting bytes.
+ const body = extractBody(bytes)
- try {
- return this[kHandler].onData(chunk)
- } catch (err) {
- this.abort(err)
- return false
- }
- }
+ // 3. Let responseObject be the result of creating a Response object, given a new response,
+ // "response", and this’s relevant Realm.
+ const relevantRealm = { settingsObject: {} }
+ const responseObject = new Response()
+ responseObject[kRealm] = relevantRealm
+ responseObject[kHeaders][kGuard] = 'response'
+ responseObject[kHeaders][kRealm] = relevantRealm
- onUpgrade (statusCode, headers, socket) {
- assert(!this.aborted)
- assert(!this.completed)
+ // 4. Perform initialize a response given responseObject, init, and (body, "application/json").
+ initializeResponse(responseObject, init, { body: body[0], type: 'application/json' })
- return this[kHandler].onUpgrade(statusCode, headers, socket)
+ // 5. Return responseObject.
+ return responseObject
}
- onComplete (trailers) {
- this.onFinally()
+ // Creates a redirect Response that redirects to url with status status.
+ static redirect (url, status = 302) {
+ const relevantRealm = { settingsObject: {} }
- assert(!this.aborted)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' })
- this.completed = true
- if (channels.trailers.hasSubscribers) {
- channels.trailers.publish({ request: this, trailers })
- }
+ 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 {
- return this[kHandler].onComplete(trailers)
+ parsedURL = new URL(url, getGlobalOrigin())
} 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 })
+ throw Object.assign(new TypeError('Failed to parse URL from ' + url), {
+ cause: err
+ })
}
- if (this.aborted) {
- return
+ // 3. If status is not a redirect status, then throw a RangeError.
+ if (!redirectStatusSet.has(status)) {
+ throw new RangeError('Invalid status code ' + status)
}
- this.aborted = true
- return this[kHandler].onError(error)
- }
+ // 4. Let responseObject be the result of creating a Response object,
+ // given a new response, "immutable", and this’s relevant Realm.
+ const responseObject = new Response()
+ responseObject[kRealm] = relevantRealm
+ responseObject[kHeaders][kGuard] = 'immutable'
+ responseObject[kHeaders][kRealm] = relevantRealm
- onFinally () {
- if (this.errorHandler) {
- this.body.off('error', this.errorHandler)
- this.errorHandler = null
- }
+ // 5. Set responseObject’s response’s status to status.
+ responseObject[kState].status = status
- if (this.endHandler) {
- this.body.off('end', this.endHandler)
- this.endHandler = null
- }
- }
+ // 6. Let value be parsedURL, serialized and isomorphic encoded.
+ const value = isomorphicEncode(URLSerializer(parsedURL))
- // TODO: adjust to support H2
- addHeader (key, value) {
- processHeader(this, key, value)
- return this
- }
+ // 7. Append `Location`/value to responseObject’s response’s header list.
+ responseObject[kState].headersList.append('location', value)
- static [kHTTP1BuildRequest] (origin, opts, handler) {
- // TODO: Migrate header parsing here, to make Requests
- // HTTP agnostic
- return new Request(origin, opts, handler)
+ // 8. Return responseObject.
+ return responseObject
}
- static [kHTTP2BuildRequest] (origin, opts, handler) {
- const headers = opts.headers
- opts = { ...opts, headers: null }
-
- const request = new Request(origin, opts, handler)
-
- request.headers = {}
-
- 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(request, headers[i], headers[i + 1], true)
- }
- } else if (headers && typeof headers === 'object') {
- const keys = Object.keys(headers)
- for (let i = 0; i < keys.length; i++) {
- const key = keys[i]
- processHeader(request, key, headers[key], true)
- }
- } else if (headers != null) {
- throw new InvalidArgumentError('headers must be an object or an array')
+ // https://fetch.spec.whatwg.org/#dom-response
+ constructor (body = null, init = {}) {
+ if (body !== null) {
+ body = webidl.converters.BodyInit(body)
}
- return request
- }
-
- static [kHTTP2CopyHeaders] (raw) {
- const rawHeaders = raw.split('\r\n')
- const headers = {}
-
- for (const header of rawHeaders) {
- const [key, value] = header.split(': ')
+ init = webidl.converters.ResponseInit(init)
- if (value == null || value.length === 0) continue
+ // TODO
+ this[kRealm] = { settingsObject: {} }
- if (headers[key]) headers[key] += `,${value}`
- else headers[key] = value
- }
+ // 1. Set this’s response to a new response.
+ this[kState] = makeResponse({})
- return headers
- }
-}
+ // 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[kHeaders] = new Headers(kConstruct)
+ this[kHeaders][kGuard] = 'response'
+ this[kHeaders][kHeadersList] = this[kState].headersList
+ this[kHeaders][kRealm] = this[kRealm]
-function processHeaderValue (key, val, skipAppend) {
- if (val && typeof val === 'object') {
- throw new InvalidArgumentError(`invalid ${key} header`)
- }
+ // 3. Let bodyWithType be null.
+ let bodyWithType = null
- val = val != null ? `${val}` : ''
+ // 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 }
+ }
- if (headerCharRegex.exec(val) !== null) {
- throw new InvalidArgumentError(`invalid ${key} header`)
+ // 5. Perform initialize a response given this, init, and bodyWithType.
+ initializeResponse(this, init, bodyWithType)
}
- return skipAppend ? val : `${key}: ${val}\r\n`
-}
-
-function processHeader (request, key, val, skipAppend = false) {
- if (val && (typeof val === 'object' && !Array.isArray(val))) {
- throw new InvalidArgumentError(`invalid ${key} header`)
- } else if (val === undefined) {
- return
- }
+ // Returns response’s type, e.g., "cors".
+ get type () {
+ webidl.brandCheck(this, Response)
- if (
- request.host === null &&
- key.length === 4 &&
- key.toLowerCase() === 'host'
- ) {
- if (headerCharRegex.exec(val) !== null) {
- throw new InvalidArgumentError(`invalid ${key} header`)
- }
- // Consumed by Client
- request.host = val
- } else if (
- request.contentLength === null &&
- key.length === 14 &&
- key.toLowerCase() === 'content-length'
- ) {
- request.contentLength = parseInt(val, 10)
- if (!Number.isFinite(request.contentLength)) {
- throw new InvalidArgumentError('invalid content-length header')
- }
- } else if (
- request.contentType === null &&
- key.length === 12 &&
- key.toLowerCase() === 'content-type'
- ) {
- request.contentType = val
- if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)
- else request.headers += processHeaderValue(key, val)
- } else if (
- key.length === 17 &&
- key.toLowerCase() === 'transfer-encoding'
- ) {
- throw new InvalidArgumentError('invalid transfer-encoding header')
- } else if (
- key.length === 10 &&
- key.toLowerCase() === 'connection'
- ) {
- const value = typeof val === 'string' ? val.toLowerCase() : null
- if (value !== 'close' && value !== 'keep-alive') {
- throw new InvalidArgumentError('invalid connection header')
- } else if (value === 'close') {
- request.reset = true
- }
- } else if (
- key.length === 10 &&
- key.toLowerCase() === 'keep-alive'
- ) {
- throw new InvalidArgumentError('invalid keep-alive header')
- } else if (
- key.length === 7 &&
- key.toLowerCase() === 'upgrade'
- ) {
- throw new InvalidArgumentError('invalid upgrade header')
- } else if (
- key.length === 6 &&
- key.toLowerCase() === 'expect'
- ) {
- throw new NotSupportedError('expect header not supported')
- } else if (tokenRegExp.exec(key) === null) {
- throw new InvalidArgumentError('invalid header key')
- } else {
- if (Array.isArray(val)) {
- for (let i = 0; i < val.length; i++) {
- if (skipAppend) {
- if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}`
- else request.headers[key] = processHeaderValue(key, val[i], skipAppend)
- } else {
- request.headers += processHeaderValue(key, val[i])
- }
- }
- } else {
- if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)
- else request.headers += processHeaderValue(key, val)
- }
+ // The type getter steps are to return this’s response’s type.
+ return this[kState].type
}
-}
-
-module.exports = Request
-
-
-/***/ }),
-
-/***/ 6443:
-/***/ ((module) => {
-
-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'),
- kHeadersList: Symbol('headers list'),
- 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'),
- 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'),
- 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'),
- kInterceptors: Symbol('dispatch interceptors'),
- kMaxResponseSize: Symbol('max response size'),
- kHTTP2Session: Symbol('http2Session'),
- kHTTP2SessionState: Symbol('http2Session state'),
- kHTTP2BuildRequest: Symbol('http2 build request'),
- kHTTP1BuildRequest: Symbol('http1 build request'),
- kHTTP2CopyHeaders: Symbol('http2 copy headers'),
- kHTTPConnVersion: Symbol('http connection version'),
- kRetryHandlerDefaultRetry: Symbol('retry agent default retry'),
- kConstruct: Symbol('constructable')
-}
-
-/***/ }),
-
-/***/ 3440:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // Returns response’s URL, if it has one; otherwise the empty string.
+ get url () {
+ webidl.brandCheck(this, Response)
-"use strict";
+ const urlList = this[kState].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
-const assert = __nccwpck_require__(2613)
-const { kDestroyed, kBodyUsed } = __nccwpck_require__(6443)
-const { IncomingMessage } = __nccwpck_require__(8611)
-const stream = __nccwpck_require__(2203)
-const net = __nccwpck_require__(9278)
-const { InvalidArgumentError } = __nccwpck_require__(8707)
-const { Blob } = __nccwpck_require__(181)
-const nodeUtil = __nccwpck_require__(9023)
-const { stringify } = __nccwpck_require__(3480)
-const { headerNameLowerCasedRecord } = __nccwpck_require__(735)
+ if (url === null) {
+ return ''
+ }
-const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v))
+ return URLSerializer(url, true)
+ }
-function nop () {}
+ // Returns whether response was obtained through a redirect.
+ get redirected () {
+ webidl.brandCheck(this, Response)
-function isStream (obj) {
- return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function'
-}
+ // The redirected getter steps are to return true if this’s response’s URL
+ // list has more than one item; otherwise false.
+ return this[kState].urlList.length > 1
+ }
-// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License)
-function isBlobLike (object) {
- return (Blob && object instanceof Blob) || (
- object &&
- typeof object === 'object' &&
- (typeof object.stream === 'function' ||
- typeof object.arrayBuffer === 'function') &&
- /^(Blob|File)$/.test(object[Symbol.toStringTag])
- )
-}
+ // Returns response’s status.
+ get status () {
+ webidl.brandCheck(this, Response)
-function buildURL (url, queryParams) {
- if (url.includes('?') || url.includes('#')) {
- throw new Error('Query params cannot be passed when url already contains "?" or "#".')
+ // The status getter steps are to return this’s response’s status.
+ return this[kState].status
}
- const stringified = stringify(queryParams)
+ // Returns whether response’s status is an ok status.
+ get ok () {
+ webidl.brandCheck(this, Response)
- if (stringified) {
- url += '?' + stringified
+ // The ok getter steps are to return true if this’s response’s status is an
+ // ok status; otherwise false.
+ return this[kState].status >= 200 && this[kState].status <= 299
}
- return url
-}
+ // Returns response’s status message.
+ get statusText () {
+ webidl.brandCheck(this, Response)
-function parseURL (url) {
- if (typeof url === 'string') {
- url = new URL(url)
+ // The statusText getter steps are to return this’s response’s status
+ // message.
+ return this[kState].statusText
+ }
- if (!/^https?:/.test(url.origin || url.protocol)) {
- throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
- }
+ // Returns response’s headers as Headers.
+ get headers () {
+ webidl.brandCheck(this, Response)
- return url
+ // The headers getter steps are to return this’s headers.
+ return this[kHeaders]
}
- if (!url || typeof url !== 'object') {
- throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')
- }
+ get body () {
+ webidl.brandCheck(this, Response)
- if (!/^https?:/.test(url.origin || url.protocol)) {
- throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
+ return this[kState].body ? this[kState].body.stream : null
}
- if (!(url instanceof URL)) {
- if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) {
- 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.')
- }
+ get bodyUsed () {
+ webidl.brandCheck(this, Response)
- if (url.pathname != null && typeof url.pathname !== 'string') {
- throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.')
- }
+ return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
+ }
- if (url.hostname != null && typeof url.hostname !== 'string') {
- throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.')
- }
+ // Returns a clone of response.
+ clone () {
+ webidl.brandCheck(this, Response)
- if (url.origin != null && typeof url.origin !== 'string') {
- throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.')
+ // 1. If this is unusable, then throw a TypeError.
+ if (this.bodyUsed || (this.body && this.body.locked)) {
+ throw webidl.errors.exception({
+ header: 'Response.clone',
+ message: 'Body has already been consumed.'
+ })
}
- 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 || ''}`
+ // 2. Let clonedResponse be the result of cloning this’s response.
+ const clonedResponse = cloneResponse(this[kState])
- if (origin.endsWith('/')) {
- origin = origin.substring(0, origin.length - 1)
- }
+ // 3. Return the result of creating a Response object, given
+ // clonedResponse, this’s headers’s guard, and this’s relevant Realm.
+ const clonedResponseObject = new Response()
+ clonedResponseObject[kState] = clonedResponse
+ clonedResponseObject[kRealm] = this[kRealm]
+ clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList
+ clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard]
+ clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm]
- if (path && !path.startsWith('/')) {
- 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.
- url = new URL(origin + path)
+ return clonedResponseObject
}
-
- return url
}
-function parseOrigin (url) {
- url = parseURL(url)
+mixinBody(Response)
- if (url.pathname !== '/' || url.search || url.hash) {
- throw new InvalidArgumentError('invalid url')
+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
}
+})
- return url
-}
+Object.defineProperties(Response, {
+ json: kEnumerableProperty,
+ redirect: kEnumerableProperty,
+ error: kEnumerableProperty
+})
-function getHostname (host) {
- if (host[0] === '[') {
- const idx = host.indexOf(']')
+// https://fetch.spec.whatwg.org/#concept-response-clone
+function cloneResponse (response) {
+ // To clone a response response, run these steps:
- assert(idx !== -1)
- return host.substring(1, idx)
+ // 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
+ )
}
- const idx = host.indexOf(':')
- if (idx === -1) return host
+ // 2. Let newResponse be a copy of response, except for its body.
+ const newResponse = makeResponse({ ...response, body: null })
- return host.substring(0, idx)
+ // 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)
+ }
+
+ // 4. Return newResponse.
+ return newResponse
}
-// IP addresses are not valid server names per RFC6066
-// > Currently, the only server names supported are DNS hostnames
-function getServerName (host) {
- if (!host) {
- return null
+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] : []
}
+}
- assert.strictEqual(typeof host, 'string')
+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'
+ })
+}
- const servername = getHostname(host)
- if (net.isIP(servername)) {
- return ''
+function makeFilteredResponse (response, state) {
+ state = {
+ internalResponse: response,
+ ...state
}
- return servername
+ 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
+ }
+ })
}
-function deepClone (obj) {
- return JSON.parse(JSON.stringify(obj))
-}
+// 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.
-function isAsyncIterable (obj) {
- return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function')
-}
+ // 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.
-function isIterable (obj) {
- return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function'))
-}
+ // 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.
-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 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 null
+ return makeFilteredResponse(response, {
+ type: 'opaqueredirect',
+ status: 0,
+ statusText: '',
+ headersList: [],
+ body: null
+ })
+ } else {
+ assert(false)
+ }
}
-function isDestroyed (stream) {
- return !stream || !!(stream.destroyed || stream[kDestroyed])
-}
+// https://fetch.spec.whatwg.org/#appropriate-network-error
+function makeAppropriateNetworkError (fetchParams, err = null) {
+ // 1. Assert: fetchParams is canceled.
+ assert(isCancelled(fetchParams))
-function isReadableAborted (stream) {
- const state = stream && stream._readableState
- return isDestroyed(stream) && state && !state.endEmitted
+ // 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 }))
}
-function destroy (stream, err) {
- if (stream == null || !isStream(stream) || isDestroyed(stream)) {
- return
+// 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.')
}
- if (typeof stream.destroy === 'function') {
- if (Object.getPrototypeOf(stream).constructor === IncomingMessage) {
- // See: https://github.com/nodejs/node/pull/38505/files
- stream.socket = null
+ // 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')
}
-
- stream.destroy(err)
- } else if (err) {
- process.nextTick((stream, err) => {
- stream.emit('error', err)
- }, stream, err)
}
- if (stream.destroyed !== true) {
- stream[kDestroyed] = true
+ // 3. Set response’s response’s status to init["status"].
+ if ('status' in init && init.status != null) {
+ response[kState].status = init.status
}
-}
-const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/
-function parseKeepAliveTimeout (val) {
- const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR)
- return m ? parseInt(m[1], 10) * 1000 : null
-}
+ // 4. Set response’s response’s status message to init["statusText"].
+ if ('statusText' in init && init.statusText != null) {
+ response[kState].statusText = init.statusText
+ }
-/**
- * Retrieves a header name and returns its lowercase value.
- * @param {string | Buffer} value Header name
- * @returns {string}
- */
-function headerNameToString (value) {
- return headerNameLowerCasedRecord[value] || value.toLowerCase()
-}
+ // 5. If init["headers"] exists, then fill response’s headers with init["headers"].
+ if ('headers' in init && init.headers != null) {
+ fill(response[kHeaders], init.headers)
+ }
-function parseHeaders (headers, obj = {}) {
- // For H2 support
- if (!Array.isArray(headers)) return 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
+ })
+ }
- for (let i = 0; i < headers.length; i += 2) {
- const key = headers[i].toString().toLowerCase()
- let val = obj[key]
+ // 2. Set response's body to body's body.
+ response[kState].body = body.body
- if (!val) {
- if (Array.isArray(headers[i + 1])) {
- obj[key] = headers[i + 1].map(x => x.toString('utf8'))
- } else {
- obj[key] = headers[i + 1].toString('utf8')
- }
- } else {
- if (!Array.isArray(val)) {
- val = [val]
- obj[key] = val
- }
- val.push(headers[i + 1].toString('utf8'))
+ // 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 && !response[kState].headersList.contains('Content-Type')) {
+ response[kState].headersList.append('content-type', body.type)
}
}
+}
- // 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')
- }
+webidl.converters.ReadableStream = webidl.interfaceConverter(
+ ReadableStream
+)
- return obj
-}
+webidl.converters.FormData = webidl.interfaceConverter(
+ FormData
+)
-function parseRawHeaders (headers) {
- const ret = []
- let hasContentLength = false
- let contentDispositionIdx = -1
+webidl.converters.URLSearchParams = webidl.interfaceConverter(
+ URLSearchParams
+)
- for (let n = 0; n < headers.length; n += 2) {
- const key = headers[n + 0].toString()
- const val = headers[n + 1].toString('utf8')
+// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit
+webidl.converters.XMLHttpRequestBodyInit = function (V) {
+ if (typeof V === 'string') {
+ return webidl.converters.USVString(V)
+ }
- if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) {
- ret.push(key, val)
- hasContentLength = true
- } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) {
- contentDispositionIdx = ret.push(key, val) - 1
- } else {
- ret.push(key, val)
- }
+ if (isBlobLike(V)) {
+ return webidl.converters.Blob(V, { strict: false })
}
- // See https://github.com/nodejs/node/pull/46528
- if (hasContentLength && contentDispositionIdx !== -1) {
- ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1')
+ if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) {
+ return webidl.converters.BufferSource(V)
}
- return ret
-}
+ if (util.isFormDataLike(V)) {
+ return webidl.converters.FormData(V, { strict: false })
+ }
-function isBuffer (buffer) {
- // See, https://github.com/mcollina/undici/pull/319
- return buffer instanceof Uint8Array || Buffer.isBuffer(buffer)
+ if (V instanceof URLSearchParams) {
+ return webidl.converters.URLSearchParams(V)
+ }
+
+ return webidl.converters.DOMString(V)
}
-function validateHandler (handler, method, upgrade) {
- if (!handler || typeof handler !== 'object') {
- throw new InvalidArgumentError('handler must be an object')
+// https://fetch.spec.whatwg.org/#bodyinit
+webidl.converters.BodyInit = function (V) {
+ if (V instanceof ReadableStream) {
+ return webidl.converters.ReadableStream(V)
}
- if (typeof handler.onConnect !== 'function') {
- throw new InvalidArgumentError('invalid onConnect method')
+ // Note: the spec doesn't include async iterables,
+ // this is an undici extension.
+ if (V?.[Symbol.asyncIterator]) {
+ return V
}
- if (typeof handler.onError !== 'function') {
- throw new InvalidArgumentError('invalid onError method')
- }
+ return webidl.converters.XMLHttpRequestBodyInit(V)
+}
- if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) {
- throw new InvalidArgumentError('invalid onBodySent method')
+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
}
+])
- 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')
- }
+module.exports = {
+ makeNetworkError,
+ makeResponse,
+ makeAppropriateNetworkError,
+ filterResponse,
+ Response,
+ cloneResponse
+}
+
+
+/***/ }),
+
+/***/ 89710:
+/***/ ((module) => {
+
+"use strict";
+
+
+module.exports = {
+ kUrl: Symbol('url'),
+ kHeaders: Symbol('headers'),
+ kSignal: Symbol('signal'),
+ kState: Symbol('state'),
+ kGuard: Symbol('guard'),
+ kRealm: Symbol('realm')
+}
+
+
+/***/ }),
+
+/***/ 15523:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
- if (typeof handler.onData !== 'function') {
- throw new InvalidArgumentError('invalid onData method')
- }
- if (typeof handler.onComplete !== 'function') {
- throw new InvalidArgumentError('invalid onComplete method')
- }
- }
-}
+const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(87326)
+const { getGlobalOrigin } = __nccwpck_require__(75628)
+const { performance } = __nccwpck_require__(82987)
+const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(3440)
+const assert = __nccwpck_require__(42613)
+const { isUint8Array } = __nccwpck_require__(98253)
-// A body is disturbed if it has been read from and it cannot
-// be re-used without losing state or data.
-function isDisturbed (body) {
- return !!(body && (
- stream.isDisturbed
- ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed?
- : body[kBodyUsed] ||
- body.readableDidRead ||
- (body._readableState && body._readableState.dataEmitted) ||
- isReadableAborted(body)
- ))
-}
+let supportedHashes = []
-function isErrored (body) {
- return !!(body && (
- stream.isErrored
- ? stream.isErrored(body)
- : /state: 'errored'/.test(nodeUtil.inspect(body)
- )))
+// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable
+/** @type {import('crypto')|undefined} */
+let crypto
+
+try {
+ crypto = __nccwpck_require__(76982)
+ const possibleRelevantHashes = ['sha256', 'sha384', 'sha512']
+ supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash))
+/* c8 ignore next 3 */
+} catch {
}
-function isReadable (body) {
- return !!(body && (
- stream.isReadable
- ? stream.isReadable(body)
- : /state: 'readable'/.test(nodeUtil.inspect(body)
- )))
+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()
}
-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
+// 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
}
-}
-async function * convertIterableToBuffer (iterable) {
- for await (const chunk of iterable) {
- yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
+ // 2. Let location be the result of extracting header list values given
+ // `Location` and response’s header list.
+ let location = response.headersList.get('location')
+
+ // 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)) {
+ location = new URL(location, responseURL(response))
}
-}
-let ReadableStream
-function ReadableStreamFrom (iterable) {
- if (!ReadableStream) {
- ReadableStream = (__nccwpck_require__(3774).ReadableStream)
+ // 4. If location is a URL whose fragment is null, then set location’s
+ // fragment to requestFragment.
+ if (location && !location.hash) {
+ location.hash = requestFragment
}
- if (ReadableStream.from) {
- return ReadableStream.from(convertIterableToBuffer(iterable))
+ // 5. Return location.
+ return location
+}
+
+/** @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'
}
- let iterator
- return new ReadableStream(
- {
- async start () {
- iterator = iterable[Symbol.asyncIterator]()
- },
- async pull (controller) {
- const { done, value } = await iterator.next()
- if (done) {
- queueMicrotask(() => {
- controller.close()
- })
- } else {
- const buf = Buffer.isBuffer(value) ? value : Buffer.from(value)
- controller.enqueue(new Uint8Array(buf))
- }
- return controller.desiredSize > 0
- },
- async cancel (reason) {
- await iterator.return()
- }
- },
- 0
- )
+ // 3. Return allowed.
+ return 'allowed'
}
-// The chunk should be a FormData instance and contains
-// all the required methods.
-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 isErrorLike (object) {
+ return object instanceof Error || (
+ object?.constructor?.name === 'Error' ||
+ object?.constructor?.name === 'DOMException'
)
}
-function throwIfAborted (signal) {
- if (!signal) { return }
- if (typeof signal.throwIfAborted === 'function') {
- signal.throwIfAborted()
- } else {
- if (signal.aborted) {
- // DOMException not available < v17.0.0
- const err = new Error('The operation was aborted')
- err.name = 'AbortError'
- throw err
+// 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
}
-function addAbortListener (signal, listener) {
- if ('addEventListener' in signal) {
- signal.addEventListener('abort', listener, { once: true })
- return () => signal.removeEventListener('abort', listener)
+/**
+ * @see https://tools.ietf.org/html/rfc7230#section-3.2.6
+ * @param {number} c
+ */
+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
}
- signal.addListener('abort', listener)
- return () => signal.removeListener('abort', listener)
}
-const hasToWellFormed = !!String.prototype.toWellFormed
-
/**
- * @param {string} val
+ * @param {string} characters
*/
-function toUSVString (val) {
- if (hasToWellFormed) {
- return `${val}`.toWellFormed()
- } else if (nodeUtil.toUSVString) {
- return nodeUtil.toUSVString(val)
+function isValidHTTPToken (characters) {
+ if (characters.length === 0) {
+ return false
}
-
- return `${val}`
-}
-
-// Parsed accordingly to RFC 9110
-// https://www.rfc-editor.org/rfc/rfc9110#field.content-range
-function parseRangeHeader (range) {
- if (range == null || range === '') return { start: 0, end: null, size: null }
-
- const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null
- return m
- ? {
- start: parseInt(m[1]),
- end: m[2] ? parseInt(m[2]) : null,
- size: m[3] ? parseInt(m[3]) : null
- }
- : null
+ for (let i = 0; i < characters.length; ++i) {
+ if (!isTokenCharCode(characters.charCodeAt(i))) {
+ return false
+ }
+ }
+ return true
}
-const kEnumerableProperty = Object.create(null)
-kEnumerableProperty.enumerable = true
-
-module.exports = {
- kEnumerableProperty,
- nop,
- isDisturbed,
- isErrored,
- isReadable,
- toUSVString,
- isReadableAborted,
- isBlobLike,
- parseOrigin,
- parseURL,
- getServerName,
- isStream,
- isIterable,
- isAsyncIterable,
- isDestroyed,
- headerNameToString,
- parseRawHeaders,
- parseHeaders,
- parseKeepAliveTimeout,
- destroy,
- bodyLength,
- deepClone,
- ReadableStreamFrom,
- isBuffer,
- validateHandler,
- getSocketInfo,
- isFormDataLike,
- buildURL,
- throwIfAborted,
- addAbortListener,
- parseRangeHeader,
- nodeMajor,
- nodeMinor,
- nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13),
- safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE']
+/**
+ * @see https://fetch.spec.whatwg.org/#header-name
+ * @param {string} potentialValue
+ */
+function isValidHeaderName (potentialValue) {
+ return isValidHTTPToken(potentialValue)
}
+/**
+ * @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.
+ if (
+ potentialValue.startsWith('\t') ||
+ potentialValue.startsWith(' ') ||
+ potentialValue.endsWith('\t') ||
+ potentialValue.endsWith(' ')
+ ) {
+ return false
+ }
-/***/ }),
-
-/***/ 1:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
+ if (
+ potentialValue.includes('\0') ||
+ potentialValue.includes('\r') ||
+ potentialValue.includes('\n')
+ ) {
+ return false
+ }
-const Dispatcher = __nccwpck_require__(992)
-const {
- ClientDestroyedError,
- ClientClosedError,
- InvalidArgumentError
-} = __nccwpck_require__(8707)
-const { kDestroy, kClose, kDispatch, kInterceptors } = __nccwpck_require__(6443)
+ return true
+}
-const kDestroyed = Symbol('destroyed')
-const kClosed = Symbol('closed')
-const kOnDestroyed = Symbol('onDestroyed')
-const kOnClosed = Symbol('onClosed')
-const kInterceptedDispatch = Symbol('Intercepted Dispatch')
+// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect
+function setRequestReferrerPolicyOnRedirect (request, actualResponse) {
+ // 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.
-class DispatcherBase extends Dispatcher {
- constructor () {
- super()
+ // 1. Let policy be the result of executing § 8.1 Parse a referrer policy
+ // from a Referrer-Policy header on actualResponse.
- this[kDestroyed] = false
- this[kOnDestroyed] = null
- this[kClosed] = false
- this[kOnClosed] = []
- }
+ // 8.1 Parse a referrer policy from a Referrer-Policy header
+ // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list.
+ const { headersList } = actualResponse
+ // 2. Let policy be the empty string.
+ // 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.
+ // 4. Return policy.
+ const policyHeader = (headersList.get('referrer-policy') ?? '').split(',')
- get destroyed () {
- return this[kDestroyed]
+ // 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
+ let policy = ''
+ if (policyHeader.length > 0) {
+ // 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
+ }
+ }
}
- get closed () {
- return this[kClosed]
+ // 2. If policy is not the empty string, then set request’s referrer policy to policy.
+ if (policy !== '') {
+ request.referrerPolicy = policy
}
+}
- get interceptors () {
- return this[kInterceptors]
- }
+// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check
+function crossOriginResourcePolicyCheck () {
+ // TODO
+ return 'allowed'
+}
- set interceptors (newInterceptors) {
- if (newInterceptors) {
- for (let i = newInterceptors.length - 1; i >= 0; i--) {
- const interceptor = this[kInterceptors][i]
- if (typeof interceptor !== 'function') {
- throw new InvalidArgumentError('interceptor must be an function')
- }
- }
- }
+// https://fetch.spec.whatwg.org/#concept-cors-check
+function corsCheck () {
+ // TODO
+ return 'success'
+}
- this[kInterceptors] = newInterceptors
- }
+// https://fetch.spec.whatwg.org/#concept-tao-check
+function TAOCheck () {
+ // TODO
+ return 'success'
+}
- close (callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- this.close((err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
- }
+function appendFetchMetadata (httpRequest) {
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header
+ // TODO
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header
- if (this[kDestroyed]) {
- queueMicrotask(() => callback(new ClientDestroyedError(), null))
- return
- }
+ // 1. Assert: r’s url is a potentially trustworthy URL.
+ // TODO
- if (this[kClosed]) {
- if (this[kOnClosed]) {
- this[kOnClosed].push(callback)
- } else {
- queueMicrotask(() => callback(null, null))
- }
- return
- }
+ // 2. Let header be a Structured Header whose value is a token.
+ let header = null
- this[kClosed] = true
- this[kOnClosed].push(callback)
+ // 3. Set header’s value to r’s mode.
+ header = httpRequest.mode
- const onClosed = () => {
- const callbacks = this[kOnClosed]
- this[kOnClosed] = null
- for (let i = 0; i < callbacks.length; i++) {
- callbacks[i](null, null)
- }
- }
+ // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list.
+ httpRequest.headersList.set('sec-fetch-mode', header)
- // Should not error.
- this[kClose]()
- .then(() => this.destroy())
- .then(() => {
- queueMicrotask(onClosed)
- })
- }
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header
+ // TODO
- destroy (err, callback) {
- if (typeof err === 'function') {
- callback = err
- err = null
- }
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header
+ // TODO
+}
- 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)
- })
- })
- }
+// 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.
+ let serializedOrigin = request.origin
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
+ // 2. If request’s response tainting is "cors" or request’s mode is "websocket", then append (`Origin`, serializedOrigin) to request’s header list.
+ if (request.responseTainting === 'cors' || request.mode === 'websocket') {
+ if (serializedOrigin) {
+ request.headersList.append('origin', serializedOrigin)
}
- if (this[kDestroyed]) {
- if (this[kOnDestroyed]) {
- this[kOnDestroyed].push(callback)
- } else {
- queueMicrotask(() => callback(null, null))
- }
- return
+ // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then:
+ } 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.
}
- if (!err) {
- err = new ClientDestroyedError()
+ if (serializedOrigin) {
+ // 2. Append (`Origin`, serializedOrigin) to request’s header list.
+ request.headersList.append('origin', serializedOrigin)
}
+ }
+}
- 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)
- }
- }
+function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) {
+ // TODO
+ return performance.now()
+}
- // Should not error.
- this[kDestroy](err).then(() => {
- queueMicrotask(onDestroyed)
- })
+// 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
}
+}
- [kInterceptedDispatch] (opts, handler) {
- if (!this[kInterceptors] || this[kInterceptors].length === 0) {
- this[kInterceptedDispatch] = this[kDispatch]
- return this[kDispatch](opts, handler)
- }
+// 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'
+ }
+}
- let dispatch = this[kDispatch].bind(this)
- for (let i = this[kInterceptors].length - 1; i >= 0; i--) {
- dispatch = this[kInterceptors][i](dispatch)
- }
- this[kInterceptedDispatch] = dispatch
- return dispatch(opts, handler)
+// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container
+function clonePolicyContainer (policyContainer) {
+ return {
+ referrerPolicy: policyContainer.referrerPolicy
}
+}
- dispatch (opts, handler) {
- if (!handler || typeof handler !== 'object') {
- throw new InvalidArgumentError('handler must be an object')
- }
+// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
+function determineRequestsReferrer (request) {
+ // 1. Let policy be request's referrer policy.
+ const policy = request.referrerPolicy
- try {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('opts must be an object.')
- }
+ // Note: policy cannot (shouldn't) be null or an empty string.
+ assert(policy)
- if (this[kDestroyed] || this[kOnDestroyed]) {
- throw new ClientDestroyedError()
- }
+ // 2. Let environment be request’s client.
- if (this[kClosed]) {
- throw new ClientClosedError()
- }
+ let referrerSource = null
- return this[kInterceptedDispatch](opts, handler)
- } catch (err) {
- if (typeof handler.onError !== 'function') {
- throw new InvalidArgumentError('invalid onError method')
- }
+ // 3. Switch on request’s referrer:
+ 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.
- handler.onError(err)
+ const globalOrigin = getGlobalOrigin()
- return false
+ if (!globalOrigin || globalOrigin.origin === 'null') {
+ return 'no-referrer'
}
- }
-}
-module.exports = DispatcherBase
+ // note: we need to clone it as it's mutated
+ referrerSource = new URL(globalOrigin)
+ } else if (request.referrer instanceof URL) {
+ // 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)
-/***/ 992:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 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
+ }
-"use strict";
+ const areSameOrigin = sameOrigin(request, referrerURL)
+ const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) &&
+ !isURLPotentiallyTrustworthy(request.url)
+ // 8. Execute the switch statements corresponding to the value of policy:
+ switch (policy) {
+ case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true)
+ case 'unsafe-url': return referrerURL
+ case 'same-origin':
+ return areSameOrigin ? referrerOrigin : 'no-referrer'
+ case 'origin-when-cross-origin':
+ return areSameOrigin ? referrerURL : referrerOrigin
+ case 'strict-origin-when-cross-origin': {
+ const currentURL = requestCurrentURL(request)
-const EventEmitter = __nccwpck_require__(4434)
+ // 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
+ }
-class Dispatcher extends EventEmitter {
- dispatch () {
- throw new Error('not implemented')
- }
+ // 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'
+ }
- close () {
- throw new Error('not implemented')
- }
+ // 3. Return referrerOrigin.
+ return referrerOrigin
+ }
+ case 'strict-origin': // eslint-disable-line
+ /**
+ * 1. If referrerURL is a potentially trustworthy URL and
+ * request’s current URL is not a potentially trustworthy URL,
+ * then return no referrer.
+ * 2. Return referrerOrigin
+ */
+ case 'no-referrer-when-downgrade': // eslint-disable-line
+ /**
+ * 1. If referrerURL is a potentially trustworthy URL and
+ * request’s current URL is not a potentially trustworthy URL,
+ * then return no referrer.
+ * 2. Return referrerOrigin
+ */
- destroy () {
- throw new Error('not implemented')
+ default: // eslint-disable-line
+ return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin
}
}
-module.exports = Dispatcher
-
+/**
+ * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url
+ * @param {URL} url
+ * @param {boolean|undefined} originOnly
+ */
+function stripURLForReferrer (url, originOnly) {
+ // 1. Assert: url is a URL.
+ assert(url instanceof URL)
-/***/ }),
+ // 2. If url’s scheme is a local scheme, then return no referrer.
+ if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') {
+ return 'no-referrer'
+ }
-/***/ 8923:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 3. Set url’s username to the empty string.
+ url.username = ''
-"use strict";
+ // 4. Set url’s password to the empty string.
+ url.password = ''
+ // 5. Set url’s fragment to null.
+ url.hash = ''
-const Busboy = __nccwpck_require__(9581)
-const util = __nccwpck_require__(3440)
-const {
- ReadableStreamFrom,
- isBlobLike,
- isReadableStreamLike,
- readableStreamClose,
- createDeferredPromise,
- fullyReadBody
-} = __nccwpck_require__(5523)
-const { FormData } = __nccwpck_require__(3073)
-const { kState } = __nccwpck_require__(9710)
-const { webidl } = __nccwpck_require__(4222)
-const { DOMException, structuredClone } = __nccwpck_require__(7326)
-const { Blob, File: NativeFile } = __nccwpck_require__(181)
-const { kBodyUsed } = __nccwpck_require__(6443)
-const assert = __nccwpck_require__(2613)
-const { isErrored } = __nccwpck_require__(3440)
-const { isUint8Array, isArrayBuffer } = __nccwpck_require__(8253)
-const { File: UndiciFile } = __nccwpck_require__(3041)
-const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322)
+ // 6. If the origin-only flag is true, then:
+ if (originOnly) {
+ // 1. Set url’s path to « the empty string ».
+ url.pathname = ''
-let ReadableStream = globalThis.ReadableStream
+ // 2. Set url’s query to null.
+ url.search = ''
+ }
-/** @type {globalThis['File']} */
-const File = NativeFile ?? UndiciFile
-const textEncoder = new TextEncoder()
-const textDecoder = new TextDecoder()
+ // 7. Return url.
+ return url
+}
-// https://fetch.spec.whatwg.org/#concept-bodyinit-extract
-function extractBody (object, keepalive = false) {
- if (!ReadableStream) {
- ReadableStream = (__nccwpck_require__(3774).ReadableStream)
+function isURLPotentiallyTrustworthy (url) {
+ if (!(url instanceof URL)) {
+ return false
}
- // 1. Let stream be null.
- let stream = null
-
- // 2. If object is a ReadableStream object, then set stream to object.
- if (object instanceof ReadableStream) {
- stream = object
- } else if (isBlobLike(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.
- stream = new ReadableStream({
- async pull (controller) {
- controller.enqueue(
- typeof source === 'string' ? textEncoder.encode(source) : source
- )
- queueMicrotask(() => readableStreamClose(controller))
- },
- start () {},
- type: undefined
- })
+ // If child of about, return true
+ if (url.href === 'about:blank' || url.href === 'about:srcdoc') {
+ return true
}
- // 5. Assert: stream is a ReadableStream object.
- assert(isReadableStreamLike(stream))
+ // If scheme is data, return true
+ if (url.protocol === 'data:') return true
- // 6. Let action be null.
- let action = null
+ // If file, return true
+ if (url.protocol === 'file:') return true
- // 7. Let source be null.
- let source = null
+ return isOriginPotentiallyTrustworthy(url.origin)
- // 8. Let length be null.
- let length = null
+ function isOriginPotentiallyTrustworthy (origin) {
+ // If origin is explicitly null, return false
+ if (origin == null || origin === 'null') return false
- // 9. Let type be null.
- let type = null
+ const originAsURL = new URL(origin)
- // 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
+ // If secure, return true
+ if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') {
+ return true
+ }
- // Set type to `text/plain;charset=UTF-8`.
- type = 'text/plain;charset=UTF-8'
- } else if (object instanceof URLSearchParams) {
- // URLSearchParams
+ // If localhost or variants, return true
+ if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) ||
+ (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) ||
+ (originAsURL.hostname.endsWith('.localhost'))) {
+ return true
+ }
- // 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
+ // If any other, return false
+ return false
+ }
+}
- // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list.
- source = object.toString()
+/**
+ * @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
+ }
- // 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
+ // 1. Let parsedMetadata be the result of parsing metadataList.
+ const parsedMetadata = parseMetadata(metadataList)
- // Set source to a copy of the bytes held by object.
- source = new Uint8Array(object.slice())
- } else if (ArrayBuffer.isView(object)) {
- // BufferSource/ArrayBufferView
+ // 2. If parsedMetadata is no metadata, return true.
+ if (parsedMetadata === 'no metadata') {
+ return true
+ }
- // 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 (util.isFormDataLike(object)) {
- const boundary = `----formdata-undici-0${`${Math.floor(Math.random() * 1e11)}`.padStart(11, '0')}`
- const prefix = `--${boundary}\r\nContent-Disposition: form-data`
+ // 3. If response is not eligible for integrity validation, return false.
+ // TODO
- /*! 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')
+ // 4. If parsedMetadata is the empty set, return true.
+ if (parsedMetadata.length === 0) {
+ return true
+ }
- // 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.
+ // 5. Let metadata be the result of getting the strongest
+ // metadata from parsedMetadata.
+ const strongest = getStrongestMetadata(parsedMetadata)
+ const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest)
- const blobParts = []
- const rn = new Uint8Array([13, 10]) // '\r\n'
- length = 0
- let hasUnknownSizeValue = false
+ // 6. For each item in metadata:
+ for (const item of metadata) {
+ // 1. Let algorithm be the alg component of item.
+ const algorithm = item.algo
- 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
- }
- }
- }
+ // 2. Let expectedValue be the val component of item.
+ const expectedValue = item.hash
- const chunk = textEncoder.encode(`--${boundary}--`)
- blobParts.push(chunk)
- length += chunk.byteLength
- if (hasUnknownSizeValue) {
- length = null
- }
+ // 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.
- // Set source to object.
- source = object
+ // 3. Let actualValue be the result of applying algorithm to bytes.
+ let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64')
- action = async function * () {
- for (const part of blobParts) {
- if (part.stream) {
- yield * part.stream()
- } else {
- yield part
- }
+ if (actualValue[actualValue.length - 1] === '=') {
+ if (actualValue[actualValue.length - 2] === '=') {
+ actualValue = actualValue.slice(0, -2)
+ } else {
+ actualValue = actualValue.slice(0, -1)
}
}
- // 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 (isBlobLike(object)) {
- // Blob
+ // 4. If actualValue is a case-sensitive match for expectedValue,
+ // return true.
+ if (compareBase64Mixed(actualValue, expectedValue)) {
+ return true
+ }
+ }
- // Set source to object.
- source = object
+ // 7. Return false.
+ return false
+}
- // Set length to object’s size.
- length = object.size
+// 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
- // 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')
- }
+/**
+ * @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 = []
- // 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'
- )
- }
+ // 2. Let empty be equal to true.
+ let empty = true
- stream =
- object instanceof ReadableStream ? object : ReadableStreamFrom(object)
- }
+ // 3. For each token returned by splitting metadata on spaces:
+ for (const token of metadata.split(' ')) {
+ // 1. Set empty to false.
+ empty = false
- // 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)
- }
+ // 2. Parse token as a hash-with-options.
+ const parsedToken = parseHashWithOptions.exec(token)
- // 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()
- })
- } 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)) {
- controller.enqueue(new Uint8Array(value))
- }
- }
- return controller.desiredSize > 0
- },
- async cancel (reason) {
- await iterator.return()
- },
- type: undefined
- })
- }
+ // 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
+ }
- // 13. Let body be a body whose stream is stream, source is source,
- // and length is length.
- const body = { stream, source, length }
+ // 4. Let algorithm be the hash-algo component of token.
+ const algorithm = parsedToken.groups.algo.toLowerCase()
- // 14. Return (body, type).
- return [body, type]
-}
+ // 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)
+ }
+ }
-// https://fetch.spec.whatwg.org/#bodyinit-safely-extract
-function safelyExtractBody (object, keepalive = false) {
- if (!ReadableStream) {
- // istanbul ignore next
- ReadableStream = (__nccwpck_require__(3774).ReadableStream)
+ // 4. Return no metadata if empty is true, otherwise return result.
+ if (empty === true) {
+ return 'no metadata'
}
- // To safely extract a body and a `Content-Type` value from
- // a byte sequence or BodyInit object object, run these steps:
+ return result
+}
- // 1. If object is a ReadableStream object, then:
- if (object instanceof ReadableStream) {
- // Assert: object is neither disturbed nor locked.
- // istanbul ignore next
- assert(!util.isDisturbed(object), 'The body has already been consumed.')
- // istanbul ignore next
- assert(!object.locked, 'The stream is locked.')
+/**
+ * @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
}
- // 2. Return the results of extracting object.
- return extractBody(object, keepalive)
+ 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 cloneBody (body) {
- // To clone a body body, run these steps:
-
- // https://fetch.spec.whatwg.org/#concept-body-clone
+function filterMetadataListByAlgorithm (metadataList, algorithm) {
+ if (metadataList.length === 1) {
+ return metadataList
+ }
- // 1. Let « out1, out2 » be the result of teeing body’s stream.
- const [out1, out2] = body.stream.tee()
- const out2Clone = structuredClone(out2, { transfer: [out2] })
- // This, for whatever reasons, unrefs out2Clone which allows
- // the process to exit by itself.
- const [, finalClone] = out2Clone.tee()
+ let pos = 0
+ for (let i = 0; i < metadataList.length; ++i) {
+ if (metadataList[i].algo === algorithm) {
+ metadataList[pos++] = metadataList[i]
+ }
+ }
- // 2. Set body’s stream to out1.
- body.stream = out1
+ metadataList.length = pos
- // 3. Return a body whose stream is out2 and other members are copied from body.
- return {
- stream: finalClone,
- length: body.length,
- source: body.source
- }
+ return metadataList
}
-async function * consumeBody (body) {
- if (body) {
- if (isUint8Array(body)) {
- yield body
- } else {
- const stream = body.stream
-
- if (util.isDisturbed(stream)) {
- throw new TypeError('The body has already been consumed.')
+/**
+ * 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
+ }
+ }
- if (stream.locked) {
- throw new TypeError('The stream is locked.')
- }
+ return true
+}
- // Compat.
- stream[kBodyUsed] = true
+// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request
+function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) {
+ // TODO
+}
- yield * stream
- }
+/**
+ * @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
}
-}
-function throwIfAborted (state) {
- if (state.aborted) {
- throw new DOMException('The operation was aborted.', 'AbortError')
+ // 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 bodyMixinMethods (instance) {
- 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 specConsumeBody(this, (bytes) => {
- let mimeType = bodyMimeType(this)
+function createDeferredPromise () {
+ let res
+ let rej
+ const promise = new Promise((resolve, reject) => {
+ res = resolve
+ rej = reject
+ })
- if (mimeType === 'failure') {
- mimeType = ''
- } else if (mimeType) {
- mimeType = serializeAMimeType(mimeType)
- }
+ return { promise, resolve: res, reject: rej }
+}
- // Return a Blob whose contents are bytes and type attribute
- // is mimeType.
- return new Blob([bytes], { type: mimeType })
- }, instance)
- },
+function isAborted (fetchParams) {
+ return fetchParams.controller.state === 'aborted'
+}
- 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 specConsumeBody(this, (bytes) => {
- return new Uint8Array(bytes).buffer
- }, instance)
- },
+function isCancelled (fetchParams) {
+ return fetchParams.controller.state === 'aborted' ||
+ fetchParams.controller.state === 'terminated'
+}
- text () {
- // The text() method steps are to return the result of running
- // consume body with this and UTF-8 decode.
- return specConsumeBody(this, utf8DecodeBytes, instance)
- },
+const normalizeMethodRecord = {
+ delete: 'DELETE',
+ DELETE: 'DELETE',
+ get: 'GET',
+ GET: 'GET',
+ head: 'HEAD',
+ HEAD: 'HEAD',
+ options: 'OPTIONS',
+ OPTIONS: 'OPTIONS',
+ post: 'POST',
+ POST: 'POST',
+ put: 'PUT',
+ PUT: 'PUT'
+}
- json () {
- // The json() method steps are to return the result of running
- // consume body with this and parse JSON from bytes.
- return specConsumeBody(this, parseJSONFromBytes, instance)
- },
+// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
+Object.setPrototypeOf(normalizeMethodRecord, null)
- async formData () {
- webidl.brandCheck(this, instance)
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-method-normalize
+ * @param {string} method
+ */
+function normalizeMethod (method) {
+ return normalizeMethodRecord[method.toLowerCase()] ?? method
+}
- throwIfAborted(this[kState])
+// 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)
- const contentType = this.headers.get('Content-Type')
+ // 2. If result is undefined, then throw a TypeError.
+ if (result === undefined) {
+ throw new TypeError('Value is not JSON serializable')
+ }
- // If mimeType’s essence is "multipart/form-data", then:
- if (/multipart\/form-data/.test(contentType)) {
- const headers = {}
- for (const [key, value] of this.headers) headers[key.toLowerCase()] = value
+ // 3. Assert: result is a string.
+ assert(typeof result === 'string')
- const responseFormData = new FormData()
+ // 4. Return result.
+ return result
+}
- let busboy
+// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object
+const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))
- try {
- busboy = new Busboy({
- headers,
- preservePath: true
- })
- } catch (err) {
- throw new DOMException(`${err}`, 'AbortError')
- }
+/**
+ * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
+ * @param {() => unknown[]} iterator
+ * @param {string} name name of the instance
+ * @param {'key'|'value'|'key+value'} kind
+ */
+function makeIterator (iterator, name, kind) {
+ const object = {
+ index: 0,
+ kind,
+ target: iterator
+ }
- busboy.on('field', (name, value) => {
- responseFormData.append(name, value)
- })
- busboy.on('file', (name, value, filename, encoding, mimeType) => {
- const chunks = []
+ const i = {
+ next () {
+ // 1. Let interface be the interface for which the iterator prototype object exists.
- if (encoding === 'base64' || encoding.toLowerCase() === 'base64') {
- let base64chunk = ''
+ // 2. Let thisValue be the this value.
- value.on('data', (chunk) => {
- base64chunk += chunk.toString().replace(/[\r\n]/gm, '')
+ // 3. Let object be ? ToObject(thisValue).
- const end = base64chunk.length - base64chunk.length % 4
- chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64'))
+ // 4. If object is a platform object, then perform a security
+ // check, passing:
- base64chunk = base64chunk.slice(end)
- })
- value.on('end', () => {
- chunks.push(Buffer.from(base64chunk, 'base64'))
- responseFormData.append(name, new File(chunks, filename, { type: mimeType }))
- })
- } else {
- value.on('data', (chunk) => {
- chunks.push(chunk)
- })
- value.on('end', () => {
- responseFormData.append(name, new File(chunks, filename, { type: mimeType }))
- })
- }
- })
+ // 5. If object is not a default iterator object for interface,
+ // then throw a TypeError.
+ if (Object.getPrototypeOf(this) !== i) {
+ throw new TypeError(
+ `'next' called on an object that does not implement interface ${name} Iterator.`
+ )
+ }
- const busboyResolve = new Promise((resolve, reject) => {
- busboy.on('finish', resolve)
- busboy.on('error', (err) => reject(new TypeError(err)))
- })
+ // 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, kind, target } = object
+ const values = target()
- if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk)
- busboy.end()
- await busboyResolve
+ // 9. Let len be the length of values.
+ const len = values.length
- return responseFormData
- } else if (/application\/x-www-form-urlencoded/.test(contentType)) {
- // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then:
+ // 10. If index is greater than or equal to len, then return
+ // CreateIterResultObject(undefined, true).
+ if (index >= len) {
+ return { value: undefined, done: true }
+ }
- // 1. Let entries be the result of parsing bytes.
- let entries
- try {
- let text = ''
- // application/x-www-form-urlencoded parser will keep the BOM.
- // https://url.spec.whatwg.org/#concept-urlencoded-parser
- // Note that streaming decoder is stateful and cannot be reused
- const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true })
+ // 11. Let pair be the entry in values at index index.
+ const pair = values[index]
- for await (const chunk of consumeBody(this[kState].body)) {
- if (!isUint8Array(chunk)) {
- throw new TypeError('Expected Uint8Array chunk')
- }
- text += streamingDecoder.decode(chunk, { stream: true })
- }
- text += streamingDecoder.decode()
- entries = new URLSearchParams(text)
- } catch (err) {
- // istanbul ignore next: Unclear when new URLSearchParams can fail on a string.
- // 2. If entries is failure, then throw a TypeError.
- throw Object.assign(new TypeError(), { cause: err })
- }
+ // 12. Set object’s index to index + 1.
+ object.index = index + 1
- // 3. Return a new FormData object whose entries are entries.
- const formData = new FormData()
- for (const [name, value] of entries) {
- formData.append(name, value)
- }
- return formData
- } else {
- // Wait a tick before checking if the request has been aborted.
- // Otherwise, a TypeError can be thrown when an AbortError should.
- await Promise.resolve()
+ // 13. Return the iterator result for pair and kind.
+ return iteratorResult(pair, kind)
+ },
+ // The class string of an iterator prototype object for a given interface is the
+ // result of concatenating the identifier of the interface and the string " Iterator".
+ [Symbol.toStringTag]: `${name} Iterator`
+ }
- throwIfAborted(this[kState])
+ // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%.
+ Object.setPrototypeOf(i, esIteratorPrototype)
+ // esIteratorPrototype needs to be the prototype of i
+ // which is the prototype of an empty object. Yes, it's confusing.
+ return Object.setPrototypeOf({}, i)
+}
- // Otherwise, throw a TypeError.
- throw webidl.errors.exception({
- header: `${instance.name}.formData`,
- message: 'Could not parse content as FormData.'
- })
- }
+// https://webidl.spec.whatwg.org/#iterator-result
+function iteratorResult (pair, kind) {
+ let result
+
+ // 1. Let result be a value determined by the value of kind:
+ switch (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 = pair[0]
+ 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 = pair[1]
+ 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 = pair
+ break
}
}
- return methods
-}
-
-function mixinBody (prototype) {
- Object.assign(prototype.prototype, bodyMixinMethods(prototype))
+ // 2. Return CreateIterResultObject(result, false).
+ return { value: result, done: false }
}
/**
- * @see https://fetch.spec.whatwg.org/#concept-body-consume-body
- * @param {Response|Request} object
- * @param {(value: unknown) => unknown} convertBytesToJSValue
- * @param {Response|Request} instance
+ * @see https://fetch.spec.whatwg.org/#body-fully-read
*/
-async function specConsumeBody (object, convertBytesToJSValue, instance) {
- webidl.brandCheck(object, instance)
-
- throwIfAborted(object[kState])
+async function fullyReadBody (body, processBody, processBodyError) {
+ // 1. If taskDestination is null, then set taskDestination to
+ // the result of starting a new parallel queue.
- // 1. If object is unusable, then return a promise rejected
- // with a TypeError.
- if (bodyUnusable(object[kState].body)) {
- throw new TypeError('Body is unusable')
- }
+ // 2. Let successSteps given a byte sequence bytes be to queue a
+ // fetch task to run processBody given bytes, with taskDestination.
+ const successSteps = processBody
- // 2. Let promise be a new promise.
- const promise = createDeferredPromise()
+ // 3. Let errorSteps be to queue a fetch task to run processBodyError,
+ // with taskDestination.
+ const errorSteps = processBodyError
- // 3. Let errorSteps given error be to reject promise with error.
- const errorSteps = (error) => promise.reject(error)
+ // 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.
+ let reader
- // 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)
- }
+ try {
+ reader = body.stream.getReader()
+ } catch (e) {
+ errorSteps(e)
+ return
}
- // 5. If object’s body is null, then run successSteps with an
- // empty byte sequence.
- if (object[kState].body == null) {
- successSteps(new Uint8Array())
- return promise.promise
+ // 5. Read all bytes from reader, given successSteps and errorSteps.
+ try {
+ const result = await readAllBytes(reader)
+ successSteps(result)
+ } catch (e) {
+ errorSteps(e)
}
+}
- // 6. Otherwise, fully read object’s body given successSteps,
- // errorSteps, and object’s relevant global object.
- await fullyReadBody(object[kState].body, successSteps, errorSteps)
+/** @type {ReadableStream} */
+let ReadableStream = globalThis.ReadableStream
- // 7. Return promise.
- return promise.promise
+function isReadableStreamLike (stream) {
+ if (!ReadableStream) {
+ ReadableStream = (__nccwpck_require__(63774).ReadableStream)
+ }
+
+ return stream instanceof ReadableStream || (
+ stream[Symbol.toStringTag] === 'ReadableStream' &&
+ typeof stream.tee === 'function'
+ )
}
-// https://fetch.spec.whatwg.org/#body-unusable
-function bodyUnusable (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))
-}
+const MAXIMUM_ARGUMENT_LENGTH = 65535
/**
- * @see https://encoding.spec.whatwg.org/#utf-8-decode
- * @param {Buffer} buffer
+ * @see https://infra.spec.whatwg.org/#isomorphic-decode
+ * @param {number[]|Uint8Array} input
*/
-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.
+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.
- // 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)
+ if (input.length < MAXIMUM_ARGUMENT_LENGTH) {
+ return String.fromCharCode(...input)
}
- // 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
+ return input.reduce((previous, current) => previous + String.fromCharCode(current), '')
}
/**
- * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value
- * @param {Uint8Array} bytes
+ * @param {ReadableStreamController} controller
*/
-function parseJSONFromBytes (bytes) {
- return JSON.parse(utf8DecodeBytes(bytes))
+function readableStreamClose (controller) {
+ try {
+ controller.close()
+ } catch (err) {
+ // TODO: add comment explaining why this error occurs.
+ if (!err.message.includes('Controller is already closed')) {
+ throw err
+ }
+ }
}
/**
- * @see https://fetch.spec.whatwg.org/#concept-body-mime-type
- * @param {import('./response').Response|import('./request').Request} object
+ * @see https://infra.spec.whatwg.org/#isomorphic-encode
+ * @param {string} input
*/
-function bodyMimeType (object) {
- const { headersList } = object[kState]
- const contentType = headersList.get('content-type')
-
- if (contentType === null) {
- return 'failure'
+function isomorphicEncode (input) {
+ // 1. Assert: input contains no code points greater than U+00FF.
+ for (let i = 0; i < input.length; i++) {
+ assert(input.charCodeAt(i) <= 0xFF)
}
- return parseMIMEType(contentType)
-}
-
-module.exports = {
- extractBody,
- safelyExtractBody,
- cloneBody,
- mixinBody
+ // 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 {ReadableStreamDefaultReader} reader
+ */
+async function readAllBytes (reader) {
+ const bytes = []
+ let byteLength = 0
-/***/ }),
-
-/***/ 7326:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(8167)
-
-const corsSafeListedMethods = ['GET', 'HEAD', 'POST']
-const corsSafeListedMethodsSet = new Set(corsSafeListedMethods)
-
-const nullBodyStatus = [101, 204, 205, 304]
-
-const redirectStatus = [301, 302, 303, 307, 308]
-const redirectStatusSet = new Set(redirectStatus)
-
-// https://fetch.spec.whatwg.org/#block-bad-port
-const badPorts = [
- '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', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697',
- '10080'
-]
-
-const badPortsSet = new Set(badPorts)
-
-// https://w3c.github.io/webappsec-referrer-policy/#referrer-policies
-const referrerPolicy = [
- '',
- 'no-referrer',
- 'no-referrer-when-downgrade',
- 'same-origin',
- 'origin',
- 'strict-origin',
- 'origin-when-cross-origin',
- 'strict-origin-when-cross-origin',
- 'unsafe-url'
-]
-const referrerPolicySet = new Set(referrerPolicy)
+ while (true) {
+ const { done, value: chunk } = await reader.read()
-const requestRedirect = ['follow', 'manual', 'error']
+ if (done) {
+ // 1. Call successSteps with bytes.
+ return Buffer.concat(bytes, byteLength)
+ }
-const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE']
-const safeMethodsSet = new Set(safeMethods)
+ // 1. If chunk is not a Uint8Array object, call failureSteps
+ // with a TypeError and abort these steps.
+ if (!isUint8Array(chunk)) {
+ throw new TypeError('Received non-Uint8Array chunk')
+ }
-const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors']
+ // 2. Append the bytes represented by chunk to bytes.
+ bytes.push(chunk)
+ byteLength += chunk.length
-const requestCredentials = ['omit', 'same-origin', 'include']
+ // 3. Read-loop given reader, bytes, successSteps, and failureSteps.
+ }
+}
-const requestCache = [
- 'default',
- 'no-store',
- 'reload',
- 'no-cache',
- 'force-cache',
- 'only-if-cached'
-]
+/**
+ * @see https://fetch.spec.whatwg.org/#is-local
+ * @param {URL} url
+ */
+function urlIsLocal (url) {
+ assert('protocol' in url) // ensure it's a url object
-// https://fetch.spec.whatwg.org/#request-body-header-name
-const requestBodyHeader = [
- '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'
-]
+ const protocol = url.protocol
-// https://fetch.spec.whatwg.org/#enumdef-requestduplex
-const requestDuplex = [
- 'half'
-]
+ return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:'
+}
-// http://fetch.spec.whatwg.org/#forbidden-method
-const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK']
-const forbiddenMethodsSet = new Set(forbiddenMethods)
+/**
+ * @param {string|URL} url
+ */
+function urlHasHttpsScheme (url) {
+ if (typeof url === 'string') {
+ return url.startsWith('https:')
+ }
-const subresource = [
- 'audio',
- 'audioworklet',
- 'font',
- 'image',
- 'manifest',
- 'paintworklet',
- 'script',
- 'style',
- 'track',
- 'video',
- 'xslt',
- ''
-]
-const subresourceSet = new Set(subresource)
+ return url.protocol === 'https:'
+}
-/** @type {globalThis['DOMException']} */
-const DOMException = globalThis.DOMException ?? (() => {
- // DOMException was only made a global in Node v17.0.0,
- // but fetch supports >= v16.8.
- try {
- atob('~')
- } catch (err) {
- return Object.getPrototypeOf(err).constructor
- }
-})()
+/**
+ * @see https://fetch.spec.whatwg.org/#http-scheme
+ * @param {URL} url
+ */
+function urlIsHttpHttpsScheme (url) {
+ assert('protocol' in url) // ensure it's a url object
-let channel
+ const protocol = url.protocol
-/** @type {globalThis['structuredClone']} */
-const structuredClone =
- globalThis.structuredClone ??
- // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js
- // structuredClone was added in v17.0.0, but fetch supports v16.8
- function structuredClone (value, options = undefined) {
- if (arguments.length === 0) {
- throw new TypeError('missing argument')
- }
+ return protocol === 'http:' || protocol === 'https:'
+}
- if (!channel) {
- channel = new MessageChannel()
- }
- channel.port1.unref()
- channel.port2.unref()
- channel.port1.postMessage(value, options?.transfer)
- return receiveMessageOnPort(channel.port2).message
- }
+/**
+ * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0.
+ */
+const hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key))
module.exports = {
- DOMException,
- structuredClone,
- subresource,
- forbiddenMethods,
- requestBodyHeader,
- referrerPolicy,
- requestRedirect,
- requestMode,
- requestCredentials,
- requestCache,
- redirectStatus,
- corsSafeListedMethods,
- nullBodyStatus,
- safeMethods,
- badPorts,
- requestDuplex,
- subresourceSet,
- badPortsSet,
- redirectStatusSet,
- corsSafeListedMethodsSet,
- safeMethodsSet,
- forbiddenMethodsSet,
- referrerPolicySet
+ isAborted,
+ isCancelled,
+ createDeferredPromise,
+ ReadableStreamFrom,
+ toUSVString,
+ tryUpgradeRequestToAPotentiallyTrustworthyURL,
+ coarsenedSharedCurrentTime,
+ determineRequestsReferrer,
+ makePolicyContainer,
+ clonePolicyContainer,
+ appendFetchMetadata,
+ appendRequestOriginHeader,
+ TAOCheck,
+ corsCheck,
+ crossOriginResourcePolicyCheck,
+ createOpaqueTimingInfo,
+ setRequestReferrerPolicyOnRedirect,
+ isValidHTTPToken,
+ requestBadPort,
+ requestCurrentURL,
+ responseURL,
+ responseLocationURL,
+ isBlobLike,
+ isURLPotentiallyTrustworthy,
+ isValidReasonPhrase,
+ sameOrigin,
+ normalizeMethod,
+ serializeJavascriptValueToJSONString,
+ makeIterator,
+ isValidHeaderName,
+ isValidHeaderValue,
+ hasOwn,
+ isErrorLike,
+ fullyReadBody,
+ bytesMatch,
+ isReadableStreamLike,
+ readableStreamClose,
+ isomorphicEncode,
+ isomorphicDecode,
+ urlIsLocal,
+ urlHasHttpsScheme,
+ urlIsHttpHttpsScheme,
+ readAllBytes,
+ normalizeMethodRecord,
+ parseMetadata
}
/***/ }),
-/***/ 4322:
+/***/ 74222:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const assert = __nccwpck_require__(2613)
-const { atob } = __nccwpck_require__(181)
-const { isomorphicDecode } = __nccwpck_require__(5523)
+"use strict";
-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
-/**
- * @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
+const { types } = __nccwpck_require__(39023)
+const { hasOwn, toUSVString } = __nccwpck_require__(15523)
-// 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:')
+/** @type {import('../../types/webidl').Webidl} */
+const webidl = {}
+webidl.converters = {}
+webidl.util = {}
+webidl.errors = {}
- // 2. Let input be the result of running the URL
- // serializer on dataURL with exclude fragment
- // set to true.
- let input = URLSerializer(dataURL, true)
+webidl.errors.exception = function (message) {
+ return new TypeError(`${message.header}: ${message.message}`)
+}
- // 3. Remove the leading "data:" string from input.
- input = input.slice(5)
+webidl.errors.conversionFailed = function (context) {
+ const plural = context.types.length === 1 ? '' : ' one of'
+ const message =
+ `${context.argument} could not be converted to` +
+ `${plural}: ${context.types.join(', ')}.`
- // 4. Let position point at the start of input.
- const position = { position: 0 }
+ return webidl.errors.exception({
+ header: context.prefix,
+ message
+ })
+}
- // 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
- )
+webidl.errors.invalidArgument = function (context) {
+ return webidl.errors.exception({
+ header: context.prefix,
+ message: `"${context.value}" is an invalid ${context.type}.`
+ })
+}
- // 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)
+// https://webidl.spec.whatwg.org/#implements
+webidl.brandCheck = function (V, I, opts = undefined) {
+ if (opts?.strict !== false && !(V instanceof I)) {
+ throw new TypeError('Illegal invocation')
+ } else {
+ return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag]
+ }
+}
- // 7. If position is past the end of input, then
- // return failure
- if (position.position >= input.length) {
- return 'failure'
+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.`,
+ ...ctx
+ })
}
+}
- // 8. Advance position by 1.
- position.position++
+webidl.illegalConstructor = function () {
+ throw webidl.errors.exception({
+ header: 'TypeError',
+ message: 'Illegal constructor'
+ })
+}
- // 9. Let encodedBody be the remainder of input.
- const encodedBody = input.slice(mimeTypeLength + 1)
+// 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'
+ }
- // 10. Let body be the percent-decoding of encodedBody.
- let body = stringPercentDecode(encodedBody)
+ return 'Object'
+ }
+ }
+}
- // 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)
+// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint
+webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) {
+ let upperBound
+ let lowerBound
- // 2. Set body to the forgiving-base64 decode of
- // stringBody.
- body = forgivingBase64(stringBody)
+ // 1. If bitLength is 64, then:
+ if (bitLength === 64) {
+ // 1. Let upperBound be 2^53 − 1.
+ upperBound = Math.pow(2, 53) - 1
- // 3. If body is failure, then return failure.
- if (body === 'failure') {
- return 'failure'
+ // 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:
- // 4. Remove the last 6 code points from mimeType.
- mimeType = mimeType.slice(0, -6)
+ // 1. Let lowerBound be 0.
+ lowerBound = 0
- // 5. Remove trailing U+0020 SPACE code points from mimeType,
- // if any.
- mimeType = mimeType.replace(/(\u0020)+$/, '')
+ // 2. Let upperBound be 2^bitLength − 1.
+ upperBound = Math.pow(2, bitLength) - 1
+ } else {
+ // 3. Otherwise:
- // 6. Remove the last U+003B (;) code point from mimeType.
- mimeType = mimeType.slice(0, -1)
- }
+ // 1. Let lowerBound be -2^bitLength − 1.
+ lowerBound = Math.pow(-2, bitLength) - 1
- // 12. If mimeType starts with U+003B (;), then prepend
- // "text/plain" to mimeType.
- if (mimeType.startsWith(';')) {
- mimeType = 'text/plain' + mimeType
+ // 2. Let upperBound be 2^bitLength − 1 − 1.
+ upperBound = Math.pow(2, bitLength - 1) - 1
}
- // 13. Let mimeTypeRecord be the result of parsing
- // mimeType.
- let mimeTypeRecord = parseMIMEType(mimeType)
+ // 4. Let x be ? ToNumber(V).
+ let x = Number(V)
- // 14. If mimeTypeRecord is failure, then set
- // mimeTypeRecord to text/plain;charset=US-ASCII.
- if (mimeTypeRecord === 'failure') {
- mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII')
+ // 5. If x is −0, then set x to +0.
+ if (x === 0) {
+ x = 0
}
- // 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 }
-}
+ // 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 ${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}.`
+ })
+ }
-// https://url.spec.whatwg.org/#concept-url-serializer
-/**
- * @param {URL} url
- * @param {boolean} excludeFragment
- */
-function URLSerializer (url, excludeFragment = false) {
- if (!excludeFragment) {
- return url.href
+ // 4. Return x.
+ return x
}
- const href = url.href
- const hashLength = url.hash.length
-
- return hashLength === 0 ? href : href.substring(0, href.length - hashLength)
-}
+ // 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)
-// 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. 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)
+ }
- // 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]
+ // 3. Return x.
+ return x
+ }
- // 2. Advance position by 1.
- position.position++
+ // 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
}
- // 3. Return result.
- return result
-}
+ // 9. Set x to IntegerPart(x).
+ x = webidl.util.IntegerPart(x)
-/**
- * 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
+ // 10. Set x to x modulo 2^bitLength.
+ x = x % Math.pow(2, bitLength)
- if (idx === -1) {
- position.position = input.length
- return input.slice(start)
+ // 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)
}
- position.position = idx
- return input.slice(start, position.position)
+ // 12. Otherwise, return x.
+ return x
}
-// 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)
+// 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. Return the percent-decoding of bytes.
- return percentDecode(bytes)
-}
+ // 2. If n < 0, then return -1 × r.
+ if (n < 0) {
+ return -1 * r
+ }
-// https://url.spec.whatwg.org/#percent-decode
-/** @param {Uint8Array} input */
-function percentDecode (input) {
- // 1. Let output be an empty byte sequence.
- /** @type {number[]} */
- const output = []
+ // 3. Otherwise, return r.
+ return r
+}
- // 2. For each byte byte in input:
- for (let i = 0; i < input.length; i++) {
- const byte = input[i]
+// https://webidl.spec.whatwg.org/#es-sequence
+webidl.sequenceConverter = function (converter) {
+ return (V) => {
+ // 1. If Type(V) is not Object, throw a TypeError.
+ if (webidl.util.Type(V) !== 'Object') {
+ throw webidl.errors.exception({
+ header: 'Sequence',
+ message: `Value of type ${webidl.util.Type(V)} is not an Object.`
+ })
+ }
- // 1. If byte is not 0x25 (%), then append byte to output.
- if (byte !== 0x25) {
- output.push(byte)
+ // 2. Let method be ? GetMethod(V, @@iterator).
+ /** @type {Generator} */
+ const method = V?.[Symbol.iterator]?.()
+ const seq = []
- // 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 &&
- !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2]))
+ // 3. If method is undefined, throw a TypeError.
+ if (
+ method === undefined ||
+ typeof method.next !== 'function'
) {
- output.push(0x25)
+ throw webidl.errors.exception({
+ header: 'Sequence',
+ message: 'Object is not an iterator.'
+ })
+ }
- // 3. Otherwise:
- } else {
- // 1. Let bytePoint be the two bytes after byte in input,
- // decoded, and then interpreted as hexadecimal number.
- const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2])
- const bytePoint = Number.parseInt(nextTwoBytes, 16)
+ // https://webidl.spec.whatwg.org/#create-sequence-from-iterable
+ while (true) {
+ const { done, value } = method.next()
- // 2. Append a byte whose value is bytePoint to output.
- output.push(bytePoint)
+ if (done) {
+ break
+ }
- // 3. Skip the next two bytes in input.
- i += 2
+ seq.push(converter(value))
}
- }
- // 3. Return output.
- return Uint8Array.from(output)
+ return seq
+ }
}
-// 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)
+// https://webidl.spec.whatwg.org/#es-to-record
+webidl.recordConverter = function (keyConverter, valueConverter) {
+ return (O) => {
+ // 1. If Type(O) is not Object, throw a TypeError.
+ if (webidl.util.Type(O) !== 'Object') {
+ throw webidl.errors.exception({
+ header: 'Record',
+ message: `Value of type ${webidl.util.Type(O)} is not an Object.`
+ })
+ }
- // 2. Let position be a position variable for input,
- // initially pointing at the start of input.
- const position = { position: 0 }
+ // 2. Let result be a new empty instance of record.
+ const result = {}
- // 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
- )
+ if (!types.isProxy(O)) {
+ // Object.keys only returns enumerable properties
+ const keys = Object.keys(O)
- // 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'
- }
+ for (const key of keys) {
+ // 1. Let typedKey be key converted to an IDL value of type K.
+ const typedKey = keyConverter(key)
- // 5. If position is past the end of input, then return
- // failure
- if (position.position > input.length) {
- return 'failure'
- }
+ // 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])
- // 6. Advance position by 1. (This skips past U+002F (/).)
- position.position++
+ // 4. Set result[typedKey] to typedValue.
+ result[typedKey] = typedValue
+ }
- // 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
- )
+ // 5. Return result.
+ return result
+ }
- // 8. Remove any trailing HTTP whitespace from subtype.
- subtype = removeHTTPWhitespace(subtype, false, true)
+ // 3. Let keys be ? O.[[OwnPropertyKeys]]().
+ const keys = Reflect.ownKeys(O)
- // 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'
- }
+ // 4. For each key of keys.
+ for (const key of keys) {
+ // 1. Let desc be ? O.[[GetOwnProperty]](key).
+ const desc = Reflect.getOwnPropertyDescriptor(O, key)
- const typeLowercase = type.toLowerCase()
- const subtypeLowercase = subtype.toLowerCase()
+ // 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)
- // 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}`
- }
+ // 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])
- // 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++
+ // 4. Set result[typedKey] to typedValue.
+ result[typedKey] = typedValue
+ }
+ }
- // 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
- )
+ // 5. Return result.
+ return result
+ }
+}
- // 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
- )
+webidl.interfaceConverter = function (i) {
+ return (V, opts = {}) => {
+ if (opts.strict !== false && !(V instanceof i)) {
+ throw webidl.errors.exception({
+ header: i.name,
+ message: `Expected ${V} to be an instance of ${i.name}.`
+ })
+ }
- // 4. Set parameterName to parameterName, in ASCII
- // lowercase.
- parameterName = parameterName.toLowerCase()
+ return V
+ }
+}
- // 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
- }
+webidl.dictionaryConverter = function (converters) {
+ return (dictionary) => {
+ const type = webidl.util.Type(dictionary)
+ const dict = {}
- // 2. Advance position by 1. (This skips past U+003D (=).)
- position.position++
+ if (type === 'Null' || type === 'Undefined') {
+ return dict
+ } else if (type !== 'Object') {
+ throw webidl.errors.exception({
+ header: 'Dictionary',
+ message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`
+ })
}
- // 6. If position is past the end of input, then break.
- if (position.position > input.length) {
- break
- }
+ for (const options of converters) {
+ const { key, defaultValue, required, converter } = options
- // 7. Let parameterValue be null.
- let parameterValue = null
+ if (required === true) {
+ if (!hasOwn(dictionary, key)) {
+ throw webidl.errors.exception({
+ header: 'Dictionary',
+ message: `Missing required key "${key}".`
+ })
+ }
+ }
- // 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)
+ let value = dictionary[key]
+ const hasDefault = hasOwn(options, 'defaultValue')
- // 2. Collect a sequence of code points that are not
- // U+003B (;) from input, given position.
- collectASequenceOfCodePointsFast(
- ';',
- input,
- position
- )
+ // Only use defaultValue if value is undefined and
+ // a defaultValue options was provided.
+ if (hasDefault && value !== null) {
+ value = value ?? defaultValue
+ }
- // 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
- )
+ // 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)
- // 2. Remove any trailing HTTP whitespace from parameterValue.
- parameterValue = removeHTTPWhitespace(parameterValue, false, true)
+ if (
+ options.allowedValues &&
+ !options.allowedValues.includes(value)
+ ) {
+ throw webidl.errors.exception({
+ header: 'Dictionary',
+ message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.`
+ })
+ }
- // 3. If parameterValue is the empty string, then continue.
- if (parameterValue.length === 0) {
- continue
+ dict[key] = value
}
}
- // 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)
- }
+ return dict
}
-
- // 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(/[\u0009\u000A\u000C\u000D\u0020]/g, '') // eslint-disable-line
+webidl.nullableConverter = function (converter) {
+ return (V) => {
+ if (V === null) {
+ return V
+ }
- // 2. If data’s code point length divides by 4 leaving
- // no remainder, then:
- if (data.length % 4 === 0) {
- // 1. If data ends with one or two U+003D (=) code points,
- // then remove them from data.
- data = data.replace(/=?=$/, '')
+ return converter(V)
}
+}
- // 3. If data’s code point length divides by 4 leaving
- // a remainder of 1, then return failure.
- if (data.length % 4 === 1) {
- return 'failure'
+// https://webidl.spec.whatwg.org/#es-DOMString
+webidl.converters.DOMString = function (V, 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 ''
}
- // 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)) {
- return 'failure'
+ // 2. Let x be ? ToString(V).
+ if (typeof V === 'symbol') {
+ throw new TypeError('Could not convert argument of type symbol to string.')
}
- const binary = atob(data)
- const bytes = new Uint8Array(binary.length)
+ // 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)
+}
- for (let byte = 0; byte < binary.length; byte++) {
- bytes[byte] = binary.charCodeAt(byte)
+// https://webidl.spec.whatwg.org/#es-ByteString
+webidl.converters.ByteString = function (V) {
+ // 1. Let x be ? ToString(V).
+ // Note: DOMString converter perform ? ToString(V)
+ const x = webidl.converters.DOMString(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.`
+ )
+ }
}
- return bytes
+ // 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
}
-// 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
- */
-function collectAnHTTPQuotedString (input, position, extractValue) {
- // 1. Let positionStart be position.
- const positionStart = position.position
+// https://webidl.spec.whatwg.org/#es-USVString
+webidl.converters.USVString = toUSVString
- // 2. Let value be the empty string.
- let value = ''
+// https://webidl.spec.whatwg.org/#es-boolean
+webidl.converters.boolean = function (V) {
+ // 1. Let x be the result of computing ToBoolean(V).
+ const x = Boolean(V)
- // 3. Assert: the code point at position within input
- // is U+0022 (").
- assert(input[position.position] === '"')
+ // 2. Return the IDL boolean value that is the one that represents
+ // the same truth value as the ECMAScript Boolean value x.
+ return x
+}
- // 4. Advance position by 1.
- position.position++
+// https://webidl.spec.whatwg.org/#es-any
+webidl.converters.any = function (V) {
+ return V
+}
- // 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
- )
+// https://webidl.spec.whatwg.org/#es-long-long
+webidl.converters['long long'] = function (V) {
+ // 1. Let x be ? ConvertToInt(V, 64, "signed").
+ const x = webidl.util.ConvertToInt(V, 64, 'signed')
- // 2. If position is past the end of input, then break.
- if (position.position >= input.length) {
- break
- }
+ // 2. Return the IDL long long value that represents
+ // the same numeric value as x.
+ return x
+}
- // 3. Let quoteOrBackslash be the code point at position within
- // input.
- const quoteOrBackslash = input[position.position]
+// https://webidl.spec.whatwg.org/#es-unsigned-long-long
+webidl.converters['unsigned long long'] = function (V) {
+ // 1. Let x be ? ConvertToInt(V, 64, "unsigned").
+ const x = webidl.util.ConvertToInt(V, 64, 'unsigned')
- // 4. Advance position by 1.
- position.position++
+ // 2. Return the IDL unsigned long long value that
+ // represents the same numeric value as x.
+ return x
+}
- // 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
- }
+// https://webidl.spec.whatwg.org/#es-unsigned-long
+webidl.converters['unsigned long'] = function (V) {
+ // 1. Let x be ? ConvertToInt(V, 32, "unsigned").
+ const x = webidl.util.ConvertToInt(V, 32, 'unsigned')
- // 2. Append the code point at position within input to value.
- value += input[position.position]
+ // 2. Return the IDL unsigned long value that
+ // represents the same numeric value as x.
+ return x
+}
- // 3. Advance position by 1.
- position.position++
+// https://webidl.spec.whatwg.org/#es-unsigned-short
+webidl.converters['unsigned short'] = function (V, opts) {
+ // 1. Let x be ? ConvertToInt(V, 16, "unsigned").
+ const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts)
- // 6. Otherwise:
- } else {
- // 1. Assert: quoteOrBackslash is U+0022 (").
- assert(quoteOrBackslash === '"')
+ // 2. Return the IDL unsigned short value that represents
+ // the same numeric value as x.
+ return x
+}
- // 2. Break.
- break
- }
+// https://webidl.spec.whatwg.org/#idl-ArrayBuffer
+webidl.converters.ArrayBuffer = function (V, 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: `${V}`,
+ argument: `${V}`,
+ types: ['ArrayBuffer']
+ })
}
- // 6. If the extract-value flag is set, then return value.
- if (extractValue) {
- return value
+ // 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.'
+ })
}
- // 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
+ // 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.
+ // Note: resizable ArrayBuffers are currently a proposal.
- // 1. Let serialization be the concatenation of mimeType’s
- // type, U+002F (/), and mimeType’s subtype.
- let serialization = essence
+ // 4. Return the IDL ArrayBuffer value that is a
+ // reference to the same object as V.
+ return V
+}
- // 2. For each name → value of mimeType’s parameters:
- for (let [name, value] of parameters.entries()) {
- // 1. Append U+003B (;) to serialization.
- serialization += ';'
+webidl.converters.TypedArray = function (V, T, opts = {}) {
+ // 1. Let T be the IDL type V is being converted to.
- // 2. Append name to serialization.
- serialization += name
+ // 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: `${T.name}`,
+ argument: `${V}`,
+ types: [T.name]
+ })
+ }
- // 3. Append U+003D (=) to serialization.
- serialization += '='
+ // 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 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 occurence of U+0022 (") or
- // U+005C (\) in value with U+005C (\).
- value = value.replace(/(\\|")/g, '\\$1')
+ // 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.
+ // Note: resizable array buffers are currently a proposal
- // 2. Prepend U+0022 (") to value.
- value = '"' + value
+ // 5. Return the IDL value of type T that is a reference
+ // to the same object as V.
+ return V
+}
- // 3. Append U+0022 (") to value.
- value += '"'
- }
+webidl.converters.DataView = function (V, 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: 'DataView',
+ message: 'Object is not a DataView.'
+ })
+ }
- // 5. Append value to serialization.
- serialization += value
+ // 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. Return serialization.
- return serialization
-}
+ // 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.
+ // Note: resizable ArrayBuffers are currently a proposal
-/**
- * @see https://fetch.spec.whatwg.org/#http-whitespace
- * @param {string} char
- */
-function isHTTPWhiteSpace (char) {
- return char === '\r' || char === '\n' || char === '\t' || char === ' '
+ // 4. Return the IDL DataView value that is a reference
+ // to the same object as V.
+ return V
}
-/**
- * @see https://fetch.spec.whatwg.org/#http-whitespace
- * @param {string} str
- */
-function removeHTTPWhitespace (str, leading = true, trailing = true) {
- let lead = 0
- let trail = str.length - 1
+// https://webidl.spec.whatwg.org/#BufferSource
+webidl.converters.BufferSource = function (V, opts = {}) {
+ if (types.isAnyArrayBuffer(V)) {
+ return webidl.converters.ArrayBuffer(V, opts)
+ }
- if (leading) {
- for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++);
+ if (types.isTypedArray(V)) {
+ return webidl.converters.TypedArray(V, V.constructor)
}
- if (trailing) {
- for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--);
+ if (types.isDataView(V)) {
+ return webidl.converters.DataView(V, opts)
}
- return str.slice(lead, trail + 1)
+ throw new TypeError(`Could not convert ${V} to a BufferSource.`)
}
-/**
- * @see https://infra.spec.whatwg.org/#ascii-whitespace
- * @param {string} char
- */
-function isASCIIWhitespace (char) {
- return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' '
+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
+)
+
+module.exports = {
+ webidl
}
+
+/***/ }),
+
+/***/ 40396:
+/***/ ((module) => {
+
+"use strict";
+
+
/**
- * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace
+ * @see https://encoding.spec.whatwg.org/#concept-encoding-get
+ * @param {string|undefined} label
*/
-function removeASCIIWhitespace (str, leading = true, trailing = true) {
- let lead = 0
- let trail = str.length - 1
-
- if (leading) {
- for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++);
+function getEncoding (label) {
+ if (!label) {
+ return 'failure'
}
- if (trailing) {
- for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--);
+ // 1. Remove any leading and trailing ASCII whitespace from label.
+ // 2. If label is an ASCII case-insensitive match for any of the
+ // labels listed in the table below, then return the
+ // corresponding encoding; otherwise return failure.
+ switch (label.trim().toLowerCase()) {
+ case 'unicode-1-1-utf-8':
+ case 'unicode11utf8':
+ case 'unicode20utf8':
+ case 'utf-8':
+ case 'utf8':
+ case 'x-unicode20utf8':
+ return 'UTF-8'
+ case '866':
+ case 'cp866':
+ case 'csibm866':
+ case 'ibm866':
+ return 'IBM866'
+ case 'csisolatin2':
+ case 'iso-8859-2':
+ case 'iso-ir-101':
+ case 'iso8859-2':
+ case 'iso88592':
+ case 'iso_8859-2':
+ case 'iso_8859-2:1987':
+ case 'l2':
+ case 'latin2':
+ return 'ISO-8859-2'
+ case 'csisolatin3':
+ case 'iso-8859-3':
+ case 'iso-ir-109':
+ case 'iso8859-3':
+ case 'iso88593':
+ case 'iso_8859-3':
+ case 'iso_8859-3:1988':
+ case 'l3':
+ case 'latin3':
+ return 'ISO-8859-3'
+ case 'csisolatin4':
+ case 'iso-8859-4':
+ case 'iso-ir-110':
+ case 'iso8859-4':
+ case 'iso88594':
+ case 'iso_8859-4':
+ case 'iso_8859-4:1988':
+ case 'l4':
+ case 'latin4':
+ return 'ISO-8859-4'
+ case 'csisolatincyrillic':
+ case 'cyrillic':
+ case 'iso-8859-5':
+ case 'iso-ir-144':
+ case 'iso8859-5':
+ case 'iso88595':
+ case 'iso_8859-5':
+ case 'iso_8859-5:1988':
+ return 'ISO-8859-5'
+ case 'arabic':
+ case 'asmo-708':
+ case 'csiso88596e':
+ case 'csiso88596i':
+ case 'csisolatinarabic':
+ case 'ecma-114':
+ case 'iso-8859-6':
+ case 'iso-8859-6-e':
+ case 'iso-8859-6-i':
+ case 'iso-ir-127':
+ case 'iso8859-6':
+ case 'iso88596':
+ case 'iso_8859-6':
+ case 'iso_8859-6:1987':
+ return 'ISO-8859-6'
+ case 'csisolatingreek':
+ case 'ecma-118':
+ case 'elot_928':
+ case 'greek':
+ case 'greek8':
+ case 'iso-8859-7':
+ case 'iso-ir-126':
+ case 'iso8859-7':
+ case 'iso88597':
+ case 'iso_8859-7':
+ case 'iso_8859-7:1987':
+ case 'sun_eu_greek':
+ return 'ISO-8859-7'
+ case 'csiso88598e':
+ case 'csisolatinhebrew':
+ case 'hebrew':
+ case 'iso-8859-8':
+ case 'iso-8859-8-e':
+ case 'iso-ir-138':
+ case 'iso8859-8':
+ case 'iso88598':
+ case 'iso_8859-8':
+ case 'iso_8859-8:1988':
+ case 'visual':
+ return 'ISO-8859-8'
+ case 'csiso88598i':
+ case 'iso-8859-8-i':
+ case 'logical':
+ return 'ISO-8859-8-I'
+ case 'csisolatin6':
+ case 'iso-8859-10':
+ case 'iso-ir-157':
+ case 'iso8859-10':
+ case 'iso885910':
+ case 'l6':
+ case 'latin6':
+ return 'ISO-8859-10'
+ case 'iso-8859-13':
+ case 'iso8859-13':
+ case 'iso885913':
+ return 'ISO-8859-13'
+ case 'iso-8859-14':
+ case 'iso8859-14':
+ case 'iso885914':
+ return 'ISO-8859-14'
+ case 'csisolatin9':
+ case 'iso-8859-15':
+ case 'iso8859-15':
+ case 'iso885915':
+ case 'iso_8859-15':
+ case 'l9':
+ return 'ISO-8859-15'
+ case 'iso-8859-16':
+ return 'ISO-8859-16'
+ case 'cskoi8r':
+ case 'koi':
+ case 'koi8':
+ case 'koi8-r':
+ case 'koi8_r':
+ return 'KOI8-R'
+ case 'koi8-ru':
+ case 'koi8-u':
+ return 'KOI8-U'
+ case 'csmacintosh':
+ case 'mac':
+ case 'macintosh':
+ case 'x-mac-roman':
+ return 'macintosh'
+ case 'iso-8859-11':
+ case 'iso8859-11':
+ case 'iso885911':
+ case 'tis-620':
+ case 'windows-874':
+ return 'windows-874'
+ case 'cp1250':
+ case 'windows-1250':
+ case 'x-cp1250':
+ return 'windows-1250'
+ case 'cp1251':
+ case 'windows-1251':
+ case 'x-cp1251':
+ return 'windows-1251'
+ case 'ansi_x3.4-1968':
+ case 'ascii':
+ case 'cp1252':
+ case 'cp819':
+ case 'csisolatin1':
+ case 'ibm819':
+ case 'iso-8859-1':
+ case 'iso-ir-100':
+ case 'iso8859-1':
+ case 'iso88591':
+ case 'iso_8859-1':
+ case 'iso_8859-1:1987':
+ case 'l1':
+ case 'latin1':
+ case 'us-ascii':
+ case 'windows-1252':
+ case 'x-cp1252':
+ return 'windows-1252'
+ case 'cp1253':
+ case 'windows-1253':
+ case 'x-cp1253':
+ return 'windows-1253'
+ case 'cp1254':
+ case 'csisolatin5':
+ case 'iso-8859-9':
+ case 'iso-ir-148':
+ case 'iso8859-9':
+ case 'iso88599':
+ case 'iso_8859-9':
+ case 'iso_8859-9:1989':
+ case 'l5':
+ case 'latin5':
+ case 'windows-1254':
+ case 'x-cp1254':
+ return 'windows-1254'
+ case 'cp1255':
+ case 'windows-1255':
+ case 'x-cp1255':
+ return 'windows-1255'
+ case 'cp1256':
+ case 'windows-1256':
+ case 'x-cp1256':
+ return 'windows-1256'
+ case 'cp1257':
+ case 'windows-1257':
+ case 'x-cp1257':
+ return 'windows-1257'
+ case 'cp1258':
+ case 'windows-1258':
+ case 'x-cp1258':
+ return 'windows-1258'
+ case 'x-mac-cyrillic':
+ case 'x-mac-ukrainian':
+ return 'x-mac-cyrillic'
+ case 'chinese':
+ case 'csgb2312':
+ case 'csiso58gb231280':
+ case 'gb2312':
+ case 'gb_2312':
+ case 'gb_2312-80':
+ case 'gbk':
+ case 'iso-ir-58':
+ case 'x-gbk':
+ return 'GBK'
+ case 'gb18030':
+ return 'gb18030'
+ case 'big5':
+ case 'big5-hkscs':
+ case 'cn-big5':
+ case 'csbig5':
+ case 'x-x-big5':
+ return 'Big5'
+ case 'cseucpkdfmtjapanese':
+ case 'euc-jp':
+ case 'x-euc-jp':
+ return 'EUC-JP'
+ case 'csiso2022jp':
+ case 'iso-2022-jp':
+ return 'ISO-2022-JP'
+ case 'csshiftjis':
+ case 'ms932':
+ case 'ms_kanji':
+ case 'shift-jis':
+ case 'shift_jis':
+ case 'sjis':
+ case 'windows-31j':
+ case 'x-sjis':
+ return 'Shift_JIS'
+ case 'cseuckr':
+ case 'csksc56011987':
+ case 'euc-kr':
+ case 'iso-ir-149':
+ case 'korean':
+ case 'ks_c_5601-1987':
+ case 'ks_c_5601-1989':
+ case 'ksc5601':
+ case 'ksc_5601':
+ case 'windows-949':
+ return 'EUC-KR'
+ case 'csiso2022kr':
+ case 'hz-gb-2312':
+ case 'iso-2022-cn':
+ case 'iso-2022-cn-ext':
+ case 'iso-2022-kr':
+ case 'replacement':
+ return 'replacement'
+ case 'unicodefffe':
+ case 'utf-16be':
+ return 'UTF-16BE'
+ case 'csunicode':
+ case 'iso-10646-ucs-2':
+ case 'ucs-2':
+ case 'unicode':
+ case 'unicodefeff':
+ case 'utf-16':
+ case 'utf-16le':
+ return 'UTF-16LE'
+ case 'x-user-defined':
+ return 'x-user-defined'
+ default: return 'failure'
}
-
- return str.slice(lead, trail + 1)
}
module.exports = {
- dataURLProcessor,
- URLSerializer,
- collectASequenceOfCodePoints,
- collectASequenceOfCodePointsFast,
- stringPercentDecode,
- parseMIMEType,
- collectAnHTTPQuotedString,
- serializeAMimeType
+ getEncoding
}
/***/ }),
-/***/ 3041:
+/***/ 82160:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-const { Blob, File: NativeFile } = __nccwpck_require__(181)
-const { types } = __nccwpck_require__(9023)
-const { kState } = __nccwpck_require__(9710)
-const { isBlobLike } = __nccwpck_require__(5523)
-const { webidl } = __nccwpck_require__(4222)
-const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322)
+const {
+ staticPropertyDescriptors,
+ readOperation,
+ fireAProgressEvent
+} = __nccwpck_require__(10165)
+const {
+ kState,
+ kError,
+ kResult,
+ kEvents,
+ kAborted
+} = __nccwpck_require__(86812)
+const { webidl } = __nccwpck_require__(74222)
const { kEnumerableProperty } = __nccwpck_require__(3440)
-const encoder = new TextEncoder()
-
-class File extends Blob {
- constructor (fileBits, fileName, options = {}) {
- // The File constructor is invoked with two or three parameters, depending
- // on whether the optional dictionary parameter is used. When the File()
- // constructor is invoked, user agents must run the following steps:
- webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' })
-
- fileBits = webidl.converters['sequence'](fileBits)
- fileName = webidl.converters.USVString(fileName)
- options = webidl.converters.FilePropertyBag(options)
-
- // 1. Let bytes be the result of processing blob parts given fileBits and
- // options.
- // Note: Blob handles this for us
-
- // 2. Let n be the fileName argument to the constructor.
- const n = fileName
-
- // 3. Process FilePropertyBag dictionary argument by running the following
- // substeps:
-
- // 1. If the type member is provided and is not the empty string, let t
- // be set to the type dictionary member. If t contains any characters
- // outside the range U+0020 to U+007E, then set t to the empty string
- // and return from these substeps.
- // 2. Convert every character in t to ASCII lowercase.
- let t = options.type
- let d
-
- // eslint-disable-next-line no-labels
- substep: {
- if (t) {
- t = parseMIMEType(t)
-
- if (t === 'failure') {
- t = ''
- // eslint-disable-next-line no-labels
- break substep
- }
-
- t = serializeAMimeType(t).toLowerCase()
- }
-
- // 3. If the lastModified member is provided, let d be set to the
- // lastModified dictionary member. If it is not provided, set d to the
- // current date and time represented as the number of milliseconds since
- // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
- d = options.lastModified
- }
-
- // 4. Return a new File object F such that:
- // F refers to the bytes byte sequence.
- // F.size is set to the number of total bytes in bytes.
- // F.name is set to n.
- // F.type is set to t.
- // F.lastModified is set to d.
-
- super(processBlobParts(fileBits, options), { type: t })
- this[kState] = {
- name: n,
- lastModified: d,
- type: t
- }
- }
-
- get name () {
- webidl.brandCheck(this, File)
-
- return this[kState].name
- }
-
- get lastModified () {
- webidl.brandCheck(this, File)
-
- return this[kState].lastModified
- }
-
- get type () {
- webidl.brandCheck(this, File)
-
- return this[kState].type
- }
-}
-
-class FileLike {
- constructor (blobLike, fileName, options = {}) {
- // TODO: argument idl type check
-
- // The File constructor is invoked with two or three parameters, depending
- // on whether the optional dictionary parameter is used. When the File()
- // constructor is invoked, user agents must run the following steps:
-
- // 1. Let bytes be the result of processing blob parts given fileBits and
- // options.
-
- // 2. Let n be the fileName argument to the constructor.
- const n = fileName
-
- // 3. Process FilePropertyBag dictionary argument by running the following
- // substeps:
-
- // 1. If the type member is provided and is not the empty string, let t
- // be set to the type dictionary member. If t contains any characters
- // outside the range U+0020 to U+007E, then set t to the empty string
- // and return from these substeps.
- // TODO
- const t = options.type
-
- // 2. Convert every character in t to ASCII lowercase.
- // TODO
-
- // 3. If the lastModified member is provided, let d be set to the
- // lastModified dictionary member. If it is not provided, set d to the
- // current date and time represented as the number of milliseconds since
- // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
- const d = options.lastModified ?? Date.now()
- // 4. Return a new File object F such that:
- // F refers to the bytes byte sequence.
- // F.size is set to the number of total bytes in bytes.
- // F.name is set to n.
- // F.type is set to t.
- // F.lastModified is set to d.
+class FileReader extends EventTarget {
+ constructor () {
+ super()
- this[kState] = {
- blobLike,
- name: n,
- type: t,
- lastModified: d
+ this[kState] = 'empty'
+ this[kResult] = null
+ this[kError] = null
+ this[kEvents] = {
+ loadend: null,
+ error: null,
+ abort: null,
+ load: null,
+ progress: null,
+ loadstart: null
}
}
- stream (...args) {
- webidl.brandCheck(this, FileLike)
-
- return this[kState].blobLike.stream(...args)
- }
-
- arrayBuffer (...args) {
- webidl.brandCheck(this, FileLike)
-
- return this[kState].blobLike.arrayBuffer(...args)
- }
-
- slice (...args) {
- webidl.brandCheck(this, FileLike)
-
- return this[kState].blobLike.slice(...args)
- }
-
- text (...args) {
- webidl.brandCheck(this, FileLike)
-
- return this[kState].blobLike.text(...args)
- }
-
- get size () {
- webidl.brandCheck(this, FileLike)
+ /**
+ * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer
+ * @param {import('buffer').Blob} blob
+ */
+ readAsArrayBuffer (blob) {
+ webidl.brandCheck(this, FileReader)
- return this[kState].blobLike.size
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' })
- get type () {
- webidl.brandCheck(this, FileLike)
+ blob = webidl.converters.Blob(blob, { strict: false })
- return this[kState].blobLike.type
+ // The readAsArrayBuffer(blob) method, when invoked,
+ // must initiate a read operation for blob with ArrayBuffer.
+ readOperation(this, blob, 'ArrayBuffer')
}
- get name () {
- webidl.brandCheck(this, FileLike)
+ /**
+ * @see https://w3c.github.io/FileAPI/#readAsBinaryString
+ * @param {import('buffer').Blob} blob
+ */
+ readAsBinaryString (blob) {
+ webidl.brandCheck(this, FileReader)
- return this[kState].name
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' })
- get lastModified () {
- webidl.brandCheck(this, FileLike)
+ blob = webidl.converters.Blob(blob, { strict: false })
- return this[kState].lastModified
+ // The readAsBinaryString(blob) method, when invoked,
+ // must initiate a read operation for blob with BinaryString.
+ readOperation(this, blob, 'BinaryString')
}
- get [Symbol.toStringTag] () {
- return 'File'
- }
-}
+ /**
+ * @see https://w3c.github.io/FileAPI/#readAsDataText
+ * @param {import('buffer').Blob} blob
+ * @param {string?} encoding
+ */
+ readAsText (blob, encoding = undefined) {
+ webidl.brandCheck(this, FileReader)
-Object.defineProperties(File.prototype, {
- [Symbol.toStringTag]: {
- value: 'File',
- configurable: true
- },
- name: kEnumerableProperty,
- lastModified: kEnumerableProperty
-})
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' })
-webidl.converters.Blob = webidl.interfaceConverter(Blob)
+ blob = webidl.converters.Blob(blob, { strict: false })
-webidl.converters.BlobPart = function (V, opts) {
- if (webidl.util.Type(V) === 'Object') {
- if (isBlobLike(V)) {
- return webidl.converters.Blob(V, { strict: false })
+ if (encoding !== undefined) {
+ encoding = webidl.converters.DOMString(encoding)
}
- if (
- ArrayBuffer.isView(V) ||
- types.isAnyArrayBuffer(V)
- ) {
- return webidl.converters.BufferSource(V, opts)
- }
+ // The readAsText(blob, encoding) method, when invoked,
+ // must initiate a read operation for blob with Text and encoding.
+ readOperation(this, blob, 'Text', encoding)
}
- return webidl.converters.USVString(V, opts)
-}
-
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.BlobPart
-)
+ /**
+ * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL
+ * @param {import('buffer').Blob} blob
+ */
+ readAsDataURL (blob) {
+ webidl.brandCheck(this, FileReader)
-// https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag
-webidl.converters.FilePropertyBag = webidl.dictionaryConverter([
- {
- key: 'lastModified',
- converter: webidl.converters['long long'],
- get defaultValue () {
- return Date.now()
- }
- },
- {
- key: 'type',
- converter: webidl.converters.DOMString,
- defaultValue: ''
- },
- {
- key: 'endings',
- converter: (value) => {
- value = webidl.converters.DOMString(value)
- value = value.toLowerCase()
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' })
- if (value !== 'native') {
- value = 'transparent'
- }
+ blob = webidl.converters.Blob(blob, { strict: false })
- return value
- },
- defaultValue: 'transparent'
+ // The readAsDataURL(blob) method, when invoked, must
+ // initiate a read operation for blob with DataURL.
+ readOperation(this, blob, 'DataURL')
}
-])
-
-/**
- * @see https://www.w3.org/TR/FileAPI/#process-blob-parts
- * @param {(NodeJS.TypedArray|Blob|string)[]} parts
- * @param {{ type: string, endings: string }} options
- */
-function processBlobParts (parts, options) {
- // 1. Let bytes be an empty sequence of bytes.
- /** @type {NodeJS.TypedArray[]} */
- const bytes = []
-
- // 2. For each element in parts:
- for (const element of parts) {
- // 1. If element is a USVString, run the following substeps:
- if (typeof element === 'string') {
- // 1. Let s be element.
- let s = element
-
- // 2. If the endings member of options is "native", set s
- // to the result of converting line endings to native
- // of element.
- if (options.endings === 'native') {
- s = convertLineEndingsNative(s)
- }
- // 3. Append the result of UTF-8 encoding s to bytes.
- bytes.push(encoder.encode(s))
- } else if (
- types.isAnyArrayBuffer(element) ||
- types.isTypedArray(element)
- ) {
- // 2. If element is a BufferSource, get a copy of the
- // bytes held by the buffer source, and append those
- // bytes to bytes.
- if (!element.buffer) { // ArrayBuffer
- bytes.push(new Uint8Array(element))
- } else {
- bytes.push(
- new Uint8Array(element.buffer, element.byteOffset, element.byteLength)
- )
- }
- } else if (isBlobLike(element)) {
- // 3. If element is a Blob, append the bytes it represents
- // to bytes.
- bytes.push(element)
+ /**
+ * @see https://w3c.github.io/FileAPI/#dfn-abort
+ */
+ abort () {
+ // 1. If this's state is "empty" or if this's state is
+ // "done" set this's result to null and terminate
+ // this algorithm.
+ if (this[kState] === 'empty' || this[kState] === 'done') {
+ this[kResult] = null
+ return
}
- }
-
- // 3. Return bytes.
- return bytes
-}
-
-/**
- * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native
- * @param {string} s
- */
-function convertLineEndingsNative (s) {
- // 1. Let native line ending be be the code point U+000A LF.
- let nativeLineEnding = '\n'
-
- // 2. If the underlying platform’s conventions are to
- // represent newlines as a carriage return and line feed
- // sequence, set native line ending to the code point
- // U+000D CR followed by the code point U+000A LF.
- if (process.platform === 'win32') {
- nativeLineEnding = '\r\n'
- }
-
- return s.replace(/\r?\n/g, nativeLineEnding)
-}
-
-// If this function is moved to ./util.js, some tools (such as
-// rollup) will warn about circular dependencies. See:
-// https://github.com/nodejs/undici/issues/1629
-function isFileLike (object) {
- return (
- (NativeFile && object instanceof NativeFile) ||
- object instanceof File || (
- object &&
- (typeof object.stream === 'function' ||
- typeof object.arrayBuffer === 'function') &&
- object[Symbol.toStringTag] === 'File'
- )
- )
-}
-
-module.exports = { File, FileLike, isFileLike }
-
-
-/***/ }),
-
-/***/ 3073:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-"use strict";
-
-
-const { isBlobLike, toUSVString, makeIterator } = __nccwpck_require__(5523)
-const { kState } = __nccwpck_require__(9710)
-const { File: UndiciFile, FileLike, isFileLike } = __nccwpck_require__(3041)
-const { webidl } = __nccwpck_require__(4222)
-const { Blob, File: NativeFile } = __nccwpck_require__(181)
-
-/** @type {globalThis['File']} */
-const File = NativeFile ?? UndiciFile
-
-// https://xhr.spec.whatwg.org/#formdata
-class FormData {
- constructor (form) {
- if (form !== undefined) {
- throw webidl.errors.conversionFailed({
- prefix: 'FormData constructor',
- argument: 'Argument 1',
- types: ['undefined']
- })
+ // 2. If this's state is "loading" set this's state to
+ // "done" and set this's result to null.
+ if (this[kState] === 'loading') {
+ this[kState] = 'done'
+ this[kResult] = null
}
- this[kState] = []
- }
+ // 3. If there are any tasks from this on the file reading
+ // task source in an affiliated task queue, then remove
+ // those tasks from that task queue.
+ this[kAborted] = true
- append (name, value, filename = undefined) {
- webidl.brandCheck(this, FormData)
+ // 4. Terminate the algorithm for the read method being processed.
+ // TODO
- webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' })
+ // 5. Fire a progress event called abort at this.
+ fireAProgressEvent('abort', this)
- if (arguments.length === 3 && !isBlobLike(value)) {
- throw new TypeError(
- "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'"
- )
+ // 6. If this's state is not "loading", fire a progress
+ // event called loadend at this.
+ if (this[kState] !== 'loading') {
+ fireAProgressEvent('loadend', this)
}
+ }
- // 1. Let value be value if given; otherwise blobValue.
-
- name = webidl.converters.USVString(name)
- value = isBlobLike(value)
- ? webidl.converters.Blob(value, { strict: false })
- : webidl.converters.USVString(value)
- filename = arguments.length === 3
- ? webidl.converters.USVString(filename)
- : undefined
-
- // 2. Let entry be the result of creating an entry with
- // name, value, and filename if given.
- const entry = makeEntry(name, value, filename)
+ /**
+ * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate
+ */
+ get readyState () {
+ webidl.brandCheck(this, FileReader)
- // 3. Append entry to this’s entry list.
- this[kState].push(entry)
+ switch (this[kState]) {
+ case 'empty': return this.EMPTY
+ case 'loading': return this.LOADING
+ case 'done': return this.DONE
+ }
}
- delete (name) {
- webidl.brandCheck(this, FormData)
+ /**
+ * @see https://w3c.github.io/FileAPI/#dom-filereader-result
+ */
+ get result () {
+ webidl.brandCheck(this, FileReader)
- webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' })
+ // The result attribute’s getter, when invoked, must return
+ // this's result.
+ return this[kResult]
+ }
- name = webidl.converters.USVString(name)
+ /**
+ * @see https://w3c.github.io/FileAPI/#dom-filereader-error
+ */
+ get error () {
+ webidl.brandCheck(this, FileReader)
- // The delete(name) method steps are to remove all entries whose name
- // is name from this’s entry list.
- this[kState] = this[kState].filter(entry => entry.name !== name)
+ // The error attribute’s getter, when invoked, must return
+ // this's error.
+ return this[kError]
}
- get (name) {
- webidl.brandCheck(this, FormData)
+ get onloadend () {
+ webidl.brandCheck(this, FileReader)
- webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' })
+ return this[kEvents].loadend
+ }
- name = webidl.converters.USVString(name)
+ set onloadend (fn) {
+ webidl.brandCheck(this, FileReader)
- // 1. If there is no entry whose name is name in this’s entry list,
- // then return null.
- const idx = this[kState].findIndex((entry) => entry.name === name)
- if (idx === -1) {
- return null
+ if (this[kEvents].loadend) {
+ this.removeEventListener('loadend', this[kEvents].loadend)
}
- // 2. Return the value of the first entry whose name is name from
- // this’s entry list.
- return this[kState][idx].value
+ if (typeof fn === 'function') {
+ this[kEvents].loadend = fn
+ this.addEventListener('loadend', fn)
+ } else {
+ this[kEvents].loadend = null
+ }
}
- getAll (name) {
- webidl.brandCheck(this, FormData)
-
- webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' })
-
- name = webidl.converters.USVString(name)
+ get onerror () {
+ webidl.brandCheck(this, FileReader)
- // 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[kState]
- .filter((entry) => entry.name === name)
- .map((entry) => entry.value)
+ return this[kEvents].error
}
- has (name) {
- webidl.brandCheck(this, FormData)
+ set onerror (fn) {
+ webidl.brandCheck(this, FileReader)
- webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' })
+ if (this[kEvents].error) {
+ this.removeEventListener('error', this[kEvents].error)
+ }
- name = webidl.converters.USVString(name)
+ if (typeof fn === 'function') {
+ this[kEvents].error = fn
+ this.addEventListener('error', fn)
+ } else {
+ this[kEvents].error = null
+ }
+ }
- // 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[kState].findIndex((entry) => entry.name === name) !== -1
+ get onloadstart () {
+ webidl.brandCheck(this, FileReader)
+
+ return this[kEvents].loadstart
}
- set (name, value, filename = undefined) {
- webidl.brandCheck(this, FormData)
+ set onloadstart (fn) {
+ webidl.brandCheck(this, FileReader)
- webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' })
+ if (this[kEvents].loadstart) {
+ this.removeEventListener('loadstart', this[kEvents].loadstart)
+ }
- if (arguments.length === 3 && !isBlobLike(value)) {
- throw new TypeError(
- "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'"
- )
+ if (typeof fn === 'function') {
+ this[kEvents].loadstart = fn
+ this.addEventListener('loadstart', fn)
+ } else {
+ this[kEvents].loadstart = null
}
+ }
- // The set(name, value) and set(name, blobValue, filename) method steps
- // are:
+ get onprogress () {
+ webidl.brandCheck(this, FileReader)
- // 1. Let value be value if given; otherwise blobValue.
+ return this[kEvents].progress
+ }
- name = webidl.converters.USVString(name)
- value = isBlobLike(value)
- ? webidl.converters.Blob(value, { strict: false })
- : webidl.converters.USVString(value)
- filename = arguments.length === 3
- ? toUSVString(filename)
- : undefined
+ set onprogress (fn) {
+ webidl.brandCheck(this, FileReader)
- // 2. Let entry be the result of creating an entry with name, value, and
- // filename if given.
- const entry = makeEntry(name, value, filename)
+ if (this[kEvents].progress) {
+ this.removeEventListener('progress', this[kEvents].progress)
+ }
- // 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[kState].findIndex((entry) => entry.name === name)
- if (idx !== -1) {
- this[kState] = [
- ...this[kState].slice(0, idx),
- entry,
- ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name)
- ]
+ if (typeof fn === 'function') {
+ this[kEvents].progress = fn
+ this.addEventListener('progress', fn)
} else {
- // 4. Otherwise, append entry to this’s entry list.
- this[kState].push(entry)
+ this[kEvents].progress = null
}
}
- entries () {
- webidl.brandCheck(this, FormData)
+ get onload () {
+ webidl.brandCheck(this, FileReader)
- return makeIterator(
- () => this[kState].map(pair => [pair.name, pair.value]),
- 'FormData',
- 'key+value'
- )
+ return this[kEvents].load
}
- keys () {
- webidl.brandCheck(this, FormData)
+ set onload (fn) {
+ webidl.brandCheck(this, FileReader)
- return makeIterator(
- () => this[kState].map(pair => [pair.name, pair.value]),
- 'FormData',
- 'key'
- )
+ if (this[kEvents].load) {
+ this.removeEventListener('load', this[kEvents].load)
+ }
+
+ if (typeof fn === 'function') {
+ this[kEvents].load = fn
+ this.addEventListener('load', fn)
+ } else {
+ this[kEvents].load = null
+ }
}
- values () {
- webidl.brandCheck(this, FormData)
+ get onabort () {
+ webidl.brandCheck(this, FileReader)
- return makeIterator(
- () => this[kState].map(pair => [pair.name, pair.value]),
- 'FormData',
- 'value'
- )
+ return this[kEvents].abort
}
- /**
- * @param {(value: string, key: string, self: FormData) => void} callbackFn
- * @param {unknown} thisArg
- */
- forEach (callbackFn, thisArg = globalThis) {
- webidl.brandCheck(this, FormData)
-
- webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' })
+ set onabort (fn) {
+ webidl.brandCheck(this, FileReader)
- if (typeof callbackFn !== 'function') {
- throw new TypeError(
- "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'."
- )
+ if (this[kEvents].abort) {
+ this.removeEventListener('abort', this[kEvents].abort)
}
- for (const [key, value] of this) {
- callbackFn.apply(thisArg, [value, key, this])
+ if (typeof fn === 'function') {
+ this[kEvents].abort = fn
+ this.addEventListener('abort', fn)
+ } else {
+ this[kEvents].abort = null
}
}
}
-FormData.prototype[Symbol.iterator] = FormData.prototype.entries
+// https://w3c.github.io/FileAPI/#dom-filereader-empty
+FileReader.EMPTY = FileReader.prototype.EMPTY = 0
+// https://w3c.github.io/FileAPI/#dom-filereader-loading
+FileReader.LOADING = FileReader.prototype.LOADING = 1
+// https://w3c.github.io/FileAPI/#dom-filereader-done
+FileReader.DONE = FileReader.prototype.DONE = 2
-Object.defineProperties(FormData.prototype, {
+Object.defineProperties(FileReader.prototype, {
+ EMPTY: staticPropertyDescriptors,
+ LOADING: staticPropertyDescriptors,
+ DONE: staticPropertyDescriptors,
+ readAsArrayBuffer: kEnumerableProperty,
+ readAsBinaryString: kEnumerableProperty,
+ readAsText: kEnumerableProperty,
+ readAsDataURL: kEnumerableProperty,
+ abort: kEnumerableProperty,
+ readyState: kEnumerableProperty,
+ result: kEnumerableProperty,
+ error: kEnumerableProperty,
+ onloadstart: kEnumerableProperty,
+ onprogress: kEnumerableProperty,
+ onload: kEnumerableProperty,
+ onabort: kEnumerableProperty,
+ onerror: kEnumerableProperty,
+ onloadend: kEnumerableProperty,
[Symbol.toStringTag]: {
- value: 'FormData',
+ value: 'FileReader',
+ writable: false,
+ enumerable: false,
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.
- // "To convert a string into a scalar value string, replace any surrogates
- // with U+FFFD."
- // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end
- name = Buffer.from(name).toString('utf8')
+Object.defineProperties(FileReader, {
+ EMPTY: staticPropertyDescriptors,
+ LOADING: staticPropertyDescriptors,
+ DONE: staticPropertyDescriptors
+})
- // 2. If value is a string, then set value to the result of converting
- // value into a scalar value string.
- if (typeof value === 'string') {
- value = Buffer.from(value).toString('utf8')
- } else {
- // 3. Otherwise:
+module.exports = {
+ FileReader
+}
- // 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 (!isFileLike(value)) {
- value = value instanceof Blob
- ? new File([value], 'blob', { type: value.type })
- : new FileLike(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 = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile
- ? new File([value], filename, options)
- : new FileLike(value, filename, options)
- }
- }
+/***/ 15976:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 4. Return an entry whose name is name and whose value is value.
- return { name, value }
-}
+"use strict";
-module.exports = { FormData }
+const { webidl } = __nccwpck_require__(74222)
-/***/ }),
+const kState = Symbol('ProgressEvent state')
-/***/ 5628:
-/***/ ((module) => {
+/**
+ * @see https://xhr.spec.whatwg.org/#progressevent
+ */
+class ProgressEvent extends Event {
+ constructor (type, eventInitDict = {}) {
+ type = webidl.converters.DOMString(type)
+ eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {})
-"use strict";
+ super(type, eventInitDict)
+ this[kState] = {
+ lengthComputable: eventInitDict.lengthComputable,
+ loaded: eventInitDict.loaded,
+ total: eventInitDict.total
+ }
+ }
-// In case of breaking changes, increase the version
-// number to avoid conflicts.
-const globalOrigin = Symbol.for('undici.globalOrigin.1')
+ get lengthComputable () {
+ webidl.brandCheck(this, ProgressEvent)
-function getGlobalOrigin () {
- return globalThis[globalOrigin]
-}
+ return this[kState].lengthComputable
+ }
-function setGlobalOrigin (newOrigin) {
- if (newOrigin === undefined) {
- Object.defineProperty(globalThis, globalOrigin, {
- value: undefined,
- writable: true,
- enumerable: false,
- configurable: false
- })
+ get loaded () {
+ webidl.brandCheck(this, ProgressEvent)
- return
+ return this[kState].loaded
}
- const parsedURL = new URL(newOrigin)
+ get total () {
+ webidl.brandCheck(this, ProgressEvent)
- if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') {
- throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`)
+ return this[kState].total
}
-
- Object.defineProperty(globalThis, globalOrigin, {
- value: parsedURL,
- writable: true,
- enumerable: false,
- configurable: false
- })
}
+webidl.converters.ProgressEventInit = webidl.dictionaryConverter([
+ {
+ key: 'lengthComputable',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'loaded',
+ converter: webidl.converters['unsigned long long'],
+ defaultValue: 0
+ },
+ {
+ key: 'total',
+ converter: webidl.converters['unsigned long long'],
+ defaultValue: 0
+ },
+ {
+ key: 'bubbles',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'cancelable',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'composed',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ }
+])
+
module.exports = {
- getGlobalOrigin,
- setGlobalOrigin
+ ProgressEvent
}
/***/ }),
-/***/ 6349:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 86812:
+/***/ ((module) => {
"use strict";
-// https://github.com/Ethan-Arrowood/undici-fetch
-
-
-
-const { kHeadersList, kConstruct } = __nccwpck_require__(6443)
-const { kGuard } = __nccwpck_require__(9710)
-const { kEnumerableProperty } = __nccwpck_require__(3440)
-const {
- makeIterator,
- isValidHeaderName,
- isValidHeaderValue
-} = __nccwpck_require__(5523)
-const { webidl } = __nccwpck_require__(4222)
-const assert = __nccwpck_require__(2613)
-const kHeadersMap = Symbol('headers map')
-const kHeadersSortedMap = Symbol('headers map sorted')
-/**
- * @param {number} code
- */
-function isHTTPWhiteSpaceCharCode (code) {
- return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020
+module.exports = {
+ kState: Symbol('FileReader state'),
+ kResult: Symbol('FileReader result'),
+ kError: Symbol('FileReader error'),
+ kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'),
+ kEvents: Symbol('FileReader events'),
+ kAborted: Symbol('FileReader aborted')
}
-/**
- * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize
- * @param {string} potentialValue
- */
-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)
-}
+/***/ 10165:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-function fill (headers, object) {
- // To fill a Headers object headers with a given object object, run these steps:
+"use strict";
- // 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
+const {
+ kState,
+ kError,
+ kResult,
+ kAborted,
+ kLastProgressEventFired
+} = __nccwpck_require__(86812)
+const { ProgressEvent } = __nccwpck_require__(15976)
+const { getEncoding } = __nccwpck_require__(40396)
+const { DOMException } = __nccwpck_require__(87326)
+const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(94322)
+const { types } = __nccwpck_require__(39023)
+const { StringDecoder } = __nccwpck_require__(13193)
+const { btoa } = __nccwpck_require__(20181)
- // 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']
- })
- }
+/** @type {PropertyDescriptor} */
+const staticPropertyDescriptors = {
+ enumerable: true,
+ writable: false,
+ configurable: false
}
/**
- * @see https://fetch.spec.whatwg.org/#concept-headers-append
+ * @see https://w3c.github.io/FileAPI/#readOperation
+ * @param {import('./filereader').FileReader} fr
+ * @param {import('buffer').Blob} blob
+ * @param {string} type
+ * @param {string?} encodingName
*/
-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.
- // Note: undici does not implement forbidden header names
- if (headers[kGuard] === 'immutable') {
- throw new TypeError('immutable')
- } else if (headers[kGuard] === 'request-no-cors') {
- // 5. Otherwise, if headers’s guard is "request-no-cors":
- // TODO
+function readOperation (fr, blob, type, encodingName) {
+ // 1. If fr’s state is "loading", throw an InvalidStateError
+ // DOMException.
+ if (fr[kState] === 'loading') {
+ throw new DOMException('Invalid state', 'InvalidStateError')
}
- // 6. Otherwise, if headers’s guard is "response" and name is a
- // forbidden response-header name, return.
+ // 2. Set fr’s state to "loading".
+ fr[kState] = 'loading'
- // 7. Append (name, value) to headers’s header list.
- return headers[kHeadersList].append(name, value)
+ // 3. Set fr’s result to null.
+ fr[kResult] = null
- // 8. If headers’s guard is "request-no-cors", then remove
- // privileged no-CORS request headers from headers
-}
+ // 4. Set fr’s error to null.
+ fr[kError] = null
-class HeadersList {
- /** @type {[string, string][]|null} */
- cookies = null
+ // 5. Let stream be the result of calling get stream on blob.
+ /** @type {import('stream/web').ReadableStream} */
+ const stream = blob.stream()
- constructor (init) {
- if (init instanceof HeadersList) {
- this[kHeadersMap] = new Map(init[kHeadersMap])
- this[kHeadersSortedMap] = init[kHeadersSortedMap]
- this.cookies = init.cookies === null ? null : [...init.cookies]
- } else {
- this[kHeadersMap] = new Map(init)
- this[kHeadersSortedMap] = null
- }
- }
+ // 6. Let reader be the result of getting a reader from stream.
+ const reader = stream.getReader()
- // https://fetch.spec.whatwg.org/#header-list-contains
- contains (name) {
- // A header list list contains a header name name if list
- // contains a header whose name is a byte-case-insensitive
- // match for name.
- name = name.toLowerCase()
+ // 7. Let bytes be an empty byte sequence.
+ /** @type {Uint8Array[]} */
+ const bytes = []
- return this[kHeadersMap].has(name)
- }
+ // 8. Let chunkPromise be the result of reading a chunk from
+ // stream with reader.
+ let chunkPromise = reader.read()
- clear () {
- this[kHeadersMap].clear()
- this[kHeadersSortedMap] = null
- this.cookies = null
- }
+ // 9. Let isFirstChunk be true.
+ let isFirstChunk = true
- // https://fetch.spec.whatwg.org/#concept-header-list-append
- append (name, value) {
- this[kHeadersSortedMap] = null
+ // 10. In parallel, while true:
+ // Note: "In parallel" just means non-blocking
+ // Note 2: readOperation itself cannot be async as double
+ // reading the body would then reject the promise, instead
+ // of throwing an error.
+ ;(async () => {
+ while (!fr[kAborted]) {
+ // 1. Wait for chunkPromise to be fulfilled or rejected.
+ try {
+ const { done, value } = await chunkPromise
- // 1. If list contains name, then set name to the first such
- // header’s name.
- const lowercaseName = name.toLowerCase()
- const exists = this[kHeadersMap].get(lowercaseName)
+ // 2. If chunkPromise is fulfilled, and isFirstChunk is
+ // true, queue a task to fire a progress event called
+ // loadstart at fr.
+ if (isFirstChunk && !fr[kAborted]) {
+ queueMicrotask(() => {
+ fireAProgressEvent('loadstart', fr)
+ })
+ }
- // 2. Append (name, value) to list.
- if (exists) {
- const delimiter = lowercaseName === 'cookie' ? '; ' : ', '
- this[kHeadersMap].set(lowercaseName, {
- name: exists.name,
- value: `${exists.value}${delimiter}${value}`
- })
- } else {
- this[kHeadersMap].set(lowercaseName, { name, value })
- }
+ // 3. Set isFirstChunk to false.
+ isFirstChunk = false
- if (lowercaseName === 'set-cookie') {
- this.cookies ??= []
- this.cookies.push(value)
- }
- }
+ // 4. If chunkPromise is fulfilled with an object whose
+ // done property is false and whose value property is
+ // a Uint8Array object, run these steps:
+ if (!done && types.isUint8Array(value)) {
+ // 1. Let bs be the byte sequence represented by the
+ // Uint8Array object.
- // https://fetch.spec.whatwg.org/#concept-header-list-set
- set (name, value) {
- this[kHeadersSortedMap] = null
- const lowercaseName = name.toLowerCase()
+ // 2. Append bs to bytes.
+ bytes.push(value)
- if (lowercaseName === 'set-cookie') {
- this.cookies = [value]
- }
+ // 3. If roughly 50ms have passed since these steps
+ // were last invoked, queue a task to fire a
+ // progress event called progress at fr.
+ if (
+ (
+ fr[kLastProgressEventFired] === undefined ||
+ Date.now() - fr[kLastProgressEventFired] >= 50
+ ) &&
+ !fr[kAborted]
+ ) {
+ fr[kLastProgressEventFired] = Date.now()
+ queueMicrotask(() => {
+ fireAProgressEvent('progress', fr)
+ })
+ }
- // 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[kHeadersMap].set(lowercaseName, { name, value })
- }
+ // 4. Set chunkPromise to the result of reading a
+ // chunk from stream with reader.
+ chunkPromise = reader.read()
+ } else if (done) {
+ // 5. Otherwise, if chunkPromise is fulfilled with an
+ // object whose done property is true, queue a task
+ // to run the following steps and abort this algorithm:
+ queueMicrotask(() => {
+ // 1. Set fr’s state to "done".
+ fr[kState] = 'done'
- // https://fetch.spec.whatwg.org/#concept-header-list-delete
- delete (name) {
- this[kHeadersSortedMap] = null
+ // 2. Let result be the result of package data given
+ // bytes, type, blob’s type, and encodingName.
+ try {
+ const result = packageData(bytes, type, blob.type, encodingName)
- name = name.toLowerCase()
+ // 4. Else:
- if (name === 'set-cookie') {
- this.cookies = null
- }
+ if (fr[kAborted]) {
+ return
+ }
- this[kHeadersMap].delete(name)
- }
+ // 1. Set fr’s result to result.
+ fr[kResult] = result
- // https://fetch.spec.whatwg.org/#concept-header-list-get
- get (name) {
- const value = this[kHeadersMap].get(name.toLowerCase())
+ // 2. Fire a progress event called load at the fr.
+ fireAProgressEvent('load', fr)
+ } catch (error) {
+ // 3. If package data threw an exception error:
- // 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 value === undefined ? null : value.value
- }
+ // 1. Set fr’s error to error.
+ fr[kError] = error
- * [Symbol.iterator] () {
- // use the lowercased name
- for (const [name, { value }] of this[kHeadersMap]) {
- yield [name, value]
- }
- }
+ // 2. Fire a progress event called error at fr.
+ fireAProgressEvent('error', fr)
+ }
- get entries () {
- const headers = {}
+ // 5. If fr’s state is not "loading", fire a progress
+ // event called loadend at the fr.
+ if (fr[kState] !== 'loading') {
+ fireAProgressEvent('loadend', fr)
+ }
+ })
- if (this[kHeadersMap].size) {
- for (const { name, value } of this[kHeadersMap].values()) {
- headers[name] = value
- }
- }
+ break
+ }
+ } catch (error) {
+ if (fr[kAborted]) {
+ return
+ }
- return headers
- }
-}
+ // 6. Otherwise, if chunkPromise is rejected with an
+ // error error, queue a task to run the following
+ // steps and abort this algorithm:
+ queueMicrotask(() => {
+ // 1. Set fr’s state to "done".
+ fr[kState] = 'done'
-// https://fetch.spec.whatwg.org/#headers-class
-class Headers {
- constructor (init = undefined) {
- if (init === kConstruct) {
- return
- }
- this[kHeadersList] = new HeadersList()
+ // 2. Set fr’s error to error.
+ fr[kError] = error
- // The new Headers(init) constructor steps are:
+ // 3. Fire a progress event called error at fr.
+ fireAProgressEvent('error', fr)
- // 1. Set this’s guard to "none".
- this[kGuard] = 'none'
+ // 4. If fr’s state is not "loading", fire a progress
+ // event called loadend at fr.
+ if (fr[kState] !== 'loading') {
+ fireAProgressEvent('loadend', fr)
+ }
+ })
- // 2. If init is given, then fill this with init.
- if (init !== undefined) {
- init = webidl.converters.HeadersInit(init)
- fill(this, init)
+ break
+ }
}
- }
+ })()
+}
- // https://fetch.spec.whatwg.org/#dom-headers-append
- append (name, value) {
- webidl.brandCheck(this, Headers)
+/**
+ * @see https://w3c.github.io/FileAPI/#fire-a-progress-event
+ * @see https://dom.spec.whatwg.org/#concept-event-fire
+ * @param {string} e The name of the event
+ * @param {import('./filereader').FileReader} reader
+ */
+function fireAProgressEvent (e, reader) {
+ // The progress event e does not bubble. e.bubbles must be false
+ // The progress event e is NOT cancelable. e.cancelable must be false
+ const event = new ProgressEvent(e, {
+ bubbles: false,
+ cancelable: false
+ })
- webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' })
+ reader.dispatchEvent(event)
+}
- name = webidl.converters.ByteString(name)
- value = webidl.converters.ByteString(value)
+/**
+ * @see https://w3c.github.io/FileAPI/#blob-package-data
+ * @param {Uint8Array[]} bytes
+ * @param {string} type
+ * @param {string?} mimeType
+ * @param {string?} encodingName
+ */
+function packageData (bytes, type, mimeType, encodingName) {
+ // 1. A Blob has an associated package data algorithm, given
+ // bytes, a type, a optional mimeType, and a optional
+ // encodingName, which switches on type and runs the
+ // associated steps:
- return appendHeader(this, name, value)
- }
+ switch (type) {
+ case 'DataURL': {
+ // 1. Return bytes as a DataURL [RFC2397] subject to
+ // the considerations below:
+ // * Use mimeType as part of the Data URL if it is
+ // available in keeping with the Data URL
+ // specification [RFC2397].
+ // * If mimeType is not available return a Data URL
+ // without a media-type. [RFC2397].
- // https://fetch.spec.whatwg.org/#dom-headers-delete
- delete (name) {
- webidl.brandCheck(this, Headers)
+ // https://datatracker.ietf.org/doc/html/rfc2397#section-3
+ // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
+ // mediatype := [ type "/" subtype ] *( ";" parameter )
+ // data := *urlchar
+ // parameter := attribute "=" value
+ let dataURL = 'data:'
- webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' })
+ const parsed = parseMIMEType(mimeType || 'application/octet-stream')
- name = webidl.converters.ByteString(name)
+ if (parsed !== 'failure') {
+ dataURL += serializeAMimeType(parsed)
+ }
- // 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'
- })
- }
+ dataURL += ';base64,'
- // 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[kGuard] === 'immutable') {
- throw new TypeError('immutable')
- } else if (this[kGuard] === 'request-no-cors') {
- // TODO
- }
+ const decoder = new StringDecoder('latin1')
- // 6. If this’s header list does not contain name, then
- // return.
- if (!this[kHeadersList].contains(name)) {
- return
+ for (const chunk of bytes) {
+ dataURL += btoa(decoder.write(chunk))
+ }
+
+ dataURL += btoa(decoder.end())
+
+ return dataURL
}
+ case 'Text': {
+ // 1. Let encoding be failure
+ let encoding = 'failure'
- // 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[kHeadersList].delete(name)
- }
+ // 2. If the encodingName is present, set encoding to the
+ // result of getting an encoding from encodingName.
+ if (encodingName) {
+ encoding = getEncoding(encodingName)
+ }
- // https://fetch.spec.whatwg.org/#dom-headers-get
- get (name) {
- webidl.brandCheck(this, Headers)
+ // 3. If encoding is failure, and mimeType is present:
+ if (encoding === 'failure' && mimeType) {
+ // 1. Let type be the result of parse a MIME type
+ // given mimeType.
+ const type = parseMIMEType(mimeType)
- webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' })
+ // 2. If type is not failure, set encoding to the result
+ // of getting an encoding from type’s parameters["charset"].
+ if (type !== 'failure') {
+ encoding = getEncoding(type.parameters.get('charset'))
+ }
+ }
- name = webidl.converters.ByteString(name)
+ // 4. If encoding is failure, then set encoding to UTF-8.
+ if (encoding === 'failure') {
+ encoding = 'UTF-8'
+ }
- // 1. If name is not a header name, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.get',
- value: name,
- type: 'header name'
- })
+ // 5. Decode bytes using fallback encoding encoding, and
+ // return the result.
+ return decode(bytes, encoding)
}
+ case 'ArrayBuffer': {
+ // Return a new ArrayBuffer whose contents are bytes.
+ const sequence = combineByteSequences(bytes)
- // 2. Return the result of getting name from this’s header
- // list.
- return this[kHeadersList].get(name)
- }
+ return sequence.buffer
+ }
+ case 'BinaryString': {
+ // Return bytes as a binary string, in which every byte
+ // is represented by a code unit of equal value [0..255].
+ let binaryString = ''
- // https://fetch.spec.whatwg.org/#dom-headers-has
- has (name) {
- webidl.brandCheck(this, Headers)
+ const decoder = new StringDecoder('latin1')
- webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' })
+ for (const chunk of bytes) {
+ binaryString += decoder.write(chunk)
+ }
- name = webidl.converters.ByteString(name)
+ binaryString += decoder.end()
- // 1. If name is not a header name, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.has',
- value: name,
- type: 'header name'
- })
+ return binaryString
}
-
- // 2. Return true if this’s header list contains name;
- // otherwise false.
- return this[kHeadersList].contains(name)
}
+}
- // https://fetch.spec.whatwg.org/#dom-headers-set
- set (name, value) {
- webidl.brandCheck(this, Headers)
-
- webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' })
-
- name = webidl.converters.ByteString(name)
- value = webidl.converters.ByteString(value)
+/**
+ * @see https://encoding.spec.whatwg.org/#decode
+ * @param {Uint8Array[]} ioQueue
+ * @param {string} encoding
+ */
+function decode (ioQueue, encoding) {
+ const bytes = combineByteSequences(ioQueue)
- // 1. Normalize value.
- value = headerValueNormalize(value)
+ // 1. Let BOMEncoding be the result of BOM sniffing ioQueue.
+ const BOMEncoding = BOMSniffing(bytes)
- // 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.set',
- value: name,
- type: 'header name'
- })
- } else if (!isValidHeaderValue(value)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.set',
- value,
- type: 'header value'
- })
- }
+ let slice = 0
- // 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[kGuard] === 'immutable') {
- throw new TypeError('immutable')
- } else if (this[kGuard] === 'request-no-cors') {
- // TODO
- }
+ // 2. If BOMEncoding is non-null:
+ if (BOMEncoding !== null) {
+ // 1. Set encoding to BOMEncoding.
+ encoding = BOMEncoding
- // 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[kHeadersList].set(name, value)
+ // 2. Read three bytes from ioQueue, if BOMEncoding is
+ // UTF-8; otherwise read two bytes.
+ // (Do nothing with those bytes.)
+ slice = BOMEncoding === 'UTF-8' ? 3 : 2
}
- // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie
- getSetCookie () {
- webidl.brandCheck(this, Headers)
+ // 3. Process a queue with an instance of encoding’s
+ // decoder, ioQueue, output, and "replacement".
- // 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.
+ // 4. Return output.
- const list = this[kHeadersList].cookies
+ const sliced = bytes.slice(slice)
+ return new TextDecoder(encoding).decode(sliced)
+}
- if (list) {
- return [...list]
- }
+/**
+ * @see https://encoding.spec.whatwg.org/#bom-sniff
+ * @param {Uint8Array} ioQueue
+ */
+function BOMSniffing (ioQueue) {
+ // 1. Let BOM be the result of peeking 3 bytes from ioQueue,
+ // converted to a byte sequence.
+ const [a, b, c] = ioQueue
- return []
+ // 2. For each of the rows in the table below, starting with
+ // the first one and going down, if BOM starts with the
+ // bytes given in the first column, then return the
+ // encoding given in the cell in the second column of that
+ // row. Otherwise, return null.
+ if (a === 0xEF && b === 0xBB && c === 0xBF) {
+ return 'UTF-8'
+ } else if (a === 0xFE && b === 0xFF) {
+ return 'UTF-16BE'
+ } else if (a === 0xFF && b === 0xFE) {
+ return 'UTF-16LE'
}
- // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
- get [kHeadersSortedMap] () {
- if (this[kHeadersList][kHeadersSortedMap]) {
- return this[kHeadersList][kHeadersSortedMap]
- }
+ return null
+}
- // 1. Let headers be an empty list of headers with the key being the name
- // and value the value.
- const headers = []
+/**
+ * @param {Uint8Array[]} sequences
+ */
+function combineByteSequences (sequences) {
+ const size = sequences.reduce((a, b) => {
+ return a + b.byteLength
+ }, 0)
- // 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 = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1)
- const cookies = this[kHeadersList].cookies
+ let offset = 0
- // 3. For each name of names:
- for (let i = 0; i < names.length; ++i) {
- const [name, 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.
+ return sequences.reduce((a, b) => {
+ a.set(b, offset)
+ offset += b.byteLength
+ return a
+ }, new Uint8Array(size))
+}
- // 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:
+module.exports = {
+ staticPropertyDescriptors,
+ readOperation,
+ fireAProgressEvent
+}
- // 1. Let value be the result of getting name from list.
- // 2. Assert: value is non-null.
- assert(value !== null)
+/***/ }),
- // 3. Append (name, value) to headers.
- headers.push([name, value])
- }
- }
+/***/ 32581:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- this[kHeadersList][kHeadersSortedMap] = headers
+"use strict";
- // 4. Return headers.
- return headers
- }
- keys () {
- webidl.brandCheck(this, Headers)
+// 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__(68707)
+const Agent = __nccwpck_require__(59965)
- if (this[kGuard] === 'immutable') {
- const value = this[kHeadersSortedMap]
- return makeIterator(() => value, 'Headers',
- 'key')
- }
+if (getGlobalDispatcher() === undefined) {
+ setGlobalDispatcher(new Agent())
+}
- return makeIterator(
- () => [...this[kHeadersSortedMap].values()],
- 'Headers',
- 'key'
- )
+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
+ })
+}
- values () {
- webidl.brandCheck(this, Headers)
-
- if (this[kGuard] === 'immutable') {
- const value = this[kHeadersSortedMap]
- return makeIterator(() => value, 'Headers',
- 'value')
- }
-
- return makeIterator(
- () => [...this[kHeadersSortedMap].values()],
- 'Headers',
- 'value'
- )
- }
+function getGlobalDispatcher () {
+ return globalThis[globalDispatcher]
+}
- entries () {
- webidl.brandCheck(this, Headers)
+module.exports = {
+ setGlobalDispatcher,
+ getGlobalDispatcher
+}
- if (this[kGuard] === 'immutable') {
- const value = this[kHeadersSortedMap]
- return makeIterator(() => value, 'Headers',
- 'key+value')
- }
- return makeIterator(
- () => [...this[kHeadersSortedMap].values()],
- 'Headers',
- 'key+value'
- )
- }
+/***/ }),
- /**
- * @param {(value: string, key: string, self: Headers) => void} callbackFn
- * @param {unknown} thisArg
- */
- forEach (callbackFn, thisArg = globalThis) {
- webidl.brandCheck(this, Headers)
+/***/ 78840:
+/***/ ((module) => {
- webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' })
+"use strict";
- if (typeof callbackFn !== 'function') {
- throw new TypeError(
- "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'."
- )
- }
- for (const [key, value] of this) {
- callbackFn.apply(thisArg, [value, key, this])
- }
+module.exports = class DecoratorHandler {
+ constructor (handler) {
+ this.handler = handler
}
- [Symbol.for('nodejs.util.inspect.custom')] () {
- webidl.brandCheck(this, Headers)
-
- return this[kHeadersList]
+ onConnect (...args) {
+ return this.handler.onConnect(...args)
}
-}
-Headers.prototype[Symbol.iterator] = Headers.prototype.entries
+ onError (...args) {
+ return this.handler.onError(...args)
+ }
-Object.defineProperties(Headers.prototype, {
- append: kEnumerableProperty,
- delete: kEnumerableProperty,
- get: kEnumerableProperty,
- has: kEnumerableProperty,
- set: kEnumerableProperty,
- getSetCookie: kEnumerableProperty,
- keys: kEnumerableProperty,
- values: kEnumerableProperty,
- entries: kEnumerableProperty,
- forEach: kEnumerableProperty,
- [Symbol.iterator]: { enumerable: false },
- [Symbol.toStringTag]: {
- value: 'Headers',
- configurable: true
+ onUpgrade (...args) {
+ return this.handler.onUpgrade(...args)
}
-})
-webidl.converters.HeadersInit = function (V) {
- if (webidl.util.Type(V) === 'Object') {
- if (V[Symbol.iterator]) {
- return webidl.converters['sequence>'](V)
- }
+ onHeaders (...args) {
+ return this.handler.onHeaders(...args)
+ }
- return webidl.converters['record'](V)
+ onData (...args) {
+ return this.handler.onData(...args)
}
- throw webidl.errors.conversionFailed({
- prefix: 'Headers constructor',
- argument: 'Argument 1',
- types: ['sequence>', 'record']
- })
-}
+ onComplete (...args) {
+ return this.handler.onComplete(...args)
+ }
-module.exports = {
- fill,
- Headers,
- HeadersList
+ onBodySent (...args) {
+ return this.handler.onBodySent(...args)
+ }
}
/***/ }),
-/***/ 2315:
+/***/ 48299:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-// https://github.com/Ethan-Arrowood/undici-fetch
+const util = __nccwpck_require__(3440)
+const { kBodyUsed } = __nccwpck_require__(36443)
+const assert = __nccwpck_require__(42613)
+const { InvalidArgumentError } = __nccwpck_require__(68707)
+const EE = __nccwpck_require__(24434)
-const {
- Response,
- makeNetworkError,
- makeAppropriateNetworkError,
- filterResponse,
- makeResponse
-} = __nccwpck_require__(8676)
-const { Headers } = __nccwpck_require__(6349)
-const { Request, makeRequest } = __nccwpck_require__(5194)
-const zlib = __nccwpck_require__(3106)
-const {
- bytesMatch,
- makePolicyContainer,
- clonePolicyContainer,
- requestBadPort,
- TAOCheck,
- appendRequestOriginHeader,
- responseLocationURL,
- requestCurrentURL,
- setRequestReferrerPolicyOnRedirect,
- tryUpgradeRequestToAPotentiallyTrustworthyURL,
- createOpaqueTimingInfo,
- appendFetchMetadata,
- corsCheck,
- crossOriginResourcePolicyCheck,
- determineRequestsReferrer,
- coarsenedSharedCurrentTime,
- createDeferredPromise,
- isBlobLike,
- sameOrigin,
- isCancelled,
- isAborted,
- isErrorLike,
- fullyReadBody,
- readableStreamClose,
- isomorphicEncode,
- urlIsLocal,
- urlIsHttpHttpsScheme,
- urlHasHttpsScheme
-} = __nccwpck_require__(5523)
-const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710)
-const assert = __nccwpck_require__(2613)
-const { safelyExtractBody } = __nccwpck_require__(8923)
-const {
- redirectStatusSet,
- nullBodyStatus,
- safeMethodsSet,
- requestBodyHeader,
- subresourceSet,
- DOMException
-} = __nccwpck_require__(7326)
-const { kHeadersList } = __nccwpck_require__(6443)
-const EE = __nccwpck_require__(4434)
-const { Readable, pipeline } = __nccwpck_require__(2203)
-const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = __nccwpck_require__(3440)
-const { dataURLProcessor, serializeAMimeType } = __nccwpck_require__(4322)
-const { TransformStream } = __nccwpck_require__(3774)
-const { getGlobalDispatcher } = __nccwpck_require__(2581)
-const { webidl } = __nccwpck_require__(4222)
-const { STATUS_CODES } = __nccwpck_require__(8611)
-const GET_OR_HEAD = ['GET', 'HEAD']
-
-/** @type {import('buffer').resolveObjectURL} */
-let resolveObjectURL
-let ReadableStream = globalThis.ReadableStream
+const redirectableStatusCodes = [300, 301, 302, 303, 307, 308]
-class Fetch extends EE {
- constructor (dispatcher) {
- super()
+const kBody = Symbol('body')
- this.dispatcher = dispatcher
- this.connection = null
- this.dump = false
- this.state = 'ongoing'
- // 2 terminated listeners get added per request,
- // but only 1 gets removed. If there are 20 redirects,
- // 21 listeners will be added.
- // See https://github.com/nodejs/undici/issues/1711
- // TODO (fix): Find and fix root cause for leaked listener.
- this.setMaxListeners(21)
+class BodyAsyncIterable {
+ constructor (body) {
+ this[kBody] = body
+ this[kBodyUsed] = false
}
- terminate (reason) {
- if (this.state !== 'ongoing') {
- return
- }
-
- this.state = 'terminated'
- this.connection?.destroy(reason)
- this.emit('terminated', reason)
+ async * [Symbol.asyncIterator] () {
+ assert(!this[kBodyUsed], 'disturbed')
+ this[kBodyUsed] = true
+ yield * this[kBody]
}
+}
- // https://fetch.spec.whatwg.org/#fetch-controller-abort
- abort (error) {
- if (this.state !== 'ongoing') {
- return
+class RedirectHandler {
+ constructor (dispatch, maxRedirections, opts, handler) {
+ if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
+ throw new InvalidArgumentError('maxRedirections must be a positive number')
}
- // 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')
- }
+ util.validateHandler(handler, opts.method, opts.upgrade)
- // 4. Let serializedError be StructuredSerialize(error).
- // If that threw an exception, catch it, and let
- // serializedError be StructuredSerialize(fallbackError).
+ this.dispatch = dispatch
+ this.location = null
+ this.abort = null
+ this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy
+ this.maxRedirections = maxRedirections
+ this.handler = handler
+ this.history = []
- // 5. Set controller’s serialized abort reason to serializedError.
- this.serializedAbortReason = error
+ 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)
+ })
+ }
- this.connection?.destroy(error)
- this.emit('terminated', error)
+ 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)
+ ) {
+ // TODO: Should we allow re-using iterable if !this.opts.idempotent
+ // or through some other flag?
+ this.opts.body = new BodyAsyncIterable(this.opts.body)
+ }
}
-}
-
-// https://fetch.spec.whatwg.org/#fetch-method
-function fetch (input, init = {}) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' })
-
- // 1. Let p be a new promise.
- const 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
+ onConnect (abort) {
+ this.abort = abort
+ this.handler.onConnect(abort, { history: this.history })
}
- // 3. Let request be requestObject’s request.
- const request = requestObject[kState]
-
- // 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
+ onUpgrade (statusCode, headers, socket) {
+ this.handler.onUpgrade(statusCode, headers, socket)
}
- // 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'
+ onError (error) {
+ this.handler.onError(error)
}
- // 7. Let responseObject be null.
- let responseObject = null
+ onHeaders (statusCode, headers, resume, statusText) {
+ this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body)
+ ? null
+ : parseLocation(statusCode, headers)
- // 8. Let relevantRealm be this’s relevant Realm.
- const relevantRealm = null
+ if (this.opts.origin) {
+ this.history.push(new URL(this.opts.path, this.opts.origin))
+ }
- // 9. Let locallyAborted be false.
- let locallyAborted = false
+ if (!this.location) {
+ return this.handler.onHeaders(statusCode, headers, resume, statusText)
+ }
- // 10. Let controller be null.
- let controller = null
+ 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
- // 11. Add the following abort steps to requestObject’s signal:
- addAbortListener(
- requestObject.signal,
- () => {
- // 1. Set locallyAborted to true.
- locallyAborted = true
+ // 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.maxRedirections = 0
+ this.opts.query = null
- // 2. Assert: controller is non-null.
- assert(controller != 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'
+ this.opts.body = null
+ }
+ }
- // 3. Abort controller with requestObject’s signal’s abort reason.
- controller.abort(requestObject.signal.reason)
+ onData (chunk) {
+ if (this.location) {
+ /*
+ https://tools.ietf.org/html/rfc7231#section-6.4
- // 4. Abort the fetch() call with p, request, responseObject,
- // and requestObject’s signal’s abort reason.
- abortFetch(p, request, responseObject, requestObject.signal.reason)
- }
- )
+ TLDR: undici always ignores 3xx response bodies.
- // 12. Let handleFetchDone given response response be to finalize and
- // report timing with response, globalObject, and "fetch".
- const handleFetchDone = (response) =>
- finalizeAndReportTiming(response, 'fetch')
+ Redirection is used to serve the requested resource from another URL, so it is assumes that
+ no body is generated (and thus can be ignored). Even though generating a body is not prohibited.
- // 13. Set controller to the result of calling fetch given request,
- // with processResponseEndOfBody set to handleFetchDone, and processResponse
- // given response being these substeps:
+ 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.
- const processResponse = (response) => {
- // 1. If locallyAborted is true, terminate these substeps.
- if (locallyAborted) {
- return Promise.resolve()
+ 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 explicitily 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 {
+ return this.handler.onData(chunk)
}
+ }
- // 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.
+ onComplete (trailers) {
+ if (this.location) {
+ /*
+ https://tools.ietf.org/html/rfc7231#section-6.4
- abortFetch(p, request, responseObject, controller.serializedAbortReason)
- return Promise.resolve()
- }
+ TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections
+ and neither are useful if present.
- // 3. If response is a network error, then reject p with a TypeError
- // and terminate these substeps.
- if (response.type === 'error') {
- p.reject(
- Object.assign(new TypeError('fetch failed'), { cause: response.error })
- )
- return Promise.resolve()
- }
+ See comment on onData method above for more detailed informations.
+ */
- // 4. Set responseObject to the result of creating a Response object,
- // given response, "immutable", and relevantRealm.
- responseObject = new Response()
- responseObject[kState] = response
- responseObject[kRealm] = relevantRealm
- responseObject[kHeaders][kHeadersList] = response.headersList
- responseObject[kHeaders][kGuard] = 'immutable'
- responseObject[kHeaders][kRealm] = relevantRealm
+ this.location = null
+ this.abort = null
- // 5. Resolve p with responseObject.
- p.resolve(responseObject)
+ this.dispatch(this.opts, this)
+ } else {
+ this.handler.onComplete(trailers)
+ }
}
- controller = fetching({
- request,
- processResponseEndOfBody: handleFetchDone,
- processResponse,
- dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici
- })
-
- // 14. Return p.
- return p.promise
+ onBodySent (chunk) {
+ if (this.handler.onBodySent) {
+ this.handler.onBodySent(chunk)
+ }
+ }
}
-// 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
+function parseLocation (statusCode, headers) {
+ if (redirectableStatusCodes.indexOf(statusCode) === -1) {
+ return null
}
- // 2. If response’s URL list is null or empty, then return.
- if (!response.urlList?.length) {
- return
+ for (let i = 0; i < headers.length; i += 2) {
+ if (headers[i].toString().toLowerCase() === 'location') {
+ return headers[i + 1]
+ }
}
+}
- // 3. Let originalURL be response’s URL list[0].
- const originalURL = response.urlList[0]
+// 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
+}
- // 4. Let timingInfo be response’s timing info.
- let timingInfo = response.timingInfo
+// 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') {
+ for (const key of Object.keys(headers)) {
+ if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
+ ret.push(key, headers[key])
+ }
+ }
+ } else {
+ assert(headers == null, 'headers must be an object or an array')
+ }
+ return ret
+}
- // 5. Let cacheState be response’s cache state.
- let cacheState = response.cacheState
+module.exports = RedirectHandler
- // 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
- })
+/***/ 53573:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2. Set cacheState to the empty string.
- cacheState = ''
- }
+const assert = __nccwpck_require__(42613)
- // 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()
+const { kRetryHandlerDefaultRetry } = __nccwpck_require__(36443)
+const { RequestRetryError } = __nccwpck_require__(68707)
+const { isDisturbed, parseHeaders, parseRangeHeader } = __nccwpck_require__(3440)
- // 10. Set response’s timing info to timingInfo.
- response.timingInfo = timingInfo
+function calculateRetryAfterHeader (retryAfter) {
+ const current = Date.now()
+ const diff = new Date(retryAfter).getTime() - current
- // 11. Mark resource timing for timingInfo, originalURL, initiatorType,
- // global, and cacheState.
- markResourceTiming(
- timingInfo,
- originalURL,
- initiatorType,
- globalThis,
- cacheState
- )
+ return diff
}
-// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing
-function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) {
- if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) {
- performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState)
- }
-}
+class RetryHandler {
+ constructor (opts, handlers) {
+ const { retryOptions, ...dispatchOpts } = opts
+ const {
+ // Retry scoped
+ retry: retryFn,
+ maxRetries,
+ maxTimeout,
+ minTimeout,
+ timeoutFactor,
+ // Response scoped
+ methods,
+ errorCodes,
+ retryAfter,
+ statusCodes
+ } = retryOptions ?? {}
-// https://fetch.spec.whatwg.org/#abort-fetch
-function abortFetch (p, request, responseObject, error) {
- // Note: AbortSignal.reason was added in node v17.2.0
- // which would give us an undefined error to reject with.
- // Remove this once node v16 is no longer supported.
- if (!error) {
- error = new DOMException('The operation was aborted.', 'AbortError')
- }
+ this.dispatch = handlers.dispatch
+ this.handler = handlers.handler
+ this.opts = dispatchOpts
+ this.abort = null
+ this.aborted = false
+ this.retryOpts = {
+ retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry],
+ retryAfter: retryAfter ?? true,
+ maxTimeout: maxTimeout ?? 30 * 1000, // 30s,
+ timeout: 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'
+ ]
+ }
- // 1. Reject promise with error.
- p.reject(error)
+ this.retryCount = 0
+ this.start = 0
+ this.end = null
+ this.etag = null
+ this.resume = null
- // 2. If request’s body is not null and is readable, then cancel request’s
- // body with error.
- if (request.body != null && isReadable(request.body?.stream)) {
- request.body.stream.cancel(error).catch((err) => {
- if (err.code === 'ERR_INVALID_STATE') {
- // Node bug?
- return
+ // Handle possible onConnect duplication
+ this.handler.onConnect(reason => {
+ this.aborted = true
+ if (this.abort) {
+ this.abort(reason)
+ } else {
+ this.reason = reason
}
- throw err
})
}
- // 3. If responseObject is null, then return.
- if (responseObject == null) {
- return
+ onRequestSent () {
+ if (this.handler.onRequestSent) {
+ this.handler.onRequestSent()
+ }
}
- // 4. Let response be responseObject’s response.
- const response = responseObject[kState]
+ onUpgrade (statusCode, headers, socket) {
+ if (this.handler.onUpgrade) {
+ this.handler.onUpgrade(statusCode, headers, socket)
+ }
+ }
- // 5. If response’s body is not null and is readable, then error response’s
- // body with error.
- if (response.body != null && isReadable(response.body?.stream)) {
- response.body.stream.cancel(error).catch((err) => {
- if (err.code === 'ERR_INVALID_STATE') {
- // Node bug?
- return
- }
- throw err
- })
+ onConnect (abort) {
+ if (this.aborted) {
+ abort(this.reason)
+ } else {
+ this.abort = abort
+ }
}
-}
-// https://fetch.spec.whatwg.org/#fetching
-function fetching ({
- request,
- processRequestBodyChunkLength,
- processRequestEndOfBody,
- processResponse,
- processResponseEndOfBody,
- processResponseConsumeBody,
- useParallelQueue = false,
- dispatcher // undici
-}) {
- // 1. Let taskDestination be null.
- let taskDestination = null
+ onBodySent (chunk) {
+ if (this.handler.onBodySent) return this.handler.onBodySent(chunk)
+ }
- // 2. Let crossOriginIsolatedCapability be false.
- let crossOriginIsolatedCapability = false
+ static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) {
+ const { statusCode, code, headers } = err
+ const { method, retryOptions } = opts
+ const {
+ maxRetries,
+ timeout,
+ maxTimeout,
+ timeoutFactor,
+ statusCodes,
+ errorCodes,
+ methods
+ } = retryOptions
+ let { counter, currentTimeout } = state
- // 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
+ currentTimeout =
+ currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout
- // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin
- // isolated capability.
- crossOriginIsolatedCapability =
- request.client.crossOriginIsolatedCapability
- }
+ // Any code that is not a Undici's originated and allowed to retry
+ if (
+ code &&
+ code !== 'UND_ERR_REQ_RETRY' &&
+ code !== 'UND_ERR_SOCKET' &&
+ !errorCodes.includes(code)
+ ) {
+ cb(err)
+ return
+ }
- // 4. If useParallelQueue is true, then set taskDestination to the result of
- // starting a new parallel queue.
- // TODO
+ // 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
+ }
- // 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 currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability)
- const timingInfo = createOpaqueTimingInfo({
- startTime: currenTime
- })
+ // 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
+ }
- // 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
- }
+ // If we reached the max number of retries
+ if (counter > maxRetries) {
+ cb(err)
+ return
+ }
- // 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)
+ let retryAfterHeader = headers != null && headers['retry-after']
+ if (retryAfterHeader) {
+ retryAfterHeader = Number(retryAfterHeader)
+ retryAfterHeader = isNaN(retryAfterHeader)
+ ? calculateRetryAfterHeader(retryAfterHeader)
+ : retryAfterHeader * 1e3 // Retry-After is in seconds
+ }
- // 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'
- }
+ const retryTimeout =
+ retryAfterHeader > 0
+ ? Math.min(retryAfterHeader, maxTimeout)
+ : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout)
- // 9. If request’s origin is "client", then set request’s origin to request’s
- // client’s origin.
- if (request.origin === 'client') {
- // TODO: What if request.client is null?
- request.origin = request.client?.origin
+ state.currentTimeout = retryTimeout
+
+ setTimeout(() => cb(null), retryTimeout)
}
- // 10. If all of the following conditions are true:
- // TODO
+ onHeaders (statusCode, rawHeaders, resume, statusMessage) {
+ const headers = parseHeaders(rawHeaders)
- // 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
+ this.retryCount += 1
+
+ if (statusCode >= 300) {
+ this.abort(
+ new RequestRetryError('Request failed', statusCode, {
+ headers,
+ count: this.retryCount
+ })
)
- } else {
- // 2. Otherwise, set request’s policy container to a new policy
- // container.
- request.policyContainer = makePolicyContainer()
+ return false
}
- }
- // 12. If request’s header list does not contain `Accept`, then:
- if (!request.headersList.contains('accept')) {
- // 1. Let value be `*/*`.
- const value = '*/*'
+ // Checkpoint for resume from where we left it
+ if (this.resume != null) {
+ this.resume = null
- // 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
+ if (statusCode !== 206) {
+ return true
+ }
- // 3. Append `Accept`/value to request’s header list.
- request.headersList.append('accept', value)
- }
+ const contentRange = parseRangeHeader(headers['content-range'])
+ // If no content range
+ if (!contentRange) {
+ this.abort(
+ new RequestRetryError('Content-Range mismatch', statusCode, {
+ headers,
+ count: this.retryCount
+ })
+ )
+ return false
+ }
- // 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')) {
- request.headersList.append('accept-language', '*')
- }
+ // Let's start with a weak etag check
+ if (this.etag != null && this.etag !== headers.etag) {
+ this.abort(
+ new RequestRetryError('ETag mismatch', statusCode, {
+ headers,
+ count: this.retryCount
+ })
+ )
+ return false
+ }
- // 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
- }
+ const { start, size, end = size } = contentRange
- // 15. If request is a subresource request, then:
- if (subresourceSet.has(request.destination)) {
- // TODO
- }
+ assert(this.start === start, 'content-range mismatch')
+ assert(this.end == null || this.end === end, 'content-range mismatch')
- // 16. Run main fetch given fetchParams.
- mainFetch(fetchParams)
- .catch(err => {
- fetchParams.controller.terminate(err)
- })
+ this.resume = resume
+ return true
+ }
- // 17. Return fetchParam's controller
- return fetchParams.controller
-}
+ if (this.end == null) {
+ if (statusCode === 206) {
+ // First time we receive 206
+ const range = parseRangeHeader(headers['content-range'])
-// https://fetch.spec.whatwg.org/#concept-main-fetch
-async function mainFetch (fetchParams, recursive = false) {
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
+ if (range == null) {
+ return this.handler.onHeaders(
+ statusCode,
+ rawHeaders,
+ resume,
+ statusMessage
+ )
+ }
- // 2. Let response be null.
- let response = null
+ const { start, size, end = size } = range
- // 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')
- }
+ assert(
+ start != null && Number.isFinite(start) && this.start !== start,
+ 'content-range mismatch'
+ )
+ assert(Number.isFinite(start))
+ assert(
+ end != null && Number.isFinite(end) && this.end !== end,
+ 'invalid content-length'
+ )
- // 4. Run report Content Security Policy violations for request.
- // TODO
+ 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) : null
+ }
+
+ assert(Number.isFinite(this.start))
+ assert(
+ this.end == null || Number.isFinite(this.end),
+ 'invalid content-length'
+ )
- // 5. Upgrade request to a potentially trustworthy URL, if appropriate.
- tryUpgradeRequestToAPotentiallyTrustworthyURL(request)
+ this.resume = resume
+ this.etag = headers.etag != null ? headers.etag : null
- // 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?
+ return this.handler.onHeaders(
+ statusCode,
+ rawHeaders,
+ resume,
+ statusMessage
+ )
+ }
- // 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
- }
+ const err = new RequestRetryError('Request failed', statusCode, {
+ headers,
+ count: this.retryCount
+ })
- // 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)
+ this.abort(err)
+
+ return false
}
- // 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
+ onData (chunk) {
+ this.start += chunk.length
- // 10. If recursive is false, then run the remaining steps in parallel.
- // TODO
+ return this.handler.onData(chunk)
+ }
- // 11. If response is null, then set response to the result of running
- // the steps corresponding to the first matching statement:
- if (response === null) {
- response = await (async () => {
- const currentURL = requestCurrentURL(request)
+ onComplete (rawTrailers) {
+ this.retryCount = 0
+ return this.handler.onComplete(rawTrailers)
+ }
- 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'
+ onError (err) {
+ if (this.aborted || isDisturbed(this.opts.body)) {
+ return this.handler.onError(err)
+ }
- // 2. Return the result of running scheme fetch given fetchParams.
- return await schemeFetch(fetchParams)
- }
+ this.retryOpts.retry(
+ err,
+ {
+ state: { counter: this.retryCount++, currentTimeout: this.retryAfter },
+ opts: { retryOptions: this.retryOpts, ...this.opts }
+ },
+ onRetry.bind(this)
+ )
- // request’s mode is "same-origin"
- if (request.mode === 'same-origin') {
- // 1. Return a network error.
- return makeNetworkError('request mode cannot be "same-origin"')
+ function onRetry (err) {
+ if (err != null || this.aborted || isDisturbed(this.opts.body)) {
+ return this.handler.onError(err)
}
- // request’s mode is "no-cors"
- if (request.mode === 'no-cors') {
- // 1. If request’s redirect mode is not "follow", then return a network
- // error.
- if (request.redirect !== 'follow') {
- return makeNetworkError(
- 'redirect mode cannot be "follow" for "no-cors" request'
- )
+ if (this.start !== 0) {
+ this.opts = {
+ ...this.opts,
+ headers: {
+ ...this.opts.headers,
+ range: `bytes=${this.start}-${this.end ?? ''}`
+ }
}
-
- // 2. Set request’s response tainting to "opaque".
- request.responseTainting = 'opaque'
-
- // 3. Return the result of running scheme fetch given fetchParams.
- return await schemeFetch(fetchParams)
}
- // request’s current URL’s scheme is not an HTTP(S) scheme
- if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {
- // Return a network error.
- return makeNetworkError('URL scheme must be a HTTP(S) scheme')
+ try {
+ this.dispatch(this.opts, this)
+ } catch (err) {
+ this.handler.onError(err)
}
+ }
+ }
+}
- // - 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
- // 1. Set request’s response tainting to "cors".
- request.responseTainting = 'cors'
+module.exports = RetryHandler
- // 2. Return the result of running HTTP fetch given fetchParams.
- return 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
- }
+/***/ 64415:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 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)
- }
- }
+"use strict";
- // 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)
- }
+const RedirectHandler = __nccwpck_require__(48299)
- // 16. If request’s timing allow failed flag is unset, then set
- // internalResponse’s timing allow passed flag.
- if (!request.timingAllowFailed) {
- response.timingAllowPassed = true
- }
+function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) {
+ return (dispatch) => {
+ return function Intercept (opts, handler) {
+ const { maxRedirections = defaultMaxRedirections } = opts
- // 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
+ if (!maxRedirections) {
+ return dispatch(opts, handler)
+ }
- // 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')
- ) {
- response = internalResponse = makeNetworkError()
+ const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler)
+ opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting.
+ return dispatch(opts, redirectHandler)
+ }
}
+}
- // 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
- }
+module.exports = createRedirectInterceptor
- // 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
- }
+/***/ 52824:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 2. Set response’s body to bytes as a body.
- response.body = safelyExtractBody(bytes)[0]
+"use strict";
- // 3. Run fetch finale given fetchParams and response.
- fetchFinale(fetchParams, response)
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0;
+const utils_1 = __nccwpck_require__(50172);
+// C headers
+var ERROR;
+(function (ERROR) {
+ ERROR[ERROR["OK"] = 0] = "OK";
+ ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL";
+ ERROR[ERROR["STRICT"] = 2] = "STRICT";
+ ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED";
+ ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH";
+ ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION";
+ ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD";
+ ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL";
+ ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT";
+ ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION";
+ ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN";
+ ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH";
+ ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE";
+ ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS";
+ ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE";
+ ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING";
+ ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN";
+ ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE";
+ ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE";
+ ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER";
+ ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE";
+ ERROR[ERROR["PAUSED"] = 21] = "PAUSED";
+ ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE";
+ ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE";
+ ERROR[ERROR["USER"] = 24] = "USER";
+})(ERROR = exports.ERROR || (exports.ERROR = {}));
+var TYPE;
+(function (TYPE) {
+ TYPE[TYPE["BOTH"] = 0] = "BOTH";
+ TYPE[TYPE["REQUEST"] = 1] = "REQUEST";
+ TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE";
+})(TYPE = exports.TYPE || (exports.TYPE = {}));
+var FLAGS;
+(function (FLAGS) {
+ FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE";
+ FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE";
+ FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE";
+ FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED";
+ FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE";
+ FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH";
+ FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY";
+ FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING";
+ // 1 << 8 is unused
+ FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING";
+})(FLAGS = exports.FLAGS || (exports.FLAGS = {}));
+var LENIENT_FLAGS;
+(function (LENIENT_FLAGS) {
+ LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS";
+ LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH";
+ LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE";
+})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {}));
+var METHODS;
+(function (METHODS) {
+ METHODS[METHODS["DELETE"] = 0] = "DELETE";
+ METHODS[METHODS["GET"] = 1] = "GET";
+ METHODS[METHODS["HEAD"] = 2] = "HEAD";
+ METHODS[METHODS["POST"] = 3] = "POST";
+ METHODS[METHODS["PUT"] = 4] = "PUT";
+ /* pathological */
+ METHODS[METHODS["CONNECT"] = 5] = "CONNECT";
+ METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS";
+ METHODS[METHODS["TRACE"] = 7] = "TRACE";
+ /* WebDAV */
+ METHODS[METHODS["COPY"] = 8] = "COPY";
+ METHODS[METHODS["LOCK"] = 9] = "LOCK";
+ METHODS[METHODS["MKCOL"] = 10] = "MKCOL";
+ METHODS[METHODS["MOVE"] = 11] = "MOVE";
+ METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND";
+ METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH";
+ METHODS[METHODS["SEARCH"] = 14] = "SEARCH";
+ METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK";
+ METHODS[METHODS["BIND"] = 16] = "BIND";
+ METHODS[METHODS["REBIND"] = 17] = "REBIND";
+ METHODS[METHODS["UNBIND"] = 18] = "UNBIND";
+ METHODS[METHODS["ACL"] = 19] = "ACL";
+ /* subversion */
+ METHODS[METHODS["REPORT"] = 20] = "REPORT";
+ METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY";
+ METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT";
+ METHODS[METHODS["MERGE"] = 23] = "MERGE";
+ /* upnp */
+ METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH";
+ METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY";
+ METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE";
+ METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE";
+ /* RFC-5789 */
+ METHODS[METHODS["PATCH"] = 28] = "PATCH";
+ METHODS[METHODS["PURGE"] = 29] = "PURGE";
+ /* CalDAV */
+ METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR";
+ /* RFC-2068, section 19.6.1.2 */
+ METHODS[METHODS["LINK"] = 31] = "LINK";
+ METHODS[METHODS["UNLINK"] = 32] = "UNLINK";
+ /* icecast */
+ METHODS[METHODS["SOURCE"] = 33] = "SOURCE";
+ /* RFC-7540, section 11.6 */
+ METHODS[METHODS["PRI"] = 34] = "PRI";
+ /* RFC-2326 RTSP */
+ METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE";
+ METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE";
+ METHODS[METHODS["SETUP"] = 37] = "SETUP";
+ METHODS[METHODS["PLAY"] = 38] = "PLAY";
+ METHODS[METHODS["PAUSE"] = 39] = "PAUSE";
+ METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN";
+ METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER";
+ METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER";
+ METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT";
+ METHODS[METHODS["RECORD"] = 44] = "RECORD";
+ /* RAOP */
+ METHODS[METHODS["FLUSH"] = 45] = "FLUSH";
+})(METHODS = exports.METHODS || (exports.METHODS = {}));
+exports.METHODS_HTTP = [
+ METHODS.DELETE,
+ METHODS.GET,
+ METHODS.HEAD,
+ METHODS.POST,
+ METHODS.PUT,
+ METHODS.CONNECT,
+ METHODS.OPTIONS,
+ METHODS.TRACE,
+ METHODS.COPY,
+ METHODS.LOCK,
+ METHODS.MKCOL,
+ METHODS.MOVE,
+ METHODS.PROPFIND,
+ METHODS.PROPPATCH,
+ METHODS.SEARCH,
+ METHODS.UNLOCK,
+ METHODS.BIND,
+ METHODS.REBIND,
+ METHODS.UNBIND,
+ METHODS.ACL,
+ METHODS.REPORT,
+ METHODS.MKACTIVITY,
+ METHODS.CHECKOUT,
+ METHODS.MERGE,
+ METHODS['M-SEARCH'],
+ METHODS.NOTIFY,
+ METHODS.SUBSCRIBE,
+ METHODS.UNSUBSCRIBE,
+ METHODS.PATCH,
+ METHODS.PURGE,
+ METHODS.MKCALENDAR,
+ METHODS.LINK,
+ METHODS.UNLINK,
+ METHODS.PRI,
+ // TODO(indutny): should we allow it with HTTP?
+ METHODS.SOURCE,
+];
+exports.METHODS_ICE = [
+ METHODS.SOURCE,
+];
+exports.METHODS_RTSP = [
+ METHODS.OPTIONS,
+ METHODS.DESCRIBE,
+ METHODS.ANNOUNCE,
+ METHODS.SETUP,
+ METHODS.PLAY,
+ METHODS.PAUSE,
+ METHODS.TEARDOWN,
+ METHODS.GET_PARAMETER,
+ METHODS.SET_PARAMETER,
+ METHODS.REDIRECT,
+ METHODS.RECORD,
+ METHODS.FLUSH,
+ // For AirPlay
+ METHODS.GET,
+ METHODS.POST,
+];
+exports.METHOD_MAP = utils_1.enumToMap(METHODS);
+exports.H_METHOD_MAP = {};
+Object.keys(exports.METHOD_MAP).forEach((key) => {
+ if (/^H/.test(key)) {
+ exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key];
+ }
+});
+var FINISH;
+(function (FINISH) {
+ FINISH[FINISH["SAFE"] = 0] = "SAFE";
+ FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB";
+ FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE";
+})(FINISH = exports.FINISH || (exports.FINISH = {}));
+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.STRICT_URL_CHAR = [
+ '!', '"', '$', '%', '&', '\'',
+ '(', ')', '*', '+', ',', '-', '.', '/',
+ ':', ';', '<', '=', '>',
+ '@', '[', '\\', ']', '^', '_',
+ '`',
+ '{', '|', '}', '~',
+].concat(exports.ALPHANUM);
+exports.URL_CHAR = exports.STRICT_URL_CHAR
+ .concat(['\t', '\f']);
+// All characters with 0x80 bit set to 1
+for (let i = 0x80; i <= 0xff; i++) {
+ exports.URL_CHAR.push(i);
+}
+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.STRICT_TOKEN = [
+ '!', '#', '$', '%', '&', '\'',
+ '*', '+', '-', '.',
+ '^', '_', '`',
+ '|', '~',
+].concat(exports.ALPHANUM);
+exports.TOKEN = exports.STRICT_TOKEN.concat([' ']);
+/*
+ * 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);
}
-
- // 4. Fully read response’s body given processBody and processBodyError.
- await fullyReadBody(response.body, processBody, processBodyError)
- } else {
- // 21. Otherwise, run fetch finale given fetchParams and response.
- fetchFinale(fetchParams, response)
- }
}
+// ',' = \x44
+exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44);
+exports.MAJOR = exports.NUM_MAP;
+exports.MINOR = exports.MAJOR;
+var HEADER_STATE;
+(function (HEADER_STATE) {
+ HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL";
+ HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION";
+ HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH";
+ HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING";
+ HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE";
+ HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE";
+ HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE";
+ HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE";
+ HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED";
+})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {}));
+exports.SPECIAL_HEADERS = {
+ 'connection': HEADER_STATE.CONNECTION,
+ 'content-length': HEADER_STATE.CONTENT_LENGTH,
+ 'proxy-connection': HEADER_STATE.CONNECTION,
+ 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING,
+ 'upgrade': HEADER_STATE.UPGRADE,
+};
+//# sourceMappingURL=constants.js.map
-// 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.
+/***/ 63870:
+/***/ ((module) => {
- // Otherwise, return a network error.
- return Promise.resolve(makeNetworkError('about scheme is not supported'))
- }
- case 'blob:': {
- if (!resolveObjectURL) {
- resolveObjectURL = (__nccwpck_require__(181).resolveObjectURL)
- }
+module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbn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EcUGABEYNACAAQShxRSEBCyABC6cBAQN/AkACQAJAIAAtACpFDQAgAC0AK0UNAEEAIQMgAC8BMCIEQQJxRQ0BDAILQQAhAyAALwEwIgRBAXFFDQELQQEhAyAALQAoQQFGDQAgAC8BMkH//wNxIgVBnH9qQeQASQ0AIAVBzAFGDQAgBUGwAkYNACAEQcAAcQ0AQQAhAyAEQYgEcUGABEYNACAEQShxQQBHIQMLIABBADsBMCAAQQA6AC8gAwuZAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC1kAIABBGGpCADcDACAAQgA3AwAgAEE4akIANwMAIABBMGpCADcDACAAQShqQgA3AwAgAEEgakIANwMAIABBEGpCADcDACAAQQhqQgA3AwAgAEHdATYCHEEAC3sBAX8CQCAAKAIMIgMNAAJAIAAoAgRFDQAgACABNgIECwJAIAAgASACEMSAgIAAIgMNACAAKAIMDwsgACADNgIcQQAhAyAAKAIEIgFFDQAgACABIAIgACgCCBGBgICAAAAiAUUNACAAIAI2AhQgACABNgIMIAEhAwsgAwvk8wEDDn8DfgR/I4CAgIAAQRBrIgMkgICAgAAgASEEIAEhBSABIQYgASEHIAEhCCABIQkgASEKIAEhCyABIQwgASENIAEhDiABIQ8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJA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kACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAQDscBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxweHyAhIyUoP0BBREVGR0hJSktMTU9QUVJT3gNXWVtcXWBiZWZnaGlqa2xtb3BxcnN0dXZ3eHl6e3x9foABggGFAYYBhwGJAYsBjAGNAY4BjwGQAZEBlAGVAZYBlwGYAZkBmgGbAZwBnQGeAZ8BoAGhAaIBowGkAaUBpgGnAagBqQGqAasBrAGt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AAgATYCFCAAIBA2AgxBACEQDLIBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDLEBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxRCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDLABCyAAQQA2AhwgACABNgIUIABBxoqAgAA2AhAgAEEHNgIMQQAhEAyvAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAyuAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAytAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMTQsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAysAQsgAEEANgIcIAAgATYCFCAAQdyIgIAANgIQIABBBzYCDEEAIRAMqwELIBBBP0cNASABQQFqIQELQQUhEAyQAQtBACEQIABBADYCHCAAIAE2AhQgAEH9koCAADYCECAAQQc2AgwMqAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMpwELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMpgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEYLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMpQELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0gA2AhwgACAUNgIUIAAgATYCDEEAIRAMpAELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0wA2AhwgACAUNgIUIAAgATYCDEEAIRA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MDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABOT1VOQ0VFQ0tPVVRORUNURVRFQ1JJQkVMVVNIRVRFQURTRUFSQ0hSR0VDVElWSVRZTEVOREFSVkVPVElGWVBUSU9OU0NIU0VBWVNUQVRDSEdFT1JESVJFQ1RPUlRSQ0hQQVJBTUVURVJVUkNFQlNDUklCRUFSRE9XTkFDRUlORE5LQ0tVQlNDUklCRUhUVFAvQURUUC8='
- // 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 blobURLEntryObject = resolveObjectURL(blobURLEntry.toString())
+/***/ 53434:
+/***/ ((module) => {
- // 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' || !isBlobLike(blobURLEntryObject)) {
- return Promise.resolve(makeNetworkError('invalid method'))
- }
+module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd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ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIBAOxwEAAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB4fICEjJSg/QEFERUZHSElKS0xNT1BRUlPeA1dZW1xdYGJlZmdoaWprbG1vcHFyc3R1dnd4eXp7fH1+gAGCAYUBhgGHAYkBiwGMAY0BjgGPAZABkQGUAZUBlgGXAZgBmQGaAZsBnAGdAZ4BnwGgAaEBogGjAaQBpQGmAacBqAGpAaoBqwGsAa0BrgGvAbABsQGyAbMBtAG1AbY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IAEQrYCAgAAiBA0AIAEhAQytAQsgAEHZADYCHCAAIAE2AhQgACAENgIMQQAhEAy9AQsgACgCBCEEIABBADYCBAJAIAAgBCABEK2AgIAAIgQNACABIQEMqwELIABB2gA2AhwgACABNgIUIAAgBDYCDEEAIRAMvAELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKkBCyAAQdwANgIcIAAgATYCFCAAIAQ2AgxBACEQDLsBCwJAIAEtAABBUGoiEEH/AXFBCk8NACAAIBA6ACogAUEBaiEBQc8AIRAMogELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKcBCyAAQd4ANgIcIAAgATYCFCAAIAQ2AgxBACEQDLoBCyAAQQA2AgAgF0EBaiEBAkAgAC0AKUEjTw0AIAEhAQxZCyAAQQA2AhwgACABNgIUIABB04mAgAA2AhAgAEEINgIMQQAhEAy5AQsgAEEANgIAC0EAIRAgAEEANgIcIAAgATYCFCAAQZCzgIAANgIQIABBCDYCDAy3AQsgAEEANgIAIBdBAWohAQJAIAAtAClBIUcNACABIQEMVgsgAEEANgIcIAAgATYCFCAAQZuKgIAANgIQIABBCDYCDEEAIRAMtgELIABBADYCACAXQQFqIQECQCAALQApIhBBXWpBC08NACABIQEMVQsCQCAQQQZLDQBBASAQdEHKAHFFDQAgASEBDFULQQAhECAAQQA2AhwgACABNgIUIABB94mAgAA2AhAgAEEINgIMDLUBCyAQQRVGDXEgAEEANgIcIAAgATYCFCAAQbmNgIAANgIQIABBGjYCDEEAIRAMtAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFQLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMswELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMsgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0wA2AhwgACABNgIUIAAg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DAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw=='
- // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object.
- const bodyWithType = safelyExtractBody(blobURLEntryObject)
- // 4. Let body be bodyWithType’s body.
- const body = bodyWithType[0]
+/***/ }),
- // 5. Let length be body’s length, serialized and isomorphic encoded.
- const length = isomorphicEncode(`${body.length}`)
+/***/ 50172:
+/***/ ((__unused_webpack_module, exports) => {
- // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence.
- const type = bodyWithType[1] ?? ''
+"use strict";
- // 7. Return a new response whose status message is `OK`, header list is
- // « (`Content-Length`, length), (`Content-Type`, type) », and body is body.
- const response = makeResponse({
- statusText: 'OK',
- headersList: [
- ['content-length', { name: 'Content-Length', value: length }],
- ['content-type', { name: 'Content-Type', value: type }]
- ]
- })
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.enumToMap = void 0;
+function enumToMap(obj) {
+ const res = {};
+ Object.keys(obj).forEach((key) => {
+ const value = obj[key];
+ if (typeof value === 'number') {
+ res[key] = value;
+ }
+ });
+ return res;
+}
+exports.enumToMap = enumToMap;
+//# sourceMappingURL=utils.js.map
- response.body = body
+/***/ }),
- 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)
+/***/ 47501:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2. If dataURLStruct is failure, then return a
- // network error.
- if (dataURLStruct === 'failure') {
- return Promise.resolve(makeNetworkError('failed to fetch the data URL'))
- }
+"use strict";
- // 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.
+const { kClients } = __nccwpck_require__(36443)
+const Agent = __nccwpck_require__(59965)
+const {
+ kAgent,
+ kMockAgentSet,
+ kMockAgentGet,
+ kDispatches,
+ kIsMockActive,
+ kNetConnect,
+ kGetNetConnect,
+ kOptions,
+ kFactory
+} = __nccwpck_require__(91117)
+const MockClient = __nccwpck_require__(47365)
+const MockPool = __nccwpck_require__(94004)
+const { matchValue, buildMockOptions } = __nccwpck_require__(53397)
+const { InvalidArgumentError, UndiciError } = __nccwpck_require__(68707)
+const Dispatcher = __nccwpck_require__(28611)
+const Pluralizer = __nccwpck_require__(91529)
+const PendingInterceptorsFormatter = __nccwpck_require__(56142)
- return httpFetch(fetchParams)
- .catch((err) => makeNetworkError(err))
- }
- default: {
- return Promise.resolve(makeNetworkError('unknown scheme'))
- }
+class FakeWeakRef {
+ constructor (value) {
+ this.value = value
}
-}
-
-// 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))
+ deref () {
+ return this.value
}
}
-// https://fetch.spec.whatwg.org/#fetch-finale
-function fetchFinale (fetchParams, response) {
- // 1. If response is a network error, then:
- if (response.type === 'error') {
- // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ».
- response.urlList = [fetchParams.request.urlList[0]]
-
- // 2. Set response’s timing info to the result of creating an opaque timing
- // info for fetchParams’s timing info.
- response.timingInfo = createOpaqueTimingInfo({
- startTime: fetchParams.timingInfo.startTime
- })
- }
+class MockAgent extends Dispatcher {
+ constructor (opts) {
+ super(opts)
- // 2. Let processResponseEndOfBody be the following steps:
- const processResponseEndOfBody = () => {
- // 1. Set fetchParams’s request’s done flag.
- fetchParams.request.done = true
+ this[kNetConnect] = true
+ this[kIsMockActive] = true
- // If fetchParams’s process response end-of-body is not null,
- // then queue a fetch task to run fetchParams’s process response
- // end-of-body given response with fetchParams’s task destination.
- if (fetchParams.processResponseEndOfBody != null) {
- queueMicrotask(() => fetchParams.processResponseEndOfBody(response))
+ // Instantiate Agent and encapsulate
+ if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) {
+ throw new InvalidArgumentError('Argument opts.agent must implement Agent')
}
- }
+ const agent = opts && opts.agent ? opts.agent : new Agent(opts)
+ this[kAgent] = agent
- // 3. 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))
+ this[kClients] = agent[kClients]
+ this[kOptions] = buildMockOptions(opts)
}
- // 4. If response’s body is null, then run processResponseEndOfBody.
- if (response.body == null) {
- processResponseEndOfBody()
- } else {
- // 5. Otherwise:
-
- // 1. Let transformStream be a new a TransformStream.
+ get (origin) {
+ let dispatcher = this[kMockAgentGet](origin)
- // 2. Let identityTransformAlgorithm be an algorithm which, given chunk,
- // enqueues chunk in transformStream.
- const identityTransformAlgorithm = (chunk, controller) => {
- controller.enqueue(chunk)
+ if (!dispatcher) {
+ dispatcher = this[kFactory](origin)
+ this[kMockAgentSet](origin, dispatcher)
}
-
- // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm
- // and flushAlgorithm set to processResponseEndOfBody.
- const transformStream = new TransformStream({
- start () {},
- transform: identityTransformAlgorithm,
- flush: processResponseEndOfBody
- }, {
- size () {
- return 1
- }
- }, {
- size () {
- return 1
- }
- })
-
- // 4. Set response’s body to the result of piping response’s body through transformStream.
- response.body = { stream: response.body.stream.pipeThrough(transformStream) }
+ return dispatcher
}
- // 6. If fetchParams’s process response consume body is non-null, then:
- if (fetchParams.processResponseConsumeBody != null) {
- // 1. Let processBody given nullOrBytes be this step: run fetchParams’s
- // process response consume body given response and nullOrBytes.
- const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes)
-
- // 2. Let processBodyError be this step: run fetchParams’s process
- // response consume body given response and failure.
- const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure)
-
- // 3. If response’s body is null, then queue a fetch task to run processBody
- // given null, with fetchParams’s task destination.
- if (response.body == null) {
- queueMicrotask(() => processBody(null))
- } else {
- // 4. Otherwise, fully read response’s body given processBody, processBodyError,
- // and fetchParams’s task destination.
- return fullyReadBody(response.body, processBody, processBodyError)
- }
- return Promise.resolve()
+ dispatch (opts, handler) {
+ // Call MockAgent.get to perform additional setup before dispatching as normal
+ this.get(opts.origin)
+ return this[kAgent].dispatch(opts, handler)
}
-}
-
-// 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
+ async close () {
+ await this[kAgent].close()
+ this[kClients].clear()
}
- // 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
- }
+ deactivate () {
+ this[kIsMockActive] = false
}
- // 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')
+ activate () {
+ this[kIsMockActive] = true
}
- // 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()
- }
-
- // 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)
+ 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 {
- 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
+ throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.')
}
- } 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())
+ disableNetConnect () {
+ this[kNetConnect] = false
}
- // 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)
- }
+ // This is required to bypass issues caused by using global symbols - see:
+ // https://github.com/nodejs/undici/issues/1447
+ get isMockActive () {
+ return this[kIsMockActive]
}
- // 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')
-
- // 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')
- request.headersList.delete('host')
+ [kMockAgentSet] (origin, dispatcher) {
+ this[kClients].set(origin, new FakeWeakRef(dispatcher))
}
- // 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]
+ [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)
}
- // 15. Let timingInfo be fetchParams’s timing info.
- const timingInfo = fetchParams.timingInfo
+ [kMockAgentGet] (origin) {
+ // First check if we can immediately find it
+ const ref = this[kClients].get(origin)
+ if (ref) {
+ return ref.deref()
+ }
- // 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)
+ // 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
+ }
- // 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
+ // If we match, create a pool and assign the same dispatches
+ for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) {
+ const nonExplicitDispatcher = nonExplicitRef.deref()
+ if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) {
+ const dispatcher = this[kFactory](origin)
+ this[kMockAgentSet](origin, dispatcher)
+ dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches]
+ return dispatcher
+ }
+ }
}
- // 18. Append locationURL to request’s URL list.
- request.urlList.push(locationURL)
+ [kGetNetConnect] () {
+ return this[kNetConnect]
+ }
- // 19. Invoke set request’s referrer policy on redirect on request and
- // actualResponse.
- setRequestReferrerPolicyOnRedirect(request, actualResponse)
+ pendingInterceptors () {
+ const mockAgentClients = this[kClients]
- // 20. Return the result of running main fetch given fetchParams and true.
- return mainFetch(fetchParams, true)
-}
+ return Array.from(mockAgentClients.entries())
+ .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin })))
+ .filter(({ pending }) => pending)
+ }
-// 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
+ assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {
+ const pending = this.pendingInterceptors()
- // 2. Let httpFetchParams be null.
- let httpFetchParams = null
+ if (pending.length === 0) {
+ return
+ }
- // 3. Let httpRequest be null.
- let httpRequest = null
+ const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length)
- // 4. Let response be null.
- let response = null
+ throw new UndiciError(`
+${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending:
- // 5. Let storedResponse be null.
- // TODO: cache
+${pendingInterceptorsFormatter.format(pending)}
+`.trim())
+ }
+}
- // 6. Let httpCache be null.
- const httpCache = null
+module.exports = MockAgent
- // 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:
+/***/ 47365:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 1. Set httpRequest to a clone of request.
- httpRequest = makeRequest(request)
+"use strict";
- // 2. Set httpFetchParams to a copy of fetchParams.
- httpFetchParams = { ...fetchParams }
- // 3. Set httpFetchParams’s request to httpRequest.
- httpFetchParams.request = httpRequest
- }
+const { promisify } = __nccwpck_require__(39023)
+const Client = __nccwpck_require__(86197)
+const { buildMockDispatch } = __nccwpck_require__(53397)
+const {
+ kDispatches,
+ kMockAgent,
+ kClose,
+ kOriginalClose,
+ kOrigin,
+ kOriginalDispatch,
+ kConnected
+} = __nccwpck_require__(91117)
+const { MockInterceptor } = __nccwpck_require__(31511)
+const Symbols = __nccwpck_require__(36443)
+const { InvalidArgumentError } = __nccwpck_require__(68707)
- // 3. Let includeCredentials be true if one of
- const includeCredentials =
- request.credentials === 'include' ||
- (request.credentials === 'same-origin' &&
- request.responseTainting === 'basic')
+/**
+ * MockClient provides an API that extends the Client to influence the mockDispatches.
+ */
+class MockClient extends Client {
+ constructor (origin, opts) {
+ super(origin, opts)
- // 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
+ if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
+ throw new InvalidArgumentError('Argument opts.agent must implement Agent')
+ }
- // 5. Let contentLengthHeaderValue be null.
- let contentLengthHeaderValue = null
+ this[kMockAgent] = opts.agent
+ this[kOrigin] = origin
+ this[kDispatches] = []
+ this[kConnected] = 1
+ this[kOriginalDispatch] = this.dispatch
+ this[kOriginalClose] = this.close.bind(this)
- // 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'
+ this.dispatch = buildMockDispatch.call(this)
+ this.close = this[kClose]
}
- // 7. If contentLength is non-null, then set contentLengthHeaderValue to
- // contentLength, serialized and isomorphic encoded.
- if (contentLength != null) {
- contentLengthHeaderValue = isomorphicEncode(`${contentLength}`)
+ get [Symbols.kConnected] () {
+ return this[kConnected]
}
- // 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)
+ /**
+ * Sets up the base interceptor for mocking replies from undici.
+ */
+ intercept (opts) {
+ return new MockInterceptor(opts, this[kDispatches])
}
- // 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.
+ async [kClose] () {
+ await promisify(this[kOriginalClose])()
+ this[kConnected] = 0
+ this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
}
+}
- // 11. If httpRequest’s referrer is a URL, then append
- // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded,
- // to httpRequest’s header list.
- if (httpRequest.referrer instanceof URL) {
- httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href))
- }
+module.exports = MockClient
- // 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')) {
- httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node')
- }
+/***/ 52429:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 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') ||
- httpRequest.headersList.contains('if-none-match') ||
- httpRequest.headersList.contains('if-unmodified-since') ||
- httpRequest.headersList.contains('if-match') ||
- httpRequest.headersList.contains('if-range'))
- ) {
- httpRequest.cache = 'no-store'
- }
+"use strict";
- // 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')
- ) {
- httpRequest.headersList.append('cache-control', 'max-age=0')
- }
- // 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')) {
- httpRequest.headersList.append('pragma', 'no-cache')
- }
+const { UndiciError } = __nccwpck_require__(68707)
- // 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')) {
- httpRequest.headersList.append('cache-control', 'no-cache')
- }
+class MockNotMatchedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, MockNotMatchedError)
+ this.name = 'MockNotMatchedError'
+ this.message = message || 'The request does not match any registered mock dispatches'
+ this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED'
}
+}
- // 18. If httpRequest’s header list contains `Range`, then append
- // `Accept-Encoding`/`identity` to httpRequest’s header list.
- if (httpRequest.headersList.contains('range')) {
- httpRequest.headersList.append('accept-encoding', 'identity')
- }
+module.exports = {
+ MockNotMatchedError
+}
- // 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')) {
- if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
- httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate')
- } else {
- httpRequest.headersList.append('accept-encoding', 'gzip, deflate')
- }
- }
- httpRequest.headersList.delete('host')
+/***/ }),
- // 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
- }
+/***/ 31511:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 21. If there’s a proxy-authentication entry, use it as appropriate.
- // TODO: proxy-authentication
+"use strict";
- // 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'
- }
+const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(53397)
+const {
+ kDispatches,
+ kDispatchKey,
+ kDefaultHeaders,
+ kDefaultTrailers,
+ kContentLength,
+ kMockDispatch
+} = __nccwpck_require__(91117)
+const { InvalidArgumentError } = __nccwpck_require__(68707)
+const { buildURL } = __nccwpck_require__(3440)
- // 24. If httpRequest’s cache mode is neither "no-store" nor "reload",
- // then:
- if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') {
- // TODO: cache
+/**
+ * Defines the scope API for an interceptor reply
+ */
+class MockScope {
+ constructor (mockDispatch) {
+ this[kMockDispatch] = mockDispatch
}
- // 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.mode === 'only-if-cached') {
- return makeNetworkError('only if cached')
+ /**
+ * 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')
}
- // 2. Let forwardResponse be the result of running HTTP-network fetch
- // given httpFetchParams, includeCredentials, and isNewConnectionFetch.
- const forwardResponse = await httpNetworkFetch(
- httpFetchParams,
- includeCredentials,
- isNewConnectionFetch
- )
+ this[kMockDispatch].delay = waitInMs
+ return this
+ }
- // 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
- }
+ /**
+ * For a defined reply, never mark as consumed.
+ */
+ persist () {
+ this[kMockDispatch].persist = true
+ return this
+ }
- // 4. If the revalidatingFlag is set and forwardResponse’s status is 304,
- // then:
- if (revalidatingFlag && forwardResponse.status === 304) {
- // TODO: cache
+ /**
+ * 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')
}
- // 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
- }
+ this[kMockDispatch].times = repeatTimes
+ return this
}
+}
- // 11. Set response’s URL list to a clone of httpRequest’s URL list.
- response.urlList = [...httpRequest.urlList]
+/**
+ * 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 = buildURL(opts.path, opts.query)
+ } else {
+ // Matches https://github.com/nodejs/undici/blob/main/lib/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()
+ }
- // 12. If httpRequest’s header list contains `Range`, then set response’s
- // range-requested flag.
- if (httpRequest.headersList.contains('range')) {
- response.rangeRequested = true
+ this[kDispatchKey] = buildKey(opts)
+ this[kDispatches] = mockDispatches
+ this[kDefaultHeaders] = {}
+ this[kDefaultTrailers] = {}
+ this[kContentLength] = false
}
- // 13. Set response’s request-includes-credentials to includeCredentials.
- response.requestIncludesCredentials = includeCredentials
+ 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 }
- // 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
+ return { statusCode, data, headers, trailers }
+ }
- // 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()
+ validateReplyParameters (statusCode, data, responseOptions) {
+ if (typeof statusCode === 'undefined') {
+ throw new InvalidArgumentError('statusCode must be defined')
}
-
- // 2. ???
-
- // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.
- if (isCancelled(fetchParams)) {
- return makeAppropriateNetworkError(fetchParams)
+ if (typeof data === 'undefined') {
+ throw new InvalidArgumentError('data must be defined')
+ }
+ if (typeof responseOptions !== 'object') {
+ throw new InvalidArgumentError('responseOptions must be an object')
}
+ }
- // 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?
+ /**
+ * Mock an undici request with a defined reply.
+ */
+ reply (replyData) {
+ // Values of reply aren't available right now as they
+ // can only be available when the reply callback is invoked.
+ if (typeof replyData === '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 = replyData(opts)
- // 5. Set response to the result of running HTTP-network-or-cache fetch given
- // fetchParams.
- // TODO
- return makeNetworkError('proxy authentication required')
- }
+ // Check if it is in the right format
+ if (typeof resolvedData !== 'object') {
+ throw new InvalidArgumentError('reply options callback must return an object')
+ }
- // 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:
+ const { statusCode, data = '', responseOptions = {} } = resolvedData
+ this.validateReplyParameters(statusCode, data, responseOptions)
+ // Since the values can be obtained immediately we return them
+ // from this higher order function that will be resolved later.
+ return {
+ ...this.createMockScopeDispatchData(statusCode, data, responseOptions)
+ }
+ }
- // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
- if (isCancelled(fetchParams)) {
- return makeAppropriateNetworkError(fetchParams)
+ // 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)
+ return new MockScope(newMockDispatch)
}
- // 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()
+ // 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 [statusCode, data = '', responseOptions = {}] = [...arguments]
+ this.validateReplyParameters(statusCode, data, responseOptions)
- response = await httpNetworkOrCacheFetch(
- fetchParams,
- isAuthenticationFetch,
- true
- )
+ // Send in-already provided data like usual
+ const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions)
+ const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData)
+ return new MockScope(newMockDispatch)
}
- // 17. If isAuthenticationFetch is true, then create an authentication entry
- if (isAuthenticationFetch) {
- // TODO
+ /**
+ * 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 })
+ return new MockScope(newMockDispatch)
}
- // 18. Return response.
- return response
-}
+ /**
+ * Set default reply headers on the interceptor for subsequent replies
+ */
+ defaultReplyHeaders (headers) {
+ if (typeof headers === 'undefined') {
+ throw new InvalidArgumentError('headers must be defined')
+ }
-// https://fetch.spec.whatwg.org/#http-network-fetch
-async function httpNetworkFetch (
- fetchParams,
- includeCredentials = false,
- forceNewConnection = false
-) {
- assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed)
+ this[kDefaultHeaders] = headers
+ return this
+ }
- fetchParams.controller.connection = {
- abort: null,
- destroyed: false,
- destroy (err) {
- if (!this.destroyed) {
- this.destroyed = true
- this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError'))
- }
+ /**
+ * 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
}
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
+ /**
+ * Set reply content length header for replies on the interceptor
+ */
+ replyContentLength () {
+ this[kContentLength] = true
+ return this
+ }
+}
- // 2. Let response be null.
- let response = null
+module.exports.MockInterceptor = MockInterceptor
+module.exports.MockScope = MockScope
- // 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'
- }
+/***/ 94004:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 6. Let networkPartitionKey be the result of determining the network
- // partition key given request.
- // TODO
+"use strict";
- // 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
- }
+const { promisify } = __nccwpck_require__(39023)
+const Pool = __nccwpck_require__(35076)
+const { buildMockDispatch } = __nccwpck_require__(53397)
+const {
+ kDispatches,
+ kMockAgent,
+ kClose,
+ kOriginalClose,
+ kOrigin,
+ kOriginalDispatch,
+ kConnected
+} = __nccwpck_require__(91117)
+const { MockInterceptor } = __nccwpck_require__(31511)
+const Symbols = __nccwpck_require__(36443)
+const { InvalidArgumentError } = __nccwpck_require__(68707)
- // 9. Run these steps, but abort when the ongoing fetch is terminated:
+/**
+ * MockPool provides an API that extends the Pool to influence the mockDispatches.
+ */
+class MockPool extends Pool {
+ constructor (origin, opts) {
+ super(origin, opts)
- // 1. If connection is failure, then return a network error.
+ if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
+ throw new InvalidArgumentError('Argument opts.agent must implement Agent')
+ }
- // 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.
+ this[kMockAgent] = opts.agent
+ this[kOrigin] = origin
+ this[kDispatches] = []
+ this[kConnected] = 1
+ this[kOriginalDispatch] = this.dispatch
+ this[kOriginalClose] = this.close.bind(this)
- // 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.
+ this.dispatch = buildMockDispatch.call(this)
+ this.close = this[kClose]
+ }
- // 4. Set timingInfo’s final network-request start time to the coarsened
- // shared current time given fetchParams’s cross-origin isolated
- // capability.
+ get [Symbols.kConnected] () {
+ return this[kConnected]
+ }
- // 5. Set response to the result of making an HTTP request over connection
- // using request with the following caveats:
+ /**
+ * Sets up the base interceptor for mocking replies from undici.
+ */
+ intercept (opts) {
+ return new MockInterceptor(opts, this[kDispatches])
+ }
- // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS]
- // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH]
+ async [kClose] () {
+ await promisify(this[kOriginalClose])()
+ this[kConnected] = 0
+ this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
+ }
+}
- // - 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.
+module.exports = MockPool
- // - 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.
+/***/ 91117:
+/***/ ((module) => {
- // - If request’s header list contains `Transfer-Encoding`/`chunked` and
- // response is transferred via HTTP/1.0 or older, then return a network
- // error.
+"use strict";
- // - 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.
+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'),
+ kOrigin: Symbol('origin'),
+ kIsMockActive: Symbol('is mock active'),
+ kNetConnect: Symbol('net connect'),
+ kGetNetConnect: Symbol('get net connect'),
+ kConnected: Symbol('connected')
+}
- // 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
- }
+/***/ 53397:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2. Run this step in parallel: transmit bytes.
- yield bytes
+"use strict";
- // 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
- }
+const { MockNotMatchedError } = __nccwpck_require__(52429)
+const {
+ kDispatches,
+ kMockAgent,
+ kOriginalDispatch,
+ kOrigin,
+ kGetNetConnect
+} = __nccwpck_require__(91117)
+const { buildURL, nop } = __nccwpck_require__(3440)
+const { STATUS_CODES } = __nccwpck_require__(58611)
+const {
+ types: {
+ isPromise
+ }
+} = __nccwpck_require__(39023)
- // 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()
- }
- }
+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
+}
- // 3. Let processBodyError given e be these steps:
- const processBodyError = (e) => {
- // 1. If fetchParams is canceled, then abort these steps.
- if (isCancelled(fetchParams)) {
- return
- }
+function lowerCaseEntries (headers) {
+ return Object.fromEntries(
+ Object.entries(headers).map(([headerName, headerValue]) => {
+ return [headerName.toLocaleLowerCase(), headerValue]
+ })
+ )
+}
- // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller.
- if (e.name === 'AbortError') {
- fetchParams.controller.abort()
- } else {
- fetchParams.controller.terminate(e)
+/**
+ * @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]
}
}
- // 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)
- }
- })()
+ return undefined
+ } else if (typeof headers.get === 'function') {
+ return headers.get(key)
+ } else {
+ return lowerCaseEntries(headers)[key.toLocaleLowerCase()]
}
+}
- 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()
+/** @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)
+}
- response = makeResponse({ status, statusText, headersList })
+function matchHeaders (mockDispatch, headers) {
+ if (typeof mockDispatch.headers === 'function') {
+ if (Array.isArray(headers)) { // fetch HeadersList
+ headers = buildHeadersFromArray(headers)
}
- } 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()
+ return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {})
+ }
+ if (typeof mockDispatch.headers === 'undefined') {
+ return true
+ }
+ if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') {
+ return false
+ }
- // 2. Return the appropriate network error for fetchParams.
- return makeAppropriateNetworkError(fetchParams, err)
- }
+ for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) {
+ const headerValue = getHeaderByName(headers, matchHeaderName)
- return makeNetworkError(err)
+ if (!matchValue(matchHeaderValue, headerValue)) {
+ return false
+ }
}
+ return true
+}
- // 11. Let pullAlgorithm be an action that resumes the ongoing fetch
- // if it is suspended.
- const pullAlgorithm = () => {
- fetchParams.controller.resume()
+function safeUrl (path) {
+ if (typeof path !== 'string') {
+ return path
}
- // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s
- // controller with reason, given reason.
- const cancelAlgorithm = (reason) => {
- fetchParams.controller.abort(reason)
+ const pathSegments = path.split('?')
+
+ if (pathSegments.length !== 2) {
+ return path
}
- // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by
- // the user agent.
- // TODO
+ const qp = new URLSearchParams(pathSegments.pop())
+ qp.sort()
+ return [...pathSegments, qp.toString()].join('?')
+}
- // 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
+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
+}
- // 15. Let stream be a new ReadableStream.
- // 16. Set up stream with pullAlgorithm set to pullAlgorithm,
- // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to
- // highWaterMark, and sizeAlgorithm set to sizeAlgorithm.
- if (!ReadableStream) {
- ReadableStream = (__nccwpck_require__(3774).ReadableStream)
+function getResponseData (data) {
+ if (Buffer.isBuffer(data)) {
+ return data
+ } else if (typeof data === 'object') {
+ return JSON.stringify(data)
+ } else {
+ return data.toString()
}
+}
- const stream = new ReadableStream(
- {
- async start (controller) {
- fetchParams.controller.controller = controller
- },
- async pull (controller) {
- await pullAlgorithm(controller)
- },
- async cancel (reason) {
- await cancelAlgorithm(reason)
- }
- },
- {
- highWaterMark: 0,
- size () {
- return 1
- }
- }
- )
+function getMockDispatch (mockDispatches, key) {
+ const basePath = key.query ? buildURL(key.path, key.query) : key.path
+ const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath
- // 17. Run these steps, but abort when the ongoing fetch is terminated:
+ // Match path
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath))
+ if (matchedMockDispatches.length === 0) {
+ throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`)
+ }
- // 1. Set response’s body to a new body whose stream is stream.
- response.body = { stream }
+ // 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}'`)
+ }
- // 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
+ // 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}'`)
+ }
- // 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
+ // Match headers
+ matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers))
+ if (matchedMockDispatches.length === 0) {
+ throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`)
+ }
- // 18. If aborted, then:
- // TODO
+ return matchedMockDispatches[0]
+}
- // 19. Run these steps in parallel:
+function addMockDispatch (mockDispatches, key, data) {
+ const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false }
+ const replyData = typeof data === 'function' ? { callback: data } : { ...data }
+ const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } }
+ mockDispatches.push(newMockDispatch)
+ return newMockDispatch
+}
- // 1. Run these steps, but abort when fetchParams is canceled:
- fetchParams.controller.on('terminated', onAborted)
- fetchParams.controller.resume = async () => {
- // 1. While true
- while (true) {
- // 1-3. See onData...
+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)
+ }
+}
- // 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()
+function buildKey (opts) {
+ const { path, method, body, headers, query } = opts
+ return {
+ path,
+ method,
+ body,
+ headers,
+ query
+ }
+}
- if (isAborted(fetchParams)) {
- break
- }
+function generateKeyValues (data) {
+ return Object.entries(data).reduce((keyValuePairs, [key, value]) => [
+ ...keyValuePairs,
+ Buffer.from(`${key}`),
+ Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`)
+ ], [])
+}
- bytes = done ? undefined : value
- } catch (err) {
- if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
- // zlib doesn't like empty streams.
- bytes = undefined
- } else {
- bytes = err
+/**
+ * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
+ * @param {number} statusCode
+ */
+function getStatusText (statusCode) {
+ return STATUS_CODES[statusCode] || 'unknown'
+}
- // 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
- }
- }
+async function getResponse (body) {
+ const buffers = []
+ for await (const data of body) {
+ buffers.push(data)
+ }
+ return Buffer.concat(buffers).toString('utf8')
+}
- 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)
+/**
+ * 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)
- finalizeResponse(fetchParams, response)
+ mockDispatch.timesInvoked++
- return
- }
+ // 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) }
+ }
- // 5. Increase timingInfo’s decoded body size by bytes’s length.
- timingInfo.decodedBodySize += bytes?.byteLength ?? 0
+ // Parse mockDispatch data
+ const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch
+ const { timesInvoked, times } = mockDispatch
- // 6. If bytes is failure, then terminate fetchParams’s controller.
- if (isFailure) {
- fetchParams.controller.terminate(bytes)
- return
- }
+ // If it's used up and not persistent, mark as consumed
+ mockDispatch.consumed = !persist && timesInvoked >= times
+ mockDispatch.pending = timesInvoked < times
- // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes
- // into stream.
- fetchParams.controller.controller.enqueue(new Uint8Array(bytes))
+ // If specified, trigger dispatch error
+ if (error !== null) {
+ deleteMockDispatch(this[kDispatches], key)
+ handler.onError(error)
+ return true
+ }
- // 8. If stream is errored, then terminate the ongoing fetch.
- if (isErrored(stream)) {
- fetchParams.controller.terminate()
- return
- }
+ // Handle the request with a delay if necessary
+ if (typeof delay === 'number' && delay > 0) {
+ setTimeout(() => {
+ handleReply(this[kDispatches])
+ }, delay)
+ } else {
+ handleReply(this[kDispatches])
+ }
- // 9. If stream doesn’t need more data ask the user agent to suspend
- // the ongoing fetch.
- if (!fetchParams.controller.controller.desiredSize) {
- return
- }
+ 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.abort = nop
+ handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode))
+ handler.onData(Buffer.from(responseData))
+ handler.onComplete(responseTrailers)
+ deleteMockDispatch(mockDispatches, key)
}
- // 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
+ function resume () {}
- // 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
- )
+ 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 {
- // 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
- }))
- }
+ originalDispatch.call(this, opts, handler)
}
+ }
+}
- // 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()
+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
+}
- // 20. Return response.
- return response
+function buildMockOptions (opts) {
+ if (opts) {
+ const { agent, ...mockOptions } = opts
+ return mockOptions
+ }
+}
- async function dispatch ({ body }) {
- const url = requestCurrentURL(request)
- /** @type {import('../..').Agent} */
- const agent = fetchParams.controller.dispatcher
+module.exports = {
+ getResponseData,
+ getMockDispatch,
+ addMockDispatch,
+ deleteMockDispatch,
+ buildKey,
+ generateKeyValues,
+ matchValue,
+ getResponse,
+ getStatusText,
+ mockDispatch,
+ buildMockDispatch,
+ checkNetConnect,
+ buildMockOptions,
+ getHeaderByName
+}
- return new Promise((resolve, reject) => agent.dispatch(
- {
- path: url.pathname + url.search,
- origin: url.origin,
- method: request.method,
- body: fetchParams.controller.dispatcher.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
+/***/ }),
- if (connection.destroyed) {
- abort(new DOMException('The operation was aborted.', 'AbortError'))
- } else {
- fetchParams.controller.on('terminated', abort)
- this.abort = connection.abort = abort
- }
- },
+/***/ 56142:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- onHeaders (status, headersList, resume, statusText) {
- if (status < 200) {
- return
- }
+"use strict";
- let codings = []
- let location = ''
- const headers = new Headers()
+const { Transform } = __nccwpck_require__(2203)
+const { Console } = __nccwpck_require__(64236)
- // For H2, the headers are a plain JS object
- // We distinguish between them and iterate accordingly
- if (Array.isArray(headersList)) {
- for (let n = 0; n < headersList.length; n += 2) {
- const key = headersList[n + 0].toString('latin1')
- const val = headersList[n + 1].toString('latin1')
- if (key.toLowerCase() === 'content-encoding') {
- // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
- // "All content-coding values are case-insensitive..."
- codings = val.toLowerCase().split(',').map((x) => x.trim())
- } else if (key.toLowerCase() === 'location') {
- location = val
- }
+/**
+ * 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)
+ }
+ })
- headers[kHeadersList].append(key, val)
- }
- } else {
- const keys = Object.keys(headersList)
- for (const key of keys) {
- const val = headersList[key]
- if (key.toLowerCase() === 'content-encoding') {
- // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
- // "All content-coding values are case-insensitive..."
- codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse()
- } else if (key.toLowerCase() === 'location') {
- location = val
- }
+ this.logger = new Console({
+ stdout: this.transform,
+ inspectOptions: {
+ colors: !disableColors && !process.env.CI
+ }
+ })
+ }
- headers[kHeadersList].append(key, val)
- }
- }
+ 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 ? '✅' : '❌',
+ Invocations: timesInvoked,
+ Remaining: persist ? Infinity : times - timesInvoked
+ }))
- this.body = new Readable({ read: resume })
+ this.logger.table(withPrettyHeaders)
+ return this.transform.read().toString()
+ }
+}
- const decoders = []
- const willFollow = request.redirect === 'follow' &&
- location &&
- redirectStatusSet.has(status)
+/***/ }),
- // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
- if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {
- for (const coding of codings) {
- // 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(zlib.createInflate())
- } else if (coding === 'br') {
- decoders.push(zlib.createBrotliDecompress())
- } else {
- decoders.length = 0
- break
- }
- }
- }
+/***/ 91529:
+/***/ ((module) => {
- resolve({
- status,
- statusText,
- headersList: headers[kHeadersList],
- body: decoders.length
- ? pipeline(this.body, ...decoders, () => { })
- : this.body.on('error', () => {})
- })
+"use strict";
- return true
- },
- onData (chunk) {
- if (fetchParams.controller.dump) {
- return
- }
+const singulars = {
+ pronoun: 'it',
+ is: 'is',
+ was: 'was',
+ this: 'this'
+}
- // 1. If one or more bytes have been transmitted from response’s
- // message body, then:
+const plurals = {
+ pronoun: 'they',
+ is: 'are',
+ was: 'were',
+ this: 'these'
+}
- // 1. Let bytes be the transmitted bytes.
- const bytes = chunk
+module.exports = class Pluralizer {
+ constructor (singular, plural) {
+ this.singular = singular
+ this.plural = plural
+ }
- // 2. Let codings be the result of extracting header list values
- // given `Content-Encoding` and response’s header list.
- // See pullAlgorithm.
+ pluralize (count) {
+ const one = count === 1
+ const keys = one ? singulars : plurals
+ const noun = one ? this.singular : this.plural
+ return { ...keys, count, noun }
+ }
+}
- // 3. Increase timingInfo’s encoded body size by bytes’s length.
- timingInfo.encodedBodySize += bytes.byteLength
- // 4. See pullAlgorithm...
+/***/ }),
- return this.body.push(bytes)
- },
+/***/ 34869:
+/***/ ((module) => {
- onComplete () {
- if (this.abort) {
- fetchParams.controller.off('terminated', this.abort)
- }
+"use strict";
+/* eslint-disable */
- fetchParams.controller.ended = true
- this.body.push(null)
- },
- onError (error) {
- if (this.abort) {
- fetchParams.controller.off('terminated', this.abort)
- }
+// Extracted from node/lib/internal/fixed_queue.js
- this.body?.destroy(error)
+// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two.
+const kSize = 2048;
+const kMask = kSize - 1;
- fetchParams.controller.terminate(error)
+// 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 | [empty] |
+// | item | | item | | [empty] |
+// | item | | item | | [empty] |
+// | item | | item | | [empty] |
+// | item | | item | bottom --> | item |
+// | item | | item | | item |
+// | ... | | ... | | ... |
+// | item | | item | | item |
+// | item | | item | | item |
+// | [empty] | <-- top | item | | item |
+// | [empty] | | item | | item |
+// | [empty] | | [empty] | <-- top top --> | [empty] |
+// +-----------+ +-----------+ +-----------+
+//
+// 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] |
+// +-----------+ +-----------+
+// | [empty] | | item |
+// | [empty] | | item |
+// | item | <-- bottom top --> | [empty] |
+// | item | | [empty] |
+// | [empty] | <-- top bottom --> | item |
+// | [empty] | | 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.
- reject(error)
- },
+class FixedCircularBuffer {
+ constructor() {
+ this.bottom = 0;
+ this.top = 0;
+ this.list = new Array(kSize);
+ this.next = null;
+ }
- onUpgrade (status, headersList, socket) {
- if (status !== 101) {
- return
- }
+ isEmpty() {
+ return this.top === this.bottom;
+ }
- const headers = new Headers()
+ isFull() {
+ return ((this.top + 1) & kMask) === this.bottom;
+ }
- for (let n = 0; n < headersList.length; n += 2) {
- const key = headersList[n + 0].toString('latin1')
- const val = headersList[n + 1].toString('latin1')
+ push(data) {
+ this.list[this.top] = data;
+ this.top = (this.top + 1) & kMask;
+ }
- headers[kHeadersList].append(key, val)
- }
+ 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;
+ }
+}
- resolve({
- status,
- statusText: STATUS_CODES[status],
- headersList: headers[kHeadersList],
- socket
- })
+module.exports = class FixedQueue {
+ constructor() {
+ this.head = this.tail = new FixedCircularBuffer();
+ }
- return true
- }
- }
- ))
+ isEmpty() {
+ return this.head.isEmpty();
}
-}
-module.exports = {
- fetch,
- Fetch,
- fetching,
- finalizeAndReportTiming
-}
+ 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);
+ }
+
+ 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;
+ }
+ return next;
+ }
+};
/***/ }),
-/***/ 5194:
+/***/ 58640:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-/* globals AbortController */
+const DispatcherBase = __nccwpck_require__(50001)
+const FixedQueue = __nccwpck_require__(34869)
+const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(36443)
+const PoolStats = __nccwpck_require__(24622)
-const { extractBody, mixinBody, cloneBody } = __nccwpck_require__(8923)
-const { Headers, fill: fillHeaders, HeadersList } = __nccwpck_require__(6349)
-const { FinalizationRegistry } = __nccwpck_require__(3194)()
-const util = __nccwpck_require__(3440)
-const {
- isValidHTTPToken,
- sameOrigin,
- normalizeMethod,
- makePolicyContainer,
- normalizeMethodRecord
-} = __nccwpck_require__(5523)
-const {
- forbiddenMethodsSet,
- corsSafeListedMethodsSet,
- referrerPolicy,
- requestRedirect,
- requestMode,
- requestCredentials,
- requestCache,
- requestDuplex
-} = __nccwpck_require__(7326)
-const { kEnumerableProperty } = util
-const { kHeaders, kSignal, kState, kGuard, kRealm } = __nccwpck_require__(9710)
-const { webidl } = __nccwpck_require__(4222)
-const { getGlobalOrigin } = __nccwpck_require__(5628)
-const { URLSerializer } = __nccwpck_require__(4322)
-const { kHeadersList, kConstruct } = __nccwpck_require__(6443)
-const assert = __nccwpck_require__(2613)
-const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(4434)
+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')
+const kStats = Symbol('stats')
-let TransformStream = globalThis.TransformStream
+class PoolBase extends DispatcherBase {
+ constructor () {
+ super()
-const kAbortController = Symbol('abortController')
+ this[kQueue] = new FixedQueue()
+ this[kClients] = []
+ this[kQueued] = 0
-const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {
- signal.removeEventListener('abort', abort)
-})
+ const pool = this
-// https://fetch.spec.whatwg.org/#request-class
-class Request {
- // https://fetch.spec.whatwg.org/#dom-request
- constructor (input, init = {}) {
- if (input === kConstruct) {
- return
- }
+ this[kOnDrain] = function onDrain (origin, targets) {
+ const queue = pool[kQueue]
- webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' })
+ let needDrain = false
- input = webidl.converters.RequestInfo(input)
- init = webidl.converters.RequestInit(init)
+ while (!needDrain) {
+ const item = queue.shift()
+ if (!item) {
+ break
+ }
+ pool[kQueued]--
+ needDrain = !this.dispatch(item.opts, item.handler)
+ }
- // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object
- this[kRealm] = {
- settingsObject: {
- baseUrl: getGlobalOrigin(),
- get origin () {
- return this.baseUrl?.origin
- },
- policyContainer: makePolicyContainer()
+ this[kNeedDrain] = needDrain
+
+ if (!this[kNeedDrain] && pool[kNeedDrain]) {
+ pool[kNeedDrain] = false
+ pool.emit('drain', origin, [pool, ...targets])
}
- }
- // 1. Let request be null.
- let request = null
+ if (pool[kClosedResolve] && queue.isEmpty()) {
+ Promise
+ .all(pool[kClients].map(c => c.close()))
+ .then(pool[kClosedResolve])
+ }
+ }
- // 2. Let fallbackMode be null.
- let fallbackMode = null
+ this[kOnConnect] = (origin, targets) => {
+ pool.emit('connect', origin, [pool, ...targets])
+ }
- // 3. Let baseURL be this’s relevant settings object’s API base URL.
- const baseUrl = this[kRealm].settingsObject.baseUrl
+ this[kOnDisconnect] = (origin, targets, err) => {
+ pool.emit('disconnect', origin, [pool, ...targets], err)
+ }
- // 4. Let signal be null.
- let signal = null
+ this[kOnConnectionError] = (origin, targets, err) => {
+ pool.emit('connectionError', origin, [pool, ...targets], err)
+ }
- // 5. If input is a string, then:
- if (typeof input === 'string') {
- // 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 })
- }
+ this[kStats] = new PoolStats(this)
+ }
- // 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
- )
- }
+ get [kBusy] () {
+ return this[kNeedDrain]
+ }
- // 4. Set request to a new request whose URL is parsedURL.
- request = makeRequest({ urlList: [parsedURL] })
+ get [kConnected] () {
+ return this[kClients].filter(client => client[kConnected]).length
+ }
- // 5. Set fallbackMode to "cors".
- fallbackMode = 'cors'
- } else {
- // 6. Otherwise:
+ get [kFree] () {
+ return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length
+ }
- // 7. Assert: input is a Request object.
- assert(input instanceof Request)
+ get [kPending] () {
+ let ret = this[kQueued]
+ for (const { [kPending]: pending } of this[kClients]) {
+ ret += pending
+ }
+ return ret
+ }
- // 8. Set request to input’s request.
- request = input[kState]
+ get [kRunning] () {
+ let ret = 0
+ for (const { [kRunning]: running } of this[kClients]) {
+ ret += running
+ }
+ return ret
+ }
- // 9. Set signal to input’s signal.
- signal = input[kSignal]
+ get [kSize] () {
+ let ret = this[kQueued]
+ for (const { [kSize]: size } of this[kClients]) {
+ ret += size
}
+ return ret
+ }
- // 7. Let origin be this’s relevant settings object’s origin.
- const origin = this[kRealm].settingsObject.origin
+ get stats () {
+ return this[kStats]
+ }
- // 8. Let window be "client".
- let window = 'client'
+ async [kClose] () {
+ if (this[kQueue].isEmpty()) {
+ return Promise.all(this[kClients].map(c => c.close()))
+ } else {
+ return new Promise((resolve) => {
+ this[kClosedResolve] = resolve
+ })
+ }
+ }
- // 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
+ async [kDestroy] (err) {
+ while (true) {
+ const item = this[kQueue].shift()
+ if (!item) {
+ break
+ }
+ item.handler.onError(err)
}
- // 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`)
+ return 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]()
}
- // 11. If init["window"] exists, then set window to "no-window".
- if ('window' in init) {
- window = 'no-window'
+ 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]) {
+ process.nextTick(() => {
+ if (this[kNeedDrain]) {
+ this[kOnDrain](client[kUrl], [this, client])
+ }
+ })
}
- // 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: this[kRealm].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]
+ return this
+ }
+
+ [kRemoveClient] (client) {
+ client.close(() => {
+ const idx = this[kClients].indexOf(client)
+ if (idx !== -1) {
+ this[kClients].splice(idx, 1)
+ }
})
- const initHasKey = Object.keys(init).length !== 0
+ this[kNeedDrain] = this[kClients].some(dispatcher => (
+ !dispatcher[kNeedDrain] &&
+ dispatcher.closed !== true &&
+ dispatcher.destroyed !== true
+ ))
+ }
+}
- // 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'
- }
+module.exports = {
+ PoolBase,
+ kClients,
+ kNeedDrain,
+ kAddClient,
+ kRemoveClient,
+ kGetDispatcher
+}
- // 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'
+/***/ 24622:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 5. Set request’s referrer to "client"
- request.referrer = 'client'
+const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(36443)
+const kPool = Symbol('pool')
- // 6. Set request’s referrer policy to the empty string.
- request.referrerPolicy = ''
+class PoolStats {
+ constructor (pool) {
+ this[kPool] = pool
+ }
- // 7. Set request’s URL to request’s current URL.
- request.url = request.urlList[request.urlList.length - 1]
+ get connected () {
+ return this[kPool][kConnected]
+ }
- // 8. Set request’s URL list to « request’s URL ».
- request.urlList = [request.url]
- }
+ get free () {
+ return this[kPool][kFree]
+ }
- // 14. If init["referrer"] exists, then:
- if (init.referrer !== undefined) {
- // 1. Let referrer be init["referrer"].
- const referrer = init.referrer
+ get pending () {
+ return this[kPool][kPending]
+ }
- // 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 })
- }
+ get queued () {
+ return this[kPool][kQueued]
+ }
- // 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, this[kRealm].settingsObject.baseUrl))
- ) {
- request.referrer = 'client'
- } else {
- // 4. Otherwise, set request’s referrer to parsedReferrer.
- request.referrer = parsedReferrer
- }
- }
- }
+ get running () {
+ return this[kPool][kRunning]
+ }
- // 15. If init["referrerPolicy"] exists, then set request’s referrer policy
- // to it.
- if (init.referrerPolicy !== undefined) {
- request.referrerPolicy = init.referrerPolicy
- }
+ get size () {
+ return this[kPool][kSize]
+ }
+}
- // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise.
- let mode
- if (init.mode !== undefined) {
- mode = init.mode
- } else {
- mode = fallbackMode
- }
+module.exports = PoolStats
- // 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
- }
+/***/ 35076:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 18. If init["cache"] exists, then set request’s cache mode to it.
- if (init.cache !== undefined) {
- request.cache = init.cache
- }
+"use strict";
- // 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
+const {
+ PoolBase,
+ kClients,
+ kNeedDrain,
+ kAddClient,
+ kGetDispatcher
+} = __nccwpck_require__(58640)
+const Client = __nccwpck_require__(86197)
+const {
+ InvalidArgumentError
+} = __nccwpck_require__(68707)
+const util = __nccwpck_require__(3440)
+const { kUrl, kInterceptors } = __nccwpck_require__(36443)
+const buildConnector = __nccwpck_require__(59136)
+
+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,
+ ...options
+ } = {}) {
+ super()
+
+ if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
+ throw new InvalidArgumentError('invalid connections')
}
- // 23. If init["integrity"] exists, then set request’s integrity metadata to it.
- if (init.integrity != null) {
- request.integrity = String(init.integrity)
+ if (typeof factory !== 'function') {
+ throw new InvalidArgumentError('factory must be a function.')
}
- // 24. If init["keepalive"] exists, then set request’s keepalive to it.
- if (init.keepalive !== undefined) {
- request.keepalive = Boolean(init.keepalive)
+ if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
+ throw new InvalidArgumentError('connect must be a function or an object')
}
- // 25. If init["method"] exists, then:
- if (init.method !== undefined) {
- // 1. Let method be init["method"].
- let method = init.method
+ if (typeof connect !== 'function') {
+ connect = buildConnector({
+ ...tls,
+ maxCachedSessions,
+ allowH2,
+ socketPath,
+ timeout: connectTimeout,
+ ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
+ ...connect
+ })
+ }
- // 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.`)
- }
+ this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool)
+ ? options.interceptors.Pool
+ : []
+ this[kConnections] = connections || null
+ this[kUrl] = util.parseOrigin(origin)
+ this[kOptions] = { ...util.deepClone(options), connect, allowH2 }
+ this[kOptions].interceptors = options.interceptors
+ ? { ...options.interceptors }
+ : undefined
+ this[kFactory] = factory
- if (forbiddenMethodsSet.has(method.toUpperCase())) {
- throw new TypeError(`'${method}' HTTP method is unsupported.`)
+ 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)
+ }
}
+ })
+ }
- // 3. Normalize method.
- method = normalizeMethodRecord[method] ?? normalizeMethod(method)
+ [kGetDispatcher] () {
+ let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain])
- // 4. Set request’s method to method.
- request.method = method
+ if (dispatcher) {
+ return dispatcher
}
- // 26. If init["signal"] exists, then set signal to it.
- if (init.signal !== undefined) {
- signal = init.signal
+ if (!this[kConnections] || this[kClients].length < this[kConnections]) {
+ dispatcher = this[kFactory](this[kUrl], this[kOptions])
+ this[kAddClient](dispatcher)
}
- // 27. Set this’s request to request.
- this[kState] = request
+ return dispatcher
+ }
+}
- // 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[kSignal] = ac.signal
- this[kSignal][kRealm] = this[kRealm]
+module.exports = Pool
- // 29. If signal is not null, then make this’s signal follow signal.
- if (signal != null) {
- if (
- !signal ||
- typeof signal.aborted !== 'boolean' ||
- typeof signal.addEventListener !== 'function'
- ) {
- throw new TypeError(
- "Failed to construct 'Request': member signal is not of type AbortSignal."
- )
- }
- 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 = function () {
- const ac = acRef.deref()
- if (ac !== undefined) {
- ac.abort(this.reason)
- }
- }
+/***/ 22720:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // Third-party AbortControllers may not work with these.
- // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619.
- try {
- // If the max amount of listeners is equal to the default, increase it
- // This is only available in node >= v19.9.0
- if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) {
- setMaxListeners(100, signal)
- } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) {
- setMaxListeners(100, signal)
- }
- } catch {}
+"use strict";
- util.addAbortListener(signal, abort)
- requestFinalizer.register(ac, { signal, 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[kHeaders] = new Headers(kConstruct)
- this[kHeaders][kHeadersList] = request.headersList
- this[kHeaders][kGuard] = 'request'
- this[kHeaders][kRealm] = this[kRealm]
+const { kProxy, kClose, kDestroy, kInterceptors } = __nccwpck_require__(36443)
+const { URL } = __nccwpck_require__(87016)
+const Agent = __nccwpck_require__(59965)
+const Pool = __nccwpck_require__(35076)
+const DispatcherBase = __nccwpck_require__(50001)
+const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(68707)
+const buildConnector = __nccwpck_require__(59136)
- // 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.`
- )
- }
+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')
- // 2. Set this’s headers’s guard to "request-no-cors".
- this[kHeaders][kGuard] = 'request-no-cors'
- }
+function defaultProtocolPort (protocol) {
+ return protocol === 'https:' ? 443 : 80
+}
- // 32. If init is not empty, then:
- if (initHasKey) {
- /** @type {HeadersList} */
- const headersList = this[kHeaders][kHeadersList]
- // 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)
+function buildProxyOptions (opts) {
+ if (typeof opts === 'string') {
+ opts = { uri: opts }
+ }
- // 3. Empty this’s headers’s header list.
- headersList.clear()
+ if (!opts || !opts.uri) {
+ throw new InvalidArgumentError('Proxy opts.uri is mandatory')
+ }
- // 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 [key, val] of headers) {
- headersList.append(key, val)
- }
- // Note: Copy the `set-cookie` meta-data.
- headersList.cookies = headers.cookies
- } else {
- // 5. Otherwise, fill this’s headers with headers.
- fillHeaders(this[kHeaders], headers)
- }
- }
+ return {
+ uri: opts.uri,
+ protocol: opts.protocol || 'https'
+ }
+}
- // 33. Let inputBody be input’s request’s body if input is a Request
- // object; otherwise null.
- const inputBody = input instanceof Request ? input[kState].body : null
+function defaultFactory (origin, opts) {
+ return new Pool(origin, opts)
+}
- // 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.')
+class ProxyAgent extends DispatcherBase {
+ constructor (opts) {
+ super(opts)
+ this[kProxy] = buildProxyOptions(opts)
+ this[kAgent] = new Agent(opts)
+ this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent)
+ ? opts.interceptors.ProxyAgent
+ : []
+
+ if (typeof opts === 'string') {
+ opts = { uri: opts }
}
- // 35. Let initBody be null.
- let initBody = null
+ if (!opts || !opts.uri) {
+ throw new InvalidArgumentError('Proxy opts.uri is mandatory')
+ }
- // 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
+ const { clientFactory = defaultFactory } = opts
- // 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 && !this[kHeaders][kHeadersList].contains('content-type')) {
- this[kHeaders].append('content-type', contentType)
- }
+ if (typeof clientFactory !== 'function') {
+ throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.')
}
- // 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.')
- }
+ this[kRequestTls] = opts.requestTls
+ this[kProxyTls] = opts.proxyTls
+ this[kProxyHeaders] = opts.headers || {}
- // 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"'
- )
- }
+ const resolvedUrl = new URL(opts.uri)
+ const { origin, port, host, username, password } = resolvedUrl
- // 3. Set this’s request’s use-CORS-preflight flag.
- request.useCORSPreflightFlag = true
+ 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')}`
}
- // 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 (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) {
- throw new TypeError(
- 'Cannot construct a Request with a Request object that has already been used.'
- )
+ const connect = buildConnector({ ...opts.proxyTls })
+ this[kConnectEndpoint] = buildConnector({ ...opts.requestTls })
+ this[kClient] = clientFactory(resolvedUrl, { connect })
+ this[kAgent] = new Agent({
+ ...opts,
+ connect: async (opts, callback) => {
+ let requestedHost = opts.host
+ if (!opts.port) {
+ requestedHost += `:${defaultProtocolPort(opts.protocol)}`
+ }
+ try {
+ const { socket, statusCode } = await this[kClient].connect({
+ origin,
+ port,
+ path: requestedHost,
+ signal: opts.signal,
+ headers: {
+ ...this[kProxyHeaders],
+ host
+ }
+ })
+ if (statusCode !== 200) {
+ socket.on('error', () => {}).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) {
+ callback(err)
+ }
}
+ })
+ }
- // 2. Set finalBody to the result of creating a proxy for inputBody.
- if (!TransformStream) {
- TransformStream = (__nccwpck_require__(3774).TransformStream)
- }
+ dispatch (opts, handler) {
+ const { host } = new URL(opts.origin)
+ const headers = buildHeaders(opts.headers)
+ throwIfProxyAuthIsSent(headers)
+ return this[kAgent].dispatch(
+ {
+ ...opts,
+ headers: {
+ ...headers,
+ host
+ }
+ },
+ handler
+ )
+ }
- // 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
- }
- }
+ async [kClose] () {
+ await this[kAgent].close()
+ await this[kClient].close()
+ }
- // 41. Set this’s request’s body to finalBody.
- this[kState].body = finalBody
+ async [kDestroy] () {
+ await this[kAgent].destroy()
+ await this[kClient].destroy()
}
+}
- // Returns request’s HTTP method, which is "GET" by default.
- get method () {
- webidl.brandCheck(this, Request)
+/**
+ * @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 = {}
- // The method getter steps are to return this’s request’s method.
- return this[kState].method
+ for (let i = 0; i < headers.length; i += 2) {
+ headersPair[headers[i]] = headers[i + 1]
+ }
+
+ return headersPair
}
- // Returns the URL of request as a string.
- get url () {
- webidl.brandCheck(this, Request)
+ return headers
+}
- // The url getter steps are to return this’s request’s URL, serialized.
- return URLSerializer(this[kState].url)
+/**
+ * @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')
}
+}
- // 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)
+module.exports = ProxyAgent
- // The headers getter steps are to return this’s headers.
- return this[kHeaders]
- }
- // 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[kState].destination
- }
+/***/ 28804:
+/***/ ((module) => {
- // 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)
+"use strict";
- // 1. If this’s request’s referrer is "no-referrer", then return the
- // empty string.
- if (this[kState].referrer === 'no-referrer') {
- return ''
- }
- // 2. If this’s request’s referrer is "client", then return
- // "about:client".
- if (this[kState].referrer === 'client') {
- return 'about:client'
- }
+let fastNow = Date.now()
+let fastNowTimeout
- // Return this’s request’s referrer, serialized.
- return this[kState].referrer.toString()
- }
+const fastTimers = []
- // 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)
+function onTimeout () {
+ fastNow = Date.now()
- // The referrerPolicy getter steps are to return this’s request’s referrer policy.
- return this[kState].referrerPolicy
- }
+ let len = fastTimers.length
+ let idx = 0
+ while (idx < len) {
+ const timer = fastTimers[idx]
- // 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)
+ if (timer.state === 0) {
+ timer.state = fastNow + timer.delay
+ } else if (timer.state > 0 && fastNow >= timer.state) {
+ timer.state = -1
+ timer.callback(timer.opaque)
+ }
- // The mode getter steps are to return this’s request’s mode.
- return this[kState].mode
+ if (timer.state === -1) {
+ timer.state = -2
+ if (idx !== len - 1) {
+ fastTimers[idx] = fastTimers.pop()
+ } else {
+ fastTimers.pop()
+ }
+ len -= 1
+ } else {
+ idx += 1
+ }
}
- // 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 () {
- // The credentials getter steps are to return this’s request’s credentials mode.
- return this[kState].credentials
+ if (fastTimers.length > 0) {
+ refreshTimeout()
}
+}
- // 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[kState].cache
+function refreshTimeout () {
+ if (fastNowTimeout && fastNowTimeout.refresh) {
+ fastNowTimeout.refresh()
+ } else {
+ clearTimeout(fastNowTimeout)
+ fastNowTimeout = setTimeout(onTimeout, 1e3)
+ if (fastNowTimeout.unref) {
+ fastNowTimeout.unref()
+ }
}
+}
- // 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[kState].redirect
- }
+class Timeout {
+ constructor (callback, delay, opaque) {
+ this.callback = callback
+ this.delay = delay
+ this.opaque = opaque
- // 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)
+ // -2 not in timer list
+ // -1 in timer list but inactive
+ // 0 in timer list waiting for time
+ // > 0 in timer list waiting for time to expire
+ this.state = -2
- // The integrity getter steps are to return this’s request’s integrity
- // metadata.
- return this[kState].integrity
+ this.refresh()
}
- // Returns a boolean indicating whether or not request can outlive the
- // global in which it was created.
- get keepalive () {
- webidl.brandCheck(this, Request)
+ refresh () {
+ if (this.state === -2) {
+ fastTimers.push(this)
+ if (!fastNowTimeout || fastTimers.length === 1) {
+ refreshTimeout()
+ }
+ }
- // The keepalive getter steps are to return this’s request’s keepalive.
- return this[kState].keepalive
+ this.state = 0
}
- // 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[kState].reloadNavigation
+ clear () {
+ this.state = -1
}
+}
- // Returns a boolean indicating whether or not request is for a history
- // navigation (a.k.a. back-foward 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[kState].historyNavigation
+module.exports = {
+ setTimeout (callback, delay, opaque) {
+ return delay < 1e3
+ ? setTimeout(callback, delay, opaque)
+ : new Timeout(callback, delay, opaque)
+ },
+ clearTimeout (timeout) {
+ if (timeout instanceof Timeout) {
+ timeout.clear()
+ } else {
+ clearTimeout(timeout)
+ }
}
+}
- // 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[kSignal]
- }
+/***/ }),
- get body () {
- webidl.brandCheck(this, Request)
+/***/ 68550:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- return this[kState].body ? this[kState].body.stream : null
- }
+"use strict";
- get bodyUsed () {
- webidl.brandCheck(this, Request)
- return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
- }
+const diagnosticsChannel = __nccwpck_require__(31637)
+const { uid, states } = __nccwpck_require__(45913)
+const {
+ kReadyState,
+ kSentClose,
+ kByteParser,
+ kReceivedClose
+} = __nccwpck_require__(62933)
+const { fireEvent, failWebsocketConnection } = __nccwpck_require__(3574)
+const { CloseEvent } = __nccwpck_require__(46255)
+const { makeRequest } = __nccwpck_require__(25194)
+const { fetching } = __nccwpck_require__(12315)
+const { Headers } = __nccwpck_require__(26349)
+const { getGlobalDispatcher } = __nccwpck_require__(32581)
+const { kHeadersList } = __nccwpck_require__(36443)
- get duplex () {
- webidl.brandCheck(this, Request)
+const channels = {}
+channels.open = diagnosticsChannel.channel('undici:websocket:open')
+channels.close = diagnosticsChannel.channel('undici:websocket:close')
+channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error')
- return 'half'
- }
+/** @type {import('crypto')} */
+let crypto
+try {
+ crypto = __nccwpck_require__(76982)
+} catch {
- // Returns a clone of request.
- clone () {
- webidl.brandCheck(this, Request)
+}
- // 1. If this is unusable, then throw a TypeError.
- if (this.bodyUsed || this.body?.locked) {
- throw new TypeError('unusable')
- }
+/**
+ * @see https://websockets.spec.whatwg.org/#concept-websocket-establish
+ * @param {URL} url
+ * @param {string|string[]} protocols
+ * @param {import('./websocket').WebSocket} ws
+ * @param {(response: any) => void} onEstablish
+ * @param {Partial} options
+ */
+function establishWebSocketConnection (url, protocols, ws, onEstablish, 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
- // 2. Let clonedRequest be the result of cloning this’s request.
- const clonedRequest = cloneRequest(this[kState])
+ requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:'
- // 3. Let clonedRequestObject be the result of creating a Request object,
- // given clonedRequest, this’s headers’s guard, and this’s relevant Realm.
- const clonedRequestObject = new Request(kConstruct)
- clonedRequestObject[kState] = clonedRequest
- clonedRequestObject[kRealm] = this[kRealm]
- clonedRequestObject[kHeaders] = new Headers(kConstruct)
- clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList
- clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard]
- clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm]
+ // 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],
+ serviceWorkers: 'none',
+ referrer: 'no-referrer',
+ mode: 'websocket',
+ credentials: 'include',
+ cache: 'no-store',
+ redirect: 'error'
+ })
- // 4. Make clonedRequestObject’s signal follow this’s signal.
- const ac = new AbortController()
- if (this.signal.aborted) {
- ac.abort(this.signal.reason)
- } else {
- util.addAbortListener(
- this.signal,
- () => {
- ac.abort(this.signal.reason)
- }
- )
- }
- clonedRequestObject[kSignal] = ac.signal
+ // Note: undici extension, allow setting custom headers.
+ if (options.headers) {
+ const headersList = new Headers(options.headers)[kHeadersList]
- // 4. Return clonedRequestObject.
- return clonedRequestObject
+ request.headersList = headersList
}
-}
-mixinBody(Request)
+ // 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
-function makeRequest (init) {
- // https://fetch.spec.whatwg.org/#requests
- const request = {
- method: 'GET',
- localURLsOnly: false,
- unsafeRequest: false,
- body: null,
- client: null,
- reservedClient: null,
- replacesClientId: '',
- window: 'client',
- keepalive: false,
- serviceWorkers: 'all',
- initiator: '',
- destination: '',
- priority: null,
- origin: 'client',
- policyContainer: 'client',
- referrer: 'client',
- referrerPolicy: '',
- mode: 'no-cors',
- useCORSPreflightFlag: false,
- credentials: 'same-origin',
- useCredentials: false,
- cache: 'default',
- redirect: 'follow',
- integrity: '',
- cryptoGraphicsNonceMetadata: '',
- parserMetadata: '',
- reloadNavigation: false,
- historyNavigation: false,
- userActivation: false,
- taintedOrigin: false,
- redirectCount: 0,
- responseTainting: 'basic',
- preventNoCacheCacheControlHeaderModification: false,
- done: false,
- timingAllowFailed: false,
- ...init,
- headersList: init.headersList
- ? new HeadersList(init.headersList)
- : new HeadersList()
- }
- request.url = request.urlList[0]
- return request
-}
+ // 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')
-// https://fetch.spec.whatwg.org/#concept-request-clone
-function cloneRequest (request) {
- // To clone a request request, run these steps:
+ // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s
+ // header list.
+ request.headersList.append('sec-websocket-key', keyValue)
- // 1. Let newRequest be a copy of request, except for its body.
- const newRequest = makeRequest({ ...request, body: null })
+ // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s
+ // header list.
+ request.headersList.append('sec-websocket-version', '13')
- // 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)
+ // 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)
}
- // 3. Return newRequest.
- return newRequest
-}
+ // 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
+ // TODO: enable once permessage-deflate is supported
+ const permessageDeflate = '' // 'permessage-deflate; 15'
-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
- }
-})
+ // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to
+ // request’s header list.
+ // request.headersList.append('sec-websocket-extensions', permessageDeflate)
-webidl.converters.Request = webidl.interfaceConverter(
- Request
-)
+ // 11. Fetch request with useParallelQueue set to true, and
+ // processResponse given response being these steps:
+ const controller = fetching({
+ request,
+ useParallelQueue: true,
+ dispatcher: options.dispatcher ?? getGlobalDispatcher(),
+ processResponse (response) {
+ // 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(ws, 'Received network error or non-101 status code.')
+ return
+ }
-// https://fetch.spec.whatwg.org/#requestinfo
-webidl.converters.RequestInfo = function (V) {
- if (typeof V === 'string') {
- return webidl.converters.USVString(V)
- }
+ // 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(ws, 'Server did not respond with sent protocols.')
+ return
+ }
- if (V instanceof Request) {
- return webidl.converters.Request(V)
- }
+ // 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.
- return webidl.converters.USVString(V)
-}
+ // 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(ws, 'Server did not set Upgrade header to "websocket".')
+ return
+ }
-webidl.converters.AbortSignal = webidl.interfaceConverter(
- AbortSignal
-)
+ // 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(ws, 'Server did not set Connection header to "upgrade".')
+ return
+ }
-// 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,
- { strict: false }
- )
- )
- },
- {
- key: 'window',
- converter: webidl.converters.any
- },
- {
- key: 'duplex',
- converter: webidl.converters.DOMString,
- allowedValues: requestDuplex
- }
-])
+ // 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(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.')
+ return
+ }
-module.exports = { Request, makeRequest }
+ // 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')
+ if (secExtension !== null && secExtension !== permessageDeflate) {
+ failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.')
+ 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')
-/***/ 8676:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) {
+ failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.')
+ return
+ }
-"use strict";
+ response.socket.on('data', onSocketData)
+ response.socket.on('close', onSocketClose)
+ response.socket.on('error', onSocketError)
+ if (channels.open.hasSubscribers) {
+ channels.open.publish({
+ address: response.socket.address(),
+ protocol: secProtocol,
+ extensions: secExtension
+ })
+ }
-const { Headers, HeadersList, fill } = __nccwpck_require__(6349)
-const { extractBody, cloneBody, mixinBody } = __nccwpck_require__(8923)
-const util = __nccwpck_require__(3440)
-const { kEnumerableProperty } = util
-const {
- isValidReasonPhrase,
- isCancelled,
- isAborted,
- isBlobLike,
- serializeJavascriptValueToJSONString,
- isErrorLike,
- isomorphicEncode
-} = __nccwpck_require__(5523)
-const {
- redirectStatusSet,
- nullBodyStatus,
- DOMException
-} = __nccwpck_require__(7326)
-const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710)
-const { webidl } = __nccwpck_require__(4222)
-const { FormData } = __nccwpck_require__(3073)
-const { getGlobalOrigin } = __nccwpck_require__(5628)
-const { URLSerializer } = __nccwpck_require__(4322)
-const { kHeadersList, kConstruct } = __nccwpck_require__(6443)
-const assert = __nccwpck_require__(2613)
-const { types } = __nccwpck_require__(9023)
-
-const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(3774).ReadableStream)
-const textEncoder = new TextEncoder('utf-8')
+ onEstablish(response)
+ }
+ })
-// https://fetch.spec.whatwg.org/#response-class
-class Response {
- // Creates network error Response.
- static error () {
- // TODO
- const relevantRealm = { settingsObject: {} }
+ return controller
+}
- // 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 = new Response()
- responseObject[kState] = makeNetworkError()
- responseObject[kRealm] = relevantRealm
- responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList
- responseObject[kHeaders][kGuard] = 'immutable'
- responseObject[kHeaders][kRealm] = relevantRealm
- return responseObject
+/**
+ * @param {Buffer} chunk
+ */
+function onSocketData (chunk) {
+ if (!this.ws[kByteParser].write(chunk)) {
+ this.pause()
}
+}
- // https://fetch.spec.whatwg.org/#dom-response-json
- static json (data, init = {}) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' })
+/**
+ * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
+ * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
+ */
+function onSocketClose () {
+ const { ws } = this
- if (init !== null) {
- init = webidl.converters.ResponseInit(init)
- }
+ // 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 = ws[kSentClose] && ws[kReceivedClose]
- // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data.
- const bytes = textEncoder.encode(
- serializeJavascriptValueToJSONString(data)
- )
+ let code = 1005
+ let reason = ''
- // 2. Let body be the result of extracting bytes.
- const body = extractBody(bytes)
+ const result = ws[kByteParser].closingInfo
- // 3. Let responseObject be the result of creating a Response object, given a new response,
- // "response", and this’s relevant Realm.
- const relevantRealm = { settingsObject: {} }
- const responseObject = new Response()
- responseObject[kRealm] = relevantRealm
- responseObject[kHeaders][kGuard] = 'response'
- responseObject[kHeaders][kRealm] = relevantRealm
+ if (result) {
+ code = result.code ?? 1005
+ reason = result.reason
+ } else if (!ws[kSentClose]) {
+ // 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
+ }
- // 4. Perform initialize a response given responseObject, init, and (body, "application/json").
- initializeResponse(responseObject, init, { body: body[0], type: 'application/json' })
+ // 1. Change the ready state to CLOSED (3).
+ ws[kReadyState] = 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.
+ fireEvent('close', ws, CloseEvent, {
+ wasClean, code, reason
+ })
- // 5. Return responseObject.
- return responseObject
+ if (channels.close.hasSubscribers) {
+ channels.close.publish({
+ websocket: ws,
+ code,
+ reason
+ })
}
+}
- // Creates a redirect Response that redirects to url with status status.
- static redirect (url, status = 302) {
- const relevantRealm = { settingsObject: {} }
-
- webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' })
-
- url = webidl.converters.USVString(url)
- status = webidl.converters['unsigned short'](status)
+function onSocketError (error) {
+ const { ws } = this
- // 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, getGlobalOrigin())
- } catch (err) {
- throw Object.assign(new TypeError('Failed to parse URL from ' + url), {
- cause: err
- })
- }
+ ws[kReadyState] = states.CLOSING
- // 3. If status is not a redirect status, then throw a RangeError.
- if (!redirectStatusSet.has(status)) {
- throw new RangeError('Invalid status code ' + status)
- }
+ if (channels.socketError.hasSubscribers) {
+ channels.socketError.publish(error)
+ }
- // 4. Let responseObject be the result of creating a Response object,
- // given a new response, "immutable", and this’s relevant Realm.
- const responseObject = new Response()
- responseObject[kRealm] = relevantRealm
- responseObject[kHeaders][kGuard] = 'immutable'
- responseObject[kHeaders][kRealm] = relevantRealm
+ this.destroy()
+}
- // 5. Set responseObject’s response’s status to status.
- responseObject[kState].status = status
+module.exports = {
+ establishWebSocketConnection
+}
- // 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[kState].headersList.append('location', value)
+/***/ }),
- // 8. Return responseObject.
- return responseObject
- }
+/***/ 45913:
+/***/ ((module) => {
- // https://fetch.spec.whatwg.org/#dom-response
- constructor (body = null, init = {}) {
- if (body !== null) {
- body = webidl.converters.BodyInit(body)
- }
+"use strict";
- init = webidl.converters.ResponseInit(init)
- // TODO
- this[kRealm] = { settingsObject: {} }
+// 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
+const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
- // 1. Set this’s response to a new response.
- this[kState] = makeResponse({})
+/** @type {PropertyDescriptor} */
+const staticPropertyDescriptors = {
+ enumerable: true,
+ writable: false,
+ configurable: false
+}
- // 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[kHeaders] = new Headers(kConstruct)
- this[kHeaders][kGuard] = 'response'
- this[kHeaders][kHeadersList] = this[kState].headersList
- this[kHeaders][kRealm] = this[kRealm]
+const states = {
+ CONNECTING: 0,
+ OPEN: 1,
+ CLOSING: 2,
+ CLOSED: 3
+}
- // 3. Let bodyWithType be null.
- let bodyWithType = null
+const opcodes = {
+ CONTINUATION: 0x0,
+ TEXT: 0x1,
+ BINARY: 0x2,
+ CLOSE: 0x8,
+ PING: 0x9,
+ PONG: 0xA
+}
- // 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 }
- }
+const maxUnsigned16Bit = 2 ** 16 - 1 // 65535
- // 5. Perform initialize a response given this, init, and bodyWithType.
- initializeResponse(this, init, bodyWithType)
- }
+const parserStates = {
+ INFO: 0,
+ PAYLOADLENGTH_16: 2,
+ PAYLOADLENGTH_64: 3,
+ READ_DATA: 4
+}
- // Returns response’s type, e.g., "cors".
- get type () {
- webidl.brandCheck(this, Response)
+const emptyBuffer = Buffer.allocUnsafe(0)
- // The type getter steps are to return this’s response’s type.
- return this[kState].type
- }
+module.exports = {
+ uid,
+ staticPropertyDescriptors,
+ states,
+ opcodes,
+ maxUnsigned16Bit,
+ parserStates,
+ emptyBuffer
+}
- // Returns response’s URL, if it has one; otherwise the empty string.
- get url () {
- webidl.brandCheck(this, Response)
- const urlList = this[kState].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
+/***/ 46255:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (url === null) {
- return ''
- }
+"use strict";
- return URLSerializer(url, true)
- }
- // Returns whether response was obtained through a redirect.
- get redirected () {
- webidl.brandCheck(this, Response)
+const { webidl } = __nccwpck_require__(74222)
+const { kEnumerableProperty } = __nccwpck_require__(3440)
+const { MessagePort } = __nccwpck_require__(28167)
- // The redirected getter steps are to return true if this’s response’s URL
- // list has more than one item; otherwise false.
- return this[kState].urlList.length > 1
- }
+/**
+ * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent
+ */
+class MessageEvent extends Event {
+ #eventInit
- // Returns response’s status.
- get status () {
- webidl.brandCheck(this, Response)
+ constructor (type, eventInitDict = {}) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' })
- // The status getter steps are to return this’s response’s status.
- return this[kState].status
- }
+ type = webidl.converters.DOMString(type)
+ eventInitDict = webidl.converters.MessageEventInit(eventInitDict)
- // Returns whether response’s status is an ok status.
- get ok () {
- webidl.brandCheck(this, Response)
+ super(type, eventInitDict)
- // The ok getter steps are to return true if this’s response’s status is an
- // ok status; otherwise false.
- return this[kState].status >= 200 && this[kState].status <= 299
+ this.#eventInit = eventInitDict
}
- // Returns response’s status message.
- get statusText () {
- webidl.brandCheck(this, Response)
+ get data () {
+ webidl.brandCheck(this, MessageEvent)
- // The statusText getter steps are to return this’s response’s status
- // message.
- return this[kState].statusText
+ return this.#eventInit.data
}
- // Returns response’s headers as Headers.
- get headers () {
- webidl.brandCheck(this, Response)
+ get origin () {
+ webidl.brandCheck(this, MessageEvent)
- // The headers getter steps are to return this’s headers.
- return this[kHeaders]
+ return this.#eventInit.origin
}
- get body () {
- webidl.brandCheck(this, Response)
+ get lastEventId () {
+ webidl.brandCheck(this, MessageEvent)
- return this[kState].body ? this[kState].body.stream : null
+ return this.#eventInit.lastEventId
}
- get bodyUsed () {
- webidl.brandCheck(this, Response)
+ get source () {
+ webidl.brandCheck(this, MessageEvent)
- return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
+ return this.#eventInit.source
}
- // Returns a clone of response.
- clone () {
- webidl.brandCheck(this, Response)
+ get ports () {
+ webidl.brandCheck(this, MessageEvent)
- // 1. If this is unusable, then throw a TypeError.
- if (this.bodyUsed || (this.body && this.body.locked)) {
- throw webidl.errors.exception({
- header: 'Response.clone',
- message: 'Body has already been consumed.'
- })
+ if (!Object.isFrozen(this.#eventInit.ports)) {
+ Object.freeze(this.#eventInit.ports)
}
- // 2. Let clonedResponse be the result of cloning this’s response.
- const clonedResponse = cloneResponse(this[kState])
+ return this.#eventInit.ports
+ }
- // 3. Return the result of creating a Response object, given
- // clonedResponse, this’s headers’s guard, and this’s relevant Realm.
- const clonedResponseObject = new Response()
- clonedResponseObject[kState] = clonedResponse
- clonedResponseObject[kRealm] = this[kRealm]
- clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList
- clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard]
- clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm]
+ initMessageEvent (
+ type,
+ bubbles = false,
+ cancelable = false,
+ data = null,
+ origin = '',
+ lastEventId = '',
+ source = null,
+ ports = []
+ ) {
+ webidl.brandCheck(this, MessageEvent)
- return clonedResponseObject
+ webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' })
+
+ return new MessageEvent(type, {
+ bubbles, cancelable, data, origin, lastEventId, source, ports
+ })
}
}
-mixinBody(Response)
+/**
+ * @see https://websockets.spec.whatwg.org/#the-closeevent-interface
+ */
+class CloseEvent extends Event {
+ #eventInit
-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
- }
-})
+ constructor (type, eventInitDict = {}) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' })
-Object.defineProperties(Response, {
- json: kEnumerableProperty,
- redirect: kEnumerableProperty,
- error: kEnumerableProperty
-})
+ type = webidl.converters.DOMString(type)
+ eventInitDict = webidl.converters.CloseEventInit(eventInitDict)
-// https://fetch.spec.whatwg.org/#concept-response-clone
-function cloneResponse (response) {
- // To clone a response response, run these steps:
+ super(type, eventInitDict)
- // 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
- )
+ this.#eventInit = eventInitDict
}
- // 2. Let newResponse be a copy of response, except for its body.
- const newResponse = makeResponse({ ...response, body: null })
+ get wasClean () {
+ webidl.brandCheck(this, CloseEvent)
- // 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)
+ return this.#eventInit.wasClean
}
- // 4. Return newResponse.
- return newResponse
-}
+ get code () {
+ webidl.brandCheck(this, CloseEvent)
-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] : []
+ return this.#eventInit.code
}
-}
-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'
- })
-}
+ get reason () {
+ webidl.brandCheck(this, CloseEvent)
-function makeFilteredResponse (response, state) {
- state = {
- internalResponse: response,
- ...state
+ return this.#eventInit.reason
}
-
- 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.
+// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface
+class ErrorEvent extends Event {
+ #eventInit
- // 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.
+ constructor (type, eventInitDict) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' })
- // 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.
+ super(type, eventInitDict)
- 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.
+ type = webidl.converters.DOMString(type)
+ eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {})
- return makeFilteredResponse(response, {
- type: 'opaqueredirect',
- status: 0,
- statusText: '',
- headersList: [],
- body: null
- })
- } else {
- assert(false)
+ this.#eventInit = eventInitDict
}
-}
-
-// 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 }))
-}
+ get message () {
+ webidl.brandCheck(this, ErrorEvent)
-// 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.')
+ return this.#eventInit.message
}
- // 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')
- }
- }
+ get filename () {
+ webidl.brandCheck(this, ErrorEvent)
- // 3. Set response’s response’s status to init["status"].
- if ('status' in init && init.status != null) {
- response[kState].status = init.status
+ return this.#eventInit.filename
}
- // 4. Set response’s response’s status message to init["statusText"].
- if ('statusText' in init && init.statusText != null) {
- response[kState].statusText = init.statusText
- }
+ get lineno () {
+ webidl.brandCheck(this, ErrorEvent)
- // 5. If init["headers"] exists, then fill response’s headers with init["headers"].
- if ('headers' in init && init.headers != null) {
- fill(response[kHeaders], init.headers)
+ return this.#eventInit.lineno
}
- // 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.
- response[kState].body = body.body
+ get colno () {
+ webidl.brandCheck(this, ErrorEvent)
- // 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 && !response[kState].headersList.contains('Content-Type')) {
- response[kState].headersList.append('content-type', body.type)
- }
+ return this.#eventInit.colno
}
-}
-webidl.converters.ReadableStream = webidl.interfaceConverter(
- ReadableStream
-)
+ get error () {
+ webidl.brandCheck(this, ErrorEvent)
-webidl.converters.FormData = webidl.interfaceConverter(
- FormData
-)
+ return this.#eventInit.error
+ }
+}
-webidl.converters.URLSearchParams = webidl.interfaceConverter(
- URLSearchParams
-)
+Object.defineProperties(MessageEvent.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'MessageEvent',
+ configurable: true
+ },
+ data: kEnumerableProperty,
+ origin: kEnumerableProperty,
+ lastEventId: kEnumerableProperty,
+ source: kEnumerableProperty,
+ ports: kEnumerableProperty,
+ initMessageEvent: kEnumerableProperty
+})
-// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit
-webidl.converters.XMLHttpRequestBodyInit = function (V) {
- if (typeof V === 'string') {
- return webidl.converters.USVString(V)
- }
+Object.defineProperties(CloseEvent.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'CloseEvent',
+ configurable: true
+ },
+ reason: kEnumerableProperty,
+ code: kEnumerableProperty,
+ wasClean: kEnumerableProperty
+})
- if (isBlobLike(V)) {
- return webidl.converters.Blob(V, { strict: false })
- }
+Object.defineProperties(ErrorEvent.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'ErrorEvent',
+ configurable: true
+ },
+ message: kEnumerableProperty,
+ filename: kEnumerableProperty,
+ lineno: kEnumerableProperty,
+ colno: kEnumerableProperty,
+ error: kEnumerableProperty
+})
- if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) {
- return webidl.converters.BufferSource(V)
- }
+webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort)
- if (util.isFormDataLike(V)) {
- return webidl.converters.FormData(V, { strict: false })
- }
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.MessagePort
+)
- if (V instanceof URLSearchParams) {
- return webidl.converters.URLSearchParams(V)
+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
}
+]
- return webidl.converters.DOMString(V)
-}
-
-// https://fetch.spec.whatwg.org/#bodyinit
-webidl.converters.BodyInit = function (V) {
- if (V instanceof ReadableStream) {
- return webidl.converters.ReadableStream(V)
+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'],
+ get defaultValue () {
+ return []
+ }
}
+])
- // Note: the spec doesn't include async iterables,
- // this is an undici extension.
- if (V?.[Symbol.asyncIterator]) {
- return V
+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: ''
}
+])
- return webidl.converters.XMLHttpRequestBodyInit(V)
-}
-
-webidl.converters.ResponseInit = webidl.dictionaryConverter([
+webidl.converters.ErrorEventInit = webidl.dictionaryConverter([
+ ...eventInit,
{
- key: 'status',
- converter: webidl.converters['unsigned short'],
- defaultValue: 200
+ key: 'message',
+ converter: webidl.converters.DOMString,
+ defaultValue: ''
},
{
- key: 'statusText',
- converter: webidl.converters.ByteString,
+ key: 'filename',
+ converter: webidl.converters.USVString,
defaultValue: ''
},
{
- key: 'headers',
- converter: webidl.converters.HeadersInit
+ 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 = {
- makeNetworkError,
- makeResponse,
- makeAppropriateNetworkError,
- filterResponse,
- Response,
- cloneResponse
-}
-
-
-/***/ }),
-
-/***/ 9710:
-/***/ ((module) => {
-
-"use strict";
-
-
-module.exports = {
- kUrl: Symbol('url'),
- kHeaders: Symbol('headers'),
- kSignal: Symbol('signal'),
- kState: Symbol('state'),
- kGuard: Symbol('guard'),
- kRealm: Symbol('realm')
+ MessageEvent,
+ CloseEvent,
+ ErrorEvent
}
/***/ }),
-/***/ 5523:
+/***/ 31237:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(7326)
-const { getGlobalOrigin } = __nccwpck_require__(5628)
-const { performance } = __nccwpck_require__(2987)
-const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(3440)
-const assert = __nccwpck_require__(2613)
-const { isUint8Array } = __nccwpck_require__(8253)
-
-let supportedHashes = []
+const { maxUnsigned16Bit } = __nccwpck_require__(45913)
-// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable
-/** @type {import('crypto')|undefined} */
+/** @type {import('crypto')} */
let crypto
-
try {
- crypto = __nccwpck_require__(6982)
- const possibleRelevantHashes = ['sha256', 'sha384', 'sha512']
- supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash))
-/* c8 ignore next 3 */
+ crypto = __nccwpck_require__(76982)
} 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
+class WebsocketFrameSend {
+ /**
+ * @param {Buffer|undefined} data
+ */
+ constructor (data) {
+ this.frameData = data
+ this.maskKey = crypto.randomBytes(4)
}
- // 2. Let location be the result of extracting header list values given
- // `Location` and response’s header list.
- let location = response.headersList.get('location')
+ createFrame (opcode) {
+ const bodyLength = this.frameData?.byteLength ?? 0
- // 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)) {
- location = new URL(location, responseURL(response))
- }
+ /** @type {number} */
+ let payloadLength = bodyLength // 0-125
+ let offset = 6
- // 4. If location is a URL whose fragment is null, then set location’s
- // fragment to requestFragment.
- if (location && !location.hash) {
- location.hash = requestFragment
- }
+ 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
+ }
- // 5. Return location.
- return location
-}
+ const buffer = Buffer.allocUnsafe(bodyLength + offset)
-/** @returns {URL} */
-function requestCurrentURL (request) {
- return request.urlList[request.urlList.length - 1]
-}
+ // Clear first 2 bytes, everything else is overwritten
+ buffer[0] = buffer[1] = 0
+ buffer[0] |= 0x80 // FIN
+ buffer[0] = (buffer[0] & 0xF0) + opcode // opcode
-function requestBadPort (request) {
- // 1. Let url be request’s current URL.
- const url = requestCurrentURL(request)
+ /*! ws. MIT License. Einar Otto Stangvik */
+ buffer[offset - 4] = this.maskKey[0]
+ buffer[offset - 3] = this.maskKey[1]
+ buffer[offset - 2] = this.maskKey[2]
+ buffer[offset - 1] = this.maskKey[3]
- // 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'
- }
+ buffer[1] = payloadLength
- // 3. Return allowed.
- return 'allowed'
-}
+ 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)
+ }
-function isErrorLike (object) {
- return object instanceof Error || (
- object?.constructor?.name === 'Error' ||
- object?.constructor?.name === 'DOMException'
- )
-}
+ buffer[1] |= 0x80 // MASK
-// 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
+ // mask body
+ for (let i = 0; i < bodyLength; i++) {
+ buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4]
}
- }
- return true
-}
-/**
- * @see https://tools.ietf.org/html/rfc7230#section-3.2.6
- * @param {number} c
- */
-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
+ return buffer
}
}
-/**
- * @param {string} characters
- */
-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
+module.exports = {
+ WebsocketFrameSend
}
-/**
- * @see https://fetch.spec.whatwg.org/#header-name
- * @param {string} potentialValue
- */
-function isValidHeaderName (potentialValue) {
- return isValidHTTPToken(potentialValue)
-}
-/**
- * @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.
- if (
- potentialValue.startsWith('\t') ||
- potentialValue.startsWith(' ') ||
- potentialValue.endsWith('\t') ||
- potentialValue.endsWith(' ')
- ) {
- return false
- }
+/***/ }),
- if (
- potentialValue.includes('\0') ||
- potentialValue.includes('\r') ||
- potentialValue.includes('\n')
- ) {
- return false
- }
+/***/ 43171:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- return true
-}
+"use strict";
-// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect
-function setRequestReferrerPolicyOnRedirect (request, actualResponse) {
- // 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.
- // 1. Let policy be the result of executing § 8.1 Parse a referrer policy
- // from a Referrer-Policy header on actualResponse.
+const { Writable } = __nccwpck_require__(2203)
+const diagnosticsChannel = __nccwpck_require__(31637)
+const { parserStates, opcodes, states, emptyBuffer } = __nccwpck_require__(45913)
+const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(62933)
+const { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = __nccwpck_require__(3574)
+const { WebsocketFrameSend } = __nccwpck_require__(31237)
- // 8.1 Parse a referrer policy from a Referrer-Policy header
- // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list.
- const { headersList } = actualResponse
- // 2. Let policy be the empty string.
- // 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.
- // 4. Return policy.
- const policyHeader = (headersList.get('referrer-policy') ?? '').split(',')
+// 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
- // 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
- let policy = ''
- if (policyHeader.length > 0) {
- // 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
- }
- }
+const channels = {}
+channels.ping = diagnosticsChannel.channel('undici:websocket:ping')
+channels.pong = diagnosticsChannel.channel('undici:websocket:pong')
+
+class ByteParser extends Writable {
+ #buffers = []
+ #byteOffset = 0
+
+ #state = parserStates.INFO
+
+ #info = {}
+ #fragments = []
+
+ constructor (ws) {
+ super()
+
+ this.ws = ws
}
- // 2. If policy is not the empty string, then set request’s referrer policy to policy.
- if (policy !== '') {
- request.referrerPolicy = policy
+ /**
+ * @param {Buffer} chunk
+ * @param {() => void} callback
+ */
+ _write (chunk, _, callback) {
+ this.#buffers.push(chunk)
+ this.#byteOffset += chunk.length
+
+ this.run(callback)
}
-}
-// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check
-function crossOriginResourcePolicyCheck () {
- // TODO
- return 'allowed'
-}
+ /**
+ * 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 (true) {
+ if (this.#state === parserStates.INFO) {
+ // If there aren't enough bytes to parse the payload length, etc.
+ if (this.#byteOffset < 2) {
+ return callback()
+ }
-// https://fetch.spec.whatwg.org/#concept-cors-check
-function corsCheck () {
- // TODO
- return 'success'
-}
+ const buffer = this.consume(2)
-// https://fetch.spec.whatwg.org/#concept-tao-check
-function TAOCheck () {
- // TODO
- return 'success'
-}
+ this.#info.fin = (buffer[0] & 0x80) !== 0
+ this.#info.opcode = buffer[0] & 0x0F
-function appendFetchMetadata (httpRequest) {
- // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header
- // TODO
+ // If we receive a fragmented message, we use the type of the first
+ // frame to parse the full message as binary/text, when it's terminated
+ this.#info.originalOpcode ??= this.#info.opcode
- // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header
+ this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION
+
+ if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) {
+ // Only text and binary frames can be fragmented
+ failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.')
+ return
+ }
+
+ const payloadLength = buffer[1] & 0x7F
+
+ 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 (this.#info.fragmented && payloadLength > 125) {
+ // A fragmented frame can't be fragmented itself
+ failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.')
+ return
+ } else if (
+ (this.#info.opcode === opcodes.PING ||
+ this.#info.opcode === opcodes.PONG ||
+ this.#info.opcode === opcodes.CLOSE) &&
+ payloadLength > 125
+ ) {
+ // Control frames can have a payload length of 125 bytes MAX
+ failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.')
+ return
+ } else if (this.#info.opcode === opcodes.CLOSE) {
+ if (payloadLength === 1) {
+ failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.')
+ return
+ }
- // 1. Assert: r’s url is a potentially trustworthy URL.
- // TODO
+ const body = this.consume(payloadLength)
- // 2. Let header be a Structured Header whose value is a token.
- let header = null
+ this.#info.closeInfo = this.parseCloseBody(false, body)
- // 3. Set header’s value to r’s mode.
- header = httpRequest.mode
+ if (!this.ws[kSentClose]) {
+ // 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.)
+ const body = Buffer.allocUnsafe(2)
+ body.writeUInt16BE(this.#info.closeInfo.code, 0)
+ const closeFrame = new WebsocketFrameSend(body)
- // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list.
- httpRequest.headersList.set('sec-fetch-mode', header)
+ this.ws[kResponse].socket.write(
+ closeFrame.createFrame(opcodes.CLOSE),
+ (err) => {
+ if (!err) {
+ this.ws[kSentClose] = true
+ }
+ }
+ )
+ }
- // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header
- // TODO
+ // 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.ws[kReadyState] = states.CLOSING
+ this.ws[kReceivedClose] = true
- // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header
- // TODO
-}
+ this.end()
-// 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.
- let serializedOrigin = request.origin
+ return
+ } else if (this.#info.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"
- // 2. If request’s response tainting is "cors" or request’s mode is "websocket", then append (`Origin`, serializedOrigin) to request’s header list.
- if (request.responseTainting === 'cors' || request.mode === 'websocket') {
- if (serializedOrigin) {
- request.headersList.append('origin', serializedOrigin)
- }
+ const body = this.consume(payloadLength)
- // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then:
- } 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.
- }
+ if (!this.ws[kReceivedClose]) {
+ const frame = new WebsocketFrameSend(body)
- if (serializedOrigin) {
- // 2. Append (`Origin`, serializedOrigin) to request’s header list.
- request.headersList.append('origin', serializedOrigin)
- }
- }
-}
+ this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG))
-function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) {
- // TODO
- return performance.now()
-}
+ if (channels.ping.hasSubscribers) {
+ channels.ping.publish({
+ payload: body
+ })
+ }
+ }
-// 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
- }
-}
+ this.#state = parserStates.INFO
-// 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'
- }
-}
+ if (this.#byteOffset > 0) {
+ continue
+ } else {
+ callback()
+ return
+ }
+ } else if (this.#info.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.
-// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container
-function clonePolicyContainer (policyContainer) {
- return {
- referrerPolicy: policyContainer.referrerPolicy
- }
-}
+ const body = this.consume(payloadLength)
-// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
-function determineRequestsReferrer (request) {
- // 1. Let policy be request's referrer policy.
- const policy = request.referrerPolicy
+ if (channels.pong.hasSubscribers) {
+ channels.pong.publish({
+ payload: body
+ })
+ }
- // Note: policy cannot (shouldn't) be null or an empty string.
- assert(policy)
+ if (this.#byteOffset > 0) {
+ continue
+ } else {
+ callback()
+ return
+ }
+ }
+ } else if (this.#state === parserStates.PAYLOADLENGTH_16) {
+ if (this.#byteOffset < 2) {
+ return callback()
+ }
- // 2. Let environment be request’s client.
+ const buffer = this.consume(2)
- let referrerSource = null
+ this.#info.payloadLength = buffer.readUInt16BE(0)
+ this.#state = parserStates.READ_DATA
+ } else if (this.#state === parserStates.PAYLOADLENGTH_64) {
+ if (this.#byteOffset < 8) {
+ return callback()
+ }
- // 3. Switch on request’s referrer:
- 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 buffer = this.consume(8)
+ const upper = buffer.readUInt32BE(0)
- const globalOrigin = getGlobalOrigin()
+ // 2^31 is the maxinimum 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.ws, 'Received payload length > 2^31 bytes.')
+ return
+ }
- if (!globalOrigin || globalOrigin.origin === 'null') {
- return 'no-referrer'
- }
+ const lower = buffer.readUInt32BE(4)
- // note: we need to clone it as it's mutated
- referrerSource = new URL(globalOrigin)
- } else if (request.referrer instanceof URL) {
- // Let referrerSource be request’s referrer.
- referrerSource = request.referrer
- }
+ this.#info.payloadLength = (upper << 8) + lower
+ this.#state = parserStates.READ_DATA
+ } else if (this.#state === parserStates.READ_DATA) {
+ if (this.#byteOffset < this.#info.payloadLength) {
+ // If there is still more data in this chunk that needs to be read
+ return callback()
+ } else if (this.#byteOffset >= this.#info.payloadLength) {
+ // If the server sent multiple frames in a single chunk
- // 4. Let request’s referrerURL be the result of stripping referrerSource for
- // use as a referrer.
- let referrerURL = stripURLForReferrer(referrerSource)
+ const body = this.consume(this.#info.payloadLength)
- // 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)
+ this.#fragments.push(body)
- // 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
- }
+ // If the frame is unfragmented, or a fragmented frame was terminated,
+ // a message was received
+ if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) {
+ const fullMessage = Buffer.concat(this.#fragments)
- const areSameOrigin = sameOrigin(request, referrerURL)
- const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) &&
- !isURLPotentiallyTrustworthy(request.url)
+ websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage)
- // 8. Execute the switch statements corresponding to the value of policy:
- switch (policy) {
- case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true)
- case 'unsafe-url': return referrerURL
- case 'same-origin':
- return areSameOrigin ? referrerOrigin : 'no-referrer'
- case 'origin-when-cross-origin':
- return areSameOrigin ? referrerURL : referrerOrigin
- case 'strict-origin-when-cross-origin': {
- const currentURL = requestCurrentURL(request)
+ this.#info = {}
+ this.#fragments.length = 0
+ }
- // 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
+ this.#state = parserStates.INFO
+ }
}
- // 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'
+ if (this.#byteOffset > 0) {
+ continue
+ } else {
+ callback()
+ break
}
-
- // 3. Return referrerOrigin.
- return referrerOrigin
}
- case 'strict-origin': // eslint-disable-line
- /**
- * 1. If referrerURL is a potentially trustworthy URL and
- * request’s current URL is not a potentially trustworthy URL,
- * then return no referrer.
- * 2. Return referrerOrigin
- */
- case 'no-referrer-when-downgrade': // eslint-disable-line
- /**
- * 1. If referrerURL is a potentially trustworthy URL and
- * request’s current URL is not a potentially trustworthy URL,
- * then return no referrer.
- * 2. Return referrerOrigin
- */
-
- default: // eslint-disable-line
- return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin
- }
-}
-
-/**
- * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url
- * @param {URL} url
- * @param {boolean|undefined} originOnly
- */
-function stripURLForReferrer (url, originOnly) {
- // 1. Assert: url is a URL.
- assert(url instanceof URL)
-
- // 2. If url’s scheme is a local scheme, then return no referrer.
- if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') {
- 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 = ''
+ /**
+ * Take n bytes from the buffered Buffers
+ * @param {number} n
+ * @returns {Buffer|null}
+ */
+ consume (n) {
+ if (n > this.#byteOffset) {
+ return null
+ } else if (n === 0) {
+ return emptyBuffer
+ }
- // 5. Set url’s fragment to null.
- url.hash = ''
+ if (this.#buffers[0].length === n) {
+ this.#byteOffset -= this.#buffers[0].length
+ return this.#buffers.shift()
+ }
- // 6. If the origin-only flag is true, then:
- if (originOnly) {
- // 1. Set url’s path to « the empty string ».
- url.pathname = ''
+ const buffer = Buffer.allocUnsafe(n)
+ let offset = 0
- // 2. Set url’s query to null.
- url.search = ''
- }
+ while (offset !== n) {
+ const next = this.#buffers[0]
+ const { length } = next
- // 7. Return url.
- return url
-}
+ 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 += next.length
+ }
+ }
-function isURLPotentiallyTrustworthy (url) {
- if (!(url instanceof URL)) {
- return false
- }
+ this.#byteOffset -= n
- // If child of about, return true
- if (url.href === 'about:blank' || url.href === 'about:srcdoc') {
- return true
+ return buffer
}
- // If scheme is data, return true
- if (url.protocol === 'data:') return true
+ parseCloseBody (onlyCode, data) {
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5
+ /** @type {number|undefined} */
+ let code
- // If file, return true
- if (url.protocol === 'file:') return true
+ 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)
+ }
- return isOriginPotentiallyTrustworthy(url.origin)
+ if (onlyCode) {
+ if (!isValidStatusCode(code)) {
+ return null
+ }
- function isOriginPotentiallyTrustworthy (origin) {
- // If origin is explicitly null, return false
- if (origin == null || origin === 'null') return false
+ return { code }
+ }
- const originAsURL = new URL(origin)
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6
+ /** @type {Buffer} */
+ let reason = data.subarray(2)
- // If secure, return true
- if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') {
- return true
+ // Remove BOM
+ if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) {
+ reason = reason.subarray(3)
}
- // If localhost or variants, return true
- if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) ||
- (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) ||
- (originAsURL.hostname.endsWith('.localhost'))) {
- return true
+ if (code !== undefined && !isValidStatusCode(code)) {
+ return null
}
- // If any other, return false
- return false
- }
-}
-
-/**
- * @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)
+ try {
+ // TODO: optimize this
+ reason = new TextDecoder('utf-8', { fatal: true }).decode(reason)
+ } catch {
+ return null
+ }
- // 2. If parsedMetadata is no metadata, return true.
- if (parsedMetadata === 'no metadata') {
- return true
+ return { code, reason }
}
- // 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
+ get closingInfo () {
+ return this.#info.closeInfo
}
+}
- // 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
+module.exports = {
+ ByteParser
+}
- // 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')
+/***/ 62933:
+/***/ ((module) => {
- if (actualValue[actualValue.length - 1] === '=') {
- if (actualValue[actualValue.length - 2] === '=') {
- actualValue = actualValue.slice(0, -2)
- } else {
- actualValue = actualValue.slice(0, -1)
- }
- }
+"use strict";
- // 4. If actualValue is a case-sensitive match for expectedValue,
- // return true.
- if (compareBase64Mixed(actualValue, expectedValue)) {
- return true
- }
- }
- // 7. Return false.
- return false
+module.exports = {
+ kWebSocketURL: Symbol('url'),
+ kReadyState: Symbol('ready state'),
+ kController: Symbol('controller'),
+ kResponse: Symbol('response'),
+ kBinaryType: Symbol('binary type'),
+ kSentClose: Symbol('sent close'),
+ kReceivedClose: Symbol('received close'),
+ kByteParser: Symbol('byte parser')
}
-// 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)
+/***/ 3574:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 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
- }
+"use strict";
- // 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)
- }
- }
+const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(62933)
+const { states, opcodes } = __nccwpck_require__(45913)
+const { MessageEvent, ErrorEvent } = __nccwpck_require__(46255)
- // 4. Return no metadata if empty is true, otherwise return result.
- if (empty === true) {
- return 'no metadata'
- }
+/* globals Blob */
- return result
+/**
+ * @param {import('./websocket').WebSocket} ws
+ */
+function isEstablished (ws) {
+ // 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 ws[kReadyState] === states.OPEN
}
/**
- * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList
+ * @param {import('./websocket').WebSocket} ws
*/
-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
- }
+function isClosing (ws) {
+ // 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 ws[kReadyState] === states.CLOSING
+}
- 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
+/**
+ * @param {import('./websocket').WebSocket} ws
+ */
+function isClosed (ws) {
+ return ws[kReadyState] === states.CLOSED
}
-function filterMetadataListByAlgorithm (metadataList, algorithm) {
- if (metadataList.length === 1) {
- return metadataList
+/**
+ * @see https://dom.spec.whatwg.org/#concept-event-fire
+ * @param {string} e
+ * @param {EventTarget} target
+ * @param {EventInit | undefined} eventInitDict
+ */
+function fireEvent (e, target, eventConstructor = Event, 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 = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap
+
+ // 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').WebSocket} ws
+ * @param {number} type Opcode
+ * @param {Buffer} data application data
+ */
+function websocketMessageReceived (ws, type, data) {
+ // 1. If ready state is not OPEN (1), then return.
+ if (ws[kReadyState] !== states.OPEN) {
+ return
}
- let pos = 0
- for (let i = 0; i < metadataList.length; ++i) {
- if (metadataList[i].algo === algorithm) {
- metadataList[pos++] = metadataList[i]
+ // 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 = new TextDecoder('utf-8', { fatal: true }).decode(data)
+ } catch {
+ failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.')
+ return
+ }
+ } else if (type === opcodes.BINARY) {
+ if (ws[kBinaryType] === '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 = new Uint8Array(data).buffer
}
}
- metadataList.length = pos
-
- return metadataList
+ // 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', ws, MessageEvent, {
+ origin: ws[kWebSocketURL].origin,
+ data: dataForEvent
+ })
}
/**
- * Compares two base64 strings, allowing for base64url
- * in the second string.
- *
-* @param {string} actualValue always base64
- * @param {string} expectedValue base64 or base64url
- * @returns {boolean}
+ * @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
*/
-function compareBase64Mixed (actualValue, expectedValue) {
- if (actualValue.length !== expectedValue.length) {
+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 < actualValue.length; ++i) {
- if (actualValue[i] !== expectedValue[i]) {
- if (
- (actualValue[i] === '+' && expectedValue[i] === '-') ||
- (actualValue[i] === '/' && expectedValue[i] === '_')
- ) {
- continue
- }
+
+ for (const char of protocol) {
+ const code = char.charCodeAt(0)
+
+ if (
+ code < 0x21 ||
+ code > 0x7E ||
+ char === '(' ||
+ char === ')' ||
+ char === '<' ||
+ char === '>' ||
+ char === '@' ||
+ char === ',' ||
+ char === ';' ||
+ char === ':' ||
+ char === '\\' ||
+ char === '"' ||
+ char === '/' ||
+ char === '[' ||
+ char === ']' ||
+ char === '?' ||
+ char === '=' ||
+ char === '{' ||
+ char === '}' ||
+ code === 32 || // SP
+ code === 9 // HT
+ ) {
return false
}
}
@@ -66957,7541 +109574,11237 @@ function compareBase64Mixed (actualValue, expectedValue) {
return true
}
-// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request
-function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) {
- // TODO
+/**
+ * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4
+ * @param {number} code
+ */
+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
}
/**
- * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin}
- * @param {URL} A
- * @param {URL} B
+ * @param {import('./websocket').WebSocket} ws
+ * @param {string|undefined} reason
*/
-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
- }
+function failWebsocketConnection (ws, reason) {
+ const { [kController]: controller, [kResponse]: response } = ws
- // 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
+ controller.abort()
+
+ if (response?.socket && !response.socket.destroyed) {
+ response.socket.destroy()
}
- // 3. Return false.
- return false
+ if (reason) {
+ fireEvent('error', ws, ErrorEvent, {
+ error: new Error(reason)
+ })
+ }
}
-function createDeferredPromise () {
- let res
- let rej
- const promise = new Promise((resolve, reject) => {
- res = resolve
- rej = reject
- })
-
- return { promise, resolve: res, reject: rej }
+module.exports = {
+ isEstablished,
+ isClosing,
+ isClosed,
+ fireEvent,
+ isValidSubprotocol,
+ isValidStatusCode,
+ failWebsocketConnection,
+ websocketMessageReceived
}
-function isAborted (fetchParams) {
- return fetchParams.controller.state === 'aborted'
-}
-function isCancelled (fetchParams) {
- return fetchParams.controller.state === 'aborted' ||
- fetchParams.controller.state === 'terminated'
-}
+/***/ }),
-const normalizeMethodRecord = {
- delete: 'DELETE',
- DELETE: 'DELETE',
- get: 'GET',
- GET: 'GET',
- head: 'HEAD',
- HEAD: 'HEAD',
- options: 'OPTIONS',
- OPTIONS: 'OPTIONS',
- post: 'POST',
- POST: 'POST',
- put: 'PUT',
- PUT: 'PUT'
-}
+/***/ 55171:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
-Object.setPrototypeOf(normalizeMethodRecord, null)
+"use strict";
-/**
- * @see https://fetch.spec.whatwg.org/#concept-method-normalize
- * @param {string} method
- */
-function normalizeMethod (method) {
- return normalizeMethodRecord[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)
+const { webidl } = __nccwpck_require__(74222)
+const { DOMException } = __nccwpck_require__(87326)
+const { URLSerializer } = __nccwpck_require__(94322)
+const { getGlobalOrigin } = __nccwpck_require__(75628)
+const { staticPropertyDescriptors, states, opcodes, emptyBuffer } = __nccwpck_require__(45913)
+const {
+ kWebSocketURL,
+ kReadyState,
+ kController,
+ kBinaryType,
+ kResponse,
+ kSentClose,
+ kByteParser
+} = __nccwpck_require__(62933)
+const { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = __nccwpck_require__(3574)
+const { establishWebSocketConnection } = __nccwpck_require__(68550)
+const { WebsocketFrameSend } = __nccwpck_require__(31237)
+const { ByteParser } = __nccwpck_require__(43171)
+const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(3440)
+const { getGlobalDispatcher } = __nccwpck_require__(32581)
+const { types } = __nccwpck_require__(39023)
- // 2. If result is undefined, then throw a TypeError.
- if (result === undefined) {
- throw new TypeError('Value is not JSON serializable')
+let experimentalWarned = false
+
+// https://websockets.spec.whatwg.org/#interface-definition
+class WebSocket extends EventTarget {
+ #events = {
+ open: null,
+ error: null,
+ close: null,
+ message: null
}
- // 3. Assert: result is a string.
- assert(typeof result === 'string')
+ #bufferedAmount = 0
+ #protocol = ''
+ #extensions = ''
- // 4. Return result.
- return result
-}
+ /**
+ * @param {string} url
+ * @param {string|string[]} protocols
+ */
+ constructor (url, protocols = []) {
+ super()
-// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object
-const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))
+ webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' })
-/**
- * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
- * @param {() => unknown[]} iterator
- * @param {string} name name of the instance
- * @param {'key'|'value'|'key+value'} kind
- */
-function makeIterator (iterator, name, kind) {
- const object = {
- index: 0,
- kind,
- target: iterator
- }
+ if (!experimentalWarned) {
+ experimentalWarned = true
+ process.emitWarning('WebSockets are experimental, expect them to change at any time.', {
+ code: 'UNDICI-WS'
+ })
+ }
- const i = {
- next () {
- // 1. Let interface be the interface for which the iterator prototype object exists.
+ const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols)
- // 2. Let thisValue be the this value.
+ url = webidl.converters.USVString(url)
+ protocols = options.protocols
- // 3. Let object be ? ToObject(thisValue).
+ // 1. Let baseURL be this's relevant settings object's API base URL.
+ const baseURL = getGlobalOrigin()
- // 4. If object is a platform object, then perform a security
- // check, passing:
+ // 1. Let urlRecord be the result of applying the URL parser to url with baseURL.
+ let urlRecord
- // 5. If object is not a default iterator object for interface,
- // then throw a TypeError.
- if (Object.getPrototypeOf(this) !== i) {
- throw new TypeError(
- `'next' called on an object that does not implement interface ${name} Iterator.`
- )
- }
+ try {
+ urlRecord = new URL(url, baseURL)
+ } catch (e) {
+ // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException.
+ throw new DOMException(e, 'SyntaxError')
+ }
- // 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, kind, target } = object
- const values = target()
+ // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws".
+ if (urlRecord.protocol === 'http:') {
+ urlRecord.protocol = 'ws:'
+ } else if (urlRecord.protocol === 'https:') {
+ // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss".
+ urlRecord.protocol = 'wss:'
+ }
- // 9. Let len be the length of values.
- const len = values.length
+ // 6. 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: protocol, got ${urlRecord.protocol}`,
+ 'SyntaxError'
+ )
+ }
- // 10. If index is greater than or equal to len, then return
- // CreateIterResultObject(undefined, true).
- if (index >= len) {
- return { value: undefined, done: true }
- }
+ // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError"
+ // DOMException.
+ if (urlRecord.hash || urlRecord.href.endsWith('#')) {
+ throw new DOMException('Got fragment', 'SyntaxError')
+ }
- // 11. Let pair be the entry in values at index index.
- const pair = values[index]
+ // 8. If protocols is a string, set protocols to a sequence consisting
+ // of just that string.
+ if (typeof protocols === 'string') {
+ protocols = [protocols]
+ }
- // 12. Set object’s index to index + 1.
- object.index = index + 1
+ // 9. 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')
+ }
- // 13. Return the iterator result for pair and kind.
- return iteratorResult(pair, kind)
- },
- // The class string of an iterator prototype object for a given interface is the
- // result of concatenating the identifier of the interface and the string " Iterator".
- [Symbol.toStringTag]: `${name} Iterator`
- }
+ if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) {
+ throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')
+ }
- // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%.
- Object.setPrototypeOf(i, esIteratorPrototype)
- // esIteratorPrototype needs to be the prototype of i
- // which is the prototype of an empty object. Yes, it's confusing.
- return Object.setPrototypeOf({}, i)
-}
+ // 10. Set this's url to urlRecord.
+ this[kWebSocketURL] = new URL(urlRecord.href)
-// https://webidl.spec.whatwg.org/#iterator-result
-function iteratorResult (pair, kind) {
- let result
+ // 11. Let client be this's relevant settings object.
- // 1. Let result be a value determined by the value of kind:
- switch (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 = pair[0]
- break
+ // 12. Run this step in parallel:
+
+ // 1. Establish a WebSocket connection given urlRecord, protocols,
+ // and client.
+ this[kController] = establishWebSocketConnection(
+ urlRecord,
+ protocols,
+ this,
+ (response) => this.#onConnectionEstablished(response),
+ 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[kReadyState] = 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[kBinaryType] = '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)
+
+ if (code !== undefined) {
+ code = webidl.converters['unsigned short'](code, { clamp: true })
}
- 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 = pair[1]
- break
+
+ if (reason !== undefined) {
+ reason = webidl.converters.USVString(reason)
}
- 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 = pair
- break
+
+ // 1. If code is present, but is neither an integer equal to 1000 nor an
+ // integer in the range 3000 to 4999, inclusive, throw an
+ // "InvalidAccessError" DOMException.
+ if (code !== undefined) {
+ if (code !== 1000 && (code < 3000 || code > 4999)) {
+ throw new DOMException('invalid code', 'InvalidAccessError')
+ }
}
- }
- // 2. Return CreateIterResultObject(result, false).
- return { value: result, done: false }
-}
+ let reasonByteLength = 0
-/**
- * @see https://fetch.spec.whatwg.org/#body-fully-read
- */
-async function fullyReadBody (body, processBody, processBodyError) {
- // 1. If taskDestination is null, then set taskDestination to
- // the result of starting a new parallel queue.
+ // 2. If reason is present, then run these substeps:
+ if (reason !== undefined) {
+ // 1. Let reasonBytes be the result of encoding reason.
+ // 2. If reasonBytes is longer than 123 bytes, then throw a
+ // "SyntaxError" DOMException.
+ reasonByteLength = Buffer.byteLength(reason)
- // 2. Let successSteps given a byte sequence bytes be to queue a
- // fetch task to run processBody given bytes, with taskDestination.
- const successSteps = processBody
+ if (reasonByteLength > 123) {
+ throw new DOMException(
+ `Reason must be less than 123 bytes; received ${reasonByteLength}`,
+ 'SyntaxError'
+ )
+ }
+ }
- // 3. Let errorSteps be to queue a fetch task to run processBodyError,
- // with taskDestination.
- const errorSteps = processBodyError
+ // 3. Run the first matching steps from the following list:
+ if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) {
+ // If this's ready state is CLOSING (2) or CLOSED (3)
+ // Do nothing.
+ } else if (!isEstablished(this)) {
+ // If the WebSocket connection is not yet established
+ // Fail the WebSocket connection and set this's ready state
+ // to CLOSING (2).
+ failWebsocketConnection(this, 'Connection was closed before it was established.')
+ this[kReadyState] = WebSocket.CLOSING
+ } else if (!isClosing(this)) {
+ // If the WebSocket closing handshake has not yet been started
+ // Start the WebSocket closing handshake and set this's ready
+ // state to CLOSING (2).
+ // - 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 reason is also present, then reasonBytes must be
+ // provided in the Close message after the status code.
- // 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.
- let reader
+ const frame = new WebsocketFrameSend()
- try {
- reader = body.stream.getReader()
- } catch (e) {
- errorSteps(e)
- return
- }
+ // If neither code nor reason is present, the WebSocket Close
+ // message must not have a body.
- // 5. Read all bytes from reader, given successSteps and errorSteps.
- try {
- const result = await readAllBytes(reader)
- successSteps(result)
- } catch (e) {
- errorSteps(e)
- }
-}
+ // If code is present, then the status code to use in the
+ // WebSocket Close message must be the integer given by code.
+ if (code !== undefined && reason === undefined) {
+ frame.frameData = Buffer.allocUnsafe(2)
+ frame.frameData.writeUInt16BE(code, 0)
+ } else if (code !== undefined && reason !== undefined) {
+ // If reason is also present, then reasonBytes must be
+ // provided in the Close message after the status code.
+ frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength)
+ 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
+ }
-/** @type {ReadableStream} */
-let ReadableStream = globalThis.ReadableStream
+ /** @type {import('stream').Duplex} */
+ const socket = this[kResponse].socket
-function isReadableStreamLike (stream) {
- if (!ReadableStream) {
- ReadableStream = (__nccwpck_require__(3774).ReadableStream)
+ socket.write(frame.createFrame(opcodes.CLOSE), (err) => {
+ if (!err) {
+ this[kSentClose] = true
+ }
+ })
+
+ // 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[kReadyState] = states.CLOSING
+ } else {
+ // Otherwise
+ // Set this's ready state to CLOSING (2).
+ this[kReadyState] = WebSocket.CLOSING
+ }
}
- return stream instanceof ReadableStream || (
- stream[Symbol.toStringTag] === 'ReadableStream' &&
- typeof stream.tee === 'function'
- )
-}
+ /**
+ * @see https://websockets.spec.whatwg.org/#dom-websocket-send
+ * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data
+ */
+ send (data) {
+ webidl.brandCheck(this, WebSocket)
-const MAXIMUM_ARGUMENT_LENGTH = 65535
+ webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' })
-/**
- * @see https://infra.spec.whatwg.org/#isomorphic-decode
- * @param {number[]|Uint8Array} input
- */
-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.
+ data = webidl.converters.WebSocketSendData(data)
- if (input.length < MAXIMUM_ARGUMENT_LENGTH) {
- return String.fromCharCode(...input)
- }
+ // 1. If this's ready state is CONNECTING, then throw an
+ // "InvalidStateError" DOMException.
+ if (this[kReadyState] === WebSocket.CONNECTING) {
+ throw new DOMException('Sent before connected.', 'InvalidStateError')
+ }
- return input.reduce((previous, current) => previous + String.fromCharCode(current), '')
-}
+ // 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
-/**
- * @param {ReadableStreamController} controller
- */
-function readableStreamClose (controller) {
- try {
- controller.close()
- } catch (err) {
- // TODO: add comment explaining why this error occurs.
- if (!err.message.includes('Controller is already closed')) {
- throw err
+ if (!isEstablished(this) || isClosing(this)) {
+ return
}
- }
-}
-/**
- * @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.
- for (let i = 0; i < input.length; i++) {
- assert(input.charCodeAt(i) <= 0xFF)
- }
+ /** @type {import('stream').Duplex} */
+ const socket = this[kResponse].socket
- // 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
-}
+ // 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.
-/**
- * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes
- * @see https://streams.spec.whatwg.org/#read-loop
- * @param {ReadableStreamDefaultReader} reader
- */
-async function readAllBytes (reader) {
- const bytes = []
- let byteLength = 0
+ const value = Buffer.from(data)
+ const frame = new WebsocketFrameSend(value)
+ const buffer = frame.createFrame(opcodes.TEXT)
- while (true) {
- const { done, value: chunk } = await reader.read()
+ this.#bufferedAmount += value.byteLength
+ socket.write(buffer, () => {
+ this.#bufferedAmount -= value.byteLength
+ })
+ } 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.
- if (done) {
- // 1. Call successSteps with bytes.
- return Buffer.concat(bytes, byteLength)
- }
+ const value = Buffer.from(data)
+ const frame = new WebsocketFrameSend(value)
+ const buffer = frame.createFrame(opcodes.BINARY)
- // 1. If chunk is not a Uint8Array object, call failureSteps
- // with a TypeError and abort these steps.
- if (!isUint8Array(chunk)) {
- throw new TypeError('Received non-Uint8Array chunk')
- }
+ this.#bufferedAmount += value.byteLength
+ socket.write(buffer, () => {
+ this.#bufferedAmount -= value.byteLength
+ })
+ } 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.
- // 2. Append the bytes represented by chunk to bytes.
- bytes.push(chunk)
- byteLength += chunk.length
+ const ab = Buffer.from(data, data.byteOffset, data.byteLength)
- // 3. Read-loop given reader, bytes, successSteps, and failureSteps.
- }
-}
+ const frame = new WebsocketFrameSend(ab)
+ const buffer = frame.createFrame(opcodes.BINARY)
-/**
- * @see https://fetch.spec.whatwg.org/#is-local
- * @param {URL} url
- */
-function urlIsLocal (url) {
- assert('protocol' in url) // ensure it's a url object
+ this.#bufferedAmount += ab.byteLength
+ socket.write(buffer, () => {
+ this.#bufferedAmount -= ab.byteLength
+ })
+ } else if (isBlobLike(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.
- const protocol = url.protocol
+ const frame = new WebsocketFrameSend()
- return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:'
-}
+ data.arrayBuffer().then((ab) => {
+ const value = Buffer.from(ab)
+ frame.frameData = value
+ const buffer = frame.createFrame(opcodes.BINARY)
-/**
- * @param {string|URL} url
- */
-function urlHasHttpsScheme (url) {
- if (typeof url === 'string') {
- return url.startsWith('https:')
+ this.#bufferedAmount += value.byteLength
+ socket.write(buffer, () => {
+ this.#bufferedAmount -= value.byteLength
+ })
+ })
+ }
}
- return url.protocol === 'https:'
-}
+ get readyState () {
+ webidl.brandCheck(this, WebSocket)
-/**
- * @see https://fetch.spec.whatwg.org/#http-scheme
- * @param {URL} url
- */
-function urlIsHttpHttpsScheme (url) {
- assert('protocol' in url) // ensure it's a url object
+ // The readyState getter steps are to return this's ready state.
+ return this[kReadyState]
+ }
- const protocol = url.protocol
+ get bufferedAmount () {
+ webidl.brandCheck(this, WebSocket)
- return protocol === 'http:' || protocol === 'https:'
-}
+ return this.#bufferedAmount
+ }
-/**
- * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0.
- */
-const hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key))
+ get url () {
+ webidl.brandCheck(this, WebSocket)
-module.exports = {
- isAborted,
- isCancelled,
- createDeferredPromise,
- ReadableStreamFrom,
- toUSVString,
- tryUpgradeRequestToAPotentiallyTrustworthyURL,
- coarsenedSharedCurrentTime,
- determineRequestsReferrer,
- makePolicyContainer,
- clonePolicyContainer,
- appendFetchMetadata,
- appendRequestOriginHeader,
- TAOCheck,
- corsCheck,
- crossOriginResourcePolicyCheck,
- createOpaqueTimingInfo,
- setRequestReferrerPolicyOnRedirect,
- isValidHTTPToken,
- requestBadPort,
- requestCurrentURL,
- responseURL,
- responseLocationURL,
- isBlobLike,
- isURLPotentiallyTrustworthy,
- isValidReasonPhrase,
- sameOrigin,
- normalizeMethod,
- serializeJavascriptValueToJSONString,
- makeIterator,
- isValidHeaderName,
- isValidHeaderValue,
- hasOwn,
- isErrorLike,
- fullyReadBody,
- bytesMatch,
- isReadableStreamLike,
- readableStreamClose,
- isomorphicEncode,
- isomorphicDecode,
- urlIsLocal,
- urlHasHttpsScheme,
- urlIsHttpHttpsScheme,
- readAllBytes,
- normalizeMethodRecord,
- parseMetadata
-}
+ // The url getter steps are to return this's url, serialized.
+ return URLSerializer(this[kWebSocketURL])
+ }
+ get extensions () {
+ webidl.brandCheck(this, WebSocket)
-/***/ }),
+ return this.#extensions
+ }
-/***/ 4222:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ get protocol () {
+ webidl.brandCheck(this, WebSocket)
-"use strict";
+ return this.#protocol
+ }
+
+ get onopen () {
+ webidl.brandCheck(this, WebSocket)
+ return this.#events.open
+ }
-const { types } = __nccwpck_require__(9023)
-const { hasOwn, toUSVString } = __nccwpck_require__(5523)
+ set onopen (fn) {
+ webidl.brandCheck(this, WebSocket)
-/** @type {import('../../types/webidl').Webidl} */
-const webidl = {}
-webidl.converters = {}
-webidl.util = {}
-webidl.errors = {}
+ if (this.#events.open) {
+ this.removeEventListener('open', this.#events.open)
+ }
-webidl.errors.exception = function (message) {
- return new TypeError(`${message.header}: ${message.message}`)
-}
+ if (typeof fn === 'function') {
+ this.#events.open = fn
+ this.addEventListener('open', fn)
+ } else {
+ this.#events.open = null
+ }
+ }
-webidl.errors.conversionFailed = function (context) {
- const plural = context.types.length === 1 ? '' : ' one of'
- const message =
- `${context.argument} could not be converted to` +
- `${plural}: ${context.types.join(', ')}.`
+ get onerror () {
+ webidl.brandCheck(this, WebSocket)
- return webidl.errors.exception({
- header: context.prefix,
- message
- })
-}
+ return this.#events.error
+ }
-webidl.errors.invalidArgument = function (context) {
- return webidl.errors.exception({
- header: context.prefix,
- message: `"${context.value}" is an invalid ${context.type}.`
- })
-}
+ set onerror (fn) {
+ webidl.brandCheck(this, WebSocket)
-// https://webidl.spec.whatwg.org/#implements
-webidl.brandCheck = function (V, I, opts = undefined) {
- if (opts?.strict !== false && !(V instanceof I)) {
- throw new TypeError('Illegal invocation')
- } else {
- return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag]
+ 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
+ }
}
-}
-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.`,
- ...ctx
- })
+ get onclose () {
+ webidl.brandCheck(this, WebSocket)
+
+ return this.#events.close
}
-}
-webidl.illegalConstructor = function () {
- throw webidl.errors.exception({
- header: 'TypeError',
- message: 'Illegal constructor'
- })
-}
+ set onclose (fn) {
+ webidl.brandCheck(this, WebSocket)
-// 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'
- }
+ if (this.#events.close) {
+ this.removeEventListener('close', this.#events.close)
+ }
- return 'Object'
+ if (typeof fn === 'function') {
+ this.#events.close = fn
+ this.addEventListener('close', fn)
+ } else {
+ this.#events.close = null
}
}
-}
-// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint
-webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) {
- let upperBound
- let lowerBound
+ get onmessage () {
+ webidl.brandCheck(this, WebSocket)
- // 1. If bitLength is 64, then:
- if (bitLength === 64) {
- // 1. Let upperBound be 2^53 − 1.
- upperBound = Math.pow(2, 53) - 1
+ return this.#events.message
+ }
- // 2. If signedness is "unsigned", then let lowerBound be 0.
- if (signedness === 'unsigned') {
- lowerBound = 0
+ 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 {
- // 3. Otherwise let lowerBound be −2^53 + 1.
- lowerBound = Math.pow(-2, 53) + 1
+ this.#events.message = null
}
- } else if (signedness === 'unsigned') {
- // 2. Otherwise, if signedness is "unsigned", then:
+ }
- // 1. Let lowerBound be 0.
- lowerBound = 0
+ get binaryType () {
+ webidl.brandCheck(this, WebSocket)
- // 2. Let upperBound be 2^bitLength − 1.
- upperBound = Math.pow(2, bitLength) - 1
- } else {
- // 3. Otherwise:
+ return this[kBinaryType]
+ }
- // 1. Let lowerBound be -2^bitLength − 1.
- lowerBound = Math.pow(-2, bitLength) - 1
+ set binaryType (type) {
+ webidl.brandCheck(this, WebSocket)
- // 2. Let upperBound be 2^bitLength − 1 − 1.
- upperBound = Math.pow(2, bitLength - 1) - 1
+ if (type !== 'blob' && type !== 'arraybuffer') {
+ this[kBinaryType] = 'blob'
+ } else {
+ this[kBinaryType] = type
+ }
}
- // 4. Let x be ? ToNumber(V).
- let x = Number(V)
+ /**
+ * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
+ */
+ #onConnectionEstablished (response) {
+ // processResponse is called when the "response’s header list has been received and initialized."
+ // once this happens, the connection is open
+ this[kResponse] = response
- // 5. If x is −0, then set x to +0.
- if (x === 0) {
- x = 0
- }
+ const parser = new ByteParser(this)
+ parser.on('drain', function onParserDrain () {
+ this.ws[kResponse].socket.resume()
+ })
- // 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 ${V} to an integer.`
- })
- }
+ response.socket.ws = this
+ this[kByteParser] = parser
- // 2. Set x to IntegerPart(x).
- x = webidl.util.IntegerPart(x)
+ // 1. Change the ready state to OPEN (1).
+ this[kReadyState] = states.OPEN
- // 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}.`
- })
- }
+ // 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')
- // 4. Return x.
- return x
- }
+ if (extensions !== null) {
+ this.#extensions = extensions
+ }
- // 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)
+ // 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')
- // 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)
+ if (protocol !== null) {
+ this.#protocol = protocol
}
- // 3. Return x.
- return x
+ // 4. Fire an event named open at the WebSocket object.
+ fireEvent('open', this)
}
+}
- // 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
+// 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
}
+})
- // 9. Set x to IntegerPart(x).
- x = webidl.util.IntegerPart(x)
+Object.defineProperties(WebSocket, {
+ CONNECTING: staticPropertyDescriptors,
+ OPEN: staticPropertyDescriptors,
+ CLOSING: staticPropertyDescriptors,
+ CLOSED: staticPropertyDescriptors
+})
- // 10. Set x to x modulo 2^bitLength.
- x = x % Math.pow(2, bitLength)
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.DOMString
+)
- // 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)
+webidl.converters['DOMString or sequence'] = function (V) {
+ if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) {
+ return webidl.converters['sequence'](V)
}
- // 12. Otherwise, return x.
- return x
+ return webidl.converters.DOMString(V)
}
-// 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))
+// This implements the propsal made in https://github.com/whatwg/websockets/issues/42
+webidl.converters.WebSocketInit = webidl.dictionaryConverter([
+ {
+ key: 'protocols',
+ converter: webidl.converters['DOMString or sequence'],
+ get defaultValue () {
+ return []
+ }
+ },
+ {
+ key: 'dispatcher',
+ converter: (V) => V,
+ get defaultValue () {
+ return getGlobalDispatcher()
+ }
+ },
+ {
+ key: 'headers',
+ converter: webidl.nullableConverter(webidl.converters.HeadersInit)
+ }
+])
- // 2. If n < 0, then return -1 × r.
- if (n < 0) {
- return -1 * r
+webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) {
+ if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) {
+ return webidl.converters.WebSocketInit(V)
}
- // 3. Otherwise, return r.
- return r
+ return { protocols: webidl.converters['DOMString or sequence'](V) }
}
-// https://webidl.spec.whatwg.org/#es-sequence
-webidl.sequenceConverter = function (converter) {
- return (V) => {
- // 1. If Type(V) is not Object, throw a TypeError.
- if (webidl.util.Type(V) !== 'Object') {
- throw webidl.errors.exception({
- header: 'Sequence',
- message: `Value of type ${webidl.util.Type(V)} is not an Object.`
- })
+webidl.converters.WebSocketSendData = function (V) {
+ if (webidl.util.Type(V) === 'Object') {
+ if (isBlobLike(V)) {
+ return webidl.converters.Blob(V, { strict: false })
}
- // 2. Let method be ? GetMethod(V, @@iterator).
- /** @type {Generator} */
- const method = V?.[Symbol.iterator]?.()
- const seq = []
-
- // 3. If method is undefined, throw a TypeError.
- if (
- method === undefined ||
- typeof method.next !== 'function'
- ) {
- throw webidl.errors.exception({
- header: 'Sequence',
- message: 'Object is not an iterator.'
- })
+ if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) {
+ return webidl.converters.BufferSource(V)
}
+ }
- // https://webidl.spec.whatwg.org/#create-sequence-from-iterable
- while (true) {
- const { done, value } = method.next()
+ return webidl.converters.USVString(V)
+}
- if (done) {
- break
- }
+module.exports = {
+ WebSocket
+}
- seq.push(converter(value))
- }
- return seq
- }
-}
+/***/ }),
-// https://webidl.spec.whatwg.org/#es-to-record
-webidl.recordConverter = function (keyConverter, valueConverter) {
- return (O) => {
- // 1. If Type(O) is not Object, throw a TypeError.
- if (webidl.util.Type(O) !== 'Object') {
- throw webidl.errors.exception({
- header: 'Record',
- message: `Value of type ${webidl.util.Type(O)} is not an Object.`
- })
- }
+/***/ 33843:
+/***/ ((__unused_webpack_module, exports) => {
- // 2. Let result be a new empty instance of record.
- const result = {}
+"use strict";
- if (!types.isProxy(O)) {
- // Object.keys only returns enumerable properties
- const keys = Object.keys(O)
- for (const key of keys) {
- // 1. Let typedKey be key converted to an IDL value of type K.
- const typedKey = keyConverter(key)
+Object.defineProperty(exports, "__esModule", ({ value: true }));
- // 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])
+function getUserAgent() {
+ if (typeof navigator === "object" && "userAgent" in navigator) {
+ return navigator.userAgent;
+ }
- // 4. Set result[typedKey] to typedValue.
- result[typedKey] = typedValue
- }
+ if (typeof process === "object" && process.version !== undefined) {
+ return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`;
+ }
- // 5. Return result.
- return result
- }
+ return "";
+}
- // 3. Let keys be ? O.[[OwnPropertyKeys]]().
- const keys = Reflect.ownKeys(O)
+exports.getUserAgent = getUserAgent;
+//# sourceMappingURL=index.js.map
- // 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)
+/***/ }),
- // 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])
+/***/ 24488:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 4. Set result[typedKey] to typedValue.
- result[typedKey] = typedValue
- }
- }
- // 5. Return result.
- return result
- }
-}
+/**
+ * For Node.js, simply re-export the core `util.deprecate` function.
+ */
-webidl.interfaceConverter = function (i) {
- return (V, opts = {}) => {
- if (opts.strict !== false && !(V instanceof i)) {
- throw webidl.errors.exception({
- header: i.name,
- message: `Expected ${V} to be an instance of ${i.name}.`
- })
- }
+module.exports = __nccwpck_require__(39023).deprecate;
- return V
- }
-}
-webidl.dictionaryConverter = function (converters) {
- return (dictionary) => {
- const type = webidl.util.Type(dictionary)
- const dict = {}
+/***/ }),
- if (type === 'Null' || type === 'Undefined') {
- return dict
- } else if (type !== 'Object') {
- throw webidl.errors.exception({
- header: 'Dictionary',
- message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`
- })
- }
+/***/ 87723:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- for (const options of converters) {
- const { key, defaultValue, required, converter } = options
+var v1 = __nccwpck_require__(46626);
+var v4 = __nccwpck_require__(99021);
- if (required === true) {
- if (!hasOwn(dictionary, key)) {
- throw webidl.errors.exception({
- header: 'Dictionary',
- message: `Missing required key "${key}".`
- })
- }
- }
+var uuid = v4;
+uuid.v1 = v1;
+uuid.v4 = v4;
- let value = dictionary[key]
- const hasDefault = hasOwn(options, 'defaultValue')
+module.exports = uuid;
- // Only use defaultValue if value is undefined and
- // a defaultValue options was provided.
- if (hasDefault && value !== null) {
- value = 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)
+/***/ }),
- if (
- options.allowedValues &&
- !options.allowedValues.includes(value)
- ) {
- throw webidl.errors.exception({
- header: 'Dictionary',
- message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.`
- })
- }
+/***/ 38682:
+/***/ ((module) => {
- dict[key] = value
- }
- }
+/**
+ * Convert array of 16 byte values to UUID string format of the form:
+ * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
+ */
+var byteToHex = [];
+for (var i = 0; i < 256; ++i) {
+ byteToHex[i] = (i + 0x100).toString(16).substr(1);
+}
- return dict
- }
+function bytesToUuid(buf, offset) {
+ var i = offset || 0;
+ var bth = byteToHex;
+ // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
+ return ([
+ bth[buf[i++]], bth[buf[i++]],
+ bth[buf[i++]], bth[buf[i++]], '-',
+ bth[buf[i++]], bth[buf[i++]], '-',
+ bth[buf[i++]], bth[buf[i++]], '-',
+ bth[buf[i++]], bth[buf[i++]], '-',
+ bth[buf[i++]], bth[buf[i++]],
+ bth[buf[i++]], bth[buf[i++]],
+ bth[buf[i++]], bth[buf[i++]]
+ ]).join('');
}
-webidl.nullableConverter = function (converter) {
- return (V) => {
- if (V === null) {
- return V
- }
+module.exports = bytesToUuid;
- return converter(V)
- }
-}
-// https://webidl.spec.whatwg.org/#es-DOMString
-webidl.converters.DOMString = function (V, 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 new TypeError('Could not convert argument of type symbol to string.')
- }
+/***/ 61694:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 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)
-}
+// Unique ID creation requires a high quality random # generator. In node.js
+// this is pretty straight-forward - we use the crypto API.
-// https://webidl.spec.whatwg.org/#es-ByteString
-webidl.converters.ByteString = function (V) {
- // 1. Let x be ? ToString(V).
- // Note: DOMString converter perform ? ToString(V)
- const x = webidl.converters.DOMString(V)
+var crypto = __nccwpck_require__(76982);
- // 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.`
- )
- }
- }
+module.exports = function nodeRNG() {
+ return crypto.randomBytes(16);
+};
- // 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
-}
-// https://webidl.spec.whatwg.org/#es-USVString
-webidl.converters.USVString = toUSVString
+/***/ }),
-// https://webidl.spec.whatwg.org/#es-boolean
-webidl.converters.boolean = function (V) {
- // 1. Let x be the result of computing ToBoolean(V).
- const x = Boolean(V)
+/***/ 46626:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2. Return the IDL boolean value that is the one that represents
- // the same truth value as the ECMAScript Boolean value x.
- return x
-}
+var rng = __nccwpck_require__(61694);
+var bytesToUuid = __nccwpck_require__(38682);
-// https://webidl.spec.whatwg.org/#es-any
-webidl.converters.any = function (V) {
- return V
-}
+// **`v1()` - Generate time-based UUID**
+//
+// Inspired by https://github.com/LiosK/UUID.js
+// and http://docs.python.org/library/uuid.html
-// https://webidl.spec.whatwg.org/#es-long-long
-webidl.converters['long long'] = function (V) {
- // 1. Let x be ? ConvertToInt(V, 64, "signed").
- const x = webidl.util.ConvertToInt(V, 64, 'signed')
+var _nodeId;
+var _clockseq;
- // 2. Return the IDL long long value that represents
- // the same numeric value as x.
- return x
-}
+// Previous uuid creation time
+var _lastMSecs = 0;
+var _lastNSecs = 0;
-// https://webidl.spec.whatwg.org/#es-unsigned-long-long
-webidl.converters['unsigned long long'] = function (V) {
- // 1. Let x be ? ConvertToInt(V, 64, "unsigned").
- const x = webidl.util.ConvertToInt(V, 64, 'unsigned')
+// See https://github.com/uuidjs/uuid for API details
+function v1(options, buf, offset) {
+ var i = buf && offset || 0;
+ var b = buf || [];
- // 2. Return the IDL unsigned long long value that
- // represents the same numeric value as x.
- return x
-}
+ options = options || {};
+ var node = options.node || _nodeId;
+ var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
+
+ // node and clockseq need to be initialized to random values if they're not
+ // specified. We do this lazily to minimize issues related to insufficient
+ // system entropy. See #189
+ if (node == null || clockseq == null) {
+ var seedBytes = rng();
+ if (node == null) {
+ // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
+ node = _nodeId = [
+ seedBytes[0] | 0x01,
+ seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
+ ];
+ }
+ if (clockseq == null) {
+ // Per 4.2.2, randomize (14 bit) clockseq
+ clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
+ }
+ }
-// https://webidl.spec.whatwg.org/#es-unsigned-long
-webidl.converters['unsigned long'] = function (V) {
- // 1. Let x be ? ConvertToInt(V, 32, "unsigned").
- const x = webidl.util.ConvertToInt(V, 32, 'unsigned')
+ // UUID timestamps are 100 nano-second units since the Gregorian epoch,
+ // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
+ // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
+ // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
+ var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
- // 2. Return the IDL unsigned long value that
- // represents the same numeric value as x.
- return x
-}
+ // Per 4.2.1.2, use count of uuid's generated during the current clock
+ // cycle to simulate higher resolution clock
+ var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
-// https://webidl.spec.whatwg.org/#es-unsigned-short
-webidl.converters['unsigned short'] = function (V, opts) {
- // 1. Let x be ? ConvertToInt(V, 16, "unsigned").
- const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts)
+ // Time since last uuid creation (in msecs)
+ var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
- // 2. Return the IDL unsigned short value that represents
- // the same numeric value as x.
- return x
-}
+ // Per 4.2.1.2, Bump clockseq on clock regression
+ if (dt < 0 && options.clockseq === undefined) {
+ clockseq = clockseq + 1 & 0x3fff;
+ }
-// https://webidl.spec.whatwg.org/#idl-ArrayBuffer
-webidl.converters.ArrayBuffer = function (V, 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: `${V}`,
- argument: `${V}`,
- types: ['ArrayBuffer']
- })
+ // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
+ // time interval
+ if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
+ nsecs = 0;
}
- // 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.'
- })
+ // Per 4.2.1.2 Throw error if too many uuids are requested
+ if (nsecs >= 10000) {
+ throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
}
- // 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.
- // Note: resizable ArrayBuffers are currently a proposal.
+ _lastMSecs = msecs;
+ _lastNSecs = nsecs;
+ _clockseq = clockseq;
- // 4. Return the IDL ArrayBuffer value that is a
- // reference to the same object as V.
- return V
-}
+ // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
+ msecs += 12219292800000;
-webidl.converters.TypedArray = function (V, T, opts = {}) {
- // 1. Let T be the IDL type V is being converted to.
+ // `time_low`
+ var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
+ b[i++] = tl >>> 24 & 0xff;
+ b[i++] = tl >>> 16 & 0xff;
+ b[i++] = tl >>> 8 & 0xff;
+ b[i++] = tl & 0xff;
- // 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: `${T.name}`,
- argument: `${V}`,
- types: [T.name]
- })
- }
+ // `time_mid`
+ var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
+ b[i++] = tmh >>> 8 & 0xff;
+ b[i++] = tmh & 0xff;
- // 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.'
- })
- }
+ // `time_high_and_version`
+ b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
+ b[i++] = tmh >>> 16 & 0xff;
- // 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.
- // Note: resizable array buffers are currently a proposal
+ // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
+ b[i++] = clockseq >>> 8 | 0x80;
- // 5. Return the IDL value of type T that is a reference
- // to the same object as V.
- return V
-}
+ // `clock_seq_low`
+ b[i++] = clockseq & 0xff;
-webidl.converters.DataView = function (V, 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: 'DataView',
- message: 'Object is not a DataView.'
- })
+ // `node`
+ for (var n = 0; n < 6; ++n) {
+ b[i + n] = node[n];
}
- // 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.'
- })
- }
+ return buf ? buf : bytesToUuid(b);
+}
- // 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.
- // Note: resizable ArrayBuffers are currently a proposal
+module.exports = v1;
- // 4. Return the IDL DataView value that is a reference
- // to the same object as V.
- return V
-}
-// https://webidl.spec.whatwg.org/#BufferSource
-webidl.converters.BufferSource = function (V, opts = {}) {
- if (types.isAnyArrayBuffer(V)) {
- return webidl.converters.ArrayBuffer(V, opts)
- }
+/***/ }),
- if (types.isTypedArray(V)) {
- return webidl.converters.TypedArray(V, V.constructor)
- }
+/***/ 99021:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (types.isDataView(V)) {
- return webidl.converters.DataView(V, opts)
- }
+var rng = __nccwpck_require__(61694);
+var bytesToUuid = __nccwpck_require__(38682);
- throw new TypeError(`Could not convert ${V} to a BufferSource.`)
-}
+function v4(options, buf, offset) {
+ var i = buf && offset || 0;
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.ByteString
-)
+ if (typeof(options) == 'string') {
+ buf = options === 'binary' ? new Array(16) : null;
+ options = null;
+ }
+ options = options || {};
-webidl.converters['sequence>'] = webidl.sequenceConverter(
- webidl.converters['sequence']
-)
+ var rnds = options.random || (options.rng || rng)();
-webidl.converters['record'] = webidl.recordConverter(
- webidl.converters.ByteString,
- webidl.converters.ByteString
-)
+ // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
+ rnds[6] = (rnds[6] & 0x0f) | 0x40;
+ rnds[8] = (rnds[8] & 0x3f) | 0x80;
-module.exports = {
- webidl
+ // Copy bytes to buffer, if provided
+ if (buf) {
+ for (var ii = 0; ii < 16; ++ii) {
+ buf[i + ii] = rnds[ii];
+ }
+ }
+
+ return buf || bytesToUuid(rnds);
}
+module.exports = v4;
+
/***/ }),
-/***/ 396:
+/***/ 37125:
/***/ ((module) => {
"use strict";
-/**
- * @see https://encoding.spec.whatwg.org/#concept-encoding-get
- * @param {string|undefined} label
- */
-function getEncoding (label) {
- if (!label) {
- return 'failure'
- }
+var conversions = {};
+module.exports = conversions;
- // 1. Remove any leading and trailing ASCII whitespace from label.
- // 2. If label is an ASCII case-insensitive match for any of the
- // labels listed in the table below, then return the
- // corresponding encoding; otherwise return failure.
- switch (label.trim().toLowerCase()) {
- case 'unicode-1-1-utf-8':
- case 'unicode11utf8':
- case 'unicode20utf8':
- case 'utf-8':
- case 'utf8':
- case 'x-unicode20utf8':
- return 'UTF-8'
- case '866':
- case 'cp866':
- case 'csibm866':
- case 'ibm866':
- return 'IBM866'
- case 'csisolatin2':
- case 'iso-8859-2':
- case 'iso-ir-101':
- case 'iso8859-2':
- case 'iso88592':
- case 'iso_8859-2':
- case 'iso_8859-2:1987':
- case 'l2':
- case 'latin2':
- return 'ISO-8859-2'
- case 'csisolatin3':
- case 'iso-8859-3':
- case 'iso-ir-109':
- case 'iso8859-3':
- case 'iso88593':
- case 'iso_8859-3':
- case 'iso_8859-3:1988':
- case 'l3':
- case 'latin3':
- return 'ISO-8859-3'
- case 'csisolatin4':
- case 'iso-8859-4':
- case 'iso-ir-110':
- case 'iso8859-4':
- case 'iso88594':
- case 'iso_8859-4':
- case 'iso_8859-4:1988':
- case 'l4':
- case 'latin4':
- return 'ISO-8859-4'
- case 'csisolatincyrillic':
- case 'cyrillic':
- case 'iso-8859-5':
- case 'iso-ir-144':
- case 'iso8859-5':
- case 'iso88595':
- case 'iso_8859-5':
- case 'iso_8859-5:1988':
- return 'ISO-8859-5'
- case 'arabic':
- case 'asmo-708':
- case 'csiso88596e':
- case 'csiso88596i':
- case 'csisolatinarabic':
- case 'ecma-114':
- case 'iso-8859-6':
- case 'iso-8859-6-e':
- case 'iso-8859-6-i':
- case 'iso-ir-127':
- case 'iso8859-6':
- case 'iso88596':
- case 'iso_8859-6':
- case 'iso_8859-6:1987':
- return 'ISO-8859-6'
- case 'csisolatingreek':
- case 'ecma-118':
- case 'elot_928':
- case 'greek':
- case 'greek8':
- case 'iso-8859-7':
- case 'iso-ir-126':
- case 'iso8859-7':
- case 'iso88597':
- case 'iso_8859-7':
- case 'iso_8859-7:1987':
- case 'sun_eu_greek':
- return 'ISO-8859-7'
- case 'csiso88598e':
- case 'csisolatinhebrew':
- case 'hebrew':
- case 'iso-8859-8':
- case 'iso-8859-8-e':
- case 'iso-ir-138':
- case 'iso8859-8':
- case 'iso88598':
- case 'iso_8859-8':
- case 'iso_8859-8:1988':
- case 'visual':
- return 'ISO-8859-8'
- case 'csiso88598i':
- case 'iso-8859-8-i':
- case 'logical':
- return 'ISO-8859-8-I'
- case 'csisolatin6':
- case 'iso-8859-10':
- case 'iso-ir-157':
- case 'iso8859-10':
- case 'iso885910':
- case 'l6':
- case 'latin6':
- return 'ISO-8859-10'
- case 'iso-8859-13':
- case 'iso8859-13':
- case 'iso885913':
- return 'ISO-8859-13'
- case 'iso-8859-14':
- case 'iso8859-14':
- case 'iso885914':
- return 'ISO-8859-14'
- case 'csisolatin9':
- case 'iso-8859-15':
- case 'iso8859-15':
- case 'iso885915':
- case 'iso_8859-15':
- case 'l9':
- return 'ISO-8859-15'
- case 'iso-8859-16':
- return 'ISO-8859-16'
- case 'cskoi8r':
- case 'koi':
- case 'koi8':
- case 'koi8-r':
- case 'koi8_r':
- return 'KOI8-R'
- case 'koi8-ru':
- case 'koi8-u':
- return 'KOI8-U'
- case 'csmacintosh':
- case 'mac':
- case 'macintosh':
- case 'x-mac-roman':
- return 'macintosh'
- case 'iso-8859-11':
- case 'iso8859-11':
- case 'iso885911':
- case 'tis-620':
- case 'windows-874':
- return 'windows-874'
- case 'cp1250':
- case 'windows-1250':
- case 'x-cp1250':
- return 'windows-1250'
- case 'cp1251':
- case 'windows-1251':
- case 'x-cp1251':
- return 'windows-1251'
- case 'ansi_x3.4-1968':
- case 'ascii':
- case 'cp1252':
- case 'cp819':
- case 'csisolatin1':
- case 'ibm819':
- case 'iso-8859-1':
- case 'iso-ir-100':
- case 'iso8859-1':
- case 'iso88591':
- case 'iso_8859-1':
- case 'iso_8859-1:1987':
- case 'l1':
- case 'latin1':
- case 'us-ascii':
- case 'windows-1252':
- case 'x-cp1252':
- return 'windows-1252'
- case 'cp1253':
- case 'windows-1253':
- case 'x-cp1253':
- return 'windows-1253'
- case 'cp1254':
- case 'csisolatin5':
- case 'iso-8859-9':
- case 'iso-ir-148':
- case 'iso8859-9':
- case 'iso88599':
- case 'iso_8859-9':
- case 'iso_8859-9:1989':
- case 'l5':
- case 'latin5':
- case 'windows-1254':
- case 'x-cp1254':
- return 'windows-1254'
- case 'cp1255':
- case 'windows-1255':
- case 'x-cp1255':
- return 'windows-1255'
- case 'cp1256':
- case 'windows-1256':
- case 'x-cp1256':
- return 'windows-1256'
- case 'cp1257':
- case 'windows-1257':
- case 'x-cp1257':
- return 'windows-1257'
- case 'cp1258':
- case 'windows-1258':
- case 'x-cp1258':
- return 'windows-1258'
- case 'x-mac-cyrillic':
- case 'x-mac-ukrainian':
- return 'x-mac-cyrillic'
- case 'chinese':
- case 'csgb2312':
- case 'csiso58gb231280':
- case 'gb2312':
- case 'gb_2312':
- case 'gb_2312-80':
- case 'gbk':
- case 'iso-ir-58':
- case 'x-gbk':
- return 'GBK'
- case 'gb18030':
- return 'gb18030'
- case 'big5':
- case 'big5-hkscs':
- case 'cn-big5':
- case 'csbig5':
- case 'x-x-big5':
- return 'Big5'
- case 'cseucpkdfmtjapanese':
- case 'euc-jp':
- case 'x-euc-jp':
- return 'EUC-JP'
- case 'csiso2022jp':
- case 'iso-2022-jp':
- return 'ISO-2022-JP'
- case 'csshiftjis':
- case 'ms932':
- case 'ms_kanji':
- case 'shift-jis':
- case 'shift_jis':
- case 'sjis':
- case 'windows-31j':
- case 'x-sjis':
- return 'Shift_JIS'
- case 'cseuckr':
- case 'csksc56011987':
- case 'euc-kr':
- case 'iso-ir-149':
- case 'korean':
- case 'ks_c_5601-1987':
- case 'ks_c_5601-1989':
- case 'ksc5601':
- case 'ksc_5601':
- case 'windows-949':
- return 'EUC-KR'
- case 'csiso2022kr':
- case 'hz-gb-2312':
- case 'iso-2022-cn':
- case 'iso-2022-cn-ext':
- case 'iso-2022-kr':
- case 'replacement':
- return 'replacement'
- case 'unicodefffe':
- case 'utf-16be':
- return 'UTF-16BE'
- case 'csunicode':
- case 'iso-10646-ucs-2':
- case 'ucs-2':
- case 'unicode':
- case 'unicodefeff':
- case 'utf-16':
- case 'utf-16le':
- return 'UTF-16LE'
- case 'x-user-defined':
- return 'x-user-defined'
- default: return 'failure'
- }
+function sign(x) {
+ return x < 0 ? -1 : 1;
+}
+
+function evenRound(x) {
+ // Round x to the nearest integer, choosing the even integer if it lies halfway between two.
+ if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor)
+ return Math.floor(x);
+ } else {
+ return Math.round(x);
+ }
}
-module.exports = {
- getEncoding
+function createNumberConversion(bitLength, typeOpts) {
+ if (!typeOpts.unsigned) {
+ --bitLength;
+ }
+ const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength);
+ const upperBound = Math.pow(2, bitLength) - 1;
+
+ const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength);
+ const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1);
+
+ return function(V, opts) {
+ if (!opts) opts = {};
+
+ let x = +V;
+
+ if (opts.enforceRange) {
+ if (!Number.isFinite(x)) {
+ throw new TypeError("Argument is not a finite number");
+ }
+
+ x = sign(x) * Math.floor(Math.abs(x));
+ if (x < lowerBound || x > upperBound) {
+ throw new TypeError("Argument is not in byte range");
+ }
+
+ return x;
+ }
+
+ if (!isNaN(x) && opts.clamp) {
+ x = evenRound(x);
+
+ if (x < lowerBound) x = lowerBound;
+ if (x > upperBound) x = upperBound;
+ return x;
+ }
+
+ if (!Number.isFinite(x) || x === 0) {
+ return 0;
+ }
+
+ x = sign(x) * Math.floor(Math.abs(x));
+ x = x % moduloVal;
+
+ if (!typeOpts.unsigned && x >= moduloBound) {
+ return x - moduloVal;
+ } else if (typeOpts.unsigned) {
+ if (x < 0) {
+ x += moduloVal;
+ } else if (x === -0) { // don't return negative zero
+ return 0;
+ }
+ }
+
+ return x;
+ }
}
+conversions["void"] = function () {
+ return undefined;
+};
+
+conversions["boolean"] = function (val) {
+ return !!val;
+};
+
+conversions["byte"] = createNumberConversion(8, { unsigned: false });
+conversions["octet"] = createNumberConversion(8, { unsigned: true });
+
+conversions["short"] = createNumberConversion(16, { unsigned: false });
+conversions["unsigned short"] = createNumberConversion(16, { unsigned: true });
+
+conversions["long"] = createNumberConversion(32, { unsigned: false });
+conversions["unsigned long"] = createNumberConversion(32, { unsigned: true });
+
+conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 });
+conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 });
+
+conversions["double"] = function (V) {
+ const x = +V;
+
+ if (!Number.isFinite(x)) {
+ throw new TypeError("Argument is not a finite floating-point value");
+ }
+
+ return x;
+};
+
+conversions["unrestricted double"] = function (V) {
+ const x = +V;
+
+ if (isNaN(x)) {
+ throw new TypeError("Argument is NaN");
+ }
+
+ return x;
+};
+
+// not quite valid, but good enough for JS
+conversions["float"] = conversions["double"];
+conversions["unrestricted float"] = conversions["unrestricted double"];
+
+conversions["DOMString"] = function (V, opts) {
+ if (!opts) opts = {};
+
+ if (opts.treatNullAsEmptyString && V === null) {
+ return "";
+ }
+
+ return String(V);
+};
+
+conversions["ByteString"] = function (V, opts) {
+ const x = String(V);
+ let c = undefined;
+ for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) {
+ if (c > 255) {
+ throw new TypeError("Argument is not a valid bytestring");
+ }
+ }
+
+ return x;
+};
+
+conversions["USVString"] = function (V) {
+ const S = String(V);
+ const n = S.length;
+ const U = [];
+ for (let i = 0; i < n; ++i) {
+ const c = S.charCodeAt(i);
+ if (c < 0xD800 || c > 0xDFFF) {
+ U.push(String.fromCodePoint(c));
+ } else if (0xDC00 <= c && c <= 0xDFFF) {
+ U.push(String.fromCodePoint(0xFFFD));
+ } else {
+ if (i === n - 1) {
+ U.push(String.fromCodePoint(0xFFFD));
+ } else {
+ const d = S.charCodeAt(i + 1);
+ if (0xDC00 <= d && d <= 0xDFFF) {
+ const a = c & 0x3FF;
+ const b = d & 0x3FF;
+ U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b));
+ ++i;
+ } else {
+ U.push(String.fromCodePoint(0xFFFD));
+ }
+ }
+ }
+ }
+
+ return U.join('');
+};
+
+conversions["Date"] = function (V, opts) {
+ if (!(V instanceof Date)) {
+ throw new TypeError("Argument is not a Date object");
+ }
+ if (isNaN(V)) {
+ return undefined;
+ }
+
+ return V;
+};
+
+conversions["RegExp"] = function (V, opts) {
+ if (!(V instanceof RegExp)) {
+ V = new RegExp(V);
+ }
+
+ return V;
+};
+
/***/ }),
-/***/ 2160:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 23184:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
+const usm = __nccwpck_require__(20905);
-const {
- staticPropertyDescriptors,
- readOperation,
- fireAProgressEvent
-} = __nccwpck_require__(165)
-const {
- kState,
- kError,
- kResult,
- kEvents,
- kAborted
-} = __nccwpck_require__(6812)
-const { webidl } = __nccwpck_require__(4222)
-const { kEnumerableProperty } = __nccwpck_require__(3440)
+exports.implementation = class URLImpl {
+ constructor(constructorArgs) {
+ const url = constructorArgs[0];
+ const base = constructorArgs[1];
-class FileReader extends EventTarget {
- constructor () {
- super()
+ let parsedBase = null;
+ if (base !== undefined) {
+ parsedBase = usm.basicURLParse(base);
+ if (parsedBase === "failure") {
+ throw new TypeError("Invalid base URL");
+ }
+ }
- this[kState] = 'empty'
- this[kResult] = null
- this[kError] = null
- this[kEvents] = {
- loadend: null,
- error: null,
- abort: null,
- load: null,
- progress: null,
- loadstart: null
+ const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase });
+ if (parsedURL === "failure") {
+ throw new TypeError("Invalid URL");
}
- }
- /**
- * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer
- * @param {import('buffer').Blob} blob
- */
- readAsArrayBuffer (blob) {
- webidl.brandCheck(this, FileReader)
+ this._url = parsedURL;
- webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' })
+ // TODO: query stuff
+ }
- blob = webidl.converters.Blob(blob, { strict: false })
+ get href() {
+ return usm.serializeURL(this._url);
+ }
- // The readAsArrayBuffer(blob) method, when invoked,
- // must initiate a read operation for blob with ArrayBuffer.
- readOperation(this, blob, 'ArrayBuffer')
+ set href(v) {
+ const parsedURL = usm.basicURLParse(v);
+ if (parsedURL === "failure") {
+ throw new TypeError("Invalid URL");
+ }
+
+ this._url = parsedURL;
}
- /**
- * @see https://w3c.github.io/FileAPI/#readAsBinaryString
- * @param {import('buffer').Blob} blob
- */
- readAsBinaryString (blob) {
- webidl.brandCheck(this, FileReader)
+ get origin() {
+ return usm.serializeURLOrigin(this._url);
+ }
- webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' })
+ get protocol() {
+ return this._url.scheme + ":";
+ }
- blob = webidl.converters.Blob(blob, { strict: false })
+ set protocol(v) {
+ usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" });
+ }
- // The readAsBinaryString(blob) method, when invoked,
- // must initiate a read operation for blob with BinaryString.
- readOperation(this, blob, 'BinaryString')
+ get username() {
+ return this._url.username;
}
- /**
- * @see https://w3c.github.io/FileAPI/#readAsDataText
- * @param {import('buffer').Blob} blob
- * @param {string?} encoding
- */
- readAsText (blob, encoding = undefined) {
- webidl.brandCheck(this, FileReader)
+ set username(v) {
+ if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
+ return;
+ }
- webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' })
+ usm.setTheUsername(this._url, v);
+ }
- blob = webidl.converters.Blob(blob, { strict: false })
+ get password() {
+ return this._url.password;
+ }
- if (encoding !== undefined) {
- encoding = webidl.converters.DOMString(encoding)
+ set password(v) {
+ if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
+ return;
}
- // The readAsText(blob, encoding) method, when invoked,
- // must initiate a read operation for blob with Text and encoding.
- readOperation(this, blob, 'Text', encoding)
+ usm.setThePassword(this._url, v);
}
- /**
- * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL
- * @param {import('buffer').Blob} blob
- */
- readAsDataURL (blob) {
- webidl.brandCheck(this, FileReader)
+ get host() {
+ const url = this._url;
- webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' })
+ if (url.host === null) {
+ return "";
+ }
- blob = webidl.converters.Blob(blob, { strict: false })
+ if (url.port === null) {
+ return usm.serializeHost(url.host);
+ }
- // The readAsDataURL(blob) method, when invoked, must
- // initiate a read operation for blob with DataURL.
- readOperation(this, blob, 'DataURL')
+ return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port);
}
- /**
- * @see https://w3c.github.io/FileAPI/#dfn-abort
- */
- abort () {
- // 1. If this's state is "empty" or if this's state is
- // "done" set this's result to null and terminate
- // this algorithm.
- if (this[kState] === 'empty' || this[kState] === 'done') {
- this[kResult] = null
- return
+ set host(v) {
+ if (this._url.cannotBeABaseURL) {
+ return;
}
- // 2. If this's state is "loading" set this's state to
- // "done" and set this's result to null.
- if (this[kState] === 'loading') {
- this[kState] = 'done'
- this[kResult] = null
+ usm.basicURLParse(v, { url: this._url, stateOverride: "host" });
+ }
+
+ get hostname() {
+ if (this._url.host === null) {
+ return "";
}
- // 3. If there are any tasks from this on the file reading
- // task source in an affiliated task queue, then remove
- // those tasks from that task queue.
- this[kAborted] = true
+ return usm.serializeHost(this._url.host);
+ }
- // 4. Terminate the algorithm for the read method being processed.
- // TODO
+ set hostname(v) {
+ if (this._url.cannotBeABaseURL) {
+ return;
+ }
- // 5. Fire a progress event called abort at this.
- fireAProgressEvent('abort', this)
+ usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" });
+ }
- // 6. If this's state is not "loading", fire a progress
- // event called loadend at this.
- if (this[kState] !== 'loading') {
- fireAProgressEvent('loadend', this)
+ get port() {
+ if (this._url.port === null) {
+ return "";
}
+
+ return usm.serializeInteger(this._url.port);
}
- /**
- * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate
- */
- get readyState () {
- webidl.brandCheck(this, FileReader)
+ set port(v) {
+ if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
+ return;
+ }
- switch (this[kState]) {
- case 'empty': return this.EMPTY
- case 'loading': return this.LOADING
- case 'done': return this.DONE
+ if (v === "") {
+ this._url.port = null;
+ } else {
+ usm.basicURLParse(v, { url: this._url, stateOverride: "port" });
}
}
- /**
- * @see https://w3c.github.io/FileAPI/#dom-filereader-result
- */
- get result () {
- webidl.brandCheck(this, FileReader)
+ get pathname() {
+ if (this._url.cannotBeABaseURL) {
+ return this._url.path[0];
+ }
- // The result attribute’s getter, when invoked, must return
- // this's result.
- return this[kResult]
+ if (this._url.path.length === 0) {
+ return "";
+ }
+
+ return "/" + this._url.path.join("/");
}
- /**
- * @see https://w3c.github.io/FileAPI/#dom-filereader-error
- */
- get error () {
- webidl.brandCheck(this, FileReader)
+ set pathname(v) {
+ if (this._url.cannotBeABaseURL) {
+ return;
+ }
- // The error attribute’s getter, when invoked, must return
- // this's error.
- return this[kError]
+ this._url.path = [];
+ usm.basicURLParse(v, { url: this._url, stateOverride: "path start" });
}
- get onloadend () {
- webidl.brandCheck(this, FileReader)
+ get search() {
+ if (this._url.query === null || this._url.query === "") {
+ return "";
+ }
- return this[kEvents].loadend
+ return "?" + this._url.query;
}
- set onloadend (fn) {
- webidl.brandCheck(this, FileReader)
+ set search(v) {
+ // TODO: query stuff
- if (this[kEvents].loadend) {
- this.removeEventListener('loadend', this[kEvents].loadend)
+ const url = this._url;
+
+ if (v === "") {
+ url.query = null;
+ return;
}
- if (typeof fn === 'function') {
- this[kEvents].loadend = fn
- this.addEventListener('loadend', fn)
- } else {
- this[kEvents].loadend = null
+ const input = v[0] === "?" ? v.substring(1) : v;
+ url.query = "";
+ usm.basicURLParse(input, { url, stateOverride: "query" });
+ }
+
+ get hash() {
+ if (this._url.fragment === null || this._url.fragment === "") {
+ return "";
}
+
+ return "#" + this._url.fragment;
}
- get onerror () {
- webidl.brandCheck(this, FileReader)
+ set hash(v) {
+ if (v === "") {
+ this._url.fragment = null;
+ return;
+ }
- return this[kEvents].error
+ const input = v[0] === "#" ? v.substring(1) : v;
+ this._url.fragment = "";
+ usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" });
}
- set onerror (fn) {
- webidl.brandCheck(this, FileReader)
+ toJSON() {
+ return this.href;
+ }
+};
- if (this[kEvents].error) {
- this.removeEventListener('error', this[kEvents].error)
- }
- if (typeof fn === 'function') {
- this[kEvents].error = fn
- this.addEventListener('error', fn)
- } else {
- this[kEvents].error = null
- }
+/***/ }),
+
+/***/ 66633:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+const conversions = __nccwpck_require__(37125);
+const utils = __nccwpck_require__(39857);
+const Impl = __nccwpck_require__(23184);
+
+const impl = utils.implSymbol;
+
+function URL(url) {
+ if (!this || this[impl] || !(this instanceof URL)) {
+ throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function.");
+ }
+ if (arguments.length < 1) {
+ throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present.");
+ }
+ const args = [];
+ for (let i = 0; i < arguments.length && i < 2; ++i) {
+ args[i] = arguments[i];
+ }
+ args[0] = conversions["USVString"](args[0]);
+ if (args[1] !== undefined) {
+ args[1] = conversions["USVString"](args[1]);
}
- get onloadstart () {
- webidl.brandCheck(this, FileReader)
+ module.exports.setup(this, args);
+}
- return this[kEvents].loadstart
+URL.prototype.toJSON = function toJSON() {
+ if (!this || !module.exports.is(this)) {
+ throw new TypeError("Illegal invocation");
+ }
+ const args = [];
+ for (let i = 0; i < arguments.length && i < 0; ++i) {
+ args[i] = arguments[i];
}
+ return this[impl].toJSON.apply(this[impl], args);
+};
+Object.defineProperty(URL.prototype, "href", {
+ get() {
+ return this[impl].href;
+ },
+ set(V) {
+ V = conversions["USVString"](V);
+ this[impl].href = V;
+ },
+ enumerable: true,
+ configurable: true
+});
- set onloadstart (fn) {
- webidl.brandCheck(this, FileReader)
+URL.prototype.toString = function () {
+ if (!this || !module.exports.is(this)) {
+ throw new TypeError("Illegal invocation");
+ }
+ return this.href;
+};
- if (this[kEvents].loadstart) {
- this.removeEventListener('loadstart', this[kEvents].loadstart)
- }
+Object.defineProperty(URL.prototype, "origin", {
+ get() {
+ return this[impl].origin;
+ },
+ enumerable: true,
+ configurable: true
+});
- if (typeof fn === 'function') {
- this[kEvents].loadstart = fn
- this.addEventListener('loadstart', fn)
- } else {
- this[kEvents].loadstart = null
- }
+Object.defineProperty(URL.prototype, "protocol", {
+ get() {
+ return this[impl].protocol;
+ },
+ set(V) {
+ V = conversions["USVString"](V);
+ this[impl].protocol = V;
+ },
+ enumerable: true,
+ configurable: true
+});
+
+Object.defineProperty(URL.prototype, "username", {
+ get() {
+ return this[impl].username;
+ },
+ set(V) {
+ V = conversions["USVString"](V);
+ this[impl].username = V;
+ },
+ enumerable: true,
+ configurable: true
+});
+
+Object.defineProperty(URL.prototype, "password", {
+ get() {
+ return this[impl].password;
+ },
+ set(V) {
+ V = conversions["USVString"](V);
+ this[impl].password = V;
+ },
+ enumerable: true,
+ configurable: true
+});
+
+Object.defineProperty(URL.prototype, "host", {
+ get() {
+ return this[impl].host;
+ },
+ set(V) {
+ V = conversions["USVString"](V);
+ this[impl].host = V;
+ },
+ enumerable: true,
+ configurable: true
+});
+
+Object.defineProperty(URL.prototype, "hostname", {
+ get() {
+ return this[impl].hostname;
+ },
+ set(V) {
+ V = conversions["USVString"](V);
+ this[impl].hostname = V;
+ },
+ enumerable: true,
+ configurable: true
+});
+
+Object.defineProperty(URL.prototype, "port", {
+ get() {
+ return this[impl].port;
+ },
+ set(V) {
+ V = conversions["USVString"](V);
+ this[impl].port = V;
+ },
+ enumerable: true,
+ configurable: true
+});
+
+Object.defineProperty(URL.prototype, "pathname", {
+ get() {
+ return this[impl].pathname;
+ },
+ set(V) {
+ V = conversions["USVString"](V);
+ this[impl].pathname = V;
+ },
+ enumerable: true,
+ configurable: true
+});
+
+Object.defineProperty(URL.prototype, "search", {
+ get() {
+ return this[impl].search;
+ },
+ set(V) {
+ V = conversions["USVString"](V);
+ this[impl].search = V;
+ },
+ enumerable: true,
+ configurable: true
+});
+
+Object.defineProperty(URL.prototype, "hash", {
+ get() {
+ return this[impl].hash;
+ },
+ set(V) {
+ V = conversions["USVString"](V);
+ this[impl].hash = V;
+ },
+ enumerable: true,
+ configurable: true
+});
+
+
+module.exports = {
+ is(obj) {
+ return !!obj && obj[impl] instanceof Impl.implementation;
+ },
+ create(constructorArgs, privateData) {
+ let obj = Object.create(URL.prototype);
+ this.setup(obj, constructorArgs, privateData);
+ return obj;
+ },
+ setup(obj, constructorArgs, privateData) {
+ if (!privateData) privateData = {};
+ privateData.wrapper = obj;
+
+ obj[impl] = new Impl.implementation(constructorArgs, privateData);
+ obj[impl][utils.wrapperSymbol] = obj;
+ },
+ interface: URL,
+ expose: {
+ Window: { URL: URL },
+ Worker: { URL: URL }
}
+};
- get onprogress () {
- webidl.brandCheck(this, FileReader)
- return this[kEvents].progress
+
+/***/ }),
+
+/***/ 62686:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+exports.URL = __nccwpck_require__(66633)["interface"];
+exports.serializeURL = __nccwpck_require__(20905).serializeURL;
+exports.serializeURLOrigin = __nccwpck_require__(20905).serializeURLOrigin;
+exports.basicURLParse = __nccwpck_require__(20905).basicURLParse;
+exports.setTheUsername = __nccwpck_require__(20905).setTheUsername;
+exports.setThePassword = __nccwpck_require__(20905).setThePassword;
+exports.serializeHost = __nccwpck_require__(20905).serializeHost;
+exports.serializeInteger = __nccwpck_require__(20905).serializeInteger;
+exports.parseURL = __nccwpck_require__(20905).parseURL;
+
+
+/***/ }),
+
+/***/ 20905:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+const punycode = __nccwpck_require__(24876);
+const tr46 = __nccwpck_require__(1552);
+
+const specialSchemes = {
+ ftp: 21,
+ file: null,
+ gopher: 70,
+ http: 80,
+ https: 443,
+ ws: 80,
+ wss: 443
+};
+
+const failure = Symbol("failure");
+
+function countSymbols(str) {
+ return punycode.ucs2.decode(str).length;
+}
+
+function at(input, idx) {
+ const c = input[idx];
+ return isNaN(c) ? undefined : String.fromCodePoint(c);
+}
+
+function isASCIIDigit(c) {
+ return c >= 0x30 && c <= 0x39;
+}
+
+function isASCIIAlpha(c) {
+ return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A);
+}
+
+function isASCIIAlphanumeric(c) {
+ return isASCIIAlpha(c) || isASCIIDigit(c);
+}
+
+function isASCIIHex(c) {
+ return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66);
+}
+
+function isSingleDot(buffer) {
+ return buffer === "." || buffer.toLowerCase() === "%2e";
+}
+
+function isDoubleDot(buffer) {
+ buffer = buffer.toLowerCase();
+ return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e";
+}
+
+function isWindowsDriveLetterCodePoints(cp1, cp2) {
+ return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124);
+}
+
+function isWindowsDriveLetterString(string) {
+ return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|");
+}
+
+function isNormalizedWindowsDriveLetterString(string) {
+ return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":";
+}
+
+function containsForbiddenHostCodePoint(string) {
+ return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1;
+}
+
+function containsForbiddenHostCodePointExcludingPercent(string) {
+ return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1;
+}
+
+function isSpecialScheme(scheme) {
+ return specialSchemes[scheme] !== undefined;
+}
+
+function isSpecial(url) {
+ return isSpecialScheme(url.scheme);
+}
+
+function defaultPort(scheme) {
+ return specialSchemes[scheme];
+}
+
+function percentEncode(c) {
+ let hex = c.toString(16).toUpperCase();
+ if (hex.length === 1) {
+ hex = "0" + hex;
}
- set onprogress (fn) {
- webidl.brandCheck(this, FileReader)
+ return "%" + hex;
+}
- if (this[kEvents].progress) {
- this.removeEventListener('progress', this[kEvents].progress)
- }
+function utf8PercentEncode(c) {
+ const buf = new Buffer(c);
- if (typeof fn === 'function') {
- this[kEvents].progress = fn
- this.addEventListener('progress', fn)
+ let str = "";
+
+ for (let i = 0; i < buf.length; ++i) {
+ str += percentEncode(buf[i]);
+ }
+
+ return str;
+}
+
+function utf8PercentDecode(str) {
+ const input = new Buffer(str);
+ const output = [];
+ for (let i = 0; i < input.length; ++i) {
+ if (input[i] !== 37) {
+ output.push(input[i]);
+ } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) {
+ output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16));
+ i += 2;
} else {
- this[kEvents].progress = null
+ output.push(input[i]);
}
}
+ return new Buffer(output).toString();
+}
- get onload () {
- webidl.brandCheck(this, FileReader)
+function isC0ControlPercentEncode(c) {
+ return c <= 0x1F || c > 0x7E;
+}
- return this[kEvents].load
+const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]);
+function isPathPercentEncode(c) {
+ return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c);
+}
+
+const extraUserinfoPercentEncodeSet =
+ new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]);
+function isUserinfoPercentEncode(c) {
+ return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c);
+}
+
+function percentEncodeChar(c, encodeSetPredicate) {
+ const cStr = String.fromCodePoint(c);
+
+ if (encodeSetPredicate(c)) {
+ return utf8PercentEncode(cStr);
}
- set onload (fn) {
- webidl.brandCheck(this, FileReader)
+ return cStr;
+}
- if (this[kEvents].load) {
- this.removeEventListener('load', this[kEvents].load)
+function parseIPv4Number(input) {
+ let R = 10;
+
+ if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") {
+ input = input.substring(2);
+ R = 16;
+ } else if (input.length >= 2 && input.charAt(0) === "0") {
+ input = input.substring(1);
+ R = 8;
+ }
+
+ if (input === "") {
+ return 0;
+ }
+
+ const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/);
+ if (regex.test(input)) {
+ return failure;
+ }
+
+ return parseInt(input, R);
+}
+
+function parseIPv4(input) {
+ const parts = input.split(".");
+ if (parts[parts.length - 1] === "") {
+ if (parts.length > 1) {
+ parts.pop();
}
+ }
- if (typeof fn === 'function') {
- this[kEvents].load = fn
- this.addEventListener('load', fn)
- } else {
- this[kEvents].load = null
+ if (parts.length > 4) {
+ return input;
+ }
+
+ const numbers = [];
+ for (const part of parts) {
+ if (part === "") {
+ return input;
+ }
+ const n = parseIPv4Number(part);
+ if (n === failure) {
+ return input;
}
+
+ numbers.push(n);
}
- get onabort () {
- webidl.brandCheck(this, FileReader)
+ for (let i = 0; i < numbers.length - 1; ++i) {
+ if (numbers[i] > 255) {
+ return failure;
+ }
+ }
+ if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) {
+ return failure;
+ }
- return this[kEvents].abort
+ let ipv4 = numbers.pop();
+ let counter = 0;
+
+ for (const n of numbers) {
+ ipv4 += n * Math.pow(256, 3 - counter);
+ ++counter;
}
- set onabort (fn) {
- webidl.brandCheck(this, FileReader)
+ return ipv4;
+}
- if (this[kEvents].abort) {
- this.removeEventListener('abort', this[kEvents].abort)
- }
+function serializeIPv4(address) {
+ let output = "";
+ let n = address;
- if (typeof fn === 'function') {
- this[kEvents].abort = fn
- this.addEventListener('abort', fn)
- } else {
- this[kEvents].abort = null
+ for (let i = 1; i <= 4; ++i) {
+ output = String(n % 256) + output;
+ if (i !== 4) {
+ output = "." + output;
}
+ n = Math.floor(n / 256);
}
+
+ return output;
}
-// https://w3c.github.io/FileAPI/#dom-filereader-empty
-FileReader.EMPTY = FileReader.prototype.EMPTY = 0
-// https://w3c.github.io/FileAPI/#dom-filereader-loading
-FileReader.LOADING = FileReader.prototype.LOADING = 1
-// https://w3c.github.io/FileAPI/#dom-filereader-done
-FileReader.DONE = FileReader.prototype.DONE = 2
+function parseIPv6(input) {
+ const address = [0, 0, 0, 0, 0, 0, 0, 0];
+ let pieceIndex = 0;
+ let compress = null;
+ let pointer = 0;
-Object.defineProperties(FileReader.prototype, {
- EMPTY: staticPropertyDescriptors,
- LOADING: staticPropertyDescriptors,
- DONE: staticPropertyDescriptors,
- readAsArrayBuffer: kEnumerableProperty,
- readAsBinaryString: kEnumerableProperty,
- readAsText: kEnumerableProperty,
- readAsDataURL: kEnumerableProperty,
- abort: kEnumerableProperty,
- readyState: kEnumerableProperty,
- result: kEnumerableProperty,
- error: kEnumerableProperty,
- onloadstart: kEnumerableProperty,
- onprogress: kEnumerableProperty,
- onload: kEnumerableProperty,
- onabort: kEnumerableProperty,
- onerror: kEnumerableProperty,
- onloadend: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'FileReader',
- writable: false,
- enumerable: false,
- configurable: true
+ input = punycode.ucs2.decode(input);
+
+ if (input[pointer] === 58) {
+ if (input[pointer + 1] !== 58) {
+ return failure;
+ }
+
+ pointer += 2;
+ ++pieceIndex;
+ compress = pieceIndex;
}
-})
-Object.defineProperties(FileReader, {
- EMPTY: staticPropertyDescriptors,
- LOADING: staticPropertyDescriptors,
- DONE: staticPropertyDescriptors
-})
+ while (pointer < input.length) {
+ if (pieceIndex === 8) {
+ return failure;
+ }
-module.exports = {
- FileReader
-}
+ if (input[pointer] === 58) {
+ if (compress !== null) {
+ return failure;
+ }
+ ++pointer;
+ ++pieceIndex;
+ compress = pieceIndex;
+ continue;
+ }
+ let value = 0;
+ let length = 0;
-/***/ }),
+ while (length < 4 && isASCIIHex(input[pointer])) {
+ value = value * 0x10 + parseInt(at(input, pointer), 16);
+ ++pointer;
+ ++length;
+ }
-/***/ 5976:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (input[pointer] === 46) {
+ if (length === 0) {
+ return failure;
+ }
-"use strict";
+ pointer -= length;
+ if (pieceIndex > 6) {
+ return failure;
+ }
-const { webidl } = __nccwpck_require__(4222)
+ let numbersSeen = 0;
-const kState = Symbol('ProgressEvent state')
+ while (input[pointer] !== undefined) {
+ let ipv4Piece = null;
-/**
- * @see https://xhr.spec.whatwg.org/#progressevent
- */
-class ProgressEvent extends Event {
- constructor (type, eventInitDict = {}) {
- type = webidl.converters.DOMString(type)
- eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {})
+ if (numbersSeen > 0) {
+ if (input[pointer] === 46 && numbersSeen < 4) {
+ ++pointer;
+ } else {
+ return failure;
+ }
+ }
- super(type, eventInitDict)
+ if (!isASCIIDigit(input[pointer])) {
+ return failure;
+ }
- this[kState] = {
- lengthComputable: eventInitDict.lengthComputable,
- loaded: eventInitDict.loaded,
- total: eventInitDict.total
- }
- }
+ while (isASCIIDigit(input[pointer])) {
+ const number = parseInt(at(input, pointer));
+ if (ipv4Piece === null) {
+ ipv4Piece = number;
+ } else if (ipv4Piece === 0) {
+ return failure;
+ } else {
+ ipv4Piece = ipv4Piece * 10 + number;
+ }
+ if (ipv4Piece > 255) {
+ return failure;
+ }
+ ++pointer;
+ }
- get lengthComputable () {
- webidl.brandCheck(this, ProgressEvent)
+ address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece;
- return this[kState].lengthComputable
- }
+ ++numbersSeen;
- get loaded () {
- webidl.brandCheck(this, ProgressEvent)
+ if (numbersSeen === 2 || numbersSeen === 4) {
+ ++pieceIndex;
+ }
+ }
- return this[kState].loaded
- }
+ if (numbersSeen !== 4) {
+ return failure;
+ }
- get total () {
- webidl.brandCheck(this, ProgressEvent)
+ break;
+ } else if (input[pointer] === 58) {
+ ++pointer;
+ if (input[pointer] === undefined) {
+ return failure;
+ }
+ } else if (input[pointer] !== undefined) {
+ return failure;
+ }
- return this[kState].total
+ address[pieceIndex] = value;
+ ++pieceIndex;
}
-}
-webidl.converters.ProgressEventInit = webidl.dictionaryConverter([
- {
- key: 'lengthComputable',
- converter: webidl.converters.boolean,
- defaultValue: false
- },
- {
- key: 'loaded',
- converter: webidl.converters['unsigned long long'],
- defaultValue: 0
- },
- {
- key: 'total',
- converter: webidl.converters['unsigned long long'],
- defaultValue: 0
- },
- {
- key: 'bubbles',
- converter: webidl.converters.boolean,
- defaultValue: false
- },
- {
- key: 'cancelable',
- converter: webidl.converters.boolean,
- defaultValue: false
- },
- {
- key: 'composed',
- converter: webidl.converters.boolean,
- defaultValue: false
+ if (compress !== null) {
+ let swaps = pieceIndex - compress;
+ pieceIndex = 7;
+ while (pieceIndex !== 0 && swaps > 0) {
+ const temp = address[compress + swaps - 1];
+ address[compress + swaps - 1] = address[pieceIndex];
+ address[pieceIndex] = temp;
+ --pieceIndex;
+ --swaps;
+ }
+ } else if (compress === null && pieceIndex !== 8) {
+ return failure;
}
-])
-module.exports = {
- ProgressEvent
+ return address;
}
+function serializeIPv6(address) {
+ let output = "";
+ const seqResult = findLongestZeroSequence(address);
+ const compress = seqResult.idx;
+ let ignore0 = false;
-/***/ }),
+ for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) {
+ if (ignore0 && address[pieceIndex] === 0) {
+ continue;
+ } else if (ignore0) {
+ ignore0 = false;
+ }
-/***/ 6812:
-/***/ ((module) => {
+ if (compress === pieceIndex) {
+ const separator = pieceIndex === 0 ? "::" : ":";
+ output += separator;
+ ignore0 = true;
+ continue;
+ }
-"use strict";
+ output += address[pieceIndex].toString(16);
+ if (pieceIndex !== 7) {
+ output += ":";
+ }
+ }
-module.exports = {
- kState: Symbol('FileReader state'),
- kResult: Symbol('FileReader result'),
- kError: Symbol('FileReader error'),
- kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'),
- kEvents: Symbol('FileReader events'),
- kAborted: Symbol('FileReader aborted')
+ return output;
}
+function parseHost(input, isSpecialArg) {
+ if (input[0] === "[") {
+ if (input[input.length - 1] !== "]") {
+ return failure;
+ }
-/***/ }),
+ return parseIPv6(input.substring(1, input.length - 1));
+ }
-/***/ 165:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (!isSpecialArg) {
+ return parseOpaqueHost(input);
+ }
-"use strict";
+ const domain = utf8PercentDecode(input);
+ const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false);
+ if (asciiDomain === null) {
+ return failure;
+ }
+ if (containsForbiddenHostCodePoint(asciiDomain)) {
+ return failure;
+ }
-const {
- kState,
- kError,
- kResult,
- kAborted,
- kLastProgressEventFired
-} = __nccwpck_require__(6812)
-const { ProgressEvent } = __nccwpck_require__(5976)
-const { getEncoding } = __nccwpck_require__(396)
-const { DOMException } = __nccwpck_require__(7326)
-const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(4322)
-const { types } = __nccwpck_require__(9023)
-const { StringDecoder } = __nccwpck_require__(3193)
-const { btoa } = __nccwpck_require__(181)
+ const ipv4Host = parseIPv4(asciiDomain);
+ if (typeof ipv4Host === "number" || ipv4Host === failure) {
+ return ipv4Host;
+ }
-/** @type {PropertyDescriptor} */
-const staticPropertyDescriptors = {
- enumerable: true,
- writable: false,
- configurable: false
+ return asciiDomain;
}
-/**
- * @see https://w3c.github.io/FileAPI/#readOperation
- * @param {import('./filereader').FileReader} fr
- * @param {import('buffer').Blob} blob
- * @param {string} type
- * @param {string?} encodingName
- */
-function readOperation (fr, blob, type, encodingName) {
- // 1. If fr’s state is "loading", throw an InvalidStateError
- // DOMException.
- if (fr[kState] === 'loading') {
- throw new DOMException('Invalid state', 'InvalidStateError')
+function parseOpaqueHost(input) {
+ if (containsForbiddenHostCodePointExcludingPercent(input)) {
+ return failure;
}
- // 2. Set fr’s state to "loading".
- fr[kState] = 'loading'
+ let output = "";
+ const decoded = punycode.ucs2.decode(input);
+ for (let i = 0; i < decoded.length; ++i) {
+ output += percentEncodeChar(decoded[i], isC0ControlPercentEncode);
+ }
+ return output;
+}
- // 3. Set fr’s result to null.
- fr[kResult] = null
+function findLongestZeroSequence(arr) {
+ let maxIdx = null;
+ let maxLen = 1; // only find elements > 1
+ let currStart = null;
+ let currLen = 0;
- // 4. Set fr’s error to null.
- fr[kError] = null
+ for (let i = 0; i < arr.length; ++i) {
+ if (arr[i] !== 0) {
+ if (currLen > maxLen) {
+ maxIdx = currStart;
+ maxLen = currLen;
+ }
- // 5. Let stream be the result of calling get stream on blob.
- /** @type {import('stream/web').ReadableStream} */
- const stream = blob.stream()
+ currStart = null;
+ currLen = 0;
+ } else {
+ if (currStart === null) {
+ currStart = i;
+ }
+ ++currLen;
+ }
+ }
- // 6. Let reader be the result of getting a reader from stream.
- const reader = stream.getReader()
+ // if trailing zeros
+ if (currLen > maxLen) {
+ maxIdx = currStart;
+ maxLen = currLen;
+ }
- // 7. Let bytes be an empty byte sequence.
- /** @type {Uint8Array[]} */
- const bytes = []
+ return {
+ idx: maxIdx,
+ len: maxLen
+ };
+}
- // 8. Let chunkPromise be the result of reading a chunk from
- // stream with reader.
- let chunkPromise = reader.read()
+function serializeHost(host) {
+ if (typeof host === "number") {
+ return serializeIPv4(host);
+ }
- // 9. Let isFirstChunk be true.
- let isFirstChunk = true
+ // IPv6 serializer
+ if (host instanceof Array) {
+ return "[" + serializeIPv6(host) + "]";
+ }
- // 10. In parallel, while true:
- // Note: "In parallel" just means non-blocking
- // Note 2: readOperation itself cannot be async as double
- // reading the body would then reject the promise, instead
- // of throwing an error.
- ;(async () => {
- while (!fr[kAborted]) {
- // 1. Wait for chunkPromise to be fulfilled or rejected.
- try {
- const { done, value } = await chunkPromise
+ return host;
+}
- // 2. If chunkPromise is fulfilled, and isFirstChunk is
- // true, queue a task to fire a progress event called
- // loadstart at fr.
- if (isFirstChunk && !fr[kAborted]) {
- queueMicrotask(() => {
- fireAProgressEvent('loadstart', fr)
- })
- }
+function trimControlChars(url) {
+ return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, "");
+}
- // 3. Set isFirstChunk to false.
- isFirstChunk = false
+function trimTabAndNewline(url) {
+ return url.replace(/\u0009|\u000A|\u000D/g, "");
+}
- // 4. If chunkPromise is fulfilled with an object whose
- // done property is false and whose value property is
- // a Uint8Array object, run these steps:
- if (!done && types.isUint8Array(value)) {
- // 1. Let bs be the byte sequence represented by the
- // Uint8Array object.
+function shortenPath(url) {
+ const path = url.path;
+ if (path.length === 0) {
+ return;
+ }
+ if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) {
+ return;
+ }
- // 2. Append bs to bytes.
- bytes.push(value)
+ path.pop();
+}
- // 3. If roughly 50ms have passed since these steps
- // were last invoked, queue a task to fire a
- // progress event called progress at fr.
- if (
- (
- fr[kLastProgressEventFired] === undefined ||
- Date.now() - fr[kLastProgressEventFired] >= 50
- ) &&
- !fr[kAborted]
- ) {
- fr[kLastProgressEventFired] = Date.now()
- queueMicrotask(() => {
- fireAProgressEvent('progress', fr)
- })
- }
+function includesCredentials(url) {
+ return url.username !== "" || url.password !== "";
+}
- // 4. Set chunkPromise to the result of reading a
- // chunk from stream with reader.
- chunkPromise = reader.read()
- } else if (done) {
- // 5. Otherwise, if chunkPromise is fulfilled with an
- // object whose done property is true, queue a task
- // to run the following steps and abort this algorithm:
- queueMicrotask(() => {
- // 1. Set fr’s state to "done".
- fr[kState] = 'done'
+function cannotHaveAUsernamePasswordPort(url) {
+ return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file";
+}
- // 2. Let result be the result of package data given
- // bytes, type, blob’s type, and encodingName.
- try {
- const result = packageData(bytes, type, blob.type, encodingName)
+function isNormalizedWindowsDriveLetter(string) {
+ return /^[A-Za-z]:$/.test(string);
+}
- // 4. Else:
+function URLStateMachine(input, base, encodingOverride, url, stateOverride) {
+ this.pointer = 0;
+ this.input = input;
+ this.base = base || null;
+ this.encodingOverride = encodingOverride || "utf-8";
+ this.stateOverride = stateOverride;
+ this.url = url;
+ this.failure = false;
+ this.parseError = false;
- if (fr[kAborted]) {
- return
- }
+ if (!this.url) {
+ this.url = {
+ scheme: "",
+ username: "",
+ password: "",
+ host: null,
+ port: null,
+ path: [],
+ query: null,
+ fragment: null,
- // 1. Set fr’s result to result.
- fr[kResult] = result
+ cannotBeABaseURL: false
+ };
- // 2. Fire a progress event called load at the fr.
- fireAProgressEvent('load', fr)
- } catch (error) {
- // 3. If package data threw an exception error:
+ const res = trimControlChars(this.input);
+ if (res !== this.input) {
+ this.parseError = true;
+ }
+ this.input = res;
+ }
- // 1. Set fr’s error to error.
- fr[kError] = error
+ const res = trimTabAndNewline(this.input);
+ if (res !== this.input) {
+ this.parseError = true;
+ }
+ this.input = res;
- // 2. Fire a progress event called error at fr.
- fireAProgressEvent('error', fr)
- }
+ this.state = stateOverride || "scheme start";
- // 5. If fr’s state is not "loading", fire a progress
- // event called loadend at the fr.
- if (fr[kState] !== 'loading') {
- fireAProgressEvent('loadend', fr)
- }
- })
+ this.buffer = "";
+ this.atFlag = false;
+ this.arrFlag = false;
+ this.passwordTokenSeenFlag = false;
- break
- }
- } catch (error) {
- if (fr[kAborted]) {
- return
- }
+ this.input = punycode.ucs2.decode(this.input);
- // 6. Otherwise, if chunkPromise is rejected with an
- // error error, queue a task to run the following
- // steps and abort this algorithm:
- queueMicrotask(() => {
- // 1. Set fr’s state to "done".
- fr[kState] = 'done'
+ for (; this.pointer <= this.input.length; ++this.pointer) {
+ const c = this.input[this.pointer];
+ const cStr = isNaN(c) ? undefined : String.fromCodePoint(c);
- // 2. Set fr’s error to error.
- fr[kError] = error
+ // exec state machine
+ const ret = this["parse " + this.state](c, cStr);
+ if (!ret) {
+ break; // terminate algorithm
+ } else if (ret === failure) {
+ this.failure = true;
+ break;
+ }
+ }
+}
- // 3. Fire a progress event called error at fr.
- fireAProgressEvent('error', fr)
+URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) {
+ if (isASCIIAlpha(c)) {
+ this.buffer += cStr.toLowerCase();
+ this.state = "scheme";
+ } else if (!this.stateOverride) {
+ this.state = "no scheme";
+ --this.pointer;
+ } else {
+ this.parseError = true;
+ return failure;
+ }
- // 4. If fr’s state is not "loading", fire a progress
- // event called loadend at fr.
- if (fr[kState] !== 'loading') {
- fireAProgressEvent('loadend', fr)
- }
- })
+ return true;
+};
- break
+URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) {
+ if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) {
+ this.buffer += cStr.toLowerCase();
+ } else if (c === 58) {
+ if (this.stateOverride) {
+ if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) {
+ return false;
}
- }
- })()
-}
-/**
- * @see https://w3c.github.io/FileAPI/#fire-a-progress-event
- * @see https://dom.spec.whatwg.org/#concept-event-fire
- * @param {string} e The name of the event
- * @param {import('./filereader').FileReader} reader
- */
-function fireAProgressEvent (e, reader) {
- // The progress event e does not bubble. e.bubbles must be false
- // The progress event e is NOT cancelable. e.cancelable must be false
- const event = new ProgressEvent(e, {
- bubbles: false,
- cancelable: false
- })
+ if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) {
+ return false;
+ }
- reader.dispatchEvent(event)
-}
+ if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") {
+ return false;
+ }
-/**
- * @see https://w3c.github.io/FileAPI/#blob-package-data
- * @param {Uint8Array[]} bytes
- * @param {string} type
- * @param {string?} mimeType
- * @param {string?} encodingName
- */
-function packageData (bytes, type, mimeType, encodingName) {
- // 1. A Blob has an associated package data algorithm, given
- // bytes, a type, a optional mimeType, and a optional
- // encodingName, which switches on type and runs the
- // associated steps:
+ if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) {
+ return false;
+ }
+ }
+ this.url.scheme = this.buffer;
+ this.buffer = "";
+ if (this.stateOverride) {
+ return false;
+ }
+ if (this.url.scheme === "file") {
+ if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) {
+ this.parseError = true;
+ }
+ this.state = "file";
+ } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) {
+ this.state = "special relative or authority";
+ } else if (isSpecial(this.url)) {
+ this.state = "special authority slashes";
+ } else if (this.input[this.pointer + 1] === 47) {
+ this.state = "path or authority";
+ ++this.pointer;
+ } else {
+ this.url.cannotBeABaseURL = true;
+ this.url.path.push("");
+ this.state = "cannot-be-a-base-URL path";
+ }
+ } else if (!this.stateOverride) {
+ this.buffer = "";
+ this.state = "no scheme";
+ this.pointer = -1;
+ } else {
+ this.parseError = true;
+ return failure;
+ }
- switch (type) {
- case 'DataURL': {
- // 1. Return bytes as a DataURL [RFC2397] subject to
- // the considerations below:
- // * Use mimeType as part of the Data URL if it is
- // available in keeping with the Data URL
- // specification [RFC2397].
- // * If mimeType is not available return a Data URL
- // without a media-type. [RFC2397].
+ return true;
+};
- // https://datatracker.ietf.org/doc/html/rfc2397#section-3
- // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
- // mediatype := [ type "/" subtype ] *( ";" parameter )
- // data := *urlchar
- // parameter := attribute "=" value
- let dataURL = 'data:'
+URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) {
+ if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) {
+ return failure;
+ } else if (this.base.cannotBeABaseURL && c === 35) {
+ this.url.scheme = this.base.scheme;
+ this.url.path = this.base.path.slice();
+ this.url.query = this.base.query;
+ this.url.fragment = "";
+ this.url.cannotBeABaseURL = true;
+ this.state = "fragment";
+ } else if (this.base.scheme === "file") {
+ this.state = "file";
+ --this.pointer;
+ } else {
+ this.state = "relative";
+ --this.pointer;
+ }
- const parsed = parseMIMEType(mimeType || 'application/octet-stream')
+ return true;
+};
- if (parsed !== 'failure') {
- dataURL += serializeAMimeType(parsed)
- }
+URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) {
+ if (c === 47 && this.input[this.pointer + 1] === 47) {
+ this.state = "special authority ignore slashes";
+ ++this.pointer;
+ } else {
+ this.parseError = true;
+ this.state = "relative";
+ --this.pointer;
+ }
- dataURL += ';base64,'
+ return true;
+};
- const decoder = new StringDecoder('latin1')
+URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) {
+ if (c === 47) {
+ this.state = "authority";
+ } else {
+ this.state = "path";
+ --this.pointer;
+ }
- for (const chunk of bytes) {
- dataURL += btoa(decoder.write(chunk))
- }
+ return true;
+};
- dataURL += btoa(decoder.end())
+URLStateMachine.prototype["parse relative"] = function parseRelative(c) {
+ this.url.scheme = this.base.scheme;
+ if (isNaN(c)) {
+ this.url.username = this.base.username;
+ this.url.password = this.base.password;
+ this.url.host = this.base.host;
+ this.url.port = this.base.port;
+ this.url.path = this.base.path.slice();
+ this.url.query = this.base.query;
+ } else if (c === 47) {
+ this.state = "relative slash";
+ } else if (c === 63) {
+ this.url.username = this.base.username;
+ this.url.password = this.base.password;
+ this.url.host = this.base.host;
+ this.url.port = this.base.port;
+ this.url.path = this.base.path.slice();
+ this.url.query = "";
+ this.state = "query";
+ } else if (c === 35) {
+ this.url.username = this.base.username;
+ this.url.password = this.base.password;
+ this.url.host = this.base.host;
+ this.url.port = this.base.port;
+ this.url.path = this.base.path.slice();
+ this.url.query = this.base.query;
+ this.url.fragment = "";
+ this.state = "fragment";
+ } else if (isSpecial(this.url) && c === 92) {
+ this.parseError = true;
+ this.state = "relative slash";
+ } else {
+ this.url.username = this.base.username;
+ this.url.password = this.base.password;
+ this.url.host = this.base.host;
+ this.url.port = this.base.port;
+ this.url.path = this.base.path.slice(0, this.base.path.length - 1);
- return dataURL
+ this.state = "path";
+ --this.pointer;
+ }
+
+ return true;
+};
+
+URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) {
+ if (isSpecial(this.url) && (c === 47 || c === 92)) {
+ if (c === 92) {
+ this.parseError = true;
}
- case 'Text': {
- // 1. Let encoding be failure
- let encoding = 'failure'
+ this.state = "special authority ignore slashes";
+ } else if (c === 47) {
+ this.state = "authority";
+ } else {
+ this.url.username = this.base.username;
+ this.url.password = this.base.password;
+ this.url.host = this.base.host;
+ this.url.port = this.base.port;
+ this.state = "path";
+ --this.pointer;
+ }
- // 2. If the encodingName is present, set encoding to the
- // result of getting an encoding from encodingName.
- if (encodingName) {
- encoding = getEncoding(encodingName)
- }
+ return true;
+};
- // 3. If encoding is failure, and mimeType is present:
- if (encoding === 'failure' && mimeType) {
- // 1. Let type be the result of parse a MIME type
- // given mimeType.
- const type = parseMIMEType(mimeType)
+URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) {
+ if (c === 47 && this.input[this.pointer + 1] === 47) {
+ this.state = "special authority ignore slashes";
+ ++this.pointer;
+ } else {
+ this.parseError = true;
+ this.state = "special authority ignore slashes";
+ --this.pointer;
+ }
- // 2. If type is not failure, set encoding to the result
- // of getting an encoding from type’s parameters["charset"].
- if (type !== 'failure') {
- encoding = getEncoding(type.parameters.get('charset'))
- }
- }
+ return true;
+};
- // 4. If encoding is failure, then set encoding to UTF-8.
- if (encoding === 'failure') {
- encoding = 'UTF-8'
+URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) {
+ if (c !== 47 && c !== 92) {
+ this.state = "authority";
+ --this.pointer;
+ } else {
+ this.parseError = true;
+ }
+
+ return true;
+};
+
+URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) {
+ if (c === 64) {
+ this.parseError = true;
+ if (this.atFlag) {
+ this.buffer = "%40" + this.buffer;
+ }
+ this.atFlag = true;
+
+ // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars
+ const len = countSymbols(this.buffer);
+ for (let pointer = 0; pointer < len; ++pointer) {
+ const codePoint = this.buffer.codePointAt(pointer);
+
+ if (codePoint === 58 && !this.passwordTokenSeenFlag) {
+ this.passwordTokenSeenFlag = true;
+ continue;
}
+ const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode);
+ if (this.passwordTokenSeenFlag) {
+ this.url.password += encodedCodePoints;
+ } else {
+ this.url.username += encodedCodePoints;
+ }
+ }
+ this.buffer = "";
+ } else if (isNaN(c) || c === 47 || c === 63 || c === 35 ||
+ (isSpecial(this.url) && c === 92)) {
+ if (this.atFlag && this.buffer === "") {
+ this.parseError = true;
+ return failure;
+ }
+ this.pointer -= countSymbols(this.buffer) + 1;
+ this.buffer = "";
+ this.state = "host";
+ } else {
+ this.buffer += cStr;
+ }
- // 5. Decode bytes using fallback encoding encoding, and
- // return the result.
- return decode(bytes, encoding)
+ return true;
+};
+
+URLStateMachine.prototype["parse hostname"] =
+URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) {
+ if (this.stateOverride && this.url.scheme === "file") {
+ --this.pointer;
+ this.state = "file host";
+ } else if (c === 58 && !this.arrFlag) {
+ if (this.buffer === "") {
+ this.parseError = true;
+ return failure;
}
- case 'ArrayBuffer': {
- // Return a new ArrayBuffer whose contents are bytes.
- const sequence = combineByteSequences(bytes)
- return sequence.buffer
+ const host = parseHost(this.buffer, isSpecial(this.url));
+ if (host === failure) {
+ return failure;
}
- case 'BinaryString': {
- // Return bytes as a binary string, in which every byte
- // is represented by a code unit of equal value [0..255].
- let binaryString = ''
- const decoder = new StringDecoder('latin1')
+ this.url.host = host;
+ this.buffer = "";
+ this.state = "port";
+ if (this.stateOverride === "hostname") {
+ return false;
+ }
+ } else if (isNaN(c) || c === 47 || c === 63 || c === 35 ||
+ (isSpecial(this.url) && c === 92)) {
+ --this.pointer;
+ if (isSpecial(this.url) && this.buffer === "") {
+ this.parseError = true;
+ return failure;
+ } else if (this.stateOverride && this.buffer === "" &&
+ (includesCredentials(this.url) || this.url.port !== null)) {
+ this.parseError = true;
+ return false;
+ }
- for (const chunk of bytes) {
- binaryString += decoder.write(chunk)
- }
+ const host = parseHost(this.buffer, isSpecial(this.url));
+ if (host === failure) {
+ return failure;
+ }
- binaryString += decoder.end()
+ this.url.host = host;
+ this.buffer = "";
+ this.state = "path start";
+ if (this.stateOverride) {
+ return false;
+ }
+ } else {
+ if (c === 91) {
+ this.arrFlag = true;
+ } else if (c === 93) {
+ this.arrFlag = false;
+ }
+ this.buffer += cStr;
+ }
- return binaryString
+ return true;
+};
+
+URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) {
+ if (isASCIIDigit(c)) {
+ this.buffer += cStr;
+ } else if (isNaN(c) || c === 47 || c === 63 || c === 35 ||
+ (isSpecial(this.url) && c === 92) ||
+ this.stateOverride) {
+ if (this.buffer !== "") {
+ const port = parseInt(this.buffer);
+ if (port > Math.pow(2, 16) - 1) {
+ this.parseError = true;
+ return failure;
+ }
+ this.url.port = port === defaultPort(this.url.scheme) ? null : port;
+ this.buffer = "";
}
+ if (this.stateOverride) {
+ return false;
+ }
+ this.state = "path start";
+ --this.pointer;
+ } else {
+ this.parseError = true;
+ return failure;
}
-}
-/**
- * @see https://encoding.spec.whatwg.org/#decode
- * @param {Uint8Array[]} ioQueue
- * @param {string} encoding
- */
-function decode (ioQueue, encoding) {
- const bytes = combineByteSequences(ioQueue)
+ return true;
+};
- // 1. Let BOMEncoding be the result of BOM sniffing ioQueue.
- const BOMEncoding = BOMSniffing(bytes)
+const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]);
+
+URLStateMachine.prototype["parse file"] = function parseFile(c) {
+ this.url.scheme = "file";
+
+ if (c === 47 || c === 92) {
+ if (c === 92) {
+ this.parseError = true;
+ }
+ this.state = "file slash";
+ } else if (this.base !== null && this.base.scheme === "file") {
+ if (isNaN(c)) {
+ this.url.host = this.base.host;
+ this.url.path = this.base.path.slice();
+ this.url.query = this.base.query;
+ } else if (c === 63) {
+ this.url.host = this.base.host;
+ this.url.path = this.base.path.slice();
+ this.url.query = "";
+ this.state = "query";
+ } else if (c === 35) {
+ this.url.host = this.base.host;
+ this.url.path = this.base.path.slice();
+ this.url.query = this.base.query;
+ this.url.fragment = "";
+ this.state = "fragment";
+ } else {
+ if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points
+ !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) ||
+ (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points
+ !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) {
+ this.url.host = this.base.host;
+ this.url.path = this.base.path.slice();
+ shortenPath(this.url);
+ } else {
+ this.parseError = true;
+ }
- let slice = 0
+ this.state = "path";
+ --this.pointer;
+ }
+ } else {
+ this.state = "path";
+ --this.pointer;
+ }
- // 2. If BOMEncoding is non-null:
- if (BOMEncoding !== null) {
- // 1. Set encoding to BOMEncoding.
- encoding = BOMEncoding
+ return true;
+};
- // 2. Read three bytes from ioQueue, if BOMEncoding is
- // UTF-8; otherwise read two bytes.
- // (Do nothing with those bytes.)
- slice = BOMEncoding === 'UTF-8' ? 3 : 2
+URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) {
+ if (c === 47 || c === 92) {
+ if (c === 92) {
+ this.parseError = true;
+ }
+ this.state = "file host";
+ } else {
+ if (this.base !== null && this.base.scheme === "file") {
+ if (isNormalizedWindowsDriveLetterString(this.base.path[0])) {
+ this.url.path.push(this.base.path[0]);
+ } else {
+ this.url.host = this.base.host;
+ }
+ }
+ this.state = "path";
+ --this.pointer;
}
- // 3. Process a queue with an instance of encoding’s
- // decoder, ioQueue, output, and "replacement".
+ return true;
+};
+
+URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) {
+ if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) {
+ --this.pointer;
+ if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) {
+ this.parseError = true;
+ this.state = "path";
+ } else if (this.buffer === "") {
+ this.url.host = "";
+ if (this.stateOverride) {
+ return false;
+ }
+ this.state = "path start";
+ } else {
+ let host = parseHost(this.buffer, isSpecial(this.url));
+ if (host === failure) {
+ return failure;
+ }
+ if (host === "localhost") {
+ host = "";
+ }
+ this.url.host = host;
+
+ if (this.stateOverride) {
+ return false;
+ }
- // 4. Return output.
+ this.buffer = "";
+ this.state = "path start";
+ }
+ } else {
+ this.buffer += cStr;
+ }
- const sliced = bytes.slice(slice)
- return new TextDecoder(encoding).decode(sliced)
-}
+ return true;
+};
-/**
- * @see https://encoding.spec.whatwg.org/#bom-sniff
- * @param {Uint8Array} ioQueue
- */
-function BOMSniffing (ioQueue) {
- // 1. Let BOM be the result of peeking 3 bytes from ioQueue,
- // converted to a byte sequence.
- const [a, b, c] = ioQueue
+URLStateMachine.prototype["parse path start"] = function parsePathStart(c) {
+ if (isSpecial(this.url)) {
+ if (c === 92) {
+ this.parseError = true;
+ }
+ this.state = "path";
- // 2. For each of the rows in the table below, starting with
- // the first one and going down, if BOM starts with the
- // bytes given in the first column, then return the
- // encoding given in the cell in the second column of that
- // row. Otherwise, return null.
- if (a === 0xEF && b === 0xBB && c === 0xBF) {
- return 'UTF-8'
- } else if (a === 0xFE && b === 0xFF) {
- return 'UTF-16BE'
- } else if (a === 0xFF && b === 0xFE) {
- return 'UTF-16LE'
+ if (c !== 47 && c !== 92) {
+ --this.pointer;
+ }
+ } else if (!this.stateOverride && c === 63) {
+ this.url.query = "";
+ this.state = "query";
+ } else if (!this.stateOverride && c === 35) {
+ this.url.fragment = "";
+ this.state = "fragment";
+ } else if (c !== undefined) {
+ this.state = "path";
+ if (c !== 47) {
+ --this.pointer;
+ }
}
- return null
-}
+ return true;
+};
-/**
- * @param {Uint8Array[]} sequences
- */
-function combineByteSequences (sequences) {
- const size = sequences.reduce((a, b) => {
- return a + b.byteLength
- }, 0)
+URLStateMachine.prototype["parse path"] = function parsePath(c) {
+ if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) ||
+ (!this.stateOverride && (c === 63 || c === 35))) {
+ if (isSpecial(this.url) && c === 92) {
+ this.parseError = true;
+ }
- let offset = 0
+ if (isDoubleDot(this.buffer)) {
+ shortenPath(this.url);
+ if (c !== 47 && !(isSpecial(this.url) && c === 92)) {
+ this.url.path.push("");
+ }
+ } else if (isSingleDot(this.buffer) && c !== 47 &&
+ !(isSpecial(this.url) && c === 92)) {
+ this.url.path.push("");
+ } else if (!isSingleDot(this.buffer)) {
+ if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) {
+ if (this.url.host !== "" && this.url.host !== null) {
+ this.parseError = true;
+ this.url.host = "";
+ }
+ this.buffer = this.buffer[0] + ":";
+ }
+ this.url.path.push(this.buffer);
+ }
+ this.buffer = "";
+ if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) {
+ while (this.url.path.length > 1 && this.url.path[0] === "") {
+ this.parseError = true;
+ this.url.path.shift();
+ }
+ }
+ if (c === 63) {
+ this.url.query = "";
+ this.state = "query";
+ }
+ if (c === 35) {
+ this.url.fragment = "";
+ this.state = "fragment";
+ }
+ } else {
+ // TODO: If c is not a URL code point and not "%", parse error.
- return sequences.reduce((a, b) => {
- a.set(b, offset)
- offset += b.byteLength
- return a
- }, new Uint8Array(size))
-}
+ if (c === 37 &&
+ (!isASCIIHex(this.input[this.pointer + 1]) ||
+ !isASCIIHex(this.input[this.pointer + 2]))) {
+ this.parseError = true;
+ }
-module.exports = {
- staticPropertyDescriptors,
- readOperation,
- fireAProgressEvent
-}
+ this.buffer += percentEncodeChar(c, isPathPercentEncode);
+ }
+ return true;
+};
-/***/ }),
+URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) {
+ if (c === 63) {
+ this.url.query = "";
+ this.state = "query";
+ } else if (c === 35) {
+ this.url.fragment = "";
+ this.state = "fragment";
+ } else {
+ // TODO: Add: not a URL code point
+ if (!isNaN(c) && c !== 37) {
+ this.parseError = true;
+ }
-/***/ 2581:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (c === 37 &&
+ (!isASCIIHex(this.input[this.pointer + 1]) ||
+ !isASCIIHex(this.input[this.pointer + 2]))) {
+ this.parseError = true;
+ }
-"use strict";
+ if (!isNaN(c)) {
+ this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode);
+ }
+ }
+ return true;
+};
-// 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__(8707)
-const Agent = __nccwpck_require__(9965)
+URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) {
+ if (isNaN(c) || (!this.stateOverride && c === 35)) {
+ if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") {
+ this.encodingOverride = "utf-8";
+ }
-if (getGlobalDispatcher() === undefined) {
- setGlobalDispatcher(new Agent())
-}
+ const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead
+ for (let i = 0; i < buffer.length; ++i) {
+ if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 ||
+ buffer[i] === 0x3C || buffer[i] === 0x3E) {
+ this.url.query += percentEncode(buffer[i]);
+ } else {
+ this.url.query += String.fromCodePoint(buffer[i]);
+ }
+ }
-function setGlobalDispatcher (agent) {
- if (!agent || typeof agent.dispatch !== 'function') {
- throw new InvalidArgumentError('Argument agent must implement Agent')
+ this.buffer = "";
+ if (c === 35) {
+ this.url.fragment = "";
+ this.state = "fragment";
+ }
+ } else {
+ // TODO: If c is not a URL code point and not "%", parse error.
+ if (c === 37 &&
+ (!isASCIIHex(this.input[this.pointer + 1]) ||
+ !isASCIIHex(this.input[this.pointer + 2]))) {
+ this.parseError = true;
+ }
+
+ this.buffer += cStr;
}
- Object.defineProperty(globalThis, globalDispatcher, {
- value: agent,
- writable: true,
- enumerable: false,
- configurable: false
- })
-}
-function getGlobalDispatcher () {
- return globalThis[globalDispatcher]
-}
+ return true;
+};
-module.exports = {
- setGlobalDispatcher,
- getGlobalDispatcher
-}
+URLStateMachine.prototype["parse fragment"] = function parseFragment(c) {
+ if (isNaN(c)) { // do nothing
+ } else if (c === 0x0) {
+ this.parseError = true;
+ } else {
+ // TODO: If c is not a URL code point and not "%", parse error.
+ if (c === 37 &&
+ (!isASCIIHex(this.input[this.pointer + 1]) ||
+ !isASCIIHex(this.input[this.pointer + 2]))) {
+ this.parseError = true;
+ }
+ this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode);
+ }
-/***/ }),
+ return true;
+};
-/***/ 8840:
-/***/ ((module) => {
+function serializeURL(url, excludeFragment) {
+ let output = url.scheme + ":";
+ if (url.host !== null) {
+ output += "//";
-"use strict";
+ if (url.username !== "" || url.password !== "") {
+ output += url.username;
+ if (url.password !== "") {
+ output += ":" + url.password;
+ }
+ output += "@";
+ }
+ output += serializeHost(url.host);
-module.exports = class DecoratorHandler {
- constructor (handler) {
- this.handler = handler
+ if (url.port !== null) {
+ output += ":" + url.port;
+ }
+ } else if (url.host === null && url.scheme === "file") {
+ output += "//";
}
- onConnect (...args) {
- return this.handler.onConnect(...args)
+ if (url.cannotBeABaseURL) {
+ output += url.path[0];
+ } else {
+ for (const string of url.path) {
+ output += "/" + string;
+ }
}
- onError (...args) {
- return this.handler.onError(...args)
+ if (url.query !== null) {
+ output += "?" + url.query;
}
- onUpgrade (...args) {
- return this.handler.onUpgrade(...args)
+ if (!excludeFragment && url.fragment !== null) {
+ output += "#" + url.fragment;
}
- onHeaders (...args) {
- return this.handler.onHeaders(...args)
- }
+ return output;
+}
- onData (...args) {
- return this.handler.onData(...args)
- }
+function serializeOrigin(tuple) {
+ let result = tuple.scheme + "://";
+ result += serializeHost(tuple.host);
- onComplete (...args) {
- return this.handler.onComplete(...args)
+ if (tuple.port !== null) {
+ result += ":" + tuple.port;
}
- onBodySent (...args) {
- return this.handler.onBodySent(...args)
- }
+ return result;
}
+module.exports.serializeURL = serializeURL;
-/***/ }),
+module.exports.serializeURLOrigin = function (url) {
+ // https://url.spec.whatwg.org/#concept-url-origin
+ switch (url.scheme) {
+ case "blob":
+ try {
+ return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0]));
+ } catch (e) {
+ // serializing an opaque origin returns "null"
+ return "null";
+ }
+ case "ftp":
+ case "gopher":
+ case "http":
+ case "https":
+ case "ws":
+ case "wss":
+ return serializeOrigin({
+ scheme: url.scheme,
+ host: url.host,
+ port: url.port
+ });
+ case "file":
+ // spec says "exercise to the reader", chrome says "file://"
+ return "file://";
+ default:
+ // serializing an opaque origin returns "null"
+ return "null";
+ }
+};
-/***/ 8299:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+module.exports.basicURLParse = function (input, options) {
+ if (options === undefined) {
+ options = {};
+ }
-"use strict";
+ const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride);
+ if (usm.failure) {
+ return "failure";
+ }
+ return usm.url;
+};
-const util = __nccwpck_require__(3440)
-const { kBodyUsed } = __nccwpck_require__(6443)
-const assert = __nccwpck_require__(2613)
-const { InvalidArgumentError } = __nccwpck_require__(8707)
-const EE = __nccwpck_require__(4434)
+module.exports.setTheUsername = function (url, username) {
+ url.username = "";
+ const decoded = punycode.ucs2.decode(username);
+ for (let i = 0; i < decoded.length; ++i) {
+ url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode);
+ }
+};
-const redirectableStatusCodes = [300, 301, 302, 303, 307, 308]
+module.exports.setThePassword = function (url, password) {
+ url.password = "";
+ const decoded = punycode.ucs2.decode(password);
+ for (let i = 0; i < decoded.length; ++i) {
+ url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode);
+ }
+};
-const kBody = Symbol('body')
+module.exports.serializeHost = serializeHost;
-class BodyAsyncIterable {
- constructor (body) {
- this[kBody] = body
- this[kBodyUsed] = false
- }
+module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort;
- async * [Symbol.asyncIterator] () {
- assert(!this[kBodyUsed], 'disturbed')
- this[kBodyUsed] = true
- yield * this[kBody]
+module.exports.serializeInteger = function (integer) {
+ return String(integer);
+};
+
+module.exports.parseURL = function (input, options) {
+ if (options === undefined) {
+ options = {};
}
-}
-class RedirectHandler {
- constructor (dispatch, maxRedirections, opts, handler) {
- if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
- throw new InvalidArgumentError('maxRedirections must be a positive number')
- }
+ // We don't handle blobs, so this just delegates:
+ return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride });
+};
- util.validateHandler(handler, opts.method, opts.upgrade)
- this.dispatch = dispatch
- this.location = null
- this.abort = null
- this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy
- 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)
- })
- }
+/***/ 39857:
+/***/ ((module) => {
- 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)
- ) {
- // TODO: Should we allow re-using iterable if !this.opts.idempotent
- // or through some other flag?
- this.opts.body = new BodyAsyncIterable(this.opts.body)
- }
- }
+"use strict";
- onConnect (abort) {
- this.abort = abort
- this.handler.onConnect(abort, { history: this.history })
- }
- onUpgrade (statusCode, headers, socket) {
- this.handler.onUpgrade(statusCode, headers, socket)
+module.exports.mixin = function mixin(target, source) {
+ const keys = Object.getOwnPropertyNames(source);
+ for (let i = 0; i < keys.length; ++i) {
+ Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i]));
}
+};
- onError (error) {
- this.handler.onError(error)
- }
+module.exports.wrapperSymbol = Symbol("wrapper");
+module.exports.implSymbol = Symbol("impl");
- onHeaders (statusCode, headers, resume, statusText) {
- this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body)
- ? null
- : parseLocation(statusCode, headers)
+module.exports.wrapperForImpl = function (impl) {
+ return impl[module.exports.wrapperSymbol];
+};
- if (this.opts.origin) {
- this.history.push(new URL(this.opts.path, this.opts.origin))
- }
+module.exports.implForWrapper = function (wrapper) {
+ return wrapper[module.exports.implSymbol];
+};
- if (!this.location) {
- return this.handler.onHeaders(statusCode, headers, resume, statusText)
- }
- 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.maxRedirections = 0
- this.opts.query = 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'
- this.opts.body = null
- }
- }
+/***/ 58264:
+/***/ ((module) => {
- onData (chunk) {
- if (this.location) {
- /*
- https://tools.ietf.org/html/rfc7231#section-6.4
+// Returns a wrapper function that returns a wrapped callback
+// The wrapper function should do some stuff, and return a
+// presumably different callback function.
+// This makes sure that own properties are retained, so that
+// decorations and such are not lost along the way.
+module.exports = wrappy
+function wrappy (fn, cb) {
+ if (fn && cb) return wrappy(fn)(cb)
- TLDR: undici always ignores 3xx response bodies.
+ if (typeof fn !== 'function')
+ throw new TypeError('need wrapper function')
- Redirection is used to serve the requested resource from another URL, so it is assumes that
- no body is generated (and thus can be ignored). Even though generating a body is not prohibited.
+ Object.keys(fn).forEach(function (k) {
+ wrapper[k] = fn[k]
+ })
- 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.
+ return wrapper
- 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 explicitily 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 {
- return this.handler.onData(chunk)
+ function wrapper() {
+ var args = new Array(arguments.length)
+ for (var i = 0; i < args.length; i++) {
+ args[i] = arguments[i]
+ }
+ var ret = fn.apply(this, args)
+ var cb = args[args.length-1]
+ if (typeof ret === 'function' && ret !== cb) {
+ Object.keys(cb).forEach(function (k) {
+ ret[k] = cb[k]
+ })
}
+ return ret
}
+}
- onComplete (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 informations.
- */
+/***/ 30538:
+/***/ ((module) => {
- this.location = null
- this.abort = null
+class Node {
+ /// value;
+ /// next;
- this.dispatch(this.opts, this)
- } else {
- this.handler.onComplete(trailers)
- }
- }
+ constructor(value) {
+ this.value = value;
- onBodySent (chunk) {
- if (this.handler.onBodySent) {
- this.handler.onBodySent(chunk)
- }
- }
+ // TODO: Remove this when targeting Node.js 12.
+ this.next = undefined;
+ }
}
-function parseLocation (statusCode, headers) {
- if (redirectableStatusCodes.indexOf(statusCode) === -1) {
- return null
- }
-
- for (let i = 0; i < headers.length; i += 2) {
- if (headers[i].toString().toLowerCase() === 'location') {
- return headers[i + 1]
- }
- }
-}
+class Queue {
+ // TODO: Use private class fields when targeting Node.js 12.
+ // #_head;
+ // #_tail;
+ // #_size;
-// 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
-}
+ constructor() {
+ this.clear();
+ }
-// 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') {
- for (const key of Object.keys(headers)) {
- if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
- ret.push(key, headers[key])
- }
- }
- } else {
- assert(headers == null, 'headers must be an object or an array')
- }
- return ret
-}
+ enqueue(value) {
+ const node = new Node(value);
-module.exports = RedirectHandler
+ if (this._head) {
+ this._tail.next = node;
+ this._tail = node;
+ } else {
+ this._head = node;
+ this._tail = node;
+ }
+ this._size++;
+ }
-/***/ }),
+ dequeue() {
+ const current = this._head;
+ if (!current) {
+ return;
+ }
-/***/ 3573:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ this._head = this._head.next;
+ this._size--;
+ return current.value;
+ }
-const assert = __nccwpck_require__(2613)
+ clear() {
+ this._head = undefined;
+ this._tail = undefined;
+ this._size = 0;
+ }
-const { kRetryHandlerDefaultRetry } = __nccwpck_require__(6443)
-const { RequestRetryError } = __nccwpck_require__(8707)
-const { isDisturbed, parseHeaders, parseRangeHeader } = __nccwpck_require__(3440)
+ get size() {
+ return this._size;
+ }
-function calculateRetryAfterHeader (retryAfter) {
- const current = Date.now()
- const diff = new Date(retryAfter).getTime() - current
+ * [Symbol.iterator]() {
+ let current = this._head;
- return diff
+ while (current) {
+ yield current.value;
+ current = current.next;
+ }
+ }
}
-class RetryHandler {
- constructor (opts, handlers) {
- const { retryOptions, ...dispatchOpts } = opts
- const {
- // Retry scoped
- retry: retryFn,
- maxRetries,
- maxTimeout,
- minTimeout,
- timeoutFactor,
- // Response scoped
- methods,
- errorCodes,
- retryAfter,
- statusCodes
- } = retryOptions ?? {}
+module.exports = Queue;
- this.dispatch = handlers.dispatch
- this.handler = handlers.handler
- this.opts = dispatchOpts
- this.abort = null
- this.aborted = false
- this.retryOpts = {
- retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry],
- retryAfter: retryAfter ?? true,
- maxTimeout: maxTimeout ?? 30 * 1000, // 30s,
- timeout: 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'
- ]
- }
- this.retryCount = 0
- this.start = 0
- this.end = null
- this.etag = null
- this.resume = null
+/***/ }),
- // Handle possible onConnect duplication
- this.handler.onConnect(reason => {
- this.aborted = true
- if (this.abort) {
- this.abort(reason)
- } else {
- this.reason = reason
- }
- })
- }
+/***/ 42078:
+/***/ ((module) => {
- onRequestSent () {
- if (this.handler.onRequestSent) {
- this.handler.onRequestSent()
- }
- }
+module.exports = eval("require")("encoding");
- onUpgrade (statusCode, headers, socket) {
- if (this.handler.onUpgrade) {
- this.handler.onUpgrade(statusCode, headers, socket)
- }
- }
- onConnect (abort) {
- if (this.aborted) {
- abort(this.reason)
- } else {
- this.abort = abort
- }
- }
+/***/ }),
- onBodySent (chunk) {
- if (this.handler.onBodySent) return this.handler.onBodySent(chunk)
- }
+/***/ 60075:
+/***/ ((module) => {
- static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) {
- const { statusCode, code, headers } = err
- const { method, retryOptions } = opts
- const {
- maxRetries,
- timeout,
- maxTimeout,
- timeoutFactor,
- statusCodes,
- errorCodes,
- methods
- } = retryOptions
- let { counter, currentTimeout } = state
+module.exports = eval("require")("supports-color");
- currentTimeout =
- currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout
- // Any code that is not a Undici's originated and allowed to retry
- if (
- code &&
- code !== 'UND_ERR_REQ_RETRY' &&
- code !== 'UND_ERR_SOCKET' &&
- !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
- }
+/***/ 42613:
+/***/ ((module) => {
- // 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
- }
+"use strict";
+module.exports = require("assert");
- // If we reached the max number of retries
- if (counter > maxRetries) {
- cb(err)
- return
- }
+/***/ }),
+
+/***/ 90290:
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("async_hooks");
- let retryAfterHeader = headers != null && headers['retry-after']
- if (retryAfterHeader) {
- retryAfterHeader = Number(retryAfterHeader)
- retryAfterHeader = isNaN(retryAfterHeader)
- ? calculateRetryAfterHeader(retryAfterHeader)
- : retryAfterHeader * 1e3 // Retry-After is in seconds
- }
+/***/ }),
- const retryTimeout =
- retryAfterHeader > 0
- ? Math.min(retryAfterHeader, maxTimeout)
- : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout)
+/***/ 20181:
+/***/ ((module) => {
- state.currentTimeout = retryTimeout
+"use strict";
+module.exports = require("buffer");
- setTimeout(() => cb(null), retryTimeout)
- }
+/***/ }),
- onHeaders (statusCode, rawHeaders, resume, statusMessage) {
- const headers = parseHeaders(rawHeaders)
+/***/ 35317:
+/***/ ((module) => {
- this.retryCount += 1
+"use strict";
+module.exports = require("child_process");
- if (statusCode >= 300) {
- this.abort(
- new RequestRetryError('Request failed', statusCode, {
- headers,
- count: this.retryCount
- })
- )
- return false
- }
+/***/ }),
- // Checkpoint for resume from where we left it
- if (this.resume != null) {
- this.resume = null
+/***/ 64236:
+/***/ ((module) => {
- if (statusCode !== 206) {
- return true
- }
+"use strict";
+module.exports = require("console");
- const contentRange = parseRangeHeader(headers['content-range'])
- // If no content range
- if (!contentRange) {
- this.abort(
- new RequestRetryError('Content-Range mismatch', statusCode, {
- headers,
- count: this.retryCount
- })
- )
- return false
- }
+/***/ }),
- // Let's start with a weak etag check
- if (this.etag != null && this.etag !== headers.etag) {
- this.abort(
- new RequestRetryError('ETag mismatch', statusCode, {
- headers,
- count: this.retryCount
- })
- )
- return false
- }
+/***/ 76982:
+/***/ ((module) => {
- const { start, size, end = size } = contentRange
+"use strict";
+module.exports = require("crypto");
- assert(this.start === start, 'content-range mismatch')
- assert(this.end == null || this.end === end, 'content-range mismatch')
+/***/ }),
- this.resume = resume
- return true
- }
+/***/ 31637:
+/***/ ((module) => {
- if (this.end == null) {
- if (statusCode === 206) {
- // First time we receive 206
- const range = parseRangeHeader(headers['content-range'])
+"use strict";
+module.exports = require("diagnostics_channel");
- if (range == null) {
- return this.handler.onHeaders(
- statusCode,
- rawHeaders,
- resume,
- statusMessage
- )
- }
+/***/ }),
- const { start, size, end = size } = range
+/***/ 24434:
+/***/ ((module) => {
- assert(
- start != null && Number.isFinite(start) && this.start !== start,
- 'content-range mismatch'
- )
- assert(Number.isFinite(start))
- assert(
- end != null && Number.isFinite(end) && this.end !== end,
- 'invalid content-length'
- )
+"use strict";
+module.exports = require("events");
- 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) : null
- }
+/***/ 79896:
+/***/ ((module) => {
- assert(Number.isFinite(this.start))
- assert(
- this.end == null || Number.isFinite(this.end),
- 'invalid content-length'
- )
+"use strict";
+module.exports = require("fs");
- this.resume = resume
- this.etag = headers.etag != null ? headers.etag : null
+/***/ }),
- return this.handler.onHeaders(
- statusCode,
- rawHeaders,
- resume,
- statusMessage
- )
- }
+/***/ 91943:
+/***/ ((module) => {
- const err = new RequestRetryError('Request failed', statusCode, {
- headers,
- count: this.retryCount
- })
+"use strict";
+module.exports = require("fs/promises");
- this.abort(err)
+/***/ }),
- return false
- }
+/***/ 58611:
+/***/ ((module) => {
- onData (chunk) {
- this.start += chunk.length
+"use strict";
+module.exports = require("http");
- return this.handler.onData(chunk)
- }
+/***/ }),
- onComplete (rawTrailers) {
- this.retryCount = 0
- return this.handler.onComplete(rawTrailers)
- }
+/***/ 85675:
+/***/ ((module) => {
- onError (err) {
- if (this.aborted || isDisturbed(this.opts.body)) {
- return this.handler.onError(err)
- }
+"use strict";
+module.exports = require("http2");
- this.retryOpts.retry(
- err,
- {
- state: { counter: this.retryCount++, currentTimeout: this.retryAfter },
- opts: { retryOptions: this.retryOpts, ...this.opts }
- },
- onRetry.bind(this)
- )
+/***/ }),
- function onRetry (err) {
- if (err != null || this.aborted || isDisturbed(this.opts.body)) {
- return this.handler.onError(err)
- }
+/***/ 65692:
+/***/ ((module) => {
- if (this.start !== 0) {
- this.opts = {
- ...this.opts,
- headers: {
- ...this.opts.headers,
- range: `bytes=${this.start}-${this.end ?? ''}`
- }
- }
- }
+"use strict";
+module.exports = require("https");
- try {
- this.dispatch(this.opts, this)
- } catch (err) {
- this.handler.onError(err)
- }
- }
- }
-}
+/***/ }),
-module.exports = RetryHandler
+/***/ 69278:
+/***/ ((module) => {
+"use strict";
+module.exports = require("net");
/***/ }),
-/***/ 4415:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 77598:
+/***/ ((module) => {
"use strict";
+module.exports = require("node:crypto");
+/***/ }),
-const RedirectHandler = __nccwpck_require__(8299)
+/***/ 78474:
+/***/ ((module) => {
-function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) {
- return (dispatch) => {
- return function Intercept (opts, handler) {
- const { maxRedirections = defaultMaxRedirections } = opts
+"use strict";
+module.exports = require("node:events");
- if (!maxRedirections) {
- return dispatch(opts, handler)
- }
+/***/ }),
- const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler)
- opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting.
- return dispatch(opts, redirectHandler)
- }
- }
-}
+/***/ 37067:
+/***/ ((module) => {
-module.exports = createRedirectInterceptor
+"use strict";
+module.exports = require("node:http");
+
+/***/ }),
+/***/ 44708:
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("node:https");
/***/ }),
-/***/ 2824:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 48161:
+/***/ ((module) => {
"use strict";
+module.exports = require("node:os");
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0;
-const utils_1 = __nccwpck_require__(172);
-// C headers
-var ERROR;
-(function (ERROR) {
- ERROR[ERROR["OK"] = 0] = "OK";
- ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL";
- ERROR[ERROR["STRICT"] = 2] = "STRICT";
- ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED";
- ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH";
- ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION";
- ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD";
- ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL";
- ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT";
- ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION";
- ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN";
- ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH";
- ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE";
- ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS";
- ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE";
- ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING";
- ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN";
- ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE";
- ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE";
- ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER";
- ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE";
- ERROR[ERROR["PAUSED"] = 21] = "PAUSED";
- ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE";
- ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE";
- ERROR[ERROR["USER"] = 24] = "USER";
-})(ERROR = exports.ERROR || (exports.ERROR = {}));
-var TYPE;
-(function (TYPE) {
- TYPE[TYPE["BOTH"] = 0] = "BOTH";
- TYPE[TYPE["REQUEST"] = 1] = "REQUEST";
- TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE";
-})(TYPE = exports.TYPE || (exports.TYPE = {}));
-var FLAGS;
-(function (FLAGS) {
- FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE";
- FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE";
- FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE";
- FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED";
- FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE";
- FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH";
- FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY";
- FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING";
- // 1 << 8 is unused
- FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING";
-})(FLAGS = exports.FLAGS || (exports.FLAGS = {}));
-var LENIENT_FLAGS;
-(function (LENIENT_FLAGS) {
- LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS";
- LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH";
- LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE";
-})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {}));
-var METHODS;
-(function (METHODS) {
- METHODS[METHODS["DELETE"] = 0] = "DELETE";
- METHODS[METHODS["GET"] = 1] = "GET";
- METHODS[METHODS["HEAD"] = 2] = "HEAD";
- METHODS[METHODS["POST"] = 3] = "POST";
- METHODS[METHODS["PUT"] = 4] = "PUT";
- /* pathological */
- METHODS[METHODS["CONNECT"] = 5] = "CONNECT";
- METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS";
- METHODS[METHODS["TRACE"] = 7] = "TRACE";
- /* WebDAV */
- METHODS[METHODS["COPY"] = 8] = "COPY";
- METHODS[METHODS["LOCK"] = 9] = "LOCK";
- METHODS[METHODS["MKCOL"] = 10] = "MKCOL";
- METHODS[METHODS["MOVE"] = 11] = "MOVE";
- METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND";
- METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH";
- METHODS[METHODS["SEARCH"] = 14] = "SEARCH";
- METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK";
- METHODS[METHODS["BIND"] = 16] = "BIND";
- METHODS[METHODS["REBIND"] = 17] = "REBIND";
- METHODS[METHODS["UNBIND"] = 18] = "UNBIND";
- METHODS[METHODS["ACL"] = 19] = "ACL";
- /* subversion */
- METHODS[METHODS["REPORT"] = 20] = "REPORT";
- METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY";
- METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT";
- METHODS[METHODS["MERGE"] = 23] = "MERGE";
- /* upnp */
- METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH";
- METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY";
- METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE";
- METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE";
- /* RFC-5789 */
- METHODS[METHODS["PATCH"] = 28] = "PATCH";
- METHODS[METHODS["PURGE"] = 29] = "PURGE";
- /* CalDAV */
- METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR";
- /* RFC-2068, section 19.6.1.2 */
- METHODS[METHODS["LINK"] = 31] = "LINK";
- METHODS[METHODS["UNLINK"] = 32] = "UNLINK";
- /* icecast */
- METHODS[METHODS["SOURCE"] = 33] = "SOURCE";
- /* RFC-7540, section 11.6 */
- METHODS[METHODS["PRI"] = 34] = "PRI";
- /* RFC-2326 RTSP */
- METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE";
- METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE";
- METHODS[METHODS["SETUP"] = 37] = "SETUP";
- METHODS[METHODS["PLAY"] = 38] = "PLAY";
- METHODS[METHODS["PAUSE"] = 39] = "PAUSE";
- METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN";
- METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER";
- METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER";
- METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT";
- METHODS[METHODS["RECORD"] = 44] = "RECORD";
- /* RAOP */
- METHODS[METHODS["FLUSH"] = 45] = "FLUSH";
-})(METHODS = exports.METHODS || (exports.METHODS = {}));
-exports.METHODS_HTTP = [
- METHODS.DELETE,
- METHODS.GET,
- METHODS.HEAD,
- METHODS.POST,
- METHODS.PUT,
- METHODS.CONNECT,
- METHODS.OPTIONS,
- METHODS.TRACE,
- METHODS.COPY,
- METHODS.LOCK,
- METHODS.MKCOL,
- METHODS.MOVE,
- METHODS.PROPFIND,
- METHODS.PROPPATCH,
- METHODS.SEARCH,
- METHODS.UNLOCK,
- METHODS.BIND,
- METHODS.REBIND,
- METHODS.UNBIND,
- METHODS.ACL,
- METHODS.REPORT,
- METHODS.MKACTIVITY,
- METHODS.CHECKOUT,
- METHODS.MERGE,
- METHODS['M-SEARCH'],
- METHODS.NOTIFY,
- METHODS.SUBSCRIBE,
- METHODS.UNSUBSCRIBE,
- METHODS.PATCH,
- METHODS.PURGE,
- METHODS.MKCALENDAR,
- METHODS.LINK,
- METHODS.UNLINK,
- METHODS.PRI,
- // TODO(indutny): should we allow it with HTTP?
- METHODS.SOURCE,
-];
-exports.METHODS_ICE = [
- METHODS.SOURCE,
-];
-exports.METHODS_RTSP = [
- METHODS.OPTIONS,
- METHODS.DESCRIBE,
- METHODS.ANNOUNCE,
- METHODS.SETUP,
- METHODS.PLAY,
- METHODS.PAUSE,
- METHODS.TEARDOWN,
- METHODS.GET_PARAMETER,
- METHODS.SET_PARAMETER,
- METHODS.REDIRECT,
- METHODS.RECORD,
- METHODS.FLUSH,
- // For AirPlay
- METHODS.GET,
- METHODS.POST,
-];
-exports.METHOD_MAP = utils_1.enumToMap(METHODS);
-exports.H_METHOD_MAP = {};
-Object.keys(exports.METHOD_MAP).forEach((key) => {
- if (/^H/.test(key)) {
- exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key];
- }
-});
-var FINISH;
-(function (FINISH) {
- FINISH[FINISH["SAFE"] = 0] = "SAFE";
- FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB";
- FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE";
-})(FINISH = exports.FINISH || (exports.FINISH = {}));
-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.STRICT_URL_CHAR = [
- '!', '"', '$', '%', '&', '\'',
- '(', ')', '*', '+', ',', '-', '.', '/',
- ':', ';', '<', '=', '>',
- '@', '[', '\\', ']', '^', '_',
- '`',
- '{', '|', '}', '~',
-].concat(exports.ALPHANUM);
-exports.URL_CHAR = exports.STRICT_URL_CHAR
- .concat(['\t', '\f']);
-// All characters with 0x80 bit set to 1
-for (let i = 0x80; i <= 0xff; i++) {
- exports.URL_CHAR.push(i);
-}
-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.STRICT_TOKEN = [
- '!', '#', '$', '%', '&', '\'',
- '*', '+', '-', '.',
- '^', '_', '`',
- '|', '~',
-].concat(exports.ALPHANUM);
-exports.TOKEN = exports.STRICT_TOKEN.concat([' ']);
-/*
- * 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.MAJOR = exports.NUM_MAP;
-exports.MINOR = exports.MAJOR;
-var HEADER_STATE;
-(function (HEADER_STATE) {
- HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL";
- HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION";
- HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH";
- HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING";
- HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE";
- HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE";
- HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE";
- HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE";
- HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED";
-})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {}));
-exports.SPECIAL_HEADERS = {
- 'connection': HEADER_STATE.CONNECTION,
- 'content-length': HEADER_STATE.CONTENT_LENGTH,
- 'proxy-connection': HEADER_STATE.CONNECTION,
- 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING,
- 'upgrade': HEADER_STATE.UPGRADE,
-};
-//# sourceMappingURL=constants.js.map
+/***/ }),
+
+/***/ 1708:
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("node:process");
/***/ }),
-/***/ 3870:
+/***/ 57075:
/***/ ((module) => {
-module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA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EE4akIANwMAIABBMGpCADcDACAAQShqQgA3AwAgAEEgakIANwMAIABBEGpCADcDACAAQQhqQgA3AwAgAEHdATYCHEEAC3sBAX8CQCAAKAIMIgMNAAJAIAAoAgRFDQAgACABNgIECwJAIAAgASACEMSAgIAAIgMNACAAKAIMDwsgACADNgIcQQAhAyAAKAIEIgFFDQAgACABIAIgACgCCBGBgICAAAAiAUUNACAAIAI2AhQgACABNgIMIAEhAwsgAwvk8wEDDn8DfgR/I4CAgIAAQRBrIgMkgICAgAAgASEEIAEhBSABIQYgASEHIAEhCCABIQkgASEKIAEhCyABIQwgASENIAEhDiABIQ8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgACgCHCIQQX9qDt0B2gEB2QECAwQFBgcICQoLDA0O2AEPENcBERLWARMUFRYXGBkaG+AB3wEcHR7VAR8gISIjJCXUASYnKCkqKyzTAdIBLS7RAdABLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVG2wFHSElKzwHOAUvNAUzMAU1OT1BRUlNUVVZXWFla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0BIRAMFwtBrgEhEAwWC0EBIRAMFQtBrwEhEAwUC0GwASEQDBMLQbEBIRAMEgtBswEhEAwRC0GyASEQDBALQbQBIRAMDwtBtQEhEAwOC0G2ASEQDA0LQbcBIRAMDAtBuAEhEAwLC0G5ASEQDAoLQboBIRAMCQtBuwEhEAwIC0HGASEQDAcLQbwBIRAMBgtBvQEhEAwFC0G+ASEQDAQLQb8BIRAMAwtBwAEhEAwCC0HCASEQDAELQcEBIRALA0ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQA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EMTQsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAysAQsgAEEANgIcIAAgATYCFCAAQdyIgIAANgIQIABBBzYCDEEAIRAMqwELIBBBP0cNASABQQFqIQELQQUhEAyQAQtBACEQIABBADYCHCAAIAE2AhQgAEH9koCAADYCECAAQQc2AgwMqAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMpwELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMpgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEYLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMpQELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0gA2AhwgACAUNgIUIAAgATYCDEEAIRAMpAELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0wA2AhwgACAUNgIUIAAgATYCDEEAIRAMowELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDEMLIABB5QA2AhwgACAUNgIUIAAgATYCDEEAIRAMogELIABBADYCHCAAIBQ2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKEBCyAAQQA2AhwgACABNgIUIABBw4+AgAA2AhAgAEEHNgIMQQAhEAygAQtBACEQIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgwMnwELIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgxBACEQDJ4BCyAAQQA2AhwgACAUNgIUIABB/pGAgAA2AhAgAEEHNgIMQQAhEAydAQsgAEEANgIcIAAgATYCFCAAQY6bgIAANgIQIABBBjYCDEEAIRAMnAELIBBBFUYNVyAAQQA2AhwgACABNgIUIABBzI6AgAA2AhAgAEEgNgIMQQAhEAybAQsgAEEANgIAIBBBA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
+
+/***/ }),
+
+/***/ 57975:
+/***/ ((module) => {
+"use strict";
+module.exports = require("node:util");
/***/ }),
-/***/ 3434:
+/***/ 38522:
/***/ ((module) => {
-module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAEhJsbGh0dHBfZ2V0X3VwZ3JhZGUAEwxsbGh0dHBfcmVzZXQAFA5sbGh0dHBfZXhlY3V0ZQAVFGxsaHR0cF9zZXR0aW5nc19pbml0ABYNbGxodHRwX2ZpbmlzaAAXDGxsaHR0cF9wYXVzZQAYDWxsaHR0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JAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJA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AEEANgIcIAAgATYCFCAAQbmNgIAANgIQIABBGjYCDEEAIRAMtAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFQLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMswELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMsgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMsQELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFELIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMsAELIABBADYCHCAAIAE2AhQgAEHGioCAADYCECAAQQc2AgxBACEQDK8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDK4BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDK0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDKwBCyAAQQA2AhwgACABNgIUIABB3IiAgAA2AhAgAEEHNgIMQQAhEAyrAQsgEEE/Rw0BIAFBAWohAQtBBSEQDJABC0EAIRAgAEEANgIcIAAgATYCFCAAQf2SgIAANgIQIABBBzYCDAyoAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAynAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAymAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMRgsgAEHlADY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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAgAAAAACAAAAAAAAAAAAAAAAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw=='
+"use strict";
+module.exports = require("node:zlib");
+
+/***/ }),
+
+/***/ 70857:
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("os");
+
+/***/ }),
+
+/***/ 16928:
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("path");
+
+/***/ }),
+
+/***/ 82987:
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("perf_hooks");
+
+/***/ }),
+
+/***/ 24876:
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("punycode");
+
+/***/ }),
+
+/***/ 83480:
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("querystring");
+
+/***/ }),
+
+/***/ 2203:
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("stream");
+
+/***/ }),
+
+/***/ 63774:
+/***/ ((module) => {
+"use strict";
+module.exports = require("stream/web");
+
+/***/ }),
+
+/***/ 13193:
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("string_decoder");
+
+/***/ }),
+
+/***/ 53557:
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("timers");
+
+/***/ }),
+
+/***/ 64756:
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("tls");
+
+/***/ }),
+
+/***/ 52018:
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("tty");
+
+/***/ }),
+
+/***/ 87016:
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("url");
+
+/***/ }),
+
+/***/ 39023:
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("util");
+
+/***/ }),
+
+/***/ 98253:
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("util/types");
+
+/***/ }),
+
+/***/ 28167:
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("worker_threads");
+
+/***/ }),
+
+/***/ 43106:
+/***/ ((module) => {
+
+"use strict";
+module.exports = require("zlib");
/***/ }),
-/***/ 172:
+/***/ 50198:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.enumToMap = void 0;
-function enumToMap(obj) {
- const res = {};
- Object.keys(obj).forEach((key) => {
- const value = obj[key];
- if (typeof value === 'number') {
- res[key] = value;
+exports.AzureKeyCredential = void 0;
+/**
+ * A static-key-based credential that supports updating
+ * the underlying key value.
+ */
+class AzureKeyCredential {
+ /**
+ * The value of the key to be used in authentication
+ */
+ get key() {
+ return this._key;
+ }
+ /**
+ * Create an instance of an AzureKeyCredential for use
+ * with a service client.
+ *
+ * @param key - The initial value of the key to use in authentication
+ */
+ constructor(key) {
+ if (!key) {
+ throw new Error("key must be a non-empty string");
}
- });
- return res;
+ this._key = key;
+ }
+ /**
+ * Change the value of the key.
+ *
+ * Updates will take effect upon the next request after
+ * updating the key value.
+ *
+ * @param newKey - The new key value to be used
+ */
+ update(newKey) {
+ this._key = newKey;
+ }
}
-exports.enumToMap = enumToMap;
-//# sourceMappingURL=utils.js.map
+exports.AzureKeyCredential = AzureKeyCredential;
+//# sourceMappingURL=azureKeyCredential.js.map
/***/ }),
-/***/ 7501:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 41295:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AzureNamedKeyCredential = void 0;
+exports.isNamedKeyCredential = isNamedKeyCredential;
+const core_util_1 = __nccwpck_require__(87779);
+/**
+ * A static name/key-based credential that supports updating
+ * the underlying name and key values.
+ */
+class AzureNamedKeyCredential {
+ /**
+ * The value of the key to be used in authentication.
+ */
+ get key() {
+ return this._key;
+ }
+ /**
+ * The value of the name to be used in authentication.
+ */
+ get name() {
+ return this._name;
+ }
+ /**
+ * Create an instance of an AzureNamedKeyCredential for use
+ * with a service client.
+ *
+ * @param name - The initial value of the name to use in authentication.
+ * @param key - The initial value of the key to use in authentication.
+ */
+ constructor(name, key) {
+ if (!name || !key) {
+ throw new TypeError("name and key must be non-empty strings");
+ }
+ this._name = name;
+ this._key = key;
+ }
+ /**
+ * Change the value of the key.
+ *
+ * Updates will take effect upon the next request after
+ * updating the key value.
+ *
+ * @param newName - The new name value to be used.
+ * @param newKey - The new key value to be used.
+ */
+ update(newName, newKey) {
+ if (!newName || !newKey) {
+ throw new TypeError("newName and newKey must be non-empty strings");
+ }
+ this._name = newName;
+ this._key = newKey;
+ }
+}
+exports.AzureNamedKeyCredential = AzureNamedKeyCredential;
+/**
+ * Tests an object to determine whether it implements NamedKeyCredential.
+ *
+ * @param credential - The assumed NamedKeyCredential to be tested.
+ */
+function isNamedKeyCredential(credential) {
+ return ((0, core_util_1.isObjectWithProperties)(credential, ["name", "key"]) &&
+ typeof credential.key === "string" &&
+ typeof credential.name === "string");
+}
+//# sourceMappingURL=azureNamedKeyCredential.js.map
-const { kClients } = __nccwpck_require__(6443)
-const Agent = __nccwpck_require__(9965)
-const {
- kAgent,
- kMockAgentSet,
- kMockAgentGet,
- kDispatches,
- kIsMockActive,
- kNetConnect,
- kGetNetConnect,
- kOptions,
- kFactory
-} = __nccwpck_require__(1117)
-const MockClient = __nccwpck_require__(7365)
-const MockPool = __nccwpck_require__(4004)
-const { matchValue, buildMockOptions } = __nccwpck_require__(3397)
-const { InvalidArgumentError, UndiciError } = __nccwpck_require__(8707)
-const Dispatcher = __nccwpck_require__(992)
-const Pluralizer = __nccwpck_require__(1529)
-const PendingInterceptorsFormatter = __nccwpck_require__(6142)
+/***/ }),
-class FakeWeakRef {
- constructor (value) {
- this.value = value
- }
+/***/ 56608:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- deref () {
- return this.value
- }
-}
+"use strict";
-class MockAgent extends Dispatcher {
- constructor (opts) {
- super(opts)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AzureSASCredential = void 0;
+exports.isSASCredential = isSASCredential;
+const core_util_1 = __nccwpck_require__(87779);
+/**
+ * A static-signature-based credential that supports updating
+ * the underlying signature value.
+ */
+class AzureSASCredential {
+ /**
+ * The value of the shared access signature to be used in authentication
+ */
+ get signature() {
+ return this._signature;
+ }
+ /**
+ * Create an instance of an AzureSASCredential for use
+ * with a service client.
+ *
+ * @param signature - The initial value of the shared access signature to use in authentication
+ */
+ constructor(signature) {
+ if (!signature) {
+ throw new Error("shared access signature must be a non-empty string");
+ }
+ this._signature = signature;
+ }
+ /**
+ * Change the value of the signature.
+ *
+ * Updates will take effect upon the next request after
+ * updating the signature value.
+ *
+ * @param newSignature - The new shared access signature value to be used
+ */
+ update(newSignature) {
+ if (!newSignature) {
+ throw new Error("shared access signature must be a non-empty string");
+ }
+ this._signature = newSignature;
+ }
+}
+exports.AzureSASCredential = AzureSASCredential;
+/**
+ * Tests an object to determine whether it implements SASCredential.
+ *
+ * @param credential - The assumed SASCredential to be tested.
+ */
+function isSASCredential(credential) {
+ return ((0, core_util_1.isObjectWithProperties)(credential, ["signature"]) && typeof credential.signature === "string");
+}
+//# sourceMappingURL=azureSASCredential.js.map
- this[kNetConnect] = true
- this[kIsMockActive] = true
+/***/ }),
- // Instantiate Agent and encapsulate
- if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) {
- throw new InvalidArgumentError('Argument opts.agent must implement Agent')
- }
- const agent = opts && opts.agent ? opts.agent : new Agent(opts)
- this[kAgent] = agent
+/***/ 50417:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- this[kClients] = agent[kClients]
- this[kOptions] = buildMockOptions(opts)
- }
+"use strict";
- get (origin) {
- let dispatcher = this[kMockAgentGet](origin)
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isTokenCredential = exports.isSASCredential = exports.AzureSASCredential = exports.isNamedKeyCredential = exports.AzureNamedKeyCredential = exports.isKeyCredential = exports.AzureKeyCredential = void 0;
+var azureKeyCredential_js_1 = __nccwpck_require__(50198);
+Object.defineProperty(exports, "AzureKeyCredential", ({ enumerable: true, get: function () { return azureKeyCredential_js_1.AzureKeyCredential; } }));
+var keyCredential_js_1 = __nccwpck_require__(99155);
+Object.defineProperty(exports, "isKeyCredential", ({ enumerable: true, get: function () { return keyCredential_js_1.isKeyCredential; } }));
+var azureNamedKeyCredential_js_1 = __nccwpck_require__(41295);
+Object.defineProperty(exports, "AzureNamedKeyCredential", ({ enumerable: true, get: function () { return azureNamedKeyCredential_js_1.AzureNamedKeyCredential; } }));
+Object.defineProperty(exports, "isNamedKeyCredential", ({ enumerable: true, get: function () { return azureNamedKeyCredential_js_1.isNamedKeyCredential; } }));
+var azureSASCredential_js_1 = __nccwpck_require__(56608);
+Object.defineProperty(exports, "AzureSASCredential", ({ enumerable: true, get: function () { return azureSASCredential_js_1.AzureSASCredential; } }));
+Object.defineProperty(exports, "isSASCredential", ({ enumerable: true, get: function () { return azureSASCredential_js_1.isSASCredential; } }));
+var tokenCredential_js_1 = __nccwpck_require__(86881);
+Object.defineProperty(exports, "isTokenCredential", ({ enumerable: true, get: function () { return tokenCredential_js_1.isTokenCredential; } }));
+//# sourceMappingURL=index.js.map
- 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)
- return this[kAgent].dispatch(opts, handler)
- }
+/***/ 99155:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- async close () {
- await this[kAgent].close()
- this[kClients].clear()
- }
+"use strict";
- deactivate () {
- this[kIsMockActive] = false
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isKeyCredential = isKeyCredential;
+const core_util_1 = __nccwpck_require__(87779);
+/**
+ * Tests an object to determine whether it implements KeyCredential.
+ *
+ * @param credential - The assumed KeyCredential to be tested.
+ */
+function isKeyCredential(credential) {
+ return (0, core_util_1.isObjectWithProperties)(credential, ["key"]) && typeof credential.key === "string";
+}
+//# sourceMappingURL=keyCredential.js.map
- 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.')
- }
- }
+/***/ 86881:
+/***/ ((__unused_webpack_module, exports) => {
- disableNetConnect () {
- this[kNetConnect] = false
- }
+"use strict";
- // This is required to bypass issues caused by using global symbols - see:
- // https://github.com/nodejs/undici/issues/1447
- get isMockActive () {
- return this[kIsMockActive]
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isBearerToken = isBearerToken;
+exports.isPopToken = isPopToken;
+exports.isTokenCredential = isTokenCredential;
+/**
+ * @internal
+ * @param accessToken - Access token
+ * @returns Whether a token is bearer type or not
+ */
+function isBearerToken(accessToken) {
+ return !accessToken.tokenType || accessToken.tokenType === "Bearer";
+}
+/**
+ * @internal
+ * @param accessToken - Access token
+ * @returns Whether a token is Pop token or not
+ */
+function isPopToken(accessToken) {
+ return accessToken.tokenType === "pop";
+}
+/**
+ * Tests an object to determine whether it implements TokenCredential.
+ *
+ * @param credential - The assumed TokenCredential to be tested.
+ */
+function isTokenCredential(credential) {
+ // Check for an object with a 'getToken' function and possibly with
+ // a 'signRequest' function. We do this check to make sure that
+ // a ServiceClientCredentials implementor (like TokenClientCredentials
+ // in ms-rest-nodeauth) doesn't get mistaken for a TokenCredential if
+ // it doesn't actually implement TokenCredential also.
+ const castCredential = credential;
+ return (castCredential &&
+ typeof castCredential.getToken === "function" &&
+ (castCredential.signRequest === undefined || castCredential.getToken.length > 0));
+}
+//# sourceMappingURL=tokenCredential.js.map
- [kMockAgentSet] (origin, dispatcher) {
- this[kClients].set(origin, new FakeWeakRef(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)
- }
+/***/ 17698:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- [kMockAgentGet] (origin) {
- // First check if we can immediately find it
- const ref = this[kClients].get(origin)
- if (ref) {
- return ref.deref()
- }
+"use strict";
- // 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
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.authorizeRequestOnClaimChallenge = exports.parseCAEChallenge = void 0;
+const log_js_1 = __nccwpck_require__(89994);
+const base64_js_1 = __nccwpck_require__(20741);
+/**
+ * Converts: `Bearer a="b", c="d", Bearer d="e", f="g"`.
+ * Into: `[ { a: 'b', c: 'd' }, { d: 'e', f: 'g' } ]`.
+ *
+ * @internal
+ */
+function parseCAEChallenge(challenges) {
+ const bearerChallenges = `, ${challenges.trim()}`.split(", Bearer ").filter((x) => x);
+ return bearerChallenges.map((challenge) => {
+ const challengeParts = `${challenge.trim()}, `.split('", ').filter((x) => x);
+ const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split('="')));
+ // Key-value pairs to plain object:
+ return keyValuePairs.reduce((a, b) => (Object.assign(Object.assign({}, a), b)), {});
+ });
+}
+exports.parseCAEChallenge = parseCAEChallenge;
+/**
+ * This function can be used as a callback for the `bearerTokenAuthenticationPolicy` of `@azure/core-rest-pipeline`, to support CAE challenges:
+ * [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation).
+ *
+ * Call the `bearerTokenAuthenticationPolicy` with the following options:
+ *
+ * ```ts
+ * import { bearerTokenAuthenticationPolicy } from "@azure/core-rest-pipeline";
+ * import { authorizeRequestOnClaimChallenge } from "@azure/core-client";
+ *
+ * const bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy({
+ * authorizeRequestOnChallenge: authorizeRequestOnClaimChallenge
+ * });
+ * ```
+ *
+ * Once provided, the `bearerTokenAuthenticationPolicy` policy will internally handle Continuous Access Evaluation (CAE) challenges.
+ * When it can't complete a challenge it will return the 401 (unauthorized) response from ARM.
+ *
+ * Example challenge with claims:
+ *
+ * ```
+ * Bearer authorization_uri="https://login.windows-ppe.net/", error="invalid_token",
+ * error_description="User session has been revoked",
+ * claims="eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwgInZhbHVlIjoiMTYwMzc0MjgwMCJ9fX0="
+ * ```
+ */
+async function authorizeRequestOnClaimChallenge(onChallengeOptions) {
+ const { scopes, response } = onChallengeOptions;
+ const logger = onChallengeOptions.logger || log_js_1.logger;
+ const challenge = response.headers.get("WWW-Authenticate");
+ if (!challenge) {
+ logger.info(`The WWW-Authenticate header was missing. Failed to perform the Continuous Access Evaluation authentication flow.`);
+ return false;
}
-
- // If we match, create a pool and assign the same dispatches
- for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) {
- const nonExplicitDispatcher = nonExplicitRef.deref()
- if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) {
- const dispatcher = this[kFactory](origin)
- this[kMockAgentSet](origin, dispatcher)
- dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches]
- return dispatcher
- }
+ const challenges = parseCAEChallenge(challenge) || [];
+ const parsedChallenge = challenges.find((x) => x.claims);
+ if (!parsedChallenge) {
+ logger.info(`The WWW-Authenticate header was missing the necessary "claims" to perform the Continuous Access Evaluation authentication flow.`);
+ return false;
}
- }
-
- [kGetNetConnect] () {
- return this[kNetConnect]
- }
-
- pendingInterceptors () {
- const mockAgentClients = this[kClients]
-
- return Array.from(mockAgentClients.entries())
- .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin })))
- .filter(({ pending }) => pending)
- }
-
- assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {
- const pending = this.pendingInterceptors()
-
- if (pending.length === 0) {
- return
+ const accessToken = await onChallengeOptions.getAccessToken(parsedChallenge.scope ? [parsedChallenge.scope] : scopes, {
+ claims: (0, base64_js_1.decodeStringToString)(parsedChallenge.claims),
+ });
+ if (!accessToken) {
+ return false;
}
-
- const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length)
-
- throw new UndiciError(`
-${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending:
-
-${pendingInterceptorsFormatter.format(pending)}
-`.trim())
- }
+ onChallengeOptions.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
+ return true;
}
-
-module.exports = MockAgent
-
+exports.authorizeRequestOnClaimChallenge = authorizeRequestOnClaimChallenge;
+//# sourceMappingURL=authorizeRequestOnClaimChallenge.js.map
/***/ }),
-/***/ 7365:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 97454:
+/***/ ((__unused_webpack_module, exports) => {
"use strict";
-
-const { promisify } = __nccwpck_require__(9023)
-const Client = __nccwpck_require__(6197)
-const { buildMockDispatch } = __nccwpck_require__(3397)
-const {
- kDispatches,
- kMockAgent,
- kClose,
- kOriginalClose,
- kOrigin,
- kOriginalDispatch,
- kConnected
-} = __nccwpck_require__(1117)
-const { MockInterceptor } = __nccwpck_require__(1511)
-const Symbols = __nccwpck_require__(6443)
-const { InvalidArgumentError } = __nccwpck_require__(8707)
-
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.authorizeRequestOnTenantChallenge = void 0;
/**
- * MockClient provides an API that extends the Client to influence the mockDispatches.
+ * A set of constants used internally when processing requests.
*/
-class MockClient extends Client {
- constructor (origin, opts) {
- super(origin, opts)
-
- if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
- throw new InvalidArgumentError('Argument opts.agent must implement Agent')
+const Constants = {
+ DefaultScope: "/.default",
+ /**
+ * Defines constants for use with HTTP headers.
+ */
+ HeaderConstants: {
+ /**
+ * The Authorization header.
+ */
+ AUTHORIZATION: "authorization",
+ },
+};
+function isUuid(text) {
+ return /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(text);
+}
+/**
+ * Defines a callback to handle auth challenge for Storage APIs.
+ * This implements the bearer challenge process described here: https://docs.microsoft.com/rest/api/storageservices/authorize-with-azure-active-directory#bearer-challenge
+ * Handling has specific features for storage that departs to the general AAD challenge docs.
+ **/
+const authorizeRequestOnTenantChallenge = async (challengeOptions) => {
+ const requestOptions = requestToOptions(challengeOptions.request);
+ const challenge = getChallenge(challengeOptions.response);
+ if (challenge) {
+ const challengeInfo = parseChallenge(challenge);
+ const challengeScopes = buildScopes(challengeOptions, challengeInfo);
+ const tenantId = extractTenantId(challengeInfo);
+ if (!tenantId) {
+ return false;
+ }
+ const accessToken = await challengeOptions.getAccessToken(challengeScopes, Object.assign(Object.assign({}, requestOptions), { tenantId }));
+ if (!accessToken) {
+ return false;
+ }
+ challengeOptions.request.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${accessToken.token}`);
+ return true;
}
-
- this[kMockAgent] = opts.agent
- this[kOrigin] = origin
- 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, this[kDispatches])
- }
-
- async [kClose] () {
- await promisify(this[kOriginalClose])()
- this[kConnected] = 0
- this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
- }
+ return false;
+};
+exports.authorizeRequestOnTenantChallenge = authorizeRequestOnTenantChallenge;
+/**
+ * Extracts the tenant id from the challenge information
+ * The tenant id is contained in the authorization_uri as the first
+ * path part.
+ */
+function extractTenantId(challengeInfo) {
+ const parsedAuthUri = new URL(challengeInfo.authorization_uri);
+ const pathSegments = parsedAuthUri.pathname.split("/");
+ const tenantId = pathSegments[1];
+ if (tenantId && isUuid(tenantId)) {
+ return tenantId;
+ }
+ return undefined;
}
-
-module.exports = MockClient
-
+/**
+ * Builds the authentication scopes based on the information that comes in the
+ * challenge information. Scopes url is present in the resource_id, if it is empty
+ * we keep using the original scopes.
+ */
+function buildScopes(challengeOptions, challengeInfo) {
+ if (!challengeInfo.resource_id) {
+ return challengeOptions.scopes;
+ }
+ const challengeScopes = new URL(challengeInfo.resource_id);
+ challengeScopes.pathname = Constants.DefaultScope;
+ let scope = challengeScopes.toString();
+ if (scope === "https://disk.azure.com/.default") {
+ // the extra slash is required by the service
+ scope = "https://disk.azure.com//.default";
+ }
+ return [scope];
+}
+/**
+ * We will retrieve the challenge only if the response status code was 401,
+ * and if the response contained the header "WWW-Authenticate" with a non-empty value.
+ */
+function getChallenge(response) {
+ const challenge = response.headers.get("WWW-Authenticate");
+ if (response.status === 401 && challenge) {
+ return challenge;
+ }
+ return;
+}
+/**
+ * Converts: `Bearer a="b" c="d"`.
+ * Into: `[ { a: 'b', c: 'd' }]`.
+ *
+ * @internal
+ */
+function parseChallenge(challenge) {
+ const bearerChallenge = challenge.slice("Bearer ".length);
+ const challengeParts = `${bearerChallenge.trim()} `.split(" ").filter((x) => x);
+ const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split("=")));
+ // Key-value pairs to plain object:
+ return keyValuePairs.reduce((a, b) => (Object.assign(Object.assign({}, a), b)), {});
+}
+/**
+ * Extracts the options form a Pipeline Request for later re-use
+ */
+function requestToOptions(request) {
+ return {
+ abortSignal: request.abortSignal,
+ requestOptions: {
+ timeout: request.timeout,
+ },
+ tracingOptions: request.tracingOptions,
+ };
+}
+//# sourceMappingURL=authorizeRequestOnTenantChallenge.js.map
/***/ }),
-/***/ 2429:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 20741:
+/***/ ((__unused_webpack_module, exports) => {
"use strict";
-
-const { UndiciError } = __nccwpck_require__(8707)
-
-class MockNotMatchedError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, MockNotMatchedError)
- this.name = 'MockNotMatchedError'
- this.message = message || 'The request does not match any registered mock dispatches'
- this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED'
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.decodeStringToString = exports.decodeString = exports.encodeByteArray = exports.encodeString = void 0;
+/**
+ * Encodes a string in base64 format.
+ * @param value - the string to encode
+ * @internal
+ */
+function encodeString(value) {
+ return Buffer.from(value).toString("base64");
}
-
-module.exports = {
- MockNotMatchedError
+exports.encodeString = encodeString;
+/**
+ * Encodes a byte array in base64 format.
+ * @param value - the Uint8Aray to encode
+ * @internal
+ */
+function encodeByteArray(value) {
+ const bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer);
+ return bufferValue.toString("base64");
}
-
+exports.encodeByteArray = encodeByteArray;
+/**
+ * Decodes a base64 string into a byte array.
+ * @param value - the base64 string to decode
+ * @internal
+ */
+function decodeString(value) {
+ return Buffer.from(value, "base64");
+}
+exports.decodeString = decodeString;
+/**
+ * Decodes a base64 string into a string.
+ * @param value - the base64 string to decode
+ * @internal
+ */
+function decodeStringToString(value) {
+ return Buffer.from(value, "base64").toString();
+}
+exports.decodeStringToString = decodeStringToString;
+//# sourceMappingURL=base64.js.map
/***/ }),
-/***/ 1511:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 90111:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-
-const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(3397)
-const {
- kDispatches,
- kDispatchKey,
- kDefaultHeaders,
- kDefaultTrailers,
- kContentLength,
- kMockDispatch
-} = __nccwpck_require__(1117)
-const { InvalidArgumentError } = __nccwpck_require__(8707)
-const { buildURL } = __nccwpck_require__(3440)
-
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.deserializationPolicy = exports.deserializationPolicyName = void 0;
+const interfaces_js_1 = __nccwpck_require__(56058);
+const core_rest_pipeline_1 = __nccwpck_require__(20778);
+const serializer_js_1 = __nccwpck_require__(31530);
+const operationHelpers_js_1 = __nccwpck_require__(19688);
+const defaultJsonContentTypes = ["application/json", "text/json"];
+const defaultXmlContentTypes = ["application/xml", "application/atom+xml"];
/**
- * Defines the scope API for an interceptor reply
+ * The programmatic identifier of the deserializationPolicy.
*/
-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')
+exports.deserializationPolicyName = "deserializationPolicy";
+/**
+ * This policy handles parsing out responses according to OperationSpecs on the request.
+ */
+function deserializationPolicy(options = {}) {
+ var _a, _b, _c, _d, _e, _f, _g;
+ const jsonContentTypes = (_b = (_a = options.expectedContentTypes) === null || _a === void 0 ? void 0 : _a.json) !== null && _b !== void 0 ? _b : defaultJsonContentTypes;
+ const xmlContentTypes = (_d = (_c = options.expectedContentTypes) === null || _c === void 0 ? void 0 : _c.xml) !== null && _d !== void 0 ? _d : defaultXmlContentTypes;
+ const parseXML = options.parseXML;
+ const serializerOptions = options.serializerOptions;
+ const updatedOptions = {
+ xml: {
+ rootName: (_e = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _e !== void 0 ? _e : "",
+ includeRoot: (_f = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _f !== void 0 ? _f : false,
+ xmlCharKey: (_g = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _g !== void 0 ? _g : interfaces_js_1.XML_CHARKEY,
+ },
+ };
+ return {
+ name: exports.deserializationPolicyName,
+ async sendRequest(request, next) {
+ const response = await next(request);
+ return deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, updatedOptions, parseXML);
+ },
+ };
+}
+exports.deserializationPolicy = deserializationPolicy;
+function getOperationResponseMap(parsedResponse) {
+ let result;
+ const request = parsedResponse.request;
+ const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
+ const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
+ if (operationSpec) {
+ if (!(operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter)) {
+ result = operationSpec.responses[parsedResponse.status];
+ }
+ else {
+ result = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter(operationSpec, parsedResponse);
+ }
}
-
- 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')
+ return result;
+}
+function shouldDeserializeResponse(parsedResponse) {
+ const request = parsedResponse.request;
+ const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
+ const shouldDeserialize = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.shouldDeserialize;
+ let result;
+ if (shouldDeserialize === undefined) {
+ result = true;
}
-
- this[kMockDispatch].times = repeatTimes
- return this
- }
+ else if (typeof shouldDeserialize === "boolean") {
+ result = shouldDeserialize;
+ }
+ else {
+ result = shouldDeserialize(parsedResponse);
+ }
+ return result;
}
-
-/**
- * Defines an interceptor for a Mock
- */
-class MockInterceptor {
- constructor (opts, mockDispatches) {
- if (typeof opts !== 'object') {
- throw new InvalidArgumentError('opts must be an object')
+async function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options, parseXML) {
+ const parsedResponse = await parse(jsonContentTypes, xmlContentTypes, response, options, parseXML);
+ if (!shouldDeserializeResponse(parsedResponse)) {
+ return parsedResponse;
}
- if (typeof opts.path === 'undefined') {
- throw new InvalidArgumentError('opts.path must be defined')
+ const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(parsedResponse.request);
+ const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
+ if (!operationSpec || !operationSpec.responses) {
+ return parsedResponse;
}
- if (typeof opts.method === 'undefined') {
- opts.method = 'GET'
+ const responseSpec = getOperationResponseMap(parsedResponse);
+ const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec, options);
+ if (error) {
+ throw error;
}
- // 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 = buildURL(opts.path, opts.query)
- } else {
- // Matches https://github.com/nodejs/undici/blob/main/lib/fetch/index.js#L1811
- const parsedURL = new URL(opts.path, 'data://')
- opts.path = parsedURL.pathname + parsedURL.search
- }
+ else if (shouldReturnResponse) {
+ return parsedResponse;
}
- if (typeof opts.method === 'string') {
- opts.method = opts.method.toUpperCase()
+ // An operation response spec does exist for current status code, so
+ // use it to deserialize the response.
+ if (responseSpec) {
+ if (responseSpec.bodyMapper) {
+ let valueToDeserialize = parsedResponse.parsedBody;
+ if (operationSpec.isXML && responseSpec.bodyMapper.type.name === serializer_js_1.MapperTypeNames.Sequence) {
+ valueToDeserialize =
+ typeof valueToDeserialize === "object"
+ ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName]
+ : [];
+ }
+ try {
+ parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options);
+ }
+ catch (deserializeError) {
+ const restError = new core_rest_pipeline_1.RestError(`Error ${deserializeError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, {
+ statusCode: parsedResponse.status,
+ request: parsedResponse.request,
+ response: parsedResponse,
+ });
+ throw restError;
+ }
+ }
+ else if (operationSpec.httpMethod === "HEAD") {
+ // head methods never have a body, but we return a boolean to indicate presence/absence of the resource
+ parsedResponse.parsedBody = response.status >= 200 && response.status < 300;
+ }
+ if (responseSpec.headersMapper) {
+ parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders", { xml: {}, ignoreUnknownProperties: true });
+ }
}
-
- this[kDispatchKey] = buildKey(opts)
- this[kDispatches] = mockDispatches
- 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 (statusCode, data, responseOptions) {
- if (typeof statusCode === 'undefined') {
- throw new InvalidArgumentError('statusCode must be defined')
+ return parsedResponse;
+}
+function isOperationSpecEmpty(operationSpec) {
+ const expectedStatusCodes = Object.keys(operationSpec.responses);
+ return (expectedStatusCodes.length === 0 ||
+ (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"));
+}
+function handleErrorResponse(parsedResponse, operationSpec, responseSpec, options) {
+ var _a;
+ const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300;
+ const isExpectedStatusCode = isOperationSpecEmpty(operationSpec)
+ ? isSuccessByStatus
+ : !!responseSpec;
+ if (isExpectedStatusCode) {
+ if (responseSpec) {
+ if (!responseSpec.isError) {
+ return { error: null, shouldReturnResponse: false };
+ }
+ }
+ else {
+ return { error: null, shouldReturnResponse: false };
+ }
+ }
+ const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default;
+ const initialErrorMessage = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status))
+ ? `Unexpected status code: ${parsedResponse.status}`
+ : parsedResponse.bodyAsText;
+ const error = new core_rest_pipeline_1.RestError(initialErrorMessage, {
+ statusCode: parsedResponse.status,
+ request: parsedResponse.request,
+ response: parsedResponse,
+ });
+ // If the item failed but there's no error spec or default spec to deserialize the error,
+ // we should fail so we just throw the parsed response
+ if (!errorResponseSpec) {
+ throw error;
}
- if (typeof data === 'undefined') {
- throw new InvalidArgumentError('data must be defined')
+ const defaultBodyMapper = errorResponseSpec.bodyMapper;
+ const defaultHeadersMapper = errorResponseSpec.headersMapper;
+ try {
+ // If error response has a body, try to deserialize it using default body mapper.
+ // Then try to extract error code & message from it
+ if (parsedResponse.parsedBody) {
+ const parsedBody = parsedResponse.parsedBody;
+ let deserializedError;
+ if (defaultBodyMapper) {
+ let valueToDeserialize = parsedBody;
+ if (operationSpec.isXML && defaultBodyMapper.type.name === serializer_js_1.MapperTypeNames.Sequence) {
+ valueToDeserialize = [];
+ const elementName = defaultBodyMapper.xmlElementName;
+ if (typeof parsedBody === "object" && elementName) {
+ valueToDeserialize = parsedBody[elementName];
+ }
+ }
+ deserializedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody", options);
+ }
+ const internalError = parsedBody.error || deserializedError || parsedBody;
+ error.code = internalError.code;
+ if (internalError.message) {
+ error.message = internalError.message;
+ }
+ if (defaultBodyMapper) {
+ error.response.parsedBody = deserializedError;
+ }
+ }
+ // If error response has headers, try to deserialize it using default header mapper
+ if (parsedResponse.headers && defaultHeadersMapper) {
+ error.response.parsedHeaders =
+ operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders");
+ }
}
- if (typeof responseOptions !== 'object') {
- throw new InvalidArgumentError('responseOptions must be an object')
+ catch (defaultError) {
+ error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`;
}
- }
-
- /**
- * Mock an undici request with a defined reply.
- */
- reply (replyData) {
- // Values of reply aren't available right now as they
- // can only be available when the reply callback is invoked.
- if (typeof replyData === '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 = replyData(opts)
-
- // Check if it is in the right format
- if (typeof resolvedData !== 'object') {
- throw new InvalidArgumentError('reply options callback must return an object')
+ return { error, shouldReturnResponse: false };
+}
+async function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts, parseXML) {
+ var _a;
+ if (!((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) &&
+ operationResponse.bodyAsText) {
+ const text = operationResponse.bodyAsText;
+ const contentType = operationResponse.headers.get("Content-Type") || "";
+ const contentComponents = !contentType
+ ? []
+ : contentType.split(";").map((component) => component.toLowerCase());
+ try {
+ if (contentComponents.length === 0 ||
+ contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) {
+ operationResponse.parsedBody = JSON.parse(text);
+ return operationResponse;
+ }
+ else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) {
+ if (!parseXML) {
+ throw new Error("Parsing XML not supported.");
+ }
+ const body = await parseXML(text, opts.xml);
+ operationResponse.parsedBody = body;
+ return operationResponse;
+ }
}
-
- const { statusCode, data = '', responseOptions = {} } = resolvedData
- this.validateReplyParameters(statusCode, data, responseOptions)
- // Since the values can be obtained immediately we return them
- // from this higher order function that will be resolved later.
- return {
- ...this.createMockScopeDispatchData(statusCode, data, responseOptions)
+ catch (err) {
+ const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`;
+ const errCode = err.code || core_rest_pipeline_1.RestError.PARSE_ERROR;
+ const e = new core_rest_pipeline_1.RestError(msg, {
+ code: errCode,
+ statusCode: operationResponse.status,
+ request: operationResponse.request,
+ response: operationResponse,
+ });
+ throw e;
}
- }
-
- // 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)
- 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 [statusCode, data = '', responseOptions = {}] = [...arguments]
- this.validateReplyParameters(statusCode, data, responseOptions)
-
- // Send in-already provided data like usual
- const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions)
- const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData)
- 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')
}
+ return operationResponse;
+}
+//# sourceMappingURL=deserializationPolicy.js.map
- const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error })
- 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')
- }
+/***/ 26323:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- this[kDefaultHeaders] = headers
- return this
- }
+"use strict";
- /**
- * Set default reply trailers on the interceptor for subsequent replies
- */
- defaultReplyTrailers (trailers) {
- if (typeof trailers === 'undefined') {
- throw new InvalidArgumentError('trailers must be defined')
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getCachedDefaultHttpClient = void 0;
+const core_rest_pipeline_1 = __nccwpck_require__(20778);
+let cachedHttpClient;
+function getCachedDefaultHttpClient() {
+ if (!cachedHttpClient) {
+ cachedHttpClient = (0, core_rest_pipeline_1.createDefaultHttpClient)();
}
+ return cachedHttpClient;
+}
+exports.getCachedDefaultHttpClient = getCachedDefaultHttpClient;
+//# sourceMappingURL=httpClientCache.js.map
- this[kDefaultTrailers] = trailers
- return this
- }
+/***/ }),
- /**
- * Set reply content length header for replies on the interceptor
- */
- replyContentLength () {
- this[kContentLength] = true
- return this
- }
-}
+/***/ 60160:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-module.exports.MockInterceptor = MockInterceptor
-module.exports.MockScope = MockScope
+"use strict";
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.authorizeRequestOnTenantChallenge = exports.authorizeRequestOnClaimChallenge = exports.serializationPolicyName = exports.serializationPolicy = exports.deserializationPolicyName = exports.deserializationPolicy = exports.XML_CHARKEY = exports.XML_ATTRKEY = exports.createClientPipeline = exports.ServiceClient = exports.MapperTypeNames = exports.createSerializer = void 0;
+var serializer_js_1 = __nccwpck_require__(31530);
+Object.defineProperty(exports, "createSerializer", ({ enumerable: true, get: function () { return serializer_js_1.createSerializer; } }));
+Object.defineProperty(exports, "MapperTypeNames", ({ enumerable: true, get: function () { return serializer_js_1.MapperTypeNames; } }));
+var serviceClient_js_1 = __nccwpck_require__(89544);
+Object.defineProperty(exports, "ServiceClient", ({ enumerable: true, get: function () { return serviceClient_js_1.ServiceClient; } }));
+var pipeline_js_1 = __nccwpck_require__(74136);
+Object.defineProperty(exports, "createClientPipeline", ({ enumerable: true, get: function () { return pipeline_js_1.createClientPipeline; } }));
+var interfaces_js_1 = __nccwpck_require__(56058);
+Object.defineProperty(exports, "XML_ATTRKEY", ({ enumerable: true, get: function () { return interfaces_js_1.XML_ATTRKEY; } }));
+Object.defineProperty(exports, "XML_CHARKEY", ({ enumerable: true, get: function () { return interfaces_js_1.XML_CHARKEY; } }));
+var deserializationPolicy_js_1 = __nccwpck_require__(90111);
+Object.defineProperty(exports, "deserializationPolicy", ({ enumerable: true, get: function () { return deserializationPolicy_js_1.deserializationPolicy; } }));
+Object.defineProperty(exports, "deserializationPolicyName", ({ enumerable: true, get: function () { return deserializationPolicy_js_1.deserializationPolicyName; } }));
+var serializationPolicy_js_1 = __nccwpck_require__(56234);
+Object.defineProperty(exports, "serializationPolicy", ({ enumerable: true, get: function () { return serializationPolicy_js_1.serializationPolicy; } }));
+Object.defineProperty(exports, "serializationPolicyName", ({ enumerable: true, get: function () { return serializationPolicy_js_1.serializationPolicyName; } }));
+var authorizeRequestOnClaimChallenge_js_1 = __nccwpck_require__(17698);
+Object.defineProperty(exports, "authorizeRequestOnClaimChallenge", ({ enumerable: true, get: function () { return authorizeRequestOnClaimChallenge_js_1.authorizeRequestOnClaimChallenge; } }));
+var authorizeRequestOnTenantChallenge_js_1 = __nccwpck_require__(97454);
+Object.defineProperty(exports, "authorizeRequestOnTenantChallenge", ({ enumerable: true, get: function () { return authorizeRequestOnTenantChallenge_js_1.authorizeRequestOnTenantChallenge; } }));
+//# sourceMappingURL=index.js.map
/***/ }),
-/***/ 4004:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 92066:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-
-const { promisify } = __nccwpck_require__(9023)
-const Pool = __nccwpck_require__(5076)
-const { buildMockDispatch } = __nccwpck_require__(3397)
-const {
- kDispatches,
- kMockAgent,
- kClose,
- kOriginalClose,
- kOrigin,
- kOriginalDispatch,
- kConnected
-} = __nccwpck_require__(1117)
-const { MockInterceptor } = __nccwpck_require__(1511)
-const Symbols = __nccwpck_require__(6443)
-const { InvalidArgumentError } = __nccwpck_require__(8707)
-
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getPathStringFromParameter = exports.getStreamingResponseStatusCodes = void 0;
+const serializer_js_1 = __nccwpck_require__(31530);
/**
- * MockPool provides an API that extends the Pool to influence the mockDispatches.
+ * Gets the list of status codes for streaming responses.
+ * @internal
*/
-class MockPool extends Pool {
- constructor (origin, opts) {
- super(origin, opts)
-
- if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
- throw new InvalidArgumentError('Argument opts.agent must implement Agent')
+function getStreamingResponseStatusCodes(operationSpec) {
+ const result = new Set();
+ for (const statusCode in operationSpec.responses) {
+ const operationResponse = operationSpec.responses[statusCode];
+ if (operationResponse.bodyMapper &&
+ operationResponse.bodyMapper.type.name === serializer_js_1.MapperTypeNames.Stream) {
+ result.add(Number(statusCode));
+ }
}
-
- this[kMockAgent] = opts.agent
- this[kOrigin] = origin
- 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, this[kDispatches])
- }
-
- async [kClose] () {
- await promisify(this[kOriginalClose])()
- this[kConnected] = 0
- this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
- }
+ return result;
}
-
-module.exports = MockPool
-
+exports.getStreamingResponseStatusCodes = getStreamingResponseStatusCodes;
+/**
+ * Get the path to this parameter's value as a dotted string (a.b.c).
+ * @param parameter - The parameter to get the path string for.
+ * @returns The path to this parameter's value as a dotted string.
+ * @internal
+ */
+function getPathStringFromParameter(parameter) {
+ const { parameterPath, mapper } = parameter;
+ let result;
+ if (typeof parameterPath === "string") {
+ result = parameterPath;
+ }
+ else if (Array.isArray(parameterPath)) {
+ result = parameterPath.join(".");
+ }
+ else {
+ result = mapper.serializedName;
+ }
+ return result;
+}
+exports.getPathStringFromParameter = getPathStringFromParameter;
+//# sourceMappingURL=interfaceHelpers.js.map
/***/ }),
-/***/ 1117:
-/***/ ((module) => {
+/***/ 56058:
+/***/ ((__unused_webpack_module, exports) => {
"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'),
- kOrigin: Symbol('origin'),
- kIsMockActive: Symbol('is mock active'),
- kNetConnect: Symbol('net connect'),
- kGetNetConnect: Symbol('get net connect'),
- kConnected: Symbol('connected')
-}
-
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.XML_CHARKEY = exports.XML_ATTRKEY = void 0;
+/**
+ * Default key used to access the XML attributes.
+ */
+exports.XML_ATTRKEY = "$";
+/**
+ * Default key used to access the XML value content.
+ */
+exports.XML_CHARKEY = "_";
+//# sourceMappingURL=interfaces.js.map
/***/ }),
-/***/ 3397:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 89994:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.logger = void 0;
+const logger_1 = __nccwpck_require__(26515);
+exports.logger = (0, logger_1.createClientLogger)("core-client");
+//# sourceMappingURL=log.js.map
-const { MockNotMatchedError } = __nccwpck_require__(2429)
-const {
- kDispatches,
- kMockAgent,
- kOriginalDispatch,
- kOrigin,
- kGetNetConnect
-} = __nccwpck_require__(1117)
-const { buildURL, nop } = __nccwpck_require__(3440)
-const { STATUS_CODES } = __nccwpck_require__(8611)
-const {
- types: {
- isPromise
- }
-} = __nccwpck_require__(9023)
+/***/ }),
-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
-}
+/***/ 19688:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-function lowerCaseEntries (headers) {
- return Object.fromEntries(
- Object.entries(headers).map(([headerName, headerValue]) => {
- return [headerName.toLocaleLowerCase(), headerValue]
- })
- )
-}
+"use strict";
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getOperationRequestInfo = exports.getOperationArgumentValueFromParameter = void 0;
+const state_js_1 = __nccwpck_require__(33345);
/**
- * @param {import('../../index').Headers|string[]|Record} headers
- * @param {string} key
+ * @internal
+ * Retrieves the value to use for a given operation argument
+ * @param operationArguments - The arguments passed from the generated client
+ * @param parameter - The parameter description
+ * @param fallbackObject - If something isn't found in the arguments bag, look here.
+ * Generally used to look at the service client properties.
*/
-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]
- }
+function getOperationArgumentValueFromParameter(operationArguments, parameter, fallbackObject) {
+ let parameterPath = parameter.parameterPath;
+ const parameterMapper = parameter.mapper;
+ let value;
+ if (typeof parameterPath === "string") {
+ parameterPath = [parameterPath];
}
-
- 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)
+ if (Array.isArray(parameterPath)) {
+ if (parameterPath.length > 0) {
+ if (parameterMapper.isConstant) {
+ value = parameterMapper.defaultValue;
+ }
+ else {
+ let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath);
+ if (!propertySearchResult.propertyFound && fallbackObject) {
+ propertySearchResult = getPropertyFromParameterPath(fallbackObject, parameterPath);
+ }
+ let useDefaultValue = false;
+ if (!propertySearchResult.propertyFound) {
+ useDefaultValue =
+ parameterMapper.required ||
+ (parameterPath[0] === "options" && parameterPath.length === 2);
+ }
+ value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue;
+ }
+ }
}
- 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
+ else {
+ if (parameterMapper.required) {
+ value = {};
+ }
+ for (const propertyName in parameterPath) {
+ const propertyMapper = parameterMapper.type.modelProperties[propertyName];
+ const propertyPath = parameterPath[propertyName];
+ const propertyValue = getOperationArgumentValueFromParameter(operationArguments, {
+ parameterPath: propertyPath,
+ mapper: propertyMapper,
+ }, fallbackObject);
+ if (propertyValue !== undefined) {
+ if (!value) {
+ value = {};
+ }
+ value[propertyName] = propertyValue;
+ }
+ }
}
- }
- return true
+ return value;
}
-
-function safeUrl (path) {
- if (typeof path !== 'string') {
- return path
- }
-
- const pathSegments = path.split('?')
-
- if (pathSegments.length !== 2) {
- return path
- }
-
- const qp = new URLSearchParams(pathSegments.pop())
- qp.sort()
- return [...pathSegments, qp.toString()].join('?')
+exports.getOperationArgumentValueFromParameter = getOperationArgumentValueFromParameter;
+function getPropertyFromParameterPath(parent, parameterPath) {
+ const result = { propertyFound: false };
+ let i = 0;
+ for (; i < parameterPath.length; ++i) {
+ const parameterPathPart = parameterPath[i];
+ // Make sure to check inherited properties too, so don't use hasOwnProperty().
+ if (parent && parameterPathPart in parent) {
+ parent = parent[parameterPathPart];
+ }
+ else {
+ break;
+ }
+ }
+ if (i === parameterPath.length) {
+ result.propertyValue = parent;
+ result.propertyFound = true;
+ }
+ return result;
}
-
-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
+const originalRequestSymbol = Symbol.for("@azure/core-client original request");
+function hasOriginalRequest(request) {
+ return originalRequestSymbol in request;
}
-
-function getResponseData (data) {
- if (Buffer.isBuffer(data)) {
- return data
- } else if (typeof data === 'object') {
- return JSON.stringify(data)
- } else {
- return data.toString()
- }
+function getOperationRequestInfo(request) {
+ if (hasOriginalRequest(request)) {
+ return getOperationRequestInfo(request[originalRequestSymbol]);
+ }
+ let info = state_js_1.state.operationRequestMap.get(request);
+ if (!info) {
+ info = {};
+ state_js_1.state.operationRequestMap.set(request, info);
+ }
+ return info;
}
+exports.getOperationRequestInfo = getOperationRequestInfo;
+//# sourceMappingURL=operationHelpers.js.map
-function getMockDispatch (mockDispatches, key) {
- const basePath = key.query ? buildURL(key.path, key.query) : key.path
- const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath
+/***/ }),
- // Match path
- let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath))
- if (matchedMockDispatches.length === 0) {
- throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`)
- }
+/***/ 74136:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 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}'`)
- }
+"use strict";
- // 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}'`)
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createClientPipeline = void 0;
+const deserializationPolicy_js_1 = __nccwpck_require__(90111);
+const core_rest_pipeline_1 = __nccwpck_require__(20778);
+const serializationPolicy_js_1 = __nccwpck_require__(56234);
+/**
+ * Creates a new Pipeline for use with a Service Client.
+ * Adds in deserializationPolicy by default.
+ * Also adds in bearerTokenAuthenticationPolicy if passed a TokenCredential.
+ * @param options - Options to customize the created pipeline.
+ */
+function createClientPipeline(options = {}) {
+ const pipeline = (0, core_rest_pipeline_1.createPipelineFromOptions)(options !== null && options !== void 0 ? options : {});
+ if (options.credentialOptions) {
+ pipeline.addPolicy((0, core_rest_pipeline_1.bearerTokenAuthenticationPolicy)({
+ credential: options.credentialOptions.credential,
+ scopes: options.credentialOptions.credentialScopes,
+ }));
+ }
+ pipeline.addPolicy((0, serializationPolicy_js_1.serializationPolicy)(options.serializationOptions), { phase: "Serialize" });
+ pipeline.addPolicy((0, deserializationPolicy_js_1.deserializationPolicy)(options.deserializationOptions), {
+ phase: "Deserialize",
+ });
+ return pipeline;
+}
+exports.createClientPipeline = createClientPipeline;
+//# sourceMappingURL=pipeline.js.map
- // Match headers
- matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers))
- if (matchedMockDispatches.length === 0) {
- throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`)
- }
+/***/ }),
- return matchedMockDispatches[0]
-}
+/***/ 56234:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-function addMockDispatch (mockDispatches, key, data) {
- const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false }
- const replyData = typeof data === 'function' ? { callback: data } : { ...data }
- const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } }
- mockDispatches.push(newMockDispatch)
- return newMockDispatch
-}
+"use strict";
-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)
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.serializeRequestBody = exports.serializeHeaders = exports.serializationPolicy = exports.serializationPolicyName = void 0;
+const interfaces_js_1 = __nccwpck_require__(56058);
+const operationHelpers_js_1 = __nccwpck_require__(19688);
+const serializer_js_1 = __nccwpck_require__(31530);
+const interfaceHelpers_js_1 = __nccwpck_require__(92066);
+/**
+ * The programmatic identifier of the serializationPolicy.
+ */
+exports.serializationPolicyName = "serializationPolicy";
+/**
+ * This policy handles assembling the request body and headers using
+ * an OperationSpec and OperationArguments on the request.
+ */
+function serializationPolicy(options = {}) {
+ const stringifyXML = options.stringifyXML;
+ return {
+ name: exports.serializationPolicyName,
+ async sendRequest(request, next) {
+ const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
+ const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
+ const operationArguments = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationArguments;
+ if (operationSpec && operationArguments) {
+ serializeHeaders(request, operationArguments, operationSpec);
+ serializeRequestBody(request, operationArguments, operationSpec, stringifyXML);
+ }
+ return next(request);
+ },
+ };
}
-
-function buildKey (opts) {
- const { path, method, body, headers, query } = opts
- return {
- path,
- method,
- body,
- headers,
- query
- }
+exports.serializationPolicy = serializationPolicy;
+/**
+ * @internal
+ */
+function serializeHeaders(request, operationArguments, operationSpec) {
+ var _a, _b;
+ if (operationSpec.headerParameters) {
+ for (const headerParameter of operationSpec.headerParameters) {
+ let headerValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, headerParameter);
+ if ((headerValue !== null && headerValue !== undefined) || headerParameter.mapper.required) {
+ headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(headerParameter));
+ const headerCollectionPrefix = headerParameter.mapper
+ .headerCollectionPrefix;
+ if (headerCollectionPrefix) {
+ for (const key of Object.keys(headerValue)) {
+ request.headers.set(headerCollectionPrefix + key, headerValue[key]);
+ }
+ }
+ else {
+ request.headers.set(headerParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(headerParameter), headerValue);
+ }
+ }
+ }
+ }
+ const customHeaders = (_b = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.requestOptions) === null || _b === void 0 ? void 0 : _b.customHeaders;
+ if (customHeaders) {
+ for (const customHeaderName of Object.keys(customHeaders)) {
+ request.headers.set(customHeaderName, customHeaders[customHeaderName]);
+ }
+ }
}
-
-function generateKeyValues (data) {
- return Object.entries(data).reduce((keyValuePairs, [key, value]) => [
- ...keyValuePairs,
- Buffer.from(`${key}`),
- Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`)
- ], [])
+exports.serializeHeaders = serializeHeaders;
+/**
+ * @internal
+ */
+function serializeRequestBody(request, operationArguments, operationSpec, stringifyXML = function () {
+ throw new Error("XML serialization unsupported!");
+}) {
+ var _a, _b, _c, _d, _e;
+ const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions;
+ const updatedOptions = {
+ xml: {
+ rootName: (_b = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _b !== void 0 ? _b : "",
+ includeRoot: (_c = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _c !== void 0 ? _c : false,
+ xmlCharKey: (_d = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _d !== void 0 ? _d : interfaces_js_1.XML_CHARKEY,
+ },
+ };
+ const xmlCharKey = updatedOptions.xml.xmlCharKey;
+ if (operationSpec.requestBody && operationSpec.requestBody.mapper) {
+ request.body = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, operationSpec.requestBody);
+ const bodyMapper = operationSpec.requestBody.mapper;
+ const { required, serializedName, xmlName, xmlElementName, xmlNamespace, xmlNamespacePrefix, nullable, } = bodyMapper;
+ const typeName = bodyMapper.type.name;
+ try {
+ if ((request.body !== undefined && request.body !== null) ||
+ (nullable && request.body === null) ||
+ required) {
+ const requestBodyParameterPathString = (0, interfaceHelpers_js_1.getPathStringFromParameter)(operationSpec.requestBody);
+ request.body = operationSpec.serializer.serialize(bodyMapper, request.body, requestBodyParameterPathString, updatedOptions);
+ const isStream = typeName === serializer_js_1.MapperTypeNames.Stream;
+ if (operationSpec.isXML) {
+ const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns";
+ const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, request.body, updatedOptions);
+ if (typeName === serializer_js_1.MapperTypeNames.Sequence) {
+ request.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, xmlCharKey });
+ }
+ else if (!isStream) {
+ request.body = stringifyXML(value, {
+ rootName: xmlName || serializedName,
+ xmlCharKey,
+ });
+ }
+ }
+ else if (typeName === serializer_js_1.MapperTypeNames.String &&
+ (((_e = operationSpec.contentType) === null || _e === void 0 ? void 0 : _e.match("text/plain")) || operationSpec.mediaType === "text")) {
+ // the String serializer has validated that request body is a string
+ // so just send the string.
+ return;
+ }
+ else if (!isStream) {
+ request.body = JSON.stringify(request.body);
+ }
+ }
+ }
+ catch (error) {
+ throw new Error(`Error "${error.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, undefined, " ")}.`);
+ }
+ }
+ else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {
+ request.formData = {};
+ for (const formDataParameter of operationSpec.formDataParameters) {
+ const formDataParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, formDataParameter);
+ if (formDataParameterValue !== undefined && formDataParameterValue !== null) {
+ const formDataParameterPropertyName = formDataParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(formDataParameter);
+ request.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(formDataParameter), updatedOptions);
+ }
+ }
+ }
}
-
+exports.serializeRequestBody = serializeRequestBody;
/**
- * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
- * @param {number} statusCode
+ * Adds an xml namespace to the xml serialized object if needed, otherwise it just returns the value itself
*/
-function getStatusText (statusCode) {
- return STATUS_CODES[statusCode] || 'unknown'
+function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options) {
+ // Composite and Sequence schemas already got their root namespace set during serialization
+ // We just need to add xmlns to the other schema types
+ if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) {
+ const result = {};
+ result[options.xml.xmlCharKey] = serializedValue;
+ result[interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace };
+ return result;
+ }
+ return serializedValue;
+}
+function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) {
+ if (!Array.isArray(obj)) {
+ obj = [obj];
+ }
+ if (!xmlNamespaceKey || !xmlNamespace) {
+ return { [elementName]: obj };
+ }
+ const result = { [elementName]: obj };
+ result[interfaces_js_1.XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace };
+ return result;
}
+//# sourceMappingURL=serializationPolicy.js.map
-async function getResponse (body) {
- const buffers = []
- for await (const data of body) {
- buffers.push(data)
- }
- return Buffer.concat(buffers).toString('utf8')
+/***/ }),
+
+/***/ 31530:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.MapperTypeNames = exports.createSerializer = void 0;
+const tslib_1 = __nccwpck_require__(61860);
+const base64 = tslib_1.__importStar(__nccwpck_require__(20741));
+const interfaces_js_1 = __nccwpck_require__(56058);
+const utils_js_1 = __nccwpck_require__(31193);
+class SerializerImpl {
+ constructor(modelMappers = {}, isXML = false) {
+ this.modelMappers = modelMappers;
+ this.isXML = isXML;
+ }
+ /**
+ * @deprecated Removing the constraints validation on client side.
+ */
+ validateConstraints(mapper, value, objectName) {
+ const failValidation = (constraintName, constraintValue) => {
+ throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`);
+ };
+ if (mapper.constraints && value !== undefined && value !== null) {
+ const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems, } = mapper.constraints;
+ if (ExclusiveMaximum !== undefined && value >= ExclusiveMaximum) {
+ failValidation("ExclusiveMaximum", ExclusiveMaximum);
+ }
+ if (ExclusiveMinimum !== undefined && value <= ExclusiveMinimum) {
+ failValidation("ExclusiveMinimum", ExclusiveMinimum);
+ }
+ if (InclusiveMaximum !== undefined && value > InclusiveMaximum) {
+ failValidation("InclusiveMaximum", InclusiveMaximum);
+ }
+ if (InclusiveMinimum !== undefined && value < InclusiveMinimum) {
+ failValidation("InclusiveMinimum", InclusiveMinimum);
+ }
+ if (MaxItems !== undefined && value.length > MaxItems) {
+ failValidation("MaxItems", MaxItems);
+ }
+ if (MaxLength !== undefined && value.length > MaxLength) {
+ failValidation("MaxLength", MaxLength);
+ }
+ if (MinItems !== undefined && value.length < MinItems) {
+ failValidation("MinItems", MinItems);
+ }
+ if (MinLength !== undefined && value.length < MinLength) {
+ failValidation("MinLength", MinLength);
+ }
+ if (MultipleOf !== undefined && value % MultipleOf !== 0) {
+ failValidation("MultipleOf", MultipleOf);
+ }
+ if (Pattern) {
+ const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern;
+ if (typeof value !== "string" || value.match(pattern) === null) {
+ failValidation("Pattern", Pattern);
+ }
+ }
+ if (UniqueItems &&
+ value.some((item, i, ar) => ar.indexOf(item) !== i)) {
+ failValidation("UniqueItems", UniqueItems);
+ }
+ }
+ }
+ /**
+ * Serialize the given object based on its metadata defined in the mapper
+ *
+ * @param mapper - The mapper which defines the metadata of the serializable object
+ *
+ * @param object - A valid Javascript object to be serialized
+ *
+ * @param objectName - Name of the serialized object
+ *
+ * @param options - additional options to serialization
+ *
+ * @returns A valid serialized Javascript object
+ */
+ serialize(mapper, object, objectName, options = { xml: {} }) {
+ var _a, _b, _c;
+ const updatedOptions = {
+ xml: {
+ rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "",
+ includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false,
+ xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : interfaces_js_1.XML_CHARKEY,
+ },
+ };
+ let payload = {};
+ const mapperType = mapper.type.name;
+ if (!objectName) {
+ objectName = mapper.serializedName;
+ }
+ if (mapperType.match(/^Sequence$/i) !== null) {
+ payload = [];
+ }
+ if (mapper.isConstant) {
+ object = mapper.defaultValue;
+ }
+ // This table of allowed values should help explain
+ // the mapper.required and mapper.nullable properties.
+ // X means "neither undefined or null are allowed".
+ // || required
+ // || true | false
+ // nullable || ==========================
+ // true || null | undefined/null
+ // false || X | undefined
+ // undefined || X | undefined/null
+ const { required, nullable } = mapper;
+ if (required && nullable && object === undefined) {
+ throw new Error(`${objectName} cannot be undefined.`);
+ }
+ if (required && !nullable && (object === undefined || object === null)) {
+ throw new Error(`${objectName} cannot be null or undefined.`);
+ }
+ if (!required && nullable === false && object === null) {
+ throw new Error(`${objectName} cannot be null.`);
+ }
+ if (object === undefined || object === null) {
+ payload = object;
+ }
+ else {
+ if (mapperType.match(/^any$/i) !== null) {
+ payload = object;
+ }
+ else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) {
+ payload = serializeBasicTypes(mapperType, objectName, object);
+ }
+ else if (mapperType.match(/^Enum$/i) !== null) {
+ const enumMapper = mapper;
+ payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object);
+ }
+ else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) {
+ payload = serializeDateTypes(mapperType, object, objectName);
+ }
+ else if (mapperType.match(/^ByteArray$/i) !== null) {
+ payload = serializeByteArrayType(objectName, object);
+ }
+ else if (mapperType.match(/^Base64Url$/i) !== null) {
+ payload = serializeBase64UrlType(objectName, object);
+ }
+ else if (mapperType.match(/^Sequence$/i) !== null) {
+ payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
+ }
+ else if (mapperType.match(/^Dictionary$/i) !== null) {
+ payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
+ }
+ else if (mapperType.match(/^Composite$/i) !== null) {
+ payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
+ }
+ }
+ return payload;
+ }
+ /**
+ * Deserialize the given object based on its metadata defined in the mapper
+ *
+ * @param mapper - The mapper which defines the metadata of the serializable object
+ *
+ * @param responseBody - A valid Javascript entity to be deserialized
+ *
+ * @param objectName - Name of the deserialized object
+ *
+ * @param options - Controls behavior of XML parser and builder.
+ *
+ * @returns A valid deserialized Javascript object
+ */
+ deserialize(mapper, responseBody, objectName, options = { xml: {} }) {
+ var _a, _b, _c, _d;
+ const updatedOptions = {
+ xml: {
+ rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "",
+ includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false,
+ xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : interfaces_js_1.XML_CHARKEY,
+ },
+ ignoreUnknownProperties: (_d = options.ignoreUnknownProperties) !== null && _d !== void 0 ? _d : false,
+ };
+ if (responseBody === undefined || responseBody === null) {
+ if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) {
+ // Edge case for empty XML non-wrapped lists. xml2js can't distinguish
+ // between the list being empty versus being missing,
+ // so let's do the more user-friendly thing and return an empty list.
+ responseBody = [];
+ }
+ // specifically check for undefined as default value can be a falsey value `0, "", false, null`
+ if (mapper.defaultValue !== undefined) {
+ responseBody = mapper.defaultValue;
+ }
+ return responseBody;
+ }
+ let payload;
+ const mapperType = mapper.type.name;
+ if (!objectName) {
+ objectName = mapper.serializedName;
+ }
+ if (mapperType.match(/^Composite$/i) !== null) {
+ payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions);
+ }
+ else {
+ if (this.isXML) {
+ const xmlCharKey = updatedOptions.xml.xmlCharKey;
+ /**
+ * If the mapper specifies this as a non-composite type value but the responseBody contains
+ * both header ("$" i.e., XML_ATTRKEY) and body ("#" i.e., XML_CHARKEY) properties,
+ * then just reduce the responseBody value to the body ("#" i.e., XML_CHARKEY) property.
+ */
+ if (responseBody[interfaces_js_1.XML_ATTRKEY] !== undefined && responseBody[xmlCharKey] !== undefined) {
+ responseBody = responseBody[xmlCharKey];
+ }
+ }
+ if (mapperType.match(/^Number$/i) !== null) {
+ payload = parseFloat(responseBody);
+ if (isNaN(payload)) {
+ payload = responseBody;
+ }
+ }
+ else if (mapperType.match(/^Boolean$/i) !== null) {
+ if (responseBody === "true") {
+ payload = true;
+ }
+ else if (responseBody === "false") {
+ payload = false;
+ }
+ else {
+ payload = responseBody;
+ }
+ }
+ else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) {
+ payload = responseBody;
+ }
+ else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) {
+ payload = new Date(responseBody);
+ }
+ else if (mapperType.match(/^UnixTime$/i) !== null) {
+ payload = unixTimeToDate(responseBody);
+ }
+ else if (mapperType.match(/^ByteArray$/i) !== null) {
+ payload = base64.decodeString(responseBody);
+ }
+ else if (mapperType.match(/^Base64Url$/i) !== null) {
+ payload = base64UrlToByteArray(responseBody);
+ }
+ else if (mapperType.match(/^Sequence$/i) !== null) {
+ payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions);
+ }
+ else if (mapperType.match(/^Dictionary$/i) !== null) {
+ payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions);
+ }
+ }
+ if (mapper.isConstant) {
+ payload = mapper.defaultValue;
+ }
+ return payload;
+ }
}
-
/**
- * Mock dispatch function used to simulate undici dispatches
+ * Method that creates and returns a Serializer.
+ * @param modelMappers - Known models to map
+ * @param isXML - If XML should be supported
*/
-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.abort = nop
- handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode))
- handler.onData(Buffer.from(responseData))
- handler.onComplete(responseTrailers)
- deleteMockDispatch(mockDispatches, key)
- }
-
- function resume () {}
-
- return true
+function createSerializer(modelMappers = {}, isXML = false) {
+ return new SerializerImpl(modelMappers, isXML);
}
-
-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)
+exports.createSerializer = createSerializer;
+function trimEnd(str, ch) {
+ let len = str.length;
+ while (len - 1 >= 0 && str[len - 1] === ch) {
+ --len;
}
- }
-}
-
-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 buildMockOptions (opts) {
- if (opts) {
- const { agent, ...mockOptions } = opts
- return mockOptions
- }
+ return str.substr(0, len);
}
-
-module.exports = {
- getResponseData,
- getMockDispatch,
- addMockDispatch,
- deleteMockDispatch,
- buildKey,
- generateKeyValues,
- matchValue,
- getResponse,
- getStatusText,
- mockDispatch,
- buildMockDispatch,
- checkNetConnect,
- buildMockOptions,
- getHeaderByName
+function bufferToBase64Url(buffer) {
+ if (!buffer) {
+ return undefined;
+ }
+ if (!(buffer instanceof Uint8Array)) {
+ throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`);
+ }
+ // Uint8Array to Base64.
+ const str = base64.encodeByteArray(buffer);
+ // Base64 to Base64Url.
+ return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_");
}
-
-
-/***/ }),
-
-/***/ 6142:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-const { Transform } = __nccwpck_require__(2203)
-const { Console } = __nccwpck_require__(4236)
-
-/**
- * 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 ? '✅' : '❌',
- Invocations: timesInvoked,
- Remaining: persist ? Infinity : times - timesInvoked
- }))
-
- this.logger.table(withPrettyHeaders)
- return this.transform.read().toString()
- }
+function base64UrlToByteArray(str) {
+ if (!str) {
+ return undefined;
+ }
+ if (str && typeof str.valueOf() !== "string") {
+ throw new Error("Please provide an input of type string for converting to Uint8Array");
+ }
+ // Base64Url to Base64.
+ str = str.replace(/-/g, "+").replace(/_/g, "/");
+ // Base64 to Uint8Array.
+ return base64.decodeString(str);
}
-
-
-/***/ }),
-
-/***/ 1529:
-/***/ ((module) => {
-
-"use strict";
-
-
-const singulars = {
- pronoun: 'it',
- is: 'is',
- was: 'was',
- this: 'this'
+function splitSerializeName(prop) {
+ const classes = [];
+ let partialclass = "";
+ if (prop) {
+ const subwords = prop.split(".");
+ for (const item of subwords) {
+ if (item.charAt(item.length - 1) === "\\") {
+ partialclass += item.substr(0, item.length - 1) + ".";
+ }
+ else {
+ partialclass += item;
+ classes.push(partialclass);
+ partialclass = "";
+ }
+ }
+ }
+ return classes;
}
-
-const plurals = {
- pronoun: 'they',
- is: 'are',
- was: 'were',
- this: 'these'
+function dateToUnixTime(d) {
+ if (!d) {
+ return undefined;
+ }
+ if (typeof d.valueOf() === "string") {
+ d = new Date(d);
+ }
+ return Math.floor(d.getTime() / 1000);
}
-
-module.exports = class Pluralizer {
- constructor (singular, plural) {
- this.singular = singular
- this.plural = plural
- }
-
- pluralize (count) {
- const one = count === 1
- const keys = one ? singulars : plurals
- const noun = one ? this.singular : this.plural
- return { ...keys, count, noun }
- }
+function unixTimeToDate(n) {
+ if (!n) {
+ return undefined;
+ }
+ return new Date(n * 1000);
}
-
-
-/***/ }),
-
-/***/ 4869:
-/***/ ((module) => {
-
-"use strict";
-/* eslint-disable */
-
-
-
-// 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 | [empty] |
-// | item | | item | | [empty] |
-// | item | | item | | [empty] |
-// | item | | item | | [empty] |
-// | item | | item | bottom --> | item |
-// | item | | item | | item |
-// | ... | | ... | | ... |
-// | item | | item | | item |
-// | item | | item | | item |
-// | [empty] | <-- top | item | | item |
-// | [empty] | | item | | item |
-// | [empty] | | [empty] | <-- top top --> | [empty] |
-// +-----------+ +-----------+ +-----------+
-//
-// 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] |
-// +-----------+ +-----------+
-// | [empty] | | item |
-// | [empty] | | item |
-// | item | <-- bottom top --> | [empty] |
-// | item | | [empty] |
-// | [empty] | <-- top bottom --> | item |
-// | [empty] | | 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.
-
-class FixedCircularBuffer {
- constructor() {
- this.bottom = 0;
- this.top = 0;
- this.list = new Array(kSize);
- this.next = null;
- }
-
- isEmpty() {
- return this.top === this.bottom;
- }
-
- isFull() {
- return ((this.top + 1) & kMask) === this.bottom;
- }
-
- push(data) {
- this.list[this.top] = data;
- this.top = (this.top + 1) & kMask;
- }
-
- 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;
- }
+function serializeBasicTypes(typeName, objectName, value) {
+ if (value !== null && value !== undefined) {
+ if (typeName.match(/^Number$/i) !== null) {
+ if (typeof value !== "number") {
+ throw new Error(`${objectName} with value ${value} must be of type number.`);
+ }
+ }
+ else if (typeName.match(/^String$/i) !== null) {
+ if (typeof value.valueOf() !== "string") {
+ throw new Error(`${objectName} with value "${value}" must be of type string.`);
+ }
+ }
+ else if (typeName.match(/^Uuid$/i) !== null) {
+ if (!(typeof value.valueOf() === "string" && (0, utils_js_1.isValidUuid)(value))) {
+ throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`);
+ }
+ }
+ else if (typeName.match(/^Boolean$/i) !== null) {
+ if (typeof value !== "boolean") {
+ throw new Error(`${objectName} with value ${value} must be of type boolean.`);
+ }
+ }
+ else if (typeName.match(/^Stream$/i) !== null) {
+ const objectType = typeof value;
+ if (objectType !== "string" &&
+ typeof value.pipe !== "function" && // NodeJS.ReadableStream
+ typeof value.tee !== "function" && // browser ReadableStream
+ !(value instanceof ArrayBuffer) &&
+ !ArrayBuffer.isView(value) &&
+ // File objects count as a type of Blob, so we want to use instanceof explicitly
+ !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob) &&
+ objectType !== "function") {
+ throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, ReadableStream, or () => ReadableStream.`);
+ }
+ }
+ }
+ return value;
}
-
-module.exports = class FixedQueue {
- constructor() {
- this.head = this.tail = new FixedCircularBuffer();
- }
-
- isEmpty() {
- return this.head.isEmpty();
- }
-
- 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();
+function serializeEnumType(objectName, allowedValues, value) {
+ if (!allowedValues) {
+ throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`);
}
- this.head.push(data);
- }
-
- 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;
+ const isPresent = allowedValues.some((item) => {
+ if (typeof item.valueOf() === "string") {
+ return item.toLowerCase() === value.toLowerCase();
+ }
+ return item === value;
+ });
+ if (!isPresent) {
+ throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`);
}
- return next;
- }
-};
-
-
-/***/ }),
-
-/***/ 8640:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-const DispatcherBase = __nccwpck_require__(1)
-const FixedQueue = __nccwpck_require__(4869)
-const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(6443)
-const PoolStats = __nccwpck_require__(4622)
-
-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')
-const kStats = Symbol('stats')
-
-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
+ return value;
+}
+function serializeByteArrayType(objectName, value) {
+ if (value !== undefined && value !== null) {
+ if (!(value instanceof Uint8Array)) {
+ throw new Error(`${objectName} must be of type Uint8Array.`);
+ }
+ value = base64.encodeByteArray(value);
+ }
+ return value;
+}
+function serializeBase64UrlType(objectName, value) {
+ if (value !== undefined && value !== null) {
+ if (!(value instanceof Uint8Array)) {
+ throw new Error(`${objectName} must be of type Uint8Array.`);
+ }
+ value = bufferToBase64Url(value);
+ }
+ return value;
+}
+function serializeDateTypes(typeName, value, objectName) {
+ if (value !== undefined && value !== null) {
+ if (typeName.match(/^Date$/i) !== null) {
+ if (!(value instanceof Date ||
+ (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
+ throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
+ }
+ value =
+ value instanceof Date
+ ? value.toISOString().substring(0, 10)
+ : new Date(value).toISOString().substring(0, 10);
+ }
+ else if (typeName.match(/^DateTime$/i) !== null) {
+ if (!(value instanceof Date ||
+ (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
+ throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
+ }
+ value = value instanceof Date ? value.toISOString() : new Date(value).toISOString();
+ }
+ else if (typeName.match(/^DateTimeRfc1123$/i) !== null) {
+ if (!(value instanceof Date ||
+ (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
+ throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`);
+ }
+ value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString();
+ }
+ else if (typeName.match(/^UnixTime$/i) !== null) {
+ if (!(value instanceof Date ||
+ (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
+ throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format ` +
+ `for it to be serialized in UnixTime/Epoch format.`);
+ }
+ value = dateToUnixTime(value);
+ }
+ else if (typeName.match(/^TimeSpan$/i) !== null) {
+ if (!(0, utils_js_1.isDuration)(value)) {
+ throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`);
+ }
}
- 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])
+ return value;
+}
+function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) {
+ var _a;
+ if (!Array.isArray(object)) {
+ throw new Error(`${objectName} must be of type Array.`);
}
-
- this[kOnDisconnect] = (origin, targets, err) => {
- pool.emit('disconnect', origin, [pool, ...targets], err)
+ let elementType = mapper.type.element;
+ if (!elementType || typeof elementType !== "object") {
+ throw new Error(`element" metadata for an Array must be defined in the ` +
+ `mapper and it must of type "object" in ${objectName}.`);
}
-
- this[kOnConnectionError] = (origin, targets, err) => {
- pool.emit('connectionError', origin, [pool, ...targets], err)
+ // Quirk: Composite mappers referenced by `element` might
+ // not have *all* properties declared (like uberParent),
+ // so let's try to look up the full definition by name.
+ if (elementType.type.name === "Composite" && elementType.type.className) {
+ elementType = (_a = serializer.modelMappers[elementType.type.className]) !== null && _a !== void 0 ? _a : elementType;
}
-
- this[kStats] = new PoolStats(this)
- }
-
- 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
+ const tempArray = [];
+ for (let i = 0; i < object.length; i++) {
+ const serializedValue = serializer.serialize(elementType, object[i], objectName, options);
+ if (isXml && elementType.xmlNamespace) {
+ const xmlnsKey = elementType.xmlNamespacePrefix
+ ? `xmlns:${elementType.xmlNamespacePrefix}`
+ : "xmlns";
+ if (elementType.type.name === "Composite") {
+ tempArray[i] = Object.assign({}, serializedValue);
+ tempArray[i][interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
+ }
+ else {
+ tempArray[i] = {};
+ tempArray[i][options.xml.xmlCharKey] = serializedValue;
+ tempArray[i][interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
+ }
+ }
+ else {
+ tempArray[i] = serializedValue;
+ }
}
- return ret
- }
-
- get [kRunning] () {
- let ret = 0
- for (const { [kRunning]: running } of this[kClients]) {
- ret += running
+ return tempArray;
+}
+function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) {
+ if (typeof object !== "object") {
+ throw new Error(`${objectName} must be of type object.`);
}
- return ret
- }
-
- get [kSize] () {
- let ret = this[kQueued]
- for (const { [kSize]: size } of this[kClients]) {
- ret += size
+ const valueType = mapper.type.value;
+ if (!valueType || typeof valueType !== "object") {
+ throw new Error(`"value" metadata for a Dictionary must be defined in the ` +
+ `mapper and it must of type "object" in ${objectName}.`);
}
- return ret
- }
-
- get stats () {
- return this[kStats]
- }
-
- async [kClose] () {
- if (this[kQueue].isEmpty()) {
- return Promise.all(this[kClients].map(c => c.close()))
- } else {
- return new Promise((resolve) => {
- this[kClosedResolve] = resolve
- })
+ const tempDictionary = {};
+ for (const key of Object.keys(object)) {
+ const serializedValue = serializer.serialize(valueType, object[key], objectName, options);
+ // If the element needs an XML namespace we need to add it within the $ property
+ tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options);
}
- }
-
- async [kDestroy] (err) {
- while (true) {
- const item = this[kQueue].shift()
- if (!item) {
- break
- }
- item.handler.onError(err)
+ // Add the namespace to the root element if needed
+ if (isXml && mapper.xmlNamespace) {
+ const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns";
+ const result = tempDictionary;
+ result[interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace };
+ return result;
}
-
- return 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 tempDictionary;
+}
+/**
+ * Resolves the additionalProperties property from a referenced mapper
+ * @param serializer - the serializer containing the entire set of mappers
+ * @param mapper - the composite mapper to resolve
+ * @param objectName - name of the object being serialized
+ */
+function resolveAdditionalProperties(serializer, mapper, objectName) {
+ const additionalProperties = mapper.type.additionalProperties;
+ if (!additionalProperties && mapper.type.className) {
+ const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
+ return modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.additionalProperties;
}
-
- 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]) {
- process.nextTick(() => {
- if (this[kNeedDrain]) {
- this[kOnDrain](client[kUrl], [this, client])
+ return additionalProperties;
+}
+/**
+ * Finds the mapper referenced by className
+ * @param serializer - the serializer containing the entire set of mappers
+ * @param mapper - the composite mapper to resolve
+ * @param objectName - name of the object being serialized
+ */
+function resolveReferencedMapper(serializer, mapper, objectName) {
+ const className = mapper.type.className;
+ if (!className) {
+ throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, undefined, 2)}".`);
+ }
+ return serializer.modelMappers[className];
+}
+/**
+ * Resolves a composite mapper's modelProperties.
+ * @param serializer - the serializer containing the entire set of mappers
+ * @param mapper - the composite mapper to resolve
+ */
+function resolveModelProperties(serializer, mapper, objectName) {
+ let modelProps = mapper.type.modelProperties;
+ if (!modelProps) {
+ const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
+ if (!modelMapper) {
+ throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`);
+ }
+ modelProps = modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.modelProperties;
+ if (!modelProps) {
+ throw new Error(`modelProperties cannot be null or undefined in the ` +
+ `mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`);
}
- })
}
-
- 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
- ))
- }
+ return modelProps;
}
-
-module.exports = {
- PoolBase,
- kClients,
- kNeedDrain,
- kAddClient,
- kRemoveClient,
- kGetDispatcher
+function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) {
+ if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
+ mapper = getPolymorphicMapper(serializer, mapper, object, "clientName");
+ }
+ if (object !== undefined && object !== null) {
+ const payload = {};
+ const modelProps = resolveModelProperties(serializer, mapper, objectName);
+ for (const key of Object.keys(modelProps)) {
+ const propertyMapper = modelProps[key];
+ if (propertyMapper.readOnly) {
+ continue;
+ }
+ let propName;
+ let parentObject = payload;
+ if (serializer.isXML) {
+ if (propertyMapper.xmlIsWrapped) {
+ propName = propertyMapper.xmlName;
+ }
+ else {
+ propName = propertyMapper.xmlElementName || propertyMapper.xmlName;
+ }
+ }
+ else {
+ const paths = splitSerializeName(propertyMapper.serializedName);
+ propName = paths.pop();
+ for (const pathName of paths) {
+ const childObject = parentObject[pathName];
+ if ((childObject === undefined || childObject === null) &&
+ ((object[key] !== undefined && object[key] !== null) ||
+ propertyMapper.defaultValue !== undefined)) {
+ parentObject[pathName] = {};
+ }
+ parentObject = parentObject[pathName];
+ }
+ }
+ if (parentObject !== undefined && parentObject !== null) {
+ if (isXml && mapper.xmlNamespace) {
+ const xmlnsKey = mapper.xmlNamespacePrefix
+ ? `xmlns:${mapper.xmlNamespacePrefix}`
+ : "xmlns";
+ parentObject[interfaces_js_1.XML_ATTRKEY] = Object.assign(Object.assign({}, parentObject[interfaces_js_1.XML_ATTRKEY]), { [xmlnsKey]: mapper.xmlNamespace });
+ }
+ const propertyObjectName = propertyMapper.serializedName !== ""
+ ? objectName + "." + propertyMapper.serializedName
+ : objectName;
+ let toSerialize = object[key];
+ const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
+ if (polymorphicDiscriminator &&
+ polymorphicDiscriminator.clientName === key &&
+ (toSerialize === undefined || toSerialize === null)) {
+ toSerialize = mapper.serializedName;
+ }
+ const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options);
+ if (serializedValue !== undefined && propName !== undefined && propName !== null) {
+ const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options);
+ if (isXml && propertyMapper.xmlIsAttribute) {
+ // XML_ATTRKEY, i.e., $ is the key attributes are kept under in xml2js.
+ // This keeps things simple while preventing name collision
+ // with names in user documents.
+ parentObject[interfaces_js_1.XML_ATTRKEY] = parentObject[interfaces_js_1.XML_ATTRKEY] || {};
+ parentObject[interfaces_js_1.XML_ATTRKEY][propName] = serializedValue;
+ }
+ else if (isXml && propertyMapper.xmlIsWrapped) {
+ parentObject[propName] = { [propertyMapper.xmlElementName]: value };
+ }
+ else {
+ parentObject[propName] = value;
+ }
+ }
+ }
+ }
+ const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName);
+ if (additionalPropertiesMapper) {
+ const propNames = Object.keys(modelProps);
+ for (const clientPropName in object) {
+ const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName);
+ if (isAdditionalProperty) {
+ payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options);
+ }
+ }
+ }
+ return payload;
+ }
+ return object;
}
-
-
-/***/ }),
-
-/***/ 4622:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(6443)
-const kPool = Symbol('pool')
-
-class PoolStats {
- constructor (pool) {
- this[kPool] = pool
- }
-
- get connected () {
- return this[kPool][kConnected]
- }
-
- get free () {
- return this[kPool][kFree]
- }
-
- get pending () {
- return this[kPool][kPending]
- }
-
- get queued () {
- return this[kPool][kQueued]
- }
-
- get running () {
- return this[kPool][kRunning]
- }
-
- get size () {
- return this[kPool][kSize]
- }
+function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) {
+ if (!isXml || !propertyMapper.xmlNamespace) {
+ return serializedValue;
+ }
+ const xmlnsKey = propertyMapper.xmlNamespacePrefix
+ ? `xmlns:${propertyMapper.xmlNamespacePrefix}`
+ : "xmlns";
+ const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace };
+ if (["Composite"].includes(propertyMapper.type.name)) {
+ if (serializedValue[interfaces_js_1.XML_ATTRKEY]) {
+ return serializedValue;
+ }
+ else {
+ const result = Object.assign({}, serializedValue);
+ result[interfaces_js_1.XML_ATTRKEY] = xmlNamespace;
+ return result;
+ }
+ }
+ const result = {};
+ result[options.xml.xmlCharKey] = serializedValue;
+ result[interfaces_js_1.XML_ATTRKEY] = xmlNamespace;
+ return result;
}
-
-module.exports = PoolStats
-
-
-/***/ }),
-
-/***/ 5076:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-const {
- PoolBase,
- kClients,
- kNeedDrain,
- kAddClient,
- kGetDispatcher
-} = __nccwpck_require__(8640)
-const Client = __nccwpck_require__(6197)
-const {
- InvalidArgumentError
-} = __nccwpck_require__(8707)
-const util = __nccwpck_require__(3440)
-const { kUrl, kInterceptors } = __nccwpck_require__(6443)
-const buildConnector = __nccwpck_require__(9136)
-
-const kOptions = Symbol('options')
-const kConnections = Symbol('connections')
-const kFactory = Symbol('factory')
-
-function defaultFactory (origin, opts) {
- return new Client(origin, opts)
+function isSpecialXmlProperty(propertyName, options) {
+ return [interfaces_js_1.XML_ATTRKEY, options.xml.xmlCharKey].includes(propertyName);
}
-
-class Pool extends PoolBase {
- constructor (origin, {
- connections,
- factory = defaultFactory,
- connect,
- connectTimeout,
- tls,
- maxCachedSessions,
- socketPath,
- autoSelectFamily,
- autoSelectFamilyAttemptTimeout,
- allowH2,
- ...options
- } = {}) {
- super()
-
- if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
- throw new InvalidArgumentError('invalid connections')
+function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) {
+ var _a, _b;
+ const xmlCharKey = (_a = options.xml.xmlCharKey) !== null && _a !== void 0 ? _a : interfaces_js_1.XML_CHARKEY;
+ if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
+ mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName");
+ }
+ const modelProps = resolveModelProperties(serializer, mapper, objectName);
+ let instance = {};
+ const handledPropertyNames = [];
+ for (const key of Object.keys(modelProps)) {
+ const propertyMapper = modelProps[key];
+ const paths = splitSerializeName(modelProps[key].serializedName);
+ handledPropertyNames.push(paths[0]);
+ const { serializedName, xmlName, xmlElementName } = propertyMapper;
+ let propertyObjectName = objectName;
+ if (serializedName !== "" && serializedName !== undefined) {
+ propertyObjectName = objectName + "." + serializedName;
+ }
+ const headerCollectionPrefix = propertyMapper.headerCollectionPrefix;
+ if (headerCollectionPrefix) {
+ const dictionary = {};
+ for (const headerKey of Object.keys(responseBody)) {
+ if (headerKey.startsWith(headerCollectionPrefix)) {
+ dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options);
+ }
+ handledPropertyNames.push(headerKey);
+ }
+ instance[key] = dictionary;
+ }
+ else if (serializer.isXML) {
+ if (propertyMapper.xmlIsAttribute && responseBody[interfaces_js_1.XML_ATTRKEY]) {
+ instance[key] = serializer.deserialize(propertyMapper, responseBody[interfaces_js_1.XML_ATTRKEY][xmlName], propertyObjectName, options);
+ }
+ else if (propertyMapper.xmlIsMsText) {
+ if (responseBody[xmlCharKey] !== undefined) {
+ instance[key] = responseBody[xmlCharKey];
+ }
+ else if (typeof responseBody === "string") {
+ // The special case where xml parser parses "content" into JSON of
+ // `{ name: "content"}` instead of `{ name: { "_": "content" }}`
+ instance[key] = responseBody;
+ }
+ }
+ else {
+ const propertyName = xmlElementName || xmlName || serializedName;
+ if (propertyMapper.xmlIsWrapped) {
+ /* a list of wrapped by
+ For the xml example below
+
+ ...
+ ...
+
+ the responseBody has
+ {
+ Cors: {
+ CorsRule: [{...}, {...}]
+ }
+ }
+ xmlName is "Cors" and xmlElementName is"CorsRule".
+ */
+ const wrapped = responseBody[xmlName];
+ const elementList = (_b = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _b !== void 0 ? _b : [];
+ instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options);
+ handledPropertyNames.push(xmlName);
+ }
+ else {
+ const property = responseBody[propertyName];
+ instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options);
+ handledPropertyNames.push(propertyName);
+ }
+ }
+ }
+ else {
+ // deserialize the property if it is present in the provided responseBody instance
+ let propertyInstance;
+ let res = responseBody;
+ // traversing the object step by step.
+ let steps = 0;
+ for (const item of paths) {
+ if (!res)
+ break;
+ steps++;
+ res = res[item];
+ }
+ // only accept null when reaching the last position of object otherwise it would be undefined
+ if (res === null && steps < paths.length) {
+ res = undefined;
+ }
+ propertyInstance = res;
+ const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator;
+ // checking that the model property name (key)(ex: "fishtype") and the
+ // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype")
+ // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type")
+ // is a better approach. The generator is not consistent with escaping '\.' in the
+ // serializedName of the property (ex: "fish\.type") that is marked as polymorphic discriminator
+ // and the serializedName of the metadata polymorphicDiscriminator (ex: "fish.type"). However,
+ // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and
+ // the transformation of model property name (ex: "fishtype") is done consistently.
+ // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator.
+ if (polymorphicDiscriminator &&
+ key === polymorphicDiscriminator.clientName &&
+ (propertyInstance === undefined || propertyInstance === null)) {
+ propertyInstance = mapper.serializedName;
+ }
+ let serializedValue;
+ // paging
+ if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") {
+ propertyInstance = responseBody[key];
+ const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options);
+ // Copy over any properties that have already been added into the instance, where they do
+ // not exist on the newly de-serialized array
+ for (const [k, v] of Object.entries(instance)) {
+ if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) {
+ arrayInstance[k] = v;
+ }
+ }
+ instance = arrayInstance;
+ }
+ else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) {
+ serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options);
+ instance[key] = serializedValue;
+ }
+ }
}
-
- if (typeof factory !== 'function') {
- throw new InvalidArgumentError('factory must be a function.')
+ const additionalPropertiesMapper = mapper.type.additionalProperties;
+ if (additionalPropertiesMapper) {
+ const isAdditionalProperty = (responsePropName) => {
+ for (const clientPropName in modelProps) {
+ const paths = splitSerializeName(modelProps[clientPropName].serializedName);
+ if (paths[0] === responsePropName) {
+ return false;
+ }
+ }
+ return true;
+ };
+ for (const responsePropName in responseBody) {
+ if (isAdditionalProperty(responsePropName)) {
+ instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options);
+ }
+ }
}
-
- if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
- throw new InvalidArgumentError('connect must be a function or an object')
+ else if (responseBody && !options.ignoreUnknownProperties) {
+ for (const key of Object.keys(responseBody)) {
+ if (instance[key] === undefined &&
+ !handledPropertyNames.includes(key) &&
+ !isSpecialXmlProperty(key, options)) {
+ instance[key] = responseBody[key];
+ }
+ }
}
-
- if (typeof connect !== 'function') {
- connect = buildConnector({
- ...tls,
- maxCachedSessions,
- allowH2,
- socketPath,
- timeout: connectTimeout,
- ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
- ...connect
- })
+ return instance;
+}
+function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) {
+ /* jshint validthis: true */
+ const value = mapper.type.value;
+ if (!value || typeof value !== "object") {
+ throw new Error(`"value" metadata for a Dictionary must be defined in the ` +
+ `mapper and it must of type "object" in ${objectName}`);
}
-
- this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool)
- ? options.interceptors.Pool
- : []
- this[kConnections] = connections || null
- this[kUrl] = util.parseOrigin(origin)
- this[kOptions] = { ...util.deepClone(options), connect, allowH2 }
- this[kOptions].interceptors = options.interceptors
- ? { ...options.interceptors }
- : undefined
- this[kFactory] = factory
- }
-
- [kGetDispatcher] () {
- let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain])
-
- if (dispatcher) {
- return dispatcher
+ if (responseBody) {
+ const tempDictionary = {};
+ for (const key of Object.keys(responseBody)) {
+ tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options);
+ }
+ return tempDictionary;
}
-
- if (!this[kConnections] || this[kClients].length < this[kConnections]) {
- dispatcher = this[kFactory](this[kUrl], this[kOptions])
- this[kAddClient](dispatcher)
+ return responseBody;
+}
+function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) {
+ var _a;
+ let element = mapper.type.element;
+ if (!element || typeof element !== "object") {
+ throw new Error(`element" metadata for an Array must be defined in the ` +
+ `mapper and it must of type "object" in ${objectName}`);
}
-
- return dispatcher
- }
+ if (responseBody) {
+ if (!Array.isArray(responseBody)) {
+ // xml2js will interpret a single element array as just the element, so force it to be an array
+ responseBody = [responseBody];
+ }
+ // Quirk: Composite mappers referenced by `element` might
+ // not have *all* properties declared (like uberParent),
+ // so let's try to look up the full definition by name.
+ if (element.type.name === "Composite" && element.type.className) {
+ element = (_a = serializer.modelMappers[element.type.className]) !== null && _a !== void 0 ? _a : element;
+ }
+ const tempArray = [];
+ for (let i = 0; i < responseBody.length; i++) {
+ tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options);
+ }
+ return tempArray;
+ }
+ return responseBody;
}
-
-module.exports = Pool
-
-
-/***/ }),
-
-/***/ 2720:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-const { kProxy, kClose, kDestroy, kInterceptors } = __nccwpck_require__(6443)
-const { URL } = __nccwpck_require__(7016)
-const Agent = __nccwpck_require__(9965)
-const Pool = __nccwpck_require__(5076)
-const DispatcherBase = __nccwpck_require__(1)
-const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(8707)
-const buildConnector = __nccwpck_require__(9136)
-
-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')
-
-function defaultProtocolPort (protocol) {
- return protocol === 'https:' ? 443 : 80
+function getIndexDiscriminator(discriminators, discriminatorValue, typeName) {
+ const typeNamesToCheck = [typeName];
+ while (typeNamesToCheck.length) {
+ const currentName = typeNamesToCheck.shift();
+ const indexDiscriminator = discriminatorValue === currentName
+ ? discriminatorValue
+ : currentName + "." + discriminatorValue;
+ if (Object.prototype.hasOwnProperty.call(discriminators, indexDiscriminator)) {
+ return discriminators[indexDiscriminator];
+ }
+ else {
+ for (const [name, mapper] of Object.entries(discriminators)) {
+ if (name.startsWith(currentName + ".") &&
+ mapper.type.uberParent === currentName &&
+ mapper.type.className) {
+ typeNamesToCheck.push(mapper.type.className);
+ }
+ }
+ }
+ }
+ return undefined;
}
-
-function buildProxyOptions (opts) {
- if (typeof opts === 'string') {
- opts = { uri: opts }
- }
-
- if (!opts || !opts.uri) {
- throw new InvalidArgumentError('Proxy opts.uri is mandatory')
- }
-
- return {
- uri: opts.uri,
- protocol: opts.protocol || 'https'
- }
+function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) {
+ var _a;
+ const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
+ if (polymorphicDiscriminator) {
+ let discriminatorName = polymorphicDiscriminator[polymorphicPropertyName];
+ if (discriminatorName) {
+ // The serializedName might have \\, which we just want to ignore
+ if (polymorphicPropertyName === "serializedName") {
+ discriminatorName = discriminatorName.replace(/\\/gi, "");
+ }
+ const discriminatorValue = object[discriminatorName];
+ const typeName = (_a = mapper.type.uberParent) !== null && _a !== void 0 ? _a : mapper.type.className;
+ if (typeof discriminatorValue === "string" && typeName) {
+ const polymorphicMapper = getIndexDiscriminator(serializer.modelMappers.discriminators, discriminatorValue, typeName);
+ if (polymorphicMapper) {
+ mapper = polymorphicMapper;
+ }
+ }
+ }
+ }
+ return mapper;
}
-
-function defaultFactory (origin, opts) {
- return new Pool(origin, opts)
+function getPolymorphicDiscriminatorRecursively(serializer, mapper) {
+ return (mapper.type.polymorphicDiscriminator ||
+ getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) ||
+ getPolymorphicDiscriminatorSafely(serializer, mapper.type.className));
}
+function getPolymorphicDiscriminatorSafely(serializer, typeName) {
+ return (typeName &&
+ serializer.modelMappers[typeName] &&
+ serializer.modelMappers[typeName].type.polymorphicDiscriminator);
+}
+/**
+ * Known types of Mappers
+ */
+exports.MapperTypeNames = {
+ Base64Url: "Base64Url",
+ Boolean: "Boolean",
+ ByteArray: "ByteArray",
+ Composite: "Composite",
+ Date: "Date",
+ DateTime: "DateTime",
+ DateTimeRfc1123: "DateTimeRfc1123",
+ Dictionary: "Dictionary",
+ Enum: "Enum",
+ Number: "Number",
+ Object: "Object",
+ Sequence: "Sequence",
+ String: "String",
+ Stream: "Stream",
+ TimeSpan: "TimeSpan",
+ UnixTime: "UnixTime",
+};
+//# sourceMappingURL=serializer.js.map
-class ProxyAgent extends DispatcherBase {
- constructor (opts) {
- super(opts)
- this[kProxy] = buildProxyOptions(opts)
- this[kAgent] = new Agent(opts)
- this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent)
- ? opts.interceptors.ProxyAgent
- : []
-
- if (typeof opts === 'string') {
- opts = { uri: opts }
- }
+/***/ }),
- if (!opts || !opts.uri) {
- throw new InvalidArgumentError('Proxy opts.uri is mandatory')
- }
+/***/ 89544:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- const { clientFactory = defaultFactory } = opts
+"use strict";
- if (typeof clientFactory !== 'function') {
- throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.')
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ServiceClient = void 0;
+const core_rest_pipeline_1 = __nccwpck_require__(20778);
+const pipeline_js_1 = __nccwpck_require__(74136);
+const utils_js_1 = __nccwpck_require__(31193);
+const httpClientCache_js_1 = __nccwpck_require__(26323);
+const operationHelpers_js_1 = __nccwpck_require__(19688);
+const urlHelpers_js_1 = __nccwpck_require__(61752);
+const interfaceHelpers_js_1 = __nccwpck_require__(92066);
+const log_js_1 = __nccwpck_require__(89994);
+/**
+ * Initializes a new instance of the ServiceClient.
+ */
+class ServiceClient {
+ /**
+ * The ServiceClient constructor
+ * @param credential - The credentials used for authentication with the service.
+ * @param options - The service client options that govern the behavior of the client.
+ */
+ constructor(options = {}) {
+ var _a, _b;
+ this._requestContentType = options.requestContentType;
+ this._endpoint = (_a = options.endpoint) !== null && _a !== void 0 ? _a : options.baseUri;
+ if (options.baseUri) {
+ log_js_1.logger.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead.");
+ }
+ this._allowInsecureConnection = options.allowInsecureConnection;
+ this._httpClient = options.httpClient || (0, httpClientCache_js_1.getCachedDefaultHttpClient)();
+ this.pipeline = options.pipeline || createDefaultPipeline(options);
+ if ((_b = options.additionalPolicies) === null || _b === void 0 ? void 0 : _b.length) {
+ for (const { policy, position } of options.additionalPolicies) {
+ // Sign happens after Retry and is commonly needed to occur
+ // before policies that intercept post-retry.
+ const afterPhase = position === "perRetry" ? "Sign" : undefined;
+ this.pipeline.addPolicy(policy, {
+ afterPhase,
+ });
+ }
+ }
}
-
- this[kRequestTls] = opts.requestTls
- this[kProxyTls] = opts.proxyTls
- this[kProxyHeaders] = opts.headers || {}
-
- const resolvedUrl = new URL(opts.uri)
- const { origin, port, host, username, password } = resolvedUrl
-
- 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')}`
+ /**
+ * Send the provided httpRequest.
+ */
+ async sendRequest(request) {
+ return this.pipeline.sendRequest(this._httpClient, request);
}
-
- const connect = buildConnector({ ...opts.proxyTls })
- this[kConnectEndpoint] = buildConnector({ ...opts.requestTls })
- this[kClient] = clientFactory(resolvedUrl, { connect })
- this[kAgent] = new Agent({
- ...opts,
- connect: async (opts, callback) => {
- let requestedHost = opts.host
- if (!opts.port) {
- requestedHost += `:${defaultProtocolPort(opts.protocol)}`
+ /**
+ * Send an HTTP request that is populated using the provided OperationSpec.
+ * @typeParam T - The typed result of the request, based on the OperationSpec.
+ * @param operationArguments - The arguments that the HTTP request's templated values will be populated from.
+ * @param operationSpec - The OperationSpec to use to populate the httpRequest.
+ */
+ async sendOperationRequest(operationArguments, operationSpec) {
+ const endpoint = operationSpec.baseUrl || this._endpoint;
+ if (!endpoint) {
+ throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a endpoint string property that contains the base URL to use.");
}
- try {
- const { socket, statusCode } = await this[kClient].connect({
- origin,
- port,
- path: requestedHost,
- signal: opts.signal,
- headers: {
- ...this[kProxyHeaders],
- host
+ // Templatized URLs sometimes reference properties on the ServiceClient child class,
+ // so we have to pass `this` below in order to search these properties if they're
+ // not part of OperationArguments
+ const url = (0, urlHelpers_js_1.getRequestUrl)(endpoint, operationSpec, operationArguments, this);
+ const request = (0, core_rest_pipeline_1.createPipelineRequest)({
+ url,
+ });
+ request.method = operationSpec.httpMethod;
+ const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
+ operationInfo.operationSpec = operationSpec;
+ operationInfo.operationArguments = operationArguments;
+ const contentType = operationSpec.contentType || this._requestContentType;
+ if (contentType && operationSpec.requestBody) {
+ request.headers.set("Content-Type", contentType);
+ }
+ const options = operationArguments.options;
+ if (options) {
+ const requestOptions = options.requestOptions;
+ if (requestOptions) {
+ if (requestOptions.timeout) {
+ request.timeout = requestOptions.timeout;
+ }
+ if (requestOptions.onUploadProgress) {
+ request.onUploadProgress = requestOptions.onUploadProgress;
+ }
+ if (requestOptions.onDownloadProgress) {
+ request.onDownloadProgress = requestOptions.onDownloadProgress;
+ }
+ if (requestOptions.shouldDeserialize !== undefined) {
+ operationInfo.shouldDeserialize = requestOptions.shouldDeserialize;
+ }
+ if (requestOptions.allowInsecureConnection) {
+ request.allowInsecureConnection = true;
+ }
+ }
+ if (options.abortSignal) {
+ request.abortSignal = options.abortSignal;
+ }
+ if (options.tracingOptions) {
+ request.tracingOptions = options.tracingOptions;
}
- })
- if (statusCode !== 200) {
- socket.on('error', () => {}).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) {
- callback(err)
}
- }
- })
- }
-
- dispatch (opts, handler) {
- const { host } = new URL(opts.origin)
- const headers = buildHeaders(opts.headers)
- throwIfProxyAuthIsSent(headers)
- return this[kAgent].dispatch(
- {
- ...opts,
- headers: {
- ...headers,
- host
+ if (this._allowInsecureConnection) {
+ request.allowInsecureConnection = true;
+ }
+ if (request.streamResponseStatusCodes === undefined) {
+ request.streamResponseStatusCodes = (0, interfaceHelpers_js_1.getStreamingResponseStatusCodes)(operationSpec);
+ }
+ try {
+ const rawResponse = await this.sendRequest(request);
+ const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[rawResponse.status]);
+ if (options === null || options === void 0 ? void 0 : options.onResponse) {
+ options.onResponse(rawResponse, flatResponse);
+ }
+ return flatResponse;
+ }
+ catch (error) {
+ if (typeof error === "object" && (error === null || error === void 0 ? void 0 : error.response)) {
+ const rawResponse = error.response;
+ const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[error.statusCode] || operationSpec.responses["default"]);
+ error.details = flatResponse;
+ if (options === null || options === void 0 ? void 0 : options.onResponse) {
+ options.onResponse(rawResponse, flatResponse, error);
+ }
+ }
+ throw error;
}
- },
- handler
- )
- }
-
- async [kClose] () {
- await this[kAgent].close()
- await this[kClient].close()
- }
-
- async [kDestroy] () {
- await this[kAgent].destroy()
- await this[kClient].destroy()
- }
-}
-
-/**
- * @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')
- }
+exports.ServiceClient = ServiceClient;
+function createDefaultPipeline(options) {
+ const credentialScopes = getCredentialScopes(options);
+ const credentialOptions = options.credential && credentialScopes
+ ? { credentialScopes, credential: options.credential }
+ : undefined;
+ return (0, pipeline_js_1.createClientPipeline)(Object.assign(Object.assign({}, options), { credentialOptions }));
}
-
-module.exports = ProxyAgent
-
+function getCredentialScopes(options) {
+ if (options.credentialScopes) {
+ return options.credentialScopes;
+ }
+ if (options.endpoint) {
+ return `${options.endpoint}/.default`;
+ }
+ if (options.baseUri) {
+ return `${options.baseUri}/.default`;
+ }
+ if (options.credential && !options.credentialScopes) {
+ throw new Error(`When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`);
+ }
+ return undefined;
+}
+//# sourceMappingURL=serviceClient.js.map
/***/ }),
-/***/ 8804:
-/***/ ((module) => {
+/***/ 33345:
+/***/ ((__unused_webpack_module, exports) => {
"use strict";
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.state = void 0;
+/**
+ * Holds the singleton operationRequestMap, to be shared across CJS and ESM imports.
+ */
+exports.state = {
+ operationRequestMap: new WeakMap(),
+};
+//# sourceMappingURL=state-cjs.cjs.map
-let fastNow = Date.now()
-let fastNowTimeout
-
-const fastTimers = []
-
-function onTimeout () {
- fastNow = Date.now()
+/***/ }),
- let len = fastTimers.length
- let idx = 0
- while (idx < len) {
- const timer = fastTimers[idx]
+/***/ 61752:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (timer.state === 0) {
- timer.state = fastNow + timer.delay
- } else if (timer.state > 0 && fastNow >= timer.state) {
- timer.state = -1
- timer.callback(timer.opaque)
- }
+"use strict";
- if (timer.state === -1) {
- timer.state = -2
- if (idx !== len - 1) {
- fastTimers[idx] = fastTimers.pop()
- } else {
- fastTimers.pop()
- }
- len -= 1
- } else {
- idx += 1
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.appendQueryParams = exports.getRequestUrl = void 0;
+const operationHelpers_js_1 = __nccwpck_require__(19688);
+const interfaceHelpers_js_1 = __nccwpck_require__(92066);
+const CollectionFormatToDelimiterMap = {
+ CSV: ",",
+ SSV: " ",
+ Multi: "Multi",
+ TSV: "\t",
+ Pipes: "|",
+};
+function getRequestUrl(baseUri, operationSpec, operationArguments, fallbackObject) {
+ const urlReplacements = calculateUrlReplacements(operationSpec, operationArguments, fallbackObject);
+ let isAbsolutePath = false;
+ let requestUrl = replaceAll(baseUri, urlReplacements);
+ if (operationSpec.path) {
+ let path = replaceAll(operationSpec.path, urlReplacements);
+ // QUIRK: sometimes we get a path component like /{nextLink}
+ // which may be a fully formed URL with a leading /. In that case, we should
+ // remove the leading /
+ if (operationSpec.path === "/{nextLink}" && path.startsWith("/")) {
+ path = path.substring(1);
+ }
+ // QUIRK: sometimes we get a path component like {nextLink}
+ // which may be a fully formed URL. In that case, we should
+ // ignore the baseUri.
+ if (isAbsoluteUrl(path)) {
+ requestUrl = path;
+ isAbsolutePath = true;
+ }
+ else {
+ requestUrl = appendPath(requestUrl, path);
+ }
}
- }
-
- if (fastTimers.length > 0) {
- refreshTimeout()
- }
+ const { queryParams, sequenceParams } = calculateQueryParameters(operationSpec, operationArguments, fallbackObject);
+ /**
+ * Notice that this call sets the `noOverwrite` parameter to true if the `requestUrl`
+ * is an absolute path. This ensures that existing query parameter values in `requestUrl`
+ * do not get overwritten. On the other hand when `requestUrl` is not absolute path, it
+ * is still being built so there is nothing to overwrite.
+ */
+ requestUrl = appendQueryParams(requestUrl, queryParams, sequenceParams, isAbsolutePath);
+ return requestUrl;
}
-
-function refreshTimeout () {
- if (fastNowTimeout && fastNowTimeout.refresh) {
- fastNowTimeout.refresh()
- } else {
- clearTimeout(fastNowTimeout)
- fastNowTimeout = setTimeout(onTimeout, 1e3)
- if (fastNowTimeout.unref) {
- fastNowTimeout.unref()
+exports.getRequestUrl = getRequestUrl;
+function replaceAll(input, replacements) {
+ let result = input;
+ for (const [searchValue, replaceValue] of replacements) {
+ result = result.split(searchValue).join(replaceValue);
}
- }
+ return result;
}
-
-class Timeout {
- constructor (callback, delay, opaque) {
- this.callback = callback
- this.delay = delay
- this.opaque = opaque
-
- // -2 not in timer list
- // -1 in timer list but inactive
- // 0 in timer list waiting for time
- // > 0 in timer list waiting for time to expire
- this.state = -2
-
- this.refresh()
- }
-
- refresh () {
- if (this.state === -2) {
- fastTimers.push(this)
- if (!fastNowTimeout || fastTimers.length === 1) {
- refreshTimeout()
- }
+function calculateUrlReplacements(operationSpec, operationArguments, fallbackObject) {
+ var _a;
+ const result = new Map();
+ if ((_a = operationSpec.urlParameters) === null || _a === void 0 ? void 0 : _a.length) {
+ for (const urlParameter of operationSpec.urlParameters) {
+ let urlParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, urlParameter, fallbackObject);
+ const parameterPathString = (0, interfaceHelpers_js_1.getPathStringFromParameter)(urlParameter);
+ urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, parameterPathString);
+ if (!urlParameter.skipEncoding) {
+ urlParameterValue = encodeURIComponent(urlParameterValue);
+ }
+ result.set(`{${urlParameter.mapper.serializedName || parameterPathString}}`, urlParameterValue);
+ }
}
-
- this.state = 0
- }
-
- clear () {
- this.state = -1
- }
+ return result;
}
-
-module.exports = {
- setTimeout (callback, delay, opaque) {
- return delay < 1e3
- ? setTimeout(callback, delay, opaque)
- : new Timeout(callback, delay, opaque)
- },
- clearTimeout (timeout) {
- if (timeout instanceof Timeout) {
- timeout.clear()
- } else {
- clearTimeout(timeout)
+function isAbsoluteUrl(url) {
+ return url.includes("://");
+}
+function appendPath(url, pathToAppend) {
+ if (!pathToAppend) {
+ return url;
}
- }
+ const parsedUrl = new URL(url);
+ let newPath = parsedUrl.pathname;
+ if (!newPath.endsWith("/")) {
+ newPath = `${newPath}/`;
+ }
+ if (pathToAppend.startsWith("/")) {
+ pathToAppend = pathToAppend.substring(1);
+ }
+ const searchStart = pathToAppend.indexOf("?");
+ if (searchStart !== -1) {
+ const path = pathToAppend.substring(0, searchStart);
+ const search = pathToAppend.substring(searchStart + 1);
+ newPath = newPath + path;
+ if (search) {
+ parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}&${search}` : search;
+ }
+ }
+ else {
+ newPath = newPath + pathToAppend;
+ }
+ parsedUrl.pathname = newPath;
+ return parsedUrl.toString();
}
-
-
-/***/ }),
-
-/***/ 8550:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-const diagnosticsChannel = __nccwpck_require__(1637)
-const { uid, states } = __nccwpck_require__(5913)
-const {
- kReadyState,
- kSentClose,
- kByteParser,
- kReceivedClose
-} = __nccwpck_require__(2933)
-const { fireEvent, failWebsocketConnection } = __nccwpck_require__(3574)
-const { CloseEvent } = __nccwpck_require__(6255)
-const { makeRequest } = __nccwpck_require__(5194)
-const { fetching } = __nccwpck_require__(2315)
-const { Headers } = __nccwpck_require__(6349)
-const { getGlobalDispatcher } = __nccwpck_require__(2581)
-const { kHeadersList } = __nccwpck_require__(6443)
-
-const channels = {}
-channels.open = diagnosticsChannel.channel('undici:websocket:open')
-channels.close = diagnosticsChannel.channel('undici:websocket:close')
-channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error')
-
-/** @type {import('crypto')} */
-let crypto
-try {
- crypto = __nccwpck_require__(6982)
-} catch {
-
+function calculateQueryParameters(operationSpec, operationArguments, fallbackObject) {
+ var _a;
+ const result = new Map();
+ const sequenceParams = new Set();
+ if ((_a = operationSpec.queryParameters) === null || _a === void 0 ? void 0 : _a.length) {
+ for (const queryParameter of operationSpec.queryParameters) {
+ if (queryParameter.mapper.type.name === "Sequence" && queryParameter.mapper.serializedName) {
+ sequenceParams.add(queryParameter.mapper.serializedName);
+ }
+ let queryParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, queryParameter, fallbackObject);
+ if ((queryParameterValue !== undefined && queryParameterValue !== null) ||
+ queryParameter.mapper.required) {
+ queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(queryParameter));
+ const delimiter = queryParameter.collectionFormat
+ ? CollectionFormatToDelimiterMap[queryParameter.collectionFormat]
+ : "";
+ if (Array.isArray(queryParameterValue)) {
+ // replace null and undefined
+ queryParameterValue = queryParameterValue.map((item) => {
+ if (item === null || item === undefined) {
+ return "";
+ }
+ return item;
+ });
+ }
+ if (queryParameter.collectionFormat === "Multi" && queryParameterValue.length === 0) {
+ continue;
+ }
+ else if (Array.isArray(queryParameterValue) &&
+ (queryParameter.collectionFormat === "SSV" || queryParameter.collectionFormat === "TSV")) {
+ queryParameterValue = queryParameterValue.join(delimiter);
+ }
+ if (!queryParameter.skipEncoding) {
+ if (Array.isArray(queryParameterValue)) {
+ queryParameterValue = queryParameterValue.map((item) => {
+ return encodeURIComponent(item);
+ });
+ }
+ else {
+ queryParameterValue = encodeURIComponent(queryParameterValue);
+ }
+ }
+ // Join pipes and CSV *after* encoding, or the server will be upset.
+ if (Array.isArray(queryParameterValue) &&
+ (queryParameter.collectionFormat === "CSV" || queryParameter.collectionFormat === "Pipes")) {
+ queryParameterValue = queryParameterValue.join(delimiter);
+ }
+ result.set(queryParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(queryParameter), queryParameterValue);
+ }
+ }
+ }
+ return {
+ queryParams: result,
+ sequenceParams,
+ };
}
+function simpleParseQueryParams(queryString) {
+ const result = new Map();
+ if (!queryString || queryString[0] !== "?") {
+ return result;
+ }
+ // remove the leading ?
+ queryString = queryString.slice(1);
+ const pairs = queryString.split("&");
+ for (const pair of pairs) {
+ const [name, value] = pair.split("=", 2);
+ const existingValue = result.get(name);
+ if (existingValue) {
+ if (Array.isArray(existingValue)) {
+ existingValue.push(value);
+ }
+ else {
+ result.set(name, [existingValue, value]);
+ }
+ }
+ else {
+ result.set(name, value);
+ }
+ }
+ return result;
+}
+/** @internal */
+function appendQueryParams(url, queryParams, sequenceParams, noOverwrite = false) {
+ if (queryParams.size === 0) {
+ return url;
+ }
+ const parsedUrl = new URL(url);
+ // QUIRK: parsedUrl.searchParams will have their name/value pairs decoded, which
+ // can change their meaning to the server, such as in the case of a SAS signature.
+ // To avoid accidentally un-encoding a query param, we parse the key/values ourselves
+ const combinedParams = simpleParseQueryParams(parsedUrl.search);
+ for (const [name, value] of queryParams) {
+ const existingValue = combinedParams.get(name);
+ if (Array.isArray(existingValue)) {
+ if (Array.isArray(value)) {
+ existingValue.push(...value);
+ const valueSet = new Set(existingValue);
+ combinedParams.set(name, Array.from(valueSet));
+ }
+ else {
+ existingValue.push(value);
+ }
+ }
+ else if (existingValue) {
+ if (Array.isArray(value)) {
+ value.unshift(existingValue);
+ }
+ else if (sequenceParams.has(name)) {
+ combinedParams.set(name, [existingValue, value]);
+ }
+ if (!noOverwrite) {
+ combinedParams.set(name, value);
+ }
+ }
+ else {
+ combinedParams.set(name, value);
+ }
+ }
+ const searchPieces = [];
+ for (const [name, value] of combinedParams) {
+ if (typeof value === "string") {
+ searchPieces.push(`${name}=${value}`);
+ }
+ else if (Array.isArray(value)) {
+ // QUIRK: If we get an array of values, include multiple key/value pairs
+ for (const subValue of value) {
+ searchPieces.push(`${name}=${subValue}`);
+ }
+ }
+ else {
+ searchPieces.push(`${name}=${value}`);
+ }
+ }
+ // QUIRK: we have to set search manually as searchParams will encode comma when it shouldn't.
+ parsedUrl.search = searchPieces.length ? `?${searchPieces.join("&")}` : "";
+ return parsedUrl.toString();
+}
+exports.appendQueryParams = appendQueryParams;
+//# sourceMappingURL=urlHelpers.js.map
-/**
- * @see https://websockets.spec.whatwg.org/#concept-websocket-establish
- * @param {URL} url
- * @param {string|string[]} protocols
- * @param {import('./websocket').WebSocket} ws
- * @param {(response: any) => void} onEstablish
- * @param {Partial} options
- */
-function establishWebSocketConnection (url, protocols, ws, onEstablish, 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],
- 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 = new Headers(options.headers)[kHeadersList]
-
- 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)
-
- // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s
- // header list.
- request.headersList.append('sec-websocket-version', '13')
-
- // 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)
- }
-
- // 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
- // TODO: enable once permessage-deflate is supported
- const permessageDeflate = '' // 'permessage-deflate; 15'
-
- // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to
- // request’s header list.
- // request.headersList.append('sec-websocket-extensions', permessageDeflate)
-
- // 11. Fetch request with useParallelQueue set to true, and
- // processResponse given response being these steps:
- const controller = fetching({
- request,
- useParallelQueue: true,
- dispatcher: options.dispatcher ?? getGlobalDispatcher(),
- processResponse (response) {
- // 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(ws, 'Received network error or non-101 status code.')
- 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(ws, '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(ws, '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(ws, '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(ws, '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')
-
- if (secExtension !== null && secExtension !== permessageDeflate) {
- failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.')
- 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 && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) {
- failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.')
- return
- }
-
- response.socket.on('data', onSocketData)
- response.socket.on('close', onSocketClose)
- response.socket.on('error', onSocketError)
+/***/ }),
- if (channels.open.hasSubscribers) {
- channels.open.publish({
- address: response.socket.address(),
- protocol: secProtocol,
- extensions: secExtension
- })
- }
+/***/ 31193:
+/***/ ((__unused_webpack_module, exports) => {
- onEstablish(response)
- }
- })
+"use strict";
- return controller
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.flattenResponse = exports.isValidUuid = exports.isDuration = exports.isPrimitiveBody = void 0;
+/**
+ * A type guard for a primitive response body.
+ * @param value - Value to test
+ *
+ * @internal
+ */
+function isPrimitiveBody(value, mapperTypeName) {
+ return (mapperTypeName !== "Composite" &&
+ mapperTypeName !== "Dictionary" &&
+ (typeof value === "string" ||
+ typeof value === "number" ||
+ typeof value === "boolean" ||
+ (mapperTypeName === null || mapperTypeName === void 0 ? void 0 : mapperTypeName.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i)) !==
+ null ||
+ value === undefined ||
+ value === null));
}
-
+exports.isPrimitiveBody = isPrimitiveBody;
+const validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
/**
- * @param {Buffer} chunk
+ * Returns true if the given string is in ISO 8601 format.
+ * @param value - The value to be validated for ISO 8601 duration format.
+ * @internal
*/
-function onSocketData (chunk) {
- if (!this.ws[kByteParser].write(chunk)) {
- this.pause()
- }
+function isDuration(value) {
+ return validateISODuration.test(value);
}
-
+exports.isDuration = isDuration;
+const validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;
/**
- * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
- * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
+ * Returns true if the provided uuid is valid.
+ *
+ * @param uuid - The uuid that needs to be validated.
+ *
+ * @internal
*/
-function onSocketClose () {
- const { ws } = this
-
- // 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 = ws[kSentClose] && ws[kReceivedClose]
-
- let code = 1005
- let reason = ''
-
- const result = ws[kByteParser].closingInfo
-
- if (result) {
- code = result.code ?? 1005
- reason = result.reason
- } else if (!ws[kSentClose]) {
- // 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).
- ws[kReadyState] = 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.
- fireEvent('close', ws, CloseEvent, {
- wasClean, code, reason
- })
-
- if (channels.close.hasSubscribers) {
- channels.close.publish({
- websocket: ws,
- code,
- reason
- })
- }
+function isValidUuid(uuid) {
+ return validUuidRegex.test(uuid);
}
-
-function onSocketError (error) {
- const { ws } = this
-
- ws[kReadyState] = states.CLOSING
-
- if (channels.socketError.hasSubscribers) {
- channels.socketError.publish(error)
- }
-
- this.destroy()
+exports.isValidUuid = isValidUuid;
+/**
+ * Maps the response as follows:
+ * - wraps the response body if needed (typically if its type is primitive).
+ * - returns null if the combination of the headers and the body is empty.
+ * - otherwise, returns the combination of the headers and the body.
+ *
+ * @param responseObject - a representation of the parsed response
+ * @returns the response that will be returned to the user which can be null and/or wrapped
+ *
+ * @internal
+ */
+function handleNullableResponseAndWrappableBody(responseObject) {
+ const combinedHeadersAndBody = Object.assign(Object.assign({}, responseObject.headers), responseObject.body);
+ if (responseObject.hasNullableType &&
+ Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0) {
+ return responseObject.shouldWrapBody ? { body: null } : null;
+ }
+ else {
+ return responseObject.shouldWrapBody
+ ? Object.assign(Object.assign({}, responseObject.headers), { body: responseObject.body }) : combinedHeadersAndBody;
+ }
}
-
-module.exports = {
- establishWebSocketConnection
+/**
+ * Take a `FullOperationResponse` and turn it into a flat
+ * response object to hand back to the consumer.
+ * @param fullResponse - The processed response from the operation request
+ * @param responseSpec - The response map from the OperationSpec
+ *
+ * @internal
+ */
+function flattenResponse(fullResponse, responseSpec) {
+ var _a, _b;
+ const parsedHeaders = fullResponse.parsedHeaders;
+ // head methods never have a body, but we return a boolean set to body property
+ // to indicate presence/absence of the resource
+ if (fullResponse.request.method === "HEAD") {
+ return Object.assign(Object.assign({}, parsedHeaders), { body: fullResponse.parsedBody });
+ }
+ const bodyMapper = responseSpec && responseSpec.bodyMapper;
+ const isNullable = Boolean(bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.nullable);
+ const expectedBodyTypeName = bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.type.name;
+ /** If the body is asked for, we look at the expected body type to handle it */
+ if (expectedBodyTypeName === "Stream") {
+ return Object.assign(Object.assign({}, parsedHeaders), { blobBody: fullResponse.blobBody, readableStreamBody: fullResponse.readableStreamBody });
+ }
+ const modelProperties = (expectedBodyTypeName === "Composite" &&
+ bodyMapper.type.modelProperties) ||
+ {};
+ const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === "");
+ if (expectedBodyTypeName === "Sequence" || isPageableResponse) {
+ const arrayResponse = (_a = fullResponse.parsedBody) !== null && _a !== void 0 ? _a : [];
+ for (const key of Object.keys(modelProperties)) {
+ if (modelProperties[key].serializedName) {
+ arrayResponse[key] = (_b = fullResponse.parsedBody) === null || _b === void 0 ? void 0 : _b[key];
+ }
+ }
+ if (parsedHeaders) {
+ for (const key of Object.keys(parsedHeaders)) {
+ arrayResponse[key] = parsedHeaders[key];
+ }
+ }
+ return isNullable &&
+ !fullResponse.parsedBody &&
+ !parsedHeaders &&
+ Object.getOwnPropertyNames(modelProperties).length === 0
+ ? null
+ : arrayResponse;
+ }
+ return handleNullableResponseAndWrappableBody({
+ body: fullResponse.parsedBody,
+ headers: parsedHeaders,
+ hasNullableType: isNullable,
+ shouldWrapBody: isPrimitiveBody(fullResponse.parsedBody, expectedBodyTypeName),
+ });
}
-
+exports.flattenResponse = flattenResponse;
+//# sourceMappingURL=utils.js.map
/***/ }),
-/***/ 5913:
-/***/ ((module) => {
+/***/ 95492:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"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
-const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
-
-/** @type {PropertyDescriptor} */
-const staticPropertyDescriptors = {
- enumerable: true,
- writable: false,
- configurable: false
-}
-
-const states = {
- CONNECTING: 0,
- OPEN: 1,
- CLOSING: 2,
- CLOSED: 3
-}
-
-const opcodes = {
- CONTINUATION: 0x0,
- TEXT: 0x1,
- BINARY: 0x2,
- CLOSE: 0x8,
- PING: 0x9,
- PONG: 0xA
-}
-
-const maxUnsigned16Bit = 2 ** 16 - 1 // 65535
-
-const parserStates = {
- INFO: 0,
- PAYLOADLENGTH_16: 2,
- PAYLOADLENGTH_64: 3,
- READ_DATA: 4
-}
-
-const emptyBuffer = Buffer.allocUnsafe(0)
-
-module.exports = {
- uid,
- staticPropertyDescriptors,
- states,
- opcodes,
- maxUnsigned16Bit,
- parserStates,
- emptyBuffer
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ExtendedServiceClient = void 0;
+const disableKeepAlivePolicy_js_1 = __nccwpck_require__(32639);
+const core_rest_pipeline_1 = __nccwpck_require__(20778);
+const core_client_1 = __nccwpck_require__(60160);
+const response_js_1 = __nccwpck_require__(38153);
+/**
+ * Client to provide compatability between core V1 & V2.
+ */
+class ExtendedServiceClient extends core_client_1.ServiceClient {
+ constructor(options) {
+ var _a, _b;
+ super(options);
+ if (((_a = options.keepAliveOptions) === null || _a === void 0 ? void 0 : _a.enable) === false &&
+ !(0, disableKeepAlivePolicy_js_1.pipelineContainsDisableKeepAlivePolicy)(this.pipeline)) {
+ this.pipeline.addPolicy((0, disableKeepAlivePolicy_js_1.createDisableKeepAlivePolicy)());
+ }
+ if (((_b = options.redirectOptions) === null || _b === void 0 ? void 0 : _b.handleRedirects) === false) {
+ this.pipeline.removePolicy({
+ name: core_rest_pipeline_1.redirectPolicyName,
+ });
+ }
+ }
+ /**
+ * Compatible send operation request function.
+ *
+ * @param operationArguments - Operation arguments
+ * @param operationSpec - Operation Spec
+ * @returns
+ */
+ async sendOperationRequest(operationArguments, operationSpec) {
+ var _a;
+ const userProvidedCallBack = (_a = operationArguments === null || operationArguments === void 0 ? void 0 : operationArguments.options) === null || _a === void 0 ? void 0 : _a.onResponse;
+ let lastResponse;
+ function onResponse(rawResponse, flatResponse, error) {
+ lastResponse = rawResponse;
+ if (userProvidedCallBack) {
+ userProvidedCallBack(rawResponse, flatResponse, error);
+ }
+ }
+ operationArguments.options = Object.assign(Object.assign({}, operationArguments.options), { onResponse });
+ const result = await super.sendOperationRequest(operationArguments, operationSpec);
+ if (lastResponse) {
+ Object.defineProperty(result, "_response", {
+ value: (0, response_js_1.toCompatResponse)(lastResponse),
+ });
+ }
+ return result;
+ }
}
-
+exports.ExtendedServiceClient = ExtendedServiceClient;
+//# sourceMappingURL=extendedClient.js.map
/***/ }),
-/***/ 6255:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 2078:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-
-const { webidl } = __nccwpck_require__(4222)
-const { kEnumerableProperty } = __nccwpck_require__(3440)
-const { MessagePort } = __nccwpck_require__(8167)
-
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.convertHttpClient = void 0;
+const response_js_1 = __nccwpck_require__(38153);
+const util_js_1 = __nccwpck_require__(33850);
/**
- * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent
+ * Converts a RequestPolicy based HttpClient to a PipelineRequest based HttpClient.
+ * @param requestPolicyClient - A HttpClient compatible with core-http
+ * @returns A HttpClient compatible with core-rest-pipeline
*/
-class MessageEvent extends Event {
- #eventInit
-
- constructor (type, eventInitDict = {}) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' })
-
- type = webidl.converters.DOMString(type)
- eventInitDict = webidl.converters.MessageEventInit(eventInitDict)
-
- super(type, eventInitDict)
-
- this.#eventInit = eventInitDict
- }
-
- 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
- }
+function convertHttpClient(requestPolicyClient) {
+ return {
+ sendRequest: async (request) => {
+ const response = await requestPolicyClient.sendRequest((0, util_js_1.toWebResourceLike)(request, { createProxy: true }));
+ return (0, response_js_1.toPipelineResponse)(response);
+ },
+ };
+}
+exports.convertHttpClient = convertHttpClient;
+//# sourceMappingURL=httpClientAdapter.js.map
- initMessageEvent (
- type,
- bubbles = false,
- cancelable = false,
- data = null,
- origin = '',
- lastEventId = '',
- source = null,
- ports = []
- ) {
- webidl.brandCheck(this, MessageEvent)
+/***/ }),
- webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' })
+/***/ 61584:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- return new MessageEvent(type, {
- bubbles, cancelable, data, origin, lastEventId, source, ports
- })
- }
-}
+"use strict";
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.toHttpHeadersLike = exports.convertHttpClient = exports.disableKeepAlivePolicyName = exports.HttpPipelineLogLevel = exports.createRequestPolicyFactoryPolicy = exports.requestPolicyFactoryPolicyName = exports.ExtendedServiceClient = void 0;
/**
- * @see https://websockets.spec.whatwg.org/#the-closeevent-interface
+ * A Shim Library that provides compatibility between Core V1 & V2 Packages.
+ *
+ * @packageDocumentation
*/
-class CloseEvent extends Event {
- #eventInit
-
- constructor (type, eventInitDict = {}) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' })
-
- type = webidl.converters.DOMString(type)
- eventInitDict = webidl.converters.CloseEventInit(eventInitDict)
-
- super(type, eventInitDict)
-
- this.#eventInit = eventInitDict
- }
-
- 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) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' })
-
- super(type, eventInitDict)
+var extendedClient_js_1 = __nccwpck_require__(95492);
+Object.defineProperty(exports, "ExtendedServiceClient", ({ enumerable: true, get: function () { return extendedClient_js_1.ExtendedServiceClient; } }));
+var requestPolicyFactoryPolicy_js_1 = __nccwpck_require__(3466);
+Object.defineProperty(exports, "requestPolicyFactoryPolicyName", ({ enumerable: true, get: function () { return requestPolicyFactoryPolicy_js_1.requestPolicyFactoryPolicyName; } }));
+Object.defineProperty(exports, "createRequestPolicyFactoryPolicy", ({ enumerable: true, get: function () { return requestPolicyFactoryPolicy_js_1.createRequestPolicyFactoryPolicy; } }));
+Object.defineProperty(exports, "HttpPipelineLogLevel", ({ enumerable: true, get: function () { return requestPolicyFactoryPolicy_js_1.HttpPipelineLogLevel; } }));
+var disableKeepAlivePolicy_js_1 = __nccwpck_require__(32639);
+Object.defineProperty(exports, "disableKeepAlivePolicyName", ({ enumerable: true, get: function () { return disableKeepAlivePolicy_js_1.disableKeepAlivePolicyName; } }));
+var httpClientAdapter_js_1 = __nccwpck_require__(2078);
+Object.defineProperty(exports, "convertHttpClient", ({ enumerable: true, get: function () { return httpClientAdapter_js_1.convertHttpClient; } }));
+var util_js_1 = __nccwpck_require__(33850);
+Object.defineProperty(exports, "toHttpHeadersLike", ({ enumerable: true, get: function () { return util_js_1.toHttpHeadersLike; } }));
+//# sourceMappingURL=index.js.map
- type = webidl.converters.DOMString(type)
- eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {})
+/***/ }),
- this.#eventInit = eventInitDict
- }
+/***/ 32639:
+/***/ ((__unused_webpack_module, exports) => {
- get message () {
- webidl.brandCheck(this, ErrorEvent)
+"use strict";
- return this.#eventInit.message
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.pipelineContainsDisableKeepAlivePolicy = exports.createDisableKeepAlivePolicy = exports.disableKeepAlivePolicyName = void 0;
+exports.disableKeepAlivePolicyName = "DisableKeepAlivePolicy";
+function createDisableKeepAlivePolicy() {
+ return {
+ name: exports.disableKeepAlivePolicyName,
+ async sendRequest(request, next) {
+ request.disableKeepAlive = true;
+ return next(request);
+ },
+ };
+}
+exports.createDisableKeepAlivePolicy = createDisableKeepAlivePolicy;
+/**
+ * @internal
+ */
+function pipelineContainsDisableKeepAlivePolicy(pipeline) {
+ return pipeline.getOrderedPolicies().some((policy) => policy.name === exports.disableKeepAlivePolicyName);
+}
+exports.pipelineContainsDisableKeepAlivePolicy = pipelineContainsDisableKeepAlivePolicy;
+//# sourceMappingURL=disableKeepAlivePolicy.js.map
- get filename () {
- webidl.brandCheck(this, ErrorEvent)
+/***/ }),
- return this.#eventInit.filename
- }
+/***/ 3466:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- get lineno () {
- webidl.brandCheck(this, ErrorEvent)
+"use strict";
- return this.#eventInit.lineno
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createRequestPolicyFactoryPolicy = exports.requestPolicyFactoryPolicyName = exports.HttpPipelineLogLevel = void 0;
+const util_js_1 = __nccwpck_require__(33850);
+const response_js_1 = __nccwpck_require__(38153);
+/**
+ * An enum for compatibility with RequestPolicy
+ */
+var HttpPipelineLogLevel;
+(function (HttpPipelineLogLevel) {
+ HttpPipelineLogLevel[HttpPipelineLogLevel["ERROR"] = 1] = "ERROR";
+ HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO";
+ HttpPipelineLogLevel[HttpPipelineLogLevel["OFF"] = 0] = "OFF";
+ HttpPipelineLogLevel[HttpPipelineLogLevel["WARNING"] = 2] = "WARNING";
+})(HttpPipelineLogLevel || (exports.HttpPipelineLogLevel = HttpPipelineLogLevel = {}));
+const mockRequestPolicyOptions = {
+ log(_logLevel, _message) {
+ /* do nothing */
+ },
+ shouldLog(_logLevel) {
+ return false;
+ },
+};
+/**
+ * The name of the RequestPolicyFactoryPolicy
+ */
+exports.requestPolicyFactoryPolicyName = "RequestPolicyFactoryPolicy";
+/**
+ * A policy that wraps policies written for core-http.
+ * @param factories - An array of `RequestPolicyFactory` objects from a core-http pipeline
+ */
+function createRequestPolicyFactoryPolicy(factories) {
+ const orderedFactories = factories.slice().reverse();
+ return {
+ name: exports.requestPolicyFactoryPolicyName,
+ async sendRequest(request, next) {
+ let httpPipeline = {
+ async sendRequest(httpRequest) {
+ const response = await next((0, util_js_1.toPipelineRequest)(httpRequest));
+ return (0, response_js_1.toCompatResponse)(response, { createProxy: true });
+ },
+ };
+ for (const factory of orderedFactories) {
+ httpPipeline = factory.create(httpPipeline, mockRequestPolicyOptions);
+ }
+ const webResourceLike = (0, util_js_1.toWebResourceLike)(request, { createProxy: true });
+ const response = await httpPipeline.sendRequest(webResourceLike);
+ return (0, response_js_1.toPipelineResponse)(response);
+ },
+ };
+}
+exports.createRequestPolicyFactoryPolicy = createRequestPolicyFactoryPolicy;
+//# sourceMappingURL=requestPolicyFactoryPolicy.js.map
- get colno () {
- webidl.brandCheck(this, ErrorEvent)
+/***/ }),
- return this.#eventInit.colno
- }
+/***/ 38153:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- get error () {
- webidl.brandCheck(this, ErrorEvent)
+"use strict";
- return this.#eventInit.error
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.toPipelineResponse = exports.toCompatResponse = void 0;
+const core_rest_pipeline_1 = __nccwpck_require__(20778);
+const util_js_1 = __nccwpck_require__(33850);
+const originalResponse = Symbol("Original FullOperationResponse");
+/**
+ * A helper to convert response objects from the new pipeline back to the old one.
+ * @param response - A response object from core-client.
+ * @returns A response compatible with `HttpOperationResponse` from core-http.
+ */
+function toCompatResponse(response, options) {
+ let request = (0, util_js_1.toWebResourceLike)(response.request);
+ let headers = (0, util_js_1.toHttpHeadersLike)(response.headers);
+ if (options === null || options === void 0 ? void 0 : options.createProxy) {
+ return new Proxy(response, {
+ get(target, prop, receiver) {
+ if (prop === "headers") {
+ return headers;
+ }
+ else if (prop === "request") {
+ return request;
+ }
+ else if (prop === originalResponse) {
+ return response;
+ }
+ return Reflect.get(target, prop, receiver);
+ },
+ set(target, prop, value, receiver) {
+ if (prop === "headers") {
+ headers = value;
+ }
+ else if (prop === "request") {
+ request = value;
+ }
+ return Reflect.set(target, prop, value, receiver);
+ },
+ });
+ }
+ else {
+ return Object.assign(Object.assign({}, response), { request,
+ headers });
+ }
}
+exports.toCompatResponse = toCompatResponse;
+/**
+ * A helper to convert back to a PipelineResponse
+ * @param compatResponse - A response compatible with `HttpOperationResponse` from core-http.
+ */
+function toPipelineResponse(compatResponse) {
+ const extendedCompatResponse = compatResponse;
+ const response = extendedCompatResponse[originalResponse];
+ const headers = (0, core_rest_pipeline_1.createHttpHeaders)(compatResponse.headers.toJson({ preserveCase: true }));
+ if (response) {
+ response.headers = headers;
+ return response;
+ }
+ else {
+ return Object.assign(Object.assign({}, compatResponse), { headers, request: (0, util_js_1.toPipelineRequest)(compatResponse.request) });
+ }
+}
+exports.toPipelineResponse = toPipelineResponse;
+//# sourceMappingURL=response.js.map
-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(MessagePort)
+/***/ }),
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.MessagePort
-)
+/***/ 33850:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-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
- }
-]
+"use strict";
-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'],
- get defaultValue () {
- return []
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.HttpHeaders = exports.toHttpHeadersLike = exports.toWebResourceLike = exports.toPipelineRequest = void 0;
+const core_rest_pipeline_1 = __nccwpck_require__(20778);
+// We use a custom symbol to cache a reference to the original request without
+// exposing it on the public interface.
+const originalRequestSymbol = Symbol("Original PipelineRequest");
+// Symbol.for() will return the same symbol if it's already been created
+// This particular one is used in core-client to handle the case of when a request is
+// cloned but we need to retrieve the OperationSpec and OperationArguments from the
+// original request.
+const originalClientRequestSymbol = Symbol.for("@azure/core-client original request");
+function toPipelineRequest(webResource, options = {}) {
+ const compatWebResource = webResource;
+ const request = compatWebResource[originalRequestSymbol];
+ const headers = (0, core_rest_pipeline_1.createHttpHeaders)(webResource.headers.toJson({ preserveCase: true }));
+ if (request) {
+ request.headers = headers;
+ return request;
+ }
+ else {
+ const newRequest = (0, core_rest_pipeline_1.createPipelineRequest)({
+ url: webResource.url,
+ method: webResource.method,
+ headers,
+ withCredentials: webResource.withCredentials,
+ timeout: webResource.timeout,
+ requestId: webResource.requestId,
+ abortSignal: webResource.abortSignal,
+ body: webResource.body,
+ formData: webResource.formData,
+ disableKeepAlive: !!webResource.keepAlive,
+ onDownloadProgress: webResource.onDownloadProgress,
+ onUploadProgress: webResource.onUploadProgress,
+ proxySettings: webResource.proxySettings,
+ streamResponseStatusCodes: webResource.streamResponseStatusCodes,
+ });
+ if (options.originalRequest) {
+ newRequest[originalClientRequestSymbol] =
+ options.originalRequest;
+ }
+ return newRequest;
+ }
+}
+exports.toPipelineRequest = toPipelineRequest;
+function toWebResourceLike(request, options) {
+ var _a;
+ const originalRequest = (_a = options === null || options === void 0 ? void 0 : options.originalRequest) !== null && _a !== void 0 ? _a : request;
+ const webResource = {
+ url: request.url,
+ method: request.method,
+ headers: toHttpHeadersLike(request.headers),
+ withCredentials: request.withCredentials,
+ timeout: request.timeout,
+ requestId: request.headers.get("x-ms-client-request-id") || request.requestId,
+ abortSignal: request.abortSignal,
+ body: request.body,
+ formData: request.formData,
+ keepAlive: !!request.disableKeepAlive,
+ onDownloadProgress: request.onDownloadProgress,
+ onUploadProgress: request.onUploadProgress,
+ proxySettings: request.proxySettings,
+ streamResponseStatusCodes: request.streamResponseStatusCodes,
+ clone() {
+ throw new Error("Cannot clone a non-proxied WebResourceLike");
+ },
+ prepare() {
+ throw new Error("WebResourceLike.prepare() is not supported by @azure/core-http-compat");
+ },
+ validateRequestProperties() {
+ /** do nothing */
+ },
+ };
+ if (options === null || options === void 0 ? void 0 : options.createProxy) {
+ return new Proxy(webResource, {
+ get(target, prop, receiver) {
+ if (prop === originalRequestSymbol) {
+ return request;
+ }
+ else if (prop === "clone") {
+ return () => {
+ return toWebResourceLike(toPipelineRequest(webResource, { originalRequest }), {
+ createProxy: true,
+ originalRequest,
+ });
+ };
+ }
+ return Reflect.get(target, prop, receiver);
+ },
+ set(target, prop, value, receiver) {
+ if (prop === "keepAlive") {
+ request.disableKeepAlive = !value;
+ }
+ const passThroughProps = [
+ "url",
+ "method",
+ "withCredentials",
+ "timeout",
+ "requestId",
+ "abortSignal",
+ "body",
+ "formData",
+ "onDownloadProgress",
+ "onUploadProgress",
+ "proxySettings",
+ "streamResponseStatusCodes",
+ ];
+ if (typeof prop === "string" && passThroughProps.includes(prop)) {
+ request[prop] = value;
+ }
+ return Reflect.set(target, prop, value, receiver);
+ },
+ });
+ }
+ else {
+ return webResource;
+ }
+}
+exports.toWebResourceLike = toWebResourceLike;
+/**
+ * Converts HttpHeaders from core-rest-pipeline to look like
+ * HttpHeaders from core-http.
+ * @param headers - HttpHeaders from core-rest-pipeline
+ * @returns HttpHeaders as they looked in core-http
+ */
+function toHttpHeadersLike(headers) {
+ return new HttpHeaders(headers.toJSON({ preserveCase: true }));
+}
+exports.toHttpHeadersLike = toHttpHeadersLike;
+/**
+ * A collection of HttpHeaders that can be sent with a HTTP request.
+ */
+function getHeaderKey(headerName) {
+ return headerName.toLowerCase();
+}
+/**
+ * A collection of HTTP header key/value pairs.
+ */
+class HttpHeaders {
+ constructor(rawHeaders) {
+ this._headersMap = {};
+ if (rawHeaders) {
+ for (const headerName in rawHeaders) {
+ this.set(headerName, rawHeaders[headerName]);
+ }
+ }
+ }
+ /**
+ * Set a header in this collection with the provided name and value. The name is
+ * case-insensitive.
+ * @param headerName - The name of the header to set. This value is case-insensitive.
+ * @param headerValue - The value of the header to set.
+ */
+ set(headerName, headerValue) {
+ this._headersMap[getHeaderKey(headerName)] = {
+ name: headerName,
+ value: headerValue.toString(),
+ };
+ }
+ /**
+ * Get the header value for the provided header name, or undefined if no header exists in this
+ * collection with the provided name.
+ * @param headerName - The name of the header.
+ */
+ get(headerName) {
+ const header = this._headersMap[getHeaderKey(headerName)];
+ return !header ? undefined : header.value;
+ }
+ /**
+ * Get whether or not this header collection contains a header entry for the provided header name.
+ */
+ contains(headerName) {
+ return !!this._headersMap[getHeaderKey(headerName)];
+ }
+ /**
+ * Remove the header with the provided headerName. Return whether or not the header existed and
+ * was removed.
+ * @param headerName - The name of the header to remove.
+ */
+ remove(headerName) {
+ const result = this.contains(headerName);
+ delete this._headersMap[getHeaderKey(headerName)];
+ return result;
+ }
+ /**
+ * Get the headers that are contained this collection as an object.
+ */
+ rawHeaders() {
+ return this.toJson({ preserveCase: true });
+ }
+ /**
+ * Get the headers that are contained in this collection as an array.
+ */
+ headersArray() {
+ const headers = [];
+ for (const headerKey in this._headersMap) {
+ headers.push(this._headersMap[headerKey]);
+ }
+ return headers;
+ }
+ /**
+ * Get the header names that are contained in this collection.
+ */
+ headerNames() {
+ const headerNames = [];
+ const headers = this.headersArray();
+ for (let i = 0; i < headers.length; ++i) {
+ headerNames.push(headers[i].name);
+ }
+ return headerNames;
+ }
+ /**
+ * Get the header values that are contained in this collection.
+ */
+ headerValues() {
+ const headerValues = [];
+ const headers = this.headersArray();
+ for (let i = 0; i < headers.length; ++i) {
+ headerValues.push(headers[i].value);
+ }
+ return headerValues;
+ }
+ /**
+ * Get the JSON object representation of this HTTP header collection.
+ */
+ toJson(options = {}) {
+ const result = {};
+ if (options.preserveCase) {
+ for (const headerKey in this._headersMap) {
+ const header = this._headersMap[headerKey];
+ result[header.name] = header.value;
+ }
+ }
+ else {
+ for (const headerKey in this._headersMap) {
+ const header = this._headersMap[headerKey];
+ result[getHeaderKey(header.name)] = header.value;
+ }
+ }
+ return result;
+ }
+ /**
+ * Get the string representation of this HTTP header collection.
+ */
+ toString() {
+ return JSON.stringify(this.toJson({ preserveCase: true }));
+ }
+ /**
+ * Create a deep clone/copy of this HttpHeaders collection.
+ */
+ clone() {
+ const resultPreservingCasing = {};
+ for (const headerKey in this._headersMap) {
+ const header = this._headersMap[headerKey];
+ resultPreservingCasing[header.name] = header.value;
+ }
+ return new HttpHeaders(resultPreservingCasing);
}
- }
-])
-
-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
}
-
+exports.HttpHeaders = HttpHeaders;
+//# sourceMappingURL=util.js.map
/***/ }),
-/***/ 1237:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 93878:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-
-const { maxUnsigned16Bit } = __nccwpck_require__(5913)
-
-/** @type {import('crypto')} */
-let crypto
-try {
- crypto = __nccwpck_require__(6982)
-} catch {
-
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.pollHttpOperation = exports.isOperationError = exports.getResourceLocation = exports.getOperationStatus = exports.getOperationLocation = exports.initHttpOperation = exports.getStatusFromInitialResponse = exports.getErrorFromResponse = exports.parseRetryAfter = exports.inferLroMode = void 0;
+const operation_js_1 = __nccwpck_require__(30736);
+const logger_js_1 = __nccwpck_require__(50480);
+function getOperationLocationPollingUrl(inputs) {
+ const { azureAsyncOperation, operationLocation } = inputs;
+ return operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation;
}
-
-class WebsocketFrameSend {
- /**
- * @param {Buffer|undefined} data
- */
- constructor (data) {
- this.frameData = data
- this.maskKey = crypto.randomBytes(4)
- }
-
- createFrame (opcode) {
- const bodyLength = this.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
+function getLocationHeader(rawResponse) {
+ return rawResponse.headers["location"];
+}
+function getOperationLocationHeader(rawResponse) {
+ return rawResponse.headers["operation-location"];
+}
+function getAzureAsyncOperationHeader(rawResponse) {
+ return rawResponse.headers["azure-asyncoperation"];
+}
+function findResourceLocation(inputs) {
+ var _a;
+ const { location, requestMethod, requestPath, resourceLocationConfig } = inputs;
+ switch (requestMethod) {
+ case "PUT": {
+ return requestPath;
+ }
+ case "DELETE": {
+ return undefined;
+ }
+ case "PATCH": {
+ return (_a = getDefault()) !== null && _a !== void 0 ? _a : requestPath;
+ }
+ default: {
+ return getDefault();
+ }
}
-
- 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] = this.maskKey[0]
- buffer[offset - 3] = this.maskKey[1]
- buffer[offset - 2] = this.maskKey[2]
- buffer[offset - 1] = this.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)
+ function getDefault() {
+ switch (resourceLocationConfig) {
+ case "azure-async-operation": {
+ return undefined;
+ }
+ case "original-uri": {
+ return requestPath;
+ }
+ case "location":
+ default: {
+ return location;
+ }
+ }
}
-
- buffer[1] |= 0x80 // MASK
-
- // mask body
- for (let i = 0; i < bodyLength; i++) {
- buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4]
+}
+function inferLroMode(inputs) {
+ const { rawResponse, requestMethod, requestPath, resourceLocationConfig } = inputs;
+ const operationLocation = getOperationLocationHeader(rawResponse);
+ const azureAsyncOperation = getAzureAsyncOperationHeader(rawResponse);
+ const pollingUrl = getOperationLocationPollingUrl({ operationLocation, azureAsyncOperation });
+ const location = getLocationHeader(rawResponse);
+ const normalizedRequestMethod = requestMethod === null || requestMethod === void 0 ? void 0 : requestMethod.toLocaleUpperCase();
+ if (pollingUrl !== undefined) {
+ return {
+ mode: "OperationLocation",
+ operationLocation: pollingUrl,
+ resourceLocation: findResourceLocation({
+ requestMethod: normalizedRequestMethod,
+ location,
+ requestPath,
+ resourceLocationConfig,
+ }),
+ };
+ }
+ else if (location !== undefined) {
+ return {
+ mode: "ResourceLocation",
+ operationLocation: location,
+ };
+ }
+ else if (normalizedRequestMethod === "PUT" && requestPath) {
+ return {
+ mode: "Body",
+ operationLocation: requestPath,
+ };
+ }
+ else {
+ return undefined;
}
-
- return buffer
- }
}
-
-module.exports = {
- WebsocketFrameSend
+exports.inferLroMode = inferLroMode;
+function transformStatus(inputs) {
+ const { status, statusCode } = inputs;
+ if (typeof status !== "string" && status !== undefined) {
+ throw new Error(`Polling was unsuccessful. Expected status to have a string value or no value but it has instead: ${status}. This doesn't necessarily indicate the operation has failed. Check your Azure subscription or resource status for more information.`);
+ }
+ switch (status === null || status === void 0 ? void 0 : status.toLocaleLowerCase()) {
+ case undefined:
+ return toOperationStatus(statusCode);
+ case "succeeded":
+ return "succeeded";
+ case "failed":
+ return "failed";
+ case "running":
+ case "accepted":
+ case "started":
+ case "canceling":
+ case "cancelling":
+ return "running";
+ case "canceled":
+ case "cancelled":
+ return "canceled";
+ default: {
+ logger_js_1.logger.verbose(`LRO: unrecognized operation status: ${status}`);
+ return status;
+ }
+ }
}
-
+function getStatus(rawResponse) {
+ var _a;
+ const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
+ return transformStatus({ status, statusCode: rawResponse.statusCode });
+}
+function getProvisioningState(rawResponse) {
+ var _a, _b;
+ const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
+ const status = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState;
+ return transformStatus({ status, statusCode: rawResponse.statusCode });
+}
+function toOperationStatus(statusCode) {
+ if (statusCode === 202) {
+ return "running";
+ }
+ else if (statusCode < 300) {
+ return "succeeded";
+ }
+ else {
+ return "failed";
+ }
+}
+function parseRetryAfter({ rawResponse }) {
+ const retryAfter = rawResponse.headers["retry-after"];
+ if (retryAfter !== undefined) {
+ // Retry-After header value is either in HTTP date format, or in seconds
+ const retryAfterInSeconds = parseInt(retryAfter);
+ return isNaN(retryAfterInSeconds)
+ ? calculatePollingIntervalFromDate(new Date(retryAfter))
+ : retryAfterInSeconds * 1000;
+ }
+ return undefined;
+}
+exports.parseRetryAfter = parseRetryAfter;
+function getErrorFromResponse(response) {
+ const error = accessBodyProperty(response, "error");
+ if (!error) {
+ logger_js_1.logger.warning(`The long-running operation failed but there is no error property in the response's body`);
+ return;
+ }
+ if (!error.code || !error.message) {
+ logger_js_1.logger.warning(`The long-running operation failed but the error property in the response's body doesn't contain code or message`);
+ return;
+ }
+ return error;
+}
+exports.getErrorFromResponse = getErrorFromResponse;
+function calculatePollingIntervalFromDate(retryAfterDate) {
+ const timeNow = Math.floor(new Date().getTime());
+ const retryAfterTime = retryAfterDate.getTime();
+ if (timeNow < retryAfterTime) {
+ return retryAfterTime - timeNow;
+ }
+ return undefined;
+}
+function getStatusFromInitialResponse(inputs) {
+ const { response, state, operationLocation } = inputs;
+ function helper() {
+ var _a;
+ const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
+ switch (mode) {
+ case undefined:
+ return toOperationStatus(response.rawResponse.statusCode);
+ case "Body":
+ return getOperationStatus(response, state);
+ default:
+ return "running";
+ }
+ }
+ const status = helper();
+ return status === "running" && operationLocation === undefined ? "succeeded" : status;
+}
+exports.getStatusFromInitialResponse = getStatusFromInitialResponse;
+/**
+ * Initiates the long-running operation.
+ */
+async function initHttpOperation(inputs) {
+ const { stateProxy, resourceLocationConfig, processResult, lro, setErrorAsResult } = inputs;
+ return (0, operation_js_1.initOperation)({
+ init: async () => {
+ const response = await lro.sendInitialRequest();
+ const config = inferLroMode({
+ rawResponse: response.rawResponse,
+ requestPath: lro.requestPath,
+ requestMethod: lro.requestMethod,
+ resourceLocationConfig,
+ });
+ return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}));
+ },
+ stateProxy,
+ processResult: processResult
+ ? ({ flatResponse }, state) => processResult(flatResponse, state)
+ : ({ flatResponse }) => flatResponse,
+ getOperationStatus: getStatusFromInitialResponse,
+ setErrorAsResult,
+ });
+}
+exports.initHttpOperation = initHttpOperation;
+function getOperationLocation({ rawResponse }, state) {
+ var _a;
+ const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
+ switch (mode) {
+ case "OperationLocation": {
+ return getOperationLocationPollingUrl({
+ operationLocation: getOperationLocationHeader(rawResponse),
+ azureAsyncOperation: getAzureAsyncOperationHeader(rawResponse),
+ });
+ }
+ case "ResourceLocation": {
+ return getLocationHeader(rawResponse);
+ }
+ case "Body":
+ default: {
+ return undefined;
+ }
+ }
+}
+exports.getOperationLocation = getOperationLocation;
+function getOperationStatus({ rawResponse }, state) {
+ var _a;
+ const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
+ switch (mode) {
+ case "OperationLocation": {
+ return getStatus(rawResponse);
+ }
+ case "ResourceLocation": {
+ return toOperationStatus(rawResponse.statusCode);
+ }
+ case "Body": {
+ return getProvisioningState(rawResponse);
+ }
+ default:
+ throw new Error(`Internal error: Unexpected operation mode: ${mode}`);
+ }
+}
+exports.getOperationStatus = getOperationStatus;
+function accessBodyProperty({ flatResponse, rawResponse }, prop) {
+ var _a, _b;
+ return (_a = flatResponse === null || flatResponse === void 0 ? void 0 : flatResponse[prop]) !== null && _a !== void 0 ? _a : (_b = rawResponse.body) === null || _b === void 0 ? void 0 : _b[prop];
+}
+function getResourceLocation(res, state) {
+ const loc = accessBodyProperty(res, "resourceLocation");
+ if (loc && typeof loc === "string") {
+ state.config.resourceLocation = loc;
+ }
+ return state.config.resourceLocation;
+}
+exports.getResourceLocation = getResourceLocation;
+function isOperationError(e) {
+ return e.name === "RestError";
+}
+exports.isOperationError = isOperationError;
+/** Polls the long-running operation. */
+async function pollHttpOperation(inputs) {
+ const { lro, stateProxy, options, processResult, updateState, setDelay, state, setErrorAsResult, } = inputs;
+ return (0, operation_js_1.pollOperation)({
+ state,
+ stateProxy,
+ setDelay,
+ processResult: processResult
+ ? ({ flatResponse }, inputState) => processResult(flatResponse, inputState)
+ : ({ flatResponse }) => flatResponse,
+ getError: getErrorFromResponse,
+ updateState,
+ getPollingInterval: parseRetryAfter,
+ getOperationLocation,
+ getOperationStatus,
+ isOperationError,
+ getResourceLocation,
+ options,
+ /**
+ * The expansion here is intentional because `lro` could be an object that
+ * references an inner this, so we need to preserve a reference to it.
+ */
+ poll: async (location, inputOptions) => lro.sendPollRequest(location, inputOptions),
+ setErrorAsResult,
+ });
+}
+exports.pollHttpOperation = pollHttpOperation;
+//# sourceMappingURL=operation.js.map
/***/ }),
-/***/ 3171:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 57421:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createHttpPoller = void 0;
+const operation_js_1 = __nccwpck_require__(93878);
+const poller_js_1 = __nccwpck_require__(18835);
+/**
+ * Creates a poller that can be used to poll a long-running operation.
+ * @param lro - Description of the long-running operation
+ * @param options - options to configure the poller
+ * @returns an initialized poller
+ */
+async function createHttpPoller(lro, options) {
+ const { resourceLocationConfig, intervalInMs, processResult, restoreFrom, updateState, withOperationLocation, resolveOnUnsuccessful = false, } = options || {};
+ return (0, poller_js_1.buildCreatePoller)({
+ getStatusFromInitialResponse: operation_js_1.getStatusFromInitialResponse,
+ getStatusFromPollResponse: operation_js_1.getOperationStatus,
+ isOperationError: operation_js_1.isOperationError,
+ getOperationLocation: operation_js_1.getOperationLocation,
+ getResourceLocation: operation_js_1.getResourceLocation,
+ getPollingInterval: operation_js_1.parseRetryAfter,
+ getError: operation_js_1.getErrorFromResponse,
+ resolveOnUnsuccessful,
+ })({
+ init: async () => {
+ const response = await lro.sendInitialRequest();
+ const config = (0, operation_js_1.inferLroMode)({
+ rawResponse: response.rawResponse,
+ requestPath: lro.requestPath,
+ requestMethod: lro.requestMethod,
+ resourceLocationConfig,
+ });
+ return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}));
+ },
+ poll: lro.sendPollRequest,
+ }, {
+ intervalInMs,
+ withOperationLocation,
+ restoreFrom,
+ updateState,
+ processResult: processResult
+ ? ({ flatResponse }, state) => processResult(flatResponse, state)
+ : ({ flatResponse }) => flatResponse,
+ });
+}
+exports.createHttpPoller = createHttpPoller;
+//# sourceMappingURL=poller.js.map
-const { Writable } = __nccwpck_require__(2203)
-const diagnosticsChannel = __nccwpck_require__(1637)
-const { parserStates, opcodes, states, emptyBuffer } = __nccwpck_require__(5913)
-const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(2933)
-const { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = __nccwpck_require__(3574)
-const { WebsocketFrameSend } = __nccwpck_require__(1237)
-
-// 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
-
-const channels = {}
-channels.ping = diagnosticsChannel.channel('undici:websocket:ping')
-channels.pong = diagnosticsChannel.channel('undici:websocket:pong')
-
-class ByteParser extends Writable {
- #buffers = []
- #byteOffset = 0
-
- #state = parserStates.INFO
-
- #info = {}
- #fragments = []
-
- constructor (ws) {
- super()
+/***/ }),
- this.ws = ws
- }
+/***/ 91754:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- /**
- * @param {Buffer} chunk
- * @param {() => void} callback
- */
- _write (chunk, _, callback) {
- this.#buffers.push(chunk)
- this.#byteOffset += chunk.length
+"use strict";
- this.run(callback)
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createHttpPoller = void 0;
+const tslib_1 = __nccwpck_require__(61860);
+var poller_js_1 = __nccwpck_require__(57421);
+Object.defineProperty(exports, "createHttpPoller", ({ enumerable: true, get: function () { return poller_js_1.createHttpPoller; } }));
+/**
+ * This can be uncommented to expose the protocol-agnostic poller
+ */
+// export {
+// BuildCreatePollerOptions,
+// Operation,
+// CreatePollerOptions,
+// OperationConfig,
+// RestorableOperationState,
+// } from "./poller/models";
+// export { buildCreatePoller } from "./poller/poller";
+/** legacy */
+tslib_1.__exportStar(__nccwpck_require__(55454), exports);
+tslib_1.__exportStar(__nccwpck_require__(36272), exports);
+tslib_1.__exportStar(__nccwpck_require__(82670), exports);
+//# sourceMappingURL=index.js.map
- /**
- * 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 (true) {
- 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)
+/***/ 55454:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- this.#info.fin = (buffer[0] & 0x80) !== 0
- this.#info.opcode = buffer[0] & 0x0F
+"use strict";
- // If we receive a fragmented message, we use the type of the first
- // frame to parse the full message as binary/text, when it's terminated
- this.#info.originalOpcode ??= this.#info.opcode
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.LroEngine = void 0;
+var lroEngine_js_1 = __nccwpck_require__(91607);
+Object.defineProperty(exports, "LroEngine", ({ enumerable: true, get: function () { return lroEngine_js_1.LroEngine; } }));
+//# sourceMappingURL=index.js.map
- this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION
+/***/ }),
- if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) {
- // Only text and binary frames can be fragmented
- failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.')
- return
- }
+/***/ 91607:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- const payloadLength = buffer[1] & 0x7F
+"use strict";
- 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
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.LroEngine = void 0;
+const operation_js_1 = __nccwpck_require__(54267);
+const constants_js_1 = __nccwpck_require__(55044);
+const poller_js_1 = __nccwpck_require__(36272);
+const operation_js_2 = __nccwpck_require__(30736);
+/**
+ * The LRO Engine, a class that performs polling.
+ */
+class LroEngine extends poller_js_1.Poller {
+ constructor(lro, options) {
+ const { intervalInMs = constants_js_1.POLL_INTERVAL_IN_MS, resumeFrom, resolveOnUnsuccessful = false, isDone, lroResourceLocationConfig, processResult, updateState, } = options || {};
+ const state = resumeFrom
+ ? (0, operation_js_2.deserializeState)(resumeFrom)
+ : {};
+ const operation = new operation_js_1.GenericPollOperation(state, lro, !resolveOnUnsuccessful, lroResourceLocationConfig, processResult, updateState, isDone);
+ super(operation);
+ this.resolveOnUnsuccessful = resolveOnUnsuccessful;
+ this.config = { intervalInMs: intervalInMs };
+ operation.setPollerConfig(this.config);
+ }
+ /**
+ * The method used by the poller to wait before attempting to update its operation.
+ */
+ delay() {
+ return new Promise((resolve) => setTimeout(() => resolve(), this.config.intervalInMs));
+ }
+}
+exports.LroEngine = LroEngine;
+//# sourceMappingURL=lroEngine.js.map
- if (this.#info.fragmented && payloadLength > 125) {
- // A fragmented frame can't be fragmented itself
- failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.')
- return
- } else if (
- (this.#info.opcode === opcodes.PING ||
- this.#info.opcode === opcodes.PONG ||
- this.#info.opcode === opcodes.CLOSE) &&
- payloadLength > 125
- ) {
- // Control frames can have a payload length of 125 bytes MAX
- failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.')
- return
- } else if (this.#info.opcode === opcodes.CLOSE) {
- if (payloadLength === 1) {
- failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.')
- return
- }
+/***/ }),
- const body = this.consume(payloadLength)
+/***/ 54267:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- this.#info.closeInfo = this.parseCloseBody(false, body)
+"use strict";
- if (!this.ws[kSentClose]) {
- // 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.)
- const body = Buffer.allocUnsafe(2)
- body.writeUInt16BE(this.#info.closeInfo.code, 0)
- const closeFrame = new WebsocketFrameSend(body)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.GenericPollOperation = void 0;
+const operation_js_1 = __nccwpck_require__(93878);
+const logger_js_1 = __nccwpck_require__(50480);
+const createStateProxy = () => ({
+ initState: (config) => ({ config, isStarted: true }),
+ setCanceled: (state) => (state.isCancelled = true),
+ setError: (state, error) => (state.error = error),
+ setResult: (state, result) => (state.result = result),
+ setRunning: (state) => (state.isStarted = true),
+ setSucceeded: (state) => (state.isCompleted = true),
+ setFailed: () => {
+ /** empty body */
+ },
+ getError: (state) => state.error,
+ getResult: (state) => state.result,
+ isCanceled: (state) => !!state.isCancelled,
+ isFailed: (state) => !!state.error,
+ isRunning: (state) => !!state.isStarted,
+ isSucceeded: (state) => Boolean(state.isCompleted && !state.isCancelled && !state.error),
+});
+class GenericPollOperation {
+ constructor(state, lro, setErrorAsResult, lroResourceLocationConfig, processResult, updateState, isDone) {
+ this.state = state;
+ this.lro = lro;
+ this.setErrorAsResult = setErrorAsResult;
+ this.lroResourceLocationConfig = lroResourceLocationConfig;
+ this.processResult = processResult;
+ this.updateState = updateState;
+ this.isDone = isDone;
+ }
+ setPollerConfig(pollerConfig) {
+ this.pollerConfig = pollerConfig;
+ }
+ async update(options) {
+ var _a;
+ const stateProxy = createStateProxy();
+ if (!this.state.isStarted) {
+ this.state = Object.assign(Object.assign({}, this.state), (await (0, operation_js_1.initHttpOperation)({
+ lro: this.lro,
+ stateProxy,
+ resourceLocationConfig: this.lroResourceLocationConfig,
+ processResult: this.processResult,
+ setErrorAsResult: this.setErrorAsResult,
+ })));
+ }
+ const updateState = this.updateState;
+ const isDone = this.isDone;
+ if (!this.state.isCompleted && this.state.error === undefined) {
+ await (0, operation_js_1.pollHttpOperation)({
+ lro: this.lro,
+ state: this.state,
+ stateProxy,
+ processResult: this.processResult,
+ updateState: updateState
+ ? (state, { rawResponse }) => updateState(state, rawResponse)
+ : undefined,
+ isDone: isDone
+ ? ({ flatResponse }, state) => isDone(flatResponse, state)
+ : undefined,
+ options,
+ setDelay: (intervalInMs) => {
+ this.pollerConfig.intervalInMs = intervalInMs;
+ },
+ setErrorAsResult: this.setErrorAsResult,
+ });
+ }
+ (_a = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _a === void 0 ? void 0 : _a.call(options, this.state);
+ return this;
+ }
+ async cancel() {
+ logger_js_1.logger.error("`cancelOperation` is deprecated because it wasn't implemented");
+ return this;
+ }
+ /**
+ * Serializes the Poller operation.
+ */
+ toString() {
+ return JSON.stringify({
+ state: this.state,
+ });
+ }
+}
+exports.GenericPollOperation = GenericPollOperation;
+//# sourceMappingURL=operation.js.map
- this.ws[kResponse].socket.write(
- closeFrame.createFrame(opcodes.CLOSE),
- (err) => {
- if (!err) {
- this.ws[kSentClose] = true
- }
- }
- )
- }
+/***/ }),
- // 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.ws[kReadyState] = states.CLOSING
- this.ws[kReceivedClose] = true
+/***/ 82670:
+/***/ ((__unused_webpack_module, exports) => {
- this.end()
+"use strict";
- return
- } else if (this.#info.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"
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+//# sourceMappingURL=pollOperation.js.map
- const body = this.consume(payloadLength)
+/***/ }),
- if (!this.ws[kReceivedClose]) {
- const frame = new WebsocketFrameSend(body)
+/***/ 36272:
+/***/ ((__unused_webpack_module, exports) => {
- this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG))
+"use strict";
- if (channels.ping.hasSubscribers) {
- channels.ping.publish({
- payload: body
- })
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Poller = exports.PollerCancelledError = exports.PollerStoppedError = void 0;
+/**
+ * When a poller is manually stopped through the `stopPolling` method,
+ * the poller will be rejected with an instance of the PollerStoppedError.
+ */
+class PollerStoppedError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "PollerStoppedError";
+ Object.setPrototypeOf(this, PollerStoppedError.prototype);
+ }
+}
+exports.PollerStoppedError = PollerStoppedError;
+/**
+ * When the operation is cancelled, the poller will be rejected with an instance
+ * of the PollerCancelledError.
+ */
+class PollerCancelledError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "PollerCancelledError";
+ Object.setPrototypeOf(this, PollerCancelledError.prototype);
+ }
+}
+exports.PollerCancelledError = PollerCancelledError;
+/**
+ * A class that represents the definition of a program that polls through consecutive requests
+ * until it reaches a state of completion.
+ *
+ * A poller can be executed manually, by polling request by request by calling to the `poll()` method repeatedly, until its operation is completed.
+ * It also provides a way to wait until the operation completes, by calling `pollUntilDone()` and waiting until the operation finishes.
+ * Pollers can also request the cancellation of the ongoing process to whom is providing the underlying long running operation.
+ *
+ * ```ts
+ * const poller = new MyPoller();
+ *
+ * // Polling just once:
+ * await poller.poll();
+ *
+ * // We can try to cancel the request here, by calling:
+ * //
+ * // await poller.cancelOperation();
+ * //
+ *
+ * // Getting the final result:
+ * const result = await poller.pollUntilDone();
+ * ```
+ *
+ * The Poller is defined by two types, a type representing the state of the poller, which
+ * must include a basic set of properties from `PollOperationState`,
+ * and a return type defined by `TResult`, which can be anything.
+ *
+ * The Poller class implements the `PollerLike` interface, which allows poller implementations to avoid having
+ * to export the Poller's class directly, and instead only export the already instantiated poller with the PollerLike type.
+ *
+ * ```ts
+ * class Client {
+ * public async makePoller: PollerLike {
+ * const poller = new MyPoller({});
+ * // It might be preferred to return the poller after the first request is made,
+ * // so that some information can be obtained right away.
+ * await poller.poll();
+ * return poller;
+ * }
+ * }
+ *
+ * const poller: PollerLike = myClient.makePoller();
+ * ```
+ *
+ * A poller can be created through its constructor, then it can be polled until it's completed.
+ * At any point in time, the state of the poller can be obtained without delay through the getOperationState method.
+ * At any point in time, the intermediate forms of the result type can be requested without delay.
+ * Once the underlying operation is marked as completed, the poller will stop and the final value will be returned.
+ *
+ * ```ts
+ * const poller = myClient.makePoller();
+ * const state: MyOperationState = poller.getOperationState();
+ *
+ * // The intermediate result can be obtained at any time.
+ * const result: MyResult | undefined = poller.getResult();
+ *
+ * // The final result can only be obtained after the poller finishes.
+ * const result: MyResult = await poller.pollUntilDone();
+ * ```
+ *
+ */
+// eslint-disable-next-line no-use-before-define
+class Poller {
+ /**
+ * A poller needs to be initialized by passing in at least the basic properties of the `PollOperation`.
+ *
+ * When writing an implementation of a Poller, this implementation needs to deal with the initialization
+ * of any custom state beyond the basic definition of the poller. The basic poller assumes that the poller's
+ * operation has already been defined, at least its basic properties. The code below shows how to approach
+ * the definition of the constructor of a new custom poller.
+ *
+ * ```ts
+ * export class MyPoller extends Poller {
+ * constructor({
+ * // Anything you might need outside of the basics
+ * }) {
+ * let state: MyOperationState = {
+ * privateProperty: private,
+ * publicProperty: public,
+ * };
+ *
+ * const operation = {
+ * state,
+ * update,
+ * cancel,
+ * toString
+ * }
+ *
+ * // Sending the operation to the parent's constructor.
+ * super(operation);
+ *
+ * // You can assign more local properties here.
+ * }
+ * }
+ * ```
+ *
+ * Inside of this constructor, a new promise is created. This will be used to
+ * tell the user when the poller finishes (see `pollUntilDone()`). The promise's
+ * resolve and reject methods are also used internally to control when to resolve
+ * or reject anyone waiting for the poller to finish.
+ *
+ * The constructor of a custom implementation of a poller is where any serialized version of
+ * a previous poller's operation should be deserialized into the operation sent to the
+ * base constructor. For example:
+ *
+ * ```ts
+ * export class MyPoller extends Poller {
+ * constructor(
+ * baseOperation: string | undefined
+ * ) {
+ * let state: MyOperationState = {};
+ * if (baseOperation) {
+ * state = {
+ * ...JSON.parse(baseOperation).state,
+ * ...state
+ * };
+ * }
+ * const operation = {
+ * state,
+ * // ...
+ * }
+ * super(operation);
+ * }
+ * }
+ * ```
+ *
+ * @param operation - Must contain the basic properties of `PollOperation`.
+ */
+ constructor(operation) {
+ /** controls whether to throw an error if the operation failed or was canceled. */
+ this.resolveOnUnsuccessful = false;
+ this.stopped = true;
+ this.pollProgressCallbacks = [];
+ this.operation = operation;
+ this.promise = new Promise((resolve, reject) => {
+ this.resolve = resolve;
+ this.reject = reject;
+ });
+ // This prevents the UnhandledPromiseRejectionWarning in node.js from being thrown.
+ // The above warning would get thrown if `poller.poll` is called, it returns an error,
+ // and pullUntilDone did not have a .catch or await try/catch on it's return value.
+ this.promise.catch(() => {
+ /* intentionally blank */
+ });
+ }
+ /**
+ * Starts a loop that will break only if the poller is done
+ * or if the poller is stopped.
+ */
+ async startPolling(pollOptions = {}) {
+ if (this.stopped) {
+ this.stopped = false;
+ }
+ while (!this.isStopped() && !this.isDone()) {
+ await this.poll(pollOptions);
+ await this.delay();
+ }
+ }
+ /**
+ * pollOnce does one polling, by calling to the update method of the underlying
+ * poll operation to make any relevant change effective.
+ *
+ * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
+ *
+ * @param options - Optional properties passed to the operation's update method.
+ */
+ async pollOnce(options = {}) {
+ if (!this.isDone()) {
+ this.operation = await this.operation.update({
+ abortSignal: options.abortSignal,
+ fireProgress: this.fireProgress.bind(this),
+ });
+ }
+ this.processUpdatedState();
+ }
+ /**
+ * fireProgress calls the functions passed in via onProgress the method of the poller.
+ *
+ * It loops over all of the callbacks received from onProgress, and executes them, sending them
+ * the current operation state.
+ *
+ * @param state - The current operation state.
+ */
+ fireProgress(state) {
+ for (const callback of this.pollProgressCallbacks) {
+ callback(state);
+ }
+ }
+ /**
+ * Invokes the underlying operation's cancel method.
+ */
+ async cancelOnce(options = {}) {
+ this.operation = await this.operation.cancel(options);
+ }
+ /**
+ * Returns a promise that will resolve once a single polling request finishes.
+ * It does this by calling the update method of the Poller's operation.
+ *
+ * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
+ *
+ * @param options - Optional properties passed to the operation's update method.
+ */
+ poll(options = {}) {
+ if (!this.pollOncePromise) {
+ this.pollOncePromise = this.pollOnce(options);
+ const clearPollOncePromise = () => {
+ this.pollOncePromise = undefined;
+ };
+ this.pollOncePromise.then(clearPollOncePromise, clearPollOncePromise).catch(this.reject);
+ }
+ return this.pollOncePromise;
+ }
+ processUpdatedState() {
+ if (this.operation.state.error) {
+ this.stopped = true;
+ if (!this.resolveOnUnsuccessful) {
+ this.reject(this.operation.state.error);
+ throw this.operation.state.error;
+ }
+ }
+ if (this.operation.state.isCancelled) {
+ this.stopped = true;
+ if (!this.resolveOnUnsuccessful) {
+ const error = new PollerCancelledError("Operation was canceled");
+ this.reject(error);
+ throw error;
+ }
+ }
+ if (this.isDone() && this.resolve) {
+ // If the poller has finished polling, this means we now have a result.
+ // However, it can be the case that TResult is instantiated to void, so
+ // we are not expecting a result anyway. To assert that we might not
+ // have a result eventually after finishing polling, we cast the result
+ // to TResult.
+ this.resolve(this.getResult());
+ }
+ }
+ /**
+ * Returns a promise that will resolve once the underlying operation is completed.
+ */
+ async pollUntilDone(pollOptions = {}) {
+ if (this.stopped) {
+ this.startPolling(pollOptions).catch(this.reject);
+ }
+ // This is needed because the state could have been updated by
+ // `cancelOperation`, e.g. the operation is canceled or an error occurred.
+ this.processUpdatedState();
+ return this.promise;
+ }
+ /**
+ * Invokes the provided callback after each polling is completed,
+ * sending the current state of the poller's operation.
+ *
+ * It returns a method that can be used to stop receiving updates on the given callback function.
+ */
+ onProgress(callback) {
+ this.pollProgressCallbacks.push(callback);
+ return () => {
+ this.pollProgressCallbacks = this.pollProgressCallbacks.filter((c) => c !== callback);
+ };
+ }
+ /**
+ * Returns true if the poller has finished polling.
+ */
+ isDone() {
+ const state = this.operation.state;
+ return Boolean(state.isCompleted || state.isCancelled || state.error);
+ }
+ /**
+ * Stops the poller from continuing to poll.
+ */
+ stopPolling() {
+ if (!this.stopped) {
+ this.stopped = true;
+ if (this.reject) {
+ this.reject(new PollerStoppedError("This poller is already stopped"));
}
- }
-
- this.#state = parserStates.INFO
-
- if (this.#byteOffset > 0) {
- continue
- } else {
- callback()
- return
- }
- } else if (this.#info.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.
-
- const body = this.consume(payloadLength)
-
- if (channels.pong.hasSubscribers) {
- channels.pong.publish({
- payload: body
- })
- }
-
- if (this.#byteOffset > 0) {
- continue
- } else {
- callback()
- return
- }
}
- } else if (this.#state === parserStates.PAYLOADLENGTH_16) {
- if (this.#byteOffset < 2) {
- return callback()
+ }
+ /**
+ * Returns true if the poller is stopped.
+ */
+ isStopped() {
+ return this.stopped;
+ }
+ /**
+ * Attempts to cancel the underlying operation.
+ *
+ * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
+ *
+ * If it's called again before it finishes, it will throw an error.
+ *
+ * @param options - Optional properties passed to the operation's update method.
+ */
+ cancelOperation(options = {}) {
+ if (!this.cancelPromise) {
+ this.cancelPromise = this.cancelOnce(options);
}
-
- 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()
+ else if (options.abortSignal) {
+ throw new Error("A cancel request is currently pending");
}
+ return this.cancelPromise;
+ }
+ /**
+ * Returns the state of the operation.
+ *
+ * Even though TState will be the same type inside any of the methods of any extension of the Poller class,
+ * implementations of the pollers can customize what's shared with the public by writing their own
+ * version of the `getOperationState` method, and by defining two types, one representing the internal state of the poller
+ * and a public type representing a safe to share subset of the properties of the internal state.
+ * Their definition of getOperationState can then return their public type.
+ *
+ * Example:
+ *
+ * ```ts
+ * // Let's say we have our poller's operation state defined as:
+ * interface MyOperationState extends PollOperationState {
+ * privateProperty?: string;
+ * publicProperty?: string;
+ * }
+ *
+ * // To allow us to have a true separation of public and private state, we have to define another interface:
+ * interface PublicState extends PollOperationState {
+ * publicProperty?: string;
+ * }
+ *
+ * // Then, we define our Poller as follows:
+ * export class MyPoller extends Poller {
+ * // ... More content is needed here ...
+ *
+ * public getOperationState(): PublicState {
+ * const state: PublicState = this.operation.state;
+ * return {
+ * // Properties from PollOperationState
+ * isStarted: state.isStarted,
+ * isCompleted: state.isCompleted,
+ * isCancelled: state.isCancelled,
+ * error: state.error,
+ * result: state.result,
+ *
+ * // The only other property needed by PublicState.
+ * publicProperty: state.publicProperty
+ * }
+ * }
+ * }
+ * ```
+ *
+ * You can see this in the tests of this repository, go to the file:
+ * `../test/utils/testPoller.ts`
+ * and look for the getOperationState implementation.
+ */
+ getOperationState() {
+ return this.operation.state;
+ }
+ /**
+ * Returns the result value of the operation,
+ * regardless of the state of the poller.
+ * It can return undefined or an incomplete form of the final TResult value
+ * depending on the implementation.
+ */
+ getResult() {
+ const state = this.operation.state;
+ return state.result;
+ }
+ /**
+ * Returns a serialized version of the poller's operation
+ * by invoking the operation's toString method.
+ */
+ toString() {
+ return this.operation.toString();
+ }
+}
+exports.Poller = Poller;
+//# sourceMappingURL=poller.js.map
- const buffer = this.consume(8)
- const upper = buffer.readUInt32BE(0)
+/***/ }),
- // 2^31 is the maxinimum 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.ws, 'Received payload length > 2^31 bytes.')
- return
- }
+/***/ 50480:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- const lower = buffer.readUInt32BE(4)
+"use strict";
- this.#info.payloadLength = (upper << 8) + lower
- this.#state = parserStates.READ_DATA
- } else if (this.#state === parserStates.READ_DATA) {
- if (this.#byteOffset < this.#info.payloadLength) {
- // If there is still more data in this chunk that needs to be read
- return callback()
- } else if (this.#byteOffset >= this.#info.payloadLength) {
- // If the server sent multiple frames in a single chunk
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.logger = void 0;
+const logger_1 = __nccwpck_require__(26515);
+/**
+ * The `@azure/logger` configuration for this package.
+ * @internal
+ */
+exports.logger = (0, logger_1.createClientLogger)("core-lro");
+//# sourceMappingURL=logger.js.map
- const body = this.consume(this.#info.payloadLength)
+/***/ }),
- this.#fragments.push(body)
+/***/ 55044:
+/***/ ((__unused_webpack_module, exports) => {
- // If the frame is unfragmented, or a fragmented frame was terminated,
- // a message was received
- if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) {
- const fullMessage = Buffer.concat(this.#fragments)
+"use strict";
- websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.terminalStates = exports.POLL_INTERVAL_IN_MS = void 0;
+/**
+ * The default time interval to wait before sending the next polling request.
+ */
+exports.POLL_INTERVAL_IN_MS = 2000;
+/**
+ * The closed set of terminal states.
+ */
+exports.terminalStates = ["succeeded", "canceled", "failed"];
+//# sourceMappingURL=constants.js.map
- this.#info = {}
- this.#fragments.length = 0
- }
+/***/ }),
- this.#state = parserStates.INFO
- }
- }
+/***/ 30736:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (this.#byteOffset > 0) {
- continue
- } else {
- callback()
- break
- }
- }
- }
+"use strict";
- /**
- * Take n bytes from the buffered Buffers
- * @param {number} n
- * @returns {Buffer|null}
- */
- consume (n) {
- if (n > this.#byteOffset) {
- return null
- } else if (n === 0) {
- return emptyBuffer
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.pollOperation = exports.initOperation = exports.deserializeState = void 0;
+const logger_js_1 = __nccwpck_require__(50480);
+const constants_js_1 = __nccwpck_require__(55044);
+/**
+ * Deserializes the state
+ */
+function deserializeState(serializedState) {
+ try {
+ return JSON.parse(serializedState).state;
}
-
- if (this.#buffers[0].length === n) {
- this.#byteOffset -= this.#buffers[0].length
- return this.#buffers.shift()
+ catch (e) {
+ throw new Error(`Unable to deserialize input state: ${serializedState}`);
}
-
- const buffer = Buffer.allocUnsafe(n)
- let offset = 0
-
- while (offset !== n) {
- const next = this.#buffers[0]
- const { length } = next
-
- 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 += next.length
- }
+}
+exports.deserializeState = deserializeState;
+function setStateError(inputs) {
+ const { state, stateProxy, isOperationError } = inputs;
+ return (error) => {
+ if (isOperationError(error)) {
+ stateProxy.setError(state, error);
+ stateProxy.setFailed(state);
+ }
+ throw error;
+ };
+}
+function appendReadableErrorMessage(currentMessage, innerMessage) {
+ let message = currentMessage;
+ if (message.slice(-1) !== ".") {
+ message = message + ".";
}
-
- this.#byteOffset -= n
-
- return buffer
- }
-
- parseCloseBody (onlyCode, data) {
- // 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)
+ return message + " " + innerMessage;
+}
+function simplifyError(err) {
+ let message = err.message;
+ let code = err.code;
+ let curErr = err;
+ while (curErr.innererror) {
+ curErr = curErr.innererror;
+ code = curErr.code;
+ message = appendReadableErrorMessage(message, curErr.message);
}
-
- if (onlyCode) {
- if (!isValidStatusCode(code)) {
- return null
- }
-
- return { code }
+ return {
+ code,
+ message,
+ };
+}
+function processOperationStatus(result) {
+ const { state, stateProxy, status, isDone, processResult, getError, response, setErrorAsResult } = result;
+ switch (status) {
+ case "succeeded": {
+ stateProxy.setSucceeded(state);
+ break;
+ }
+ case "failed": {
+ const err = getError === null || getError === void 0 ? void 0 : getError(response);
+ let postfix = "";
+ if (err) {
+ const { code, message } = simplifyError(err);
+ postfix = `. ${code}. ${message}`;
+ }
+ const errStr = `The long-running operation has failed${postfix}`;
+ stateProxy.setError(state, new Error(errStr));
+ stateProxy.setFailed(state);
+ logger_js_1.logger.warning(errStr);
+ break;
+ }
+ case "canceled": {
+ stateProxy.setCanceled(state);
+ break;
+ }
}
-
- // 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)
+ if ((isDone === null || isDone === void 0 ? void 0 : isDone(response, state)) ||
+ (isDone === undefined &&
+ ["succeeded", "canceled"].concat(setErrorAsResult ? [] : ["failed"]).includes(status))) {
+ stateProxy.setResult(state, buildResult({
+ response,
+ state,
+ processResult,
+ }));
}
-
- if (code !== undefined && !isValidStatusCode(code)) {
- return null
+}
+function buildResult(inputs) {
+ const { processResult, response, state } = inputs;
+ return processResult ? processResult(response, state) : response;
+}
+/**
+ * Initiates the long-running operation.
+ */
+async function initOperation(inputs) {
+ const { init, stateProxy, processResult, getOperationStatus, withOperationLocation, setErrorAsResult, } = inputs;
+ const { operationLocation, resourceLocation, metadata, response } = await init();
+ if (operationLocation)
+ withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false);
+ const config = {
+ metadata,
+ operationLocation,
+ resourceLocation,
+ };
+ logger_js_1.logger.verbose(`LRO: Operation description:`, config);
+ const state = stateProxy.initState(config);
+ const status = getOperationStatus({ response, state, operationLocation });
+ processOperationStatus({ state, status, stateProxy, response, setErrorAsResult, processResult });
+ return state;
+}
+exports.initOperation = initOperation;
+async function pollOperationHelper(inputs) {
+ const { poll, state, stateProxy, operationLocation, getOperationStatus, getResourceLocation, isOperationError, options, } = inputs;
+ const response = await poll(operationLocation, options).catch(setStateError({
+ state,
+ stateProxy,
+ isOperationError,
+ }));
+ const status = getOperationStatus(response, state);
+ logger_js_1.logger.verbose(`LRO: Status:\n\tPolling from: ${state.config.operationLocation}\n\tOperation status: ${status}\n\tPolling status: ${constants_js_1.terminalStates.includes(status) ? "Stopped" : "Running"}`);
+ if (status === "succeeded") {
+ const resourceLocation = getResourceLocation(response, state);
+ if (resourceLocation !== undefined) {
+ return {
+ response: await poll(resourceLocation).catch(setStateError({ state, stateProxy, isOperationError })),
+ status,
+ };
+ }
}
-
- try {
- // TODO: optimize this
- reason = new TextDecoder('utf-8', { fatal: true }).decode(reason)
- } catch {
- return null
+ return { response, status };
+}
+/** Polls the long-running operation. */
+async function pollOperation(inputs) {
+ const { poll, state, stateProxy, options, getOperationStatus, getResourceLocation, getOperationLocation, isOperationError, withOperationLocation, getPollingInterval, processResult, getError, updateState, setDelay, isDone, setErrorAsResult, } = inputs;
+ const { operationLocation } = state.config;
+ if (operationLocation !== undefined) {
+ const { response, status } = await pollOperationHelper({
+ poll,
+ getOperationStatus,
+ state,
+ stateProxy,
+ operationLocation,
+ getResourceLocation,
+ isOperationError,
+ options,
+ });
+ processOperationStatus({
+ status,
+ response,
+ state,
+ stateProxy,
+ isDone,
+ processResult,
+ getError,
+ setErrorAsResult,
+ });
+ if (!constants_js_1.terminalStates.includes(status)) {
+ const intervalInMs = getPollingInterval === null || getPollingInterval === void 0 ? void 0 : getPollingInterval(response);
+ if (intervalInMs)
+ setDelay(intervalInMs);
+ const location = getOperationLocation === null || getOperationLocation === void 0 ? void 0 : getOperationLocation(response, state);
+ if (location !== undefined) {
+ const isUpdated = operationLocation !== location;
+ state.config.operationLocation = location;
+ withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(location, isUpdated);
+ }
+ else
+ withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false);
+ }
+ updateState === null || updateState === void 0 ? void 0 : updateState(state, response);
}
+}
+exports.pollOperation = pollOperation;
+//# sourceMappingURL=operation.js.map
- return { code, reason }
- }
+/***/ }),
- get closingInfo () {
- return this.#info.closeInfo
- }
-}
+/***/ 18835:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-module.exports = {
- ByteParser
+"use strict";
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.buildCreatePoller = void 0;
+const operation_js_1 = __nccwpck_require__(30736);
+const constants_js_1 = __nccwpck_require__(55044);
+const core_util_1 = __nccwpck_require__(87779);
+const createStateProxy = () => ({
+ /**
+ * The state at this point is created to be of type OperationState.
+ * It will be updated later to be of type TState when the
+ * customer-provided callback, `updateState`, is called during polling.
+ */
+ initState: (config) => ({ status: "running", config }),
+ setCanceled: (state) => (state.status = "canceled"),
+ setError: (state, error) => (state.error = error),
+ setResult: (state, result) => (state.result = result),
+ setRunning: (state) => (state.status = "running"),
+ setSucceeded: (state) => (state.status = "succeeded"),
+ setFailed: (state) => (state.status = "failed"),
+ getError: (state) => state.error,
+ getResult: (state) => state.result,
+ isCanceled: (state) => state.status === "canceled",
+ isFailed: (state) => state.status === "failed",
+ isRunning: (state) => state.status === "running",
+ isSucceeded: (state) => state.status === "succeeded",
+});
+/**
+ * Returns a poller factory.
+ */
+function buildCreatePoller(inputs) {
+ const { getOperationLocation, getStatusFromInitialResponse, getStatusFromPollResponse, isOperationError, getResourceLocation, getPollingInterval, getError, resolveOnUnsuccessful, } = inputs;
+ return async ({ init, poll }, options) => {
+ const { processResult, updateState, withOperationLocation: withOperationLocationCallback, intervalInMs = constants_js_1.POLL_INTERVAL_IN_MS, restoreFrom, } = options || {};
+ const stateProxy = createStateProxy();
+ const withOperationLocation = withOperationLocationCallback
+ ? (() => {
+ let called = false;
+ return (operationLocation, isUpdated) => {
+ if (isUpdated)
+ withOperationLocationCallback(operationLocation);
+ else if (!called)
+ withOperationLocationCallback(operationLocation);
+ called = true;
+ };
+ })()
+ : undefined;
+ const state = restoreFrom
+ ? (0, operation_js_1.deserializeState)(restoreFrom)
+ : await (0, operation_js_1.initOperation)({
+ init,
+ stateProxy,
+ processResult,
+ getOperationStatus: getStatusFromInitialResponse,
+ withOperationLocation,
+ setErrorAsResult: !resolveOnUnsuccessful,
+ });
+ let resultPromise;
+ const abortController = new AbortController();
+ const handlers = new Map();
+ const handleProgressEvents = async () => handlers.forEach((h) => h(state));
+ const cancelErrMsg = "Operation was canceled";
+ let currentPollIntervalInMs = intervalInMs;
+ const poller = {
+ getOperationState: () => state,
+ getResult: () => state.result,
+ isDone: () => ["succeeded", "failed", "canceled"].includes(state.status),
+ isStopped: () => resultPromise === undefined,
+ stopPolling: () => {
+ abortController.abort();
+ },
+ toString: () => JSON.stringify({
+ state,
+ }),
+ onProgress: (callback) => {
+ const s = Symbol();
+ handlers.set(s, callback);
+ return () => handlers.delete(s);
+ },
+ pollUntilDone: (pollOptions) => (resultPromise !== null && resultPromise !== void 0 ? resultPromise : (resultPromise = (async () => {
+ const { abortSignal: inputAbortSignal } = pollOptions || {};
+ // In the future we can use AbortSignal.any() instead
+ function abortListener() {
+ abortController.abort();
+ }
+ const abortSignal = abortController.signal;
+ if (inputAbortSignal === null || inputAbortSignal === void 0 ? void 0 : inputAbortSignal.aborted) {
+ abortController.abort();
+ }
+ else if (!abortSignal.aborted) {
+ inputAbortSignal === null || inputAbortSignal === void 0 ? void 0 : inputAbortSignal.addEventListener("abort", abortListener, { once: true });
+ }
+ try {
+ if (!poller.isDone()) {
+ await poller.poll({ abortSignal });
+ while (!poller.isDone()) {
+ await (0, core_util_1.delay)(currentPollIntervalInMs, { abortSignal });
+ await poller.poll({ abortSignal });
+ }
+ }
+ }
+ finally {
+ inputAbortSignal === null || inputAbortSignal === void 0 ? void 0 : inputAbortSignal.removeEventListener("abort", abortListener);
+ }
+ if (resolveOnUnsuccessful) {
+ return poller.getResult();
+ }
+ else {
+ switch (state.status) {
+ case "succeeded":
+ return poller.getResult();
+ case "canceled":
+ throw new Error(cancelErrMsg);
+ case "failed":
+ throw state.error;
+ case "notStarted":
+ case "running":
+ throw new Error(`Polling completed without succeeding or failing`);
+ }
+ }
+ })().finally(() => {
+ resultPromise = undefined;
+ }))),
+ async poll(pollOptions) {
+ if (resolveOnUnsuccessful) {
+ if (poller.isDone())
+ return;
+ }
+ else {
+ switch (state.status) {
+ case "succeeded":
+ return;
+ case "canceled":
+ throw new Error(cancelErrMsg);
+ case "failed":
+ throw state.error;
+ }
+ }
+ await (0, operation_js_1.pollOperation)({
+ poll,
+ state,
+ stateProxy,
+ getOperationLocation,
+ isOperationError,
+ withOperationLocation,
+ getPollingInterval,
+ getOperationStatus: getStatusFromPollResponse,
+ getResourceLocation,
+ processResult,
+ getError,
+ updateState,
+ options: pollOptions,
+ setDelay: (pollIntervalInMs) => {
+ currentPollIntervalInMs = pollIntervalInMs;
+ },
+ setErrorAsResult: !resolveOnUnsuccessful,
+ });
+ await handleProgressEvents();
+ if (!resolveOnUnsuccessful) {
+ switch (state.status) {
+ case "canceled":
+ throw new Error(cancelErrMsg);
+ case "failed":
+ throw state.error;
+ }
+ }
+ },
+ };
+ return poller;
+ };
}
-
+exports.buildCreatePoller = buildCreatePoller;
+//# sourceMappingURL=poller.js.map
/***/ }),
-/***/ 2933:
-/***/ ((module) => {
+/***/ 66427:
+/***/ ((__unused_webpack_module, exports) => {
"use strict";
-
-module.exports = {
- kWebSocketURL: Symbol('url'),
- kReadyState: Symbol('ready state'),
- kController: Symbol('controller'),
- kResponse: Symbol('response'),
- kBinaryType: Symbol('binary type'),
- kSentClose: Symbol('sent close'),
- kReceivedClose: Symbol('received close'),
- kByteParser: Symbol('byte parser')
-}
-
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.DEFAULT_RETRY_POLICY_COUNT = exports.SDK_VERSION = void 0;
+exports.SDK_VERSION = "1.18.1";
+exports.DEFAULT_RETRY_POLICY_COUNT = 3;
+//# sourceMappingURL=constants.js.map
/***/ }),
-/***/ 3574:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 90862:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-
-const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(2933)
-const { states, opcodes } = __nccwpck_require__(5913)
-const { MessageEvent, ErrorEvent } = __nccwpck_require__(6255)
-
-/* globals Blob */
-
-/**
- * @param {import('./websocket').WebSocket} ws
- */
-function isEstablished (ws) {
- // 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 ws[kReadyState] === states.OPEN
-}
-
-/**
- * @param {import('./websocket').WebSocket} ws
- */
-function isClosing (ws) {
- // 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 ws[kReadyState] === states.CLOSING
-}
-
-/**
- * @param {import('./websocket').WebSocket} ws
- */
-function isClosed (ws) {
- return ws[kReadyState] === states.CLOSED
-}
-
-/**
- * @see https://dom.spec.whatwg.org/#concept-event-fire
- * @param {string} e
- * @param {EventTarget} target
- * @param {EventInit | undefined} eventInitDict
- */
-function fireEvent (e, target, eventConstructor = Event, 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 = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap
-
- // 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)
-}
-
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createPipelineFromOptions = createPipelineFromOptions;
+const logPolicy_js_1 = __nccwpck_require__(53253);
+const pipeline_js_1 = __nccwpck_require__(29590);
+const redirectPolicy_js_1 = __nccwpck_require__(64087);
+const userAgentPolicy_js_1 = __nccwpck_require__(32799);
+const multipartPolicy_js_1 = __nccwpck_require__(45807);
+const decompressResponsePolicy_js_1 = __nccwpck_require__(39295);
+const defaultRetryPolicy_js_1 = __nccwpck_require__(48170);
+const formDataPolicy_js_1 = __nccwpck_require__(75497);
+const core_util_1 = __nccwpck_require__(87779);
+const proxyPolicy_js_1 = __nccwpck_require__(32815);
+const setClientRequestIdPolicy_js_1 = __nccwpck_require__(95686);
+const tlsPolicy_js_1 = __nccwpck_require__(75798);
+const tracingPolicy_js_1 = __nccwpck_require__(93237);
/**
- * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
- * @param {import('./websocket').WebSocket} ws
- * @param {number} type Opcode
- * @param {Buffer} data application data
+ * Create a new pipeline with a default set of customizable policies.
+ * @param options - Options to configure a custom pipeline.
*/
-function websocketMessageReceived (ws, type, data) {
- // 1. If ready state is not OPEN (1), then return.
- if (ws[kReadyState] !== 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 = new TextDecoder('utf-8', { fatal: true }).decode(data)
- } catch {
- failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.')
- return
+function createPipelineFromOptions(options) {
+ var _a;
+ const pipeline = (0, pipeline_js_1.createEmptyPipeline)();
+ if (core_util_1.isNodeLike) {
+ if (options.tlsOptions) {
+ pipeline.addPolicy((0, tlsPolicy_js_1.tlsPolicy)(options.tlsOptions));
+ }
+ pipeline.addPolicy((0, proxyPolicy_js_1.proxyPolicy)(options.proxyOptions));
+ pipeline.addPolicy((0, decompressResponsePolicy_js_1.decompressResponsePolicy)());
}
- } else if (type === opcodes.BINARY) {
- if (ws[kBinaryType] === '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 = new Uint8Array(data).buffer
+ pipeline.addPolicy((0, formDataPolicy_js_1.formDataPolicy)(), { beforePolicies: [multipartPolicy_js_1.multipartPolicyName] });
+ pipeline.addPolicy((0, userAgentPolicy_js_1.userAgentPolicy)(options.userAgentOptions));
+ pipeline.addPolicy((0, setClientRequestIdPolicy_js_1.setClientRequestIdPolicy)((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.clientRequestIdHeaderName));
+ // The multipart policy is added after policies with no phase, so that
+ // policies can be added between it and formDataPolicy to modify
+ // properties (e.g., making the boundary constant in recorded tests).
+ pipeline.addPolicy((0, multipartPolicy_js_1.multipartPolicy)(), { afterPhase: "Deserialize" });
+ pipeline.addPolicy((0, defaultRetryPolicy_js_1.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" });
+ pipeline.addPolicy((0, tracingPolicy_js_1.tracingPolicy)(Object.assign(Object.assign({}, options.userAgentOptions), options.loggingOptions)), {
+ afterPhase: "Retry",
+ });
+ if (core_util_1.isNodeLike) {
+ // Both XHR and Fetch expect to handle redirects automatically,
+ // so only include this policy when we're in Node.
+ pipeline.addPolicy((0, redirectPolicy_js_1.redirectPolicy)(options.redirectOptions), { afterPhase: "Retry" });
}
- }
-
- // 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', ws, MessageEvent, {
- origin: ws[kWebSocketURL].origin,
- data: dataForEvent
- })
+ pipeline.addPolicy((0, logPolicy_js_1.logPolicy)(options.loggingOptions), { afterPhase: "Sign" });
+ return pipeline;
}
+//# sourceMappingURL=createPipelineFromOptions.js.map
-/**
- * @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
- */
-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 (const char of protocol) {
- const code = char.charCodeAt(0)
-
- if (
- code < 0x21 ||
- code > 0x7E ||
- char === '(' ||
- char === ')' ||
- char === '<' ||
- char === '>' ||
- char === '@' ||
- char === ',' ||
- char === ';' ||
- char === ':' ||
- char === '\\' ||
- char === '"' ||
- char === '/' ||
- char === '[' ||
- char === ']' ||
- char === '?' ||
- char === '=' ||
- char === '{' ||
- char === '}' ||
- code === 32 || // SP
- code === 9 // HT
- ) {
- return false
- }
- }
-
- return true
-}
+/***/ }),
-/**
- * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4
- * @param {number} code
- */
-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"
- )
- }
+/***/ 7960:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- return code >= 3000 && code <= 4999
-}
+"use strict";
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createDefaultHttpClient = createDefaultHttpClient;
+const nodeHttpClient_js_1 = __nccwpck_require__(10195);
/**
- * @param {import('./websocket').WebSocket} ws
- * @param {string|undefined} reason
+ * Create the correct HttpClient for the current environment.
*/
-function failWebsocketConnection (ws, reason) {
- const { [kController]: controller, [kResponse]: response } = ws
-
- controller.abort()
-
- if (response?.socket && !response.socket.destroyed) {
- response.socket.destroy()
- }
-
- if (reason) {
- fireEvent('error', ws, ErrorEvent, {
- error: new Error(reason)
- })
- }
-}
-
-module.exports = {
- isEstablished,
- isClosing,
- isClosed,
- fireEvent,
- isValidSubprotocol,
- isValidStatusCode,
- failWebsocketConnection,
- websocketMessageReceived
+function createDefaultHttpClient() {
+ return (0, nodeHttpClient_js_1.createNodeHttpClient)();
}
-
+//# sourceMappingURL=defaultHttpClient.js.map
/***/ }),
-/***/ 5171:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 192:
+/***/ ((__unused_webpack_module, exports) => {
"use strict";
-
-const { webidl } = __nccwpck_require__(4222)
-const { DOMException } = __nccwpck_require__(7326)
-const { URLSerializer } = __nccwpck_require__(4322)
-const { getGlobalOrigin } = __nccwpck_require__(5628)
-const { staticPropertyDescriptors, states, opcodes, emptyBuffer } = __nccwpck_require__(5913)
-const {
- kWebSocketURL,
- kReadyState,
- kController,
- kBinaryType,
- kResponse,
- kSentClose,
- kByteParser
-} = __nccwpck_require__(2933)
-const { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = __nccwpck_require__(3574)
-const { establishWebSocketConnection } = __nccwpck_require__(8550)
-const { WebsocketFrameSend } = __nccwpck_require__(1237)
-const { ByteParser } = __nccwpck_require__(3171)
-const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(3440)
-const { getGlobalDispatcher } = __nccwpck_require__(2581)
-const { types } = __nccwpck_require__(9023)
-
-let experimentalWarned = 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 = ''
-
- /**
- * @param {string} url
- * @param {string|string[]} protocols
- */
- constructor (url, protocols = []) {
- super()
-
- webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' })
-
- if (!experimentalWarned) {
- experimentalWarned = true
- process.emitWarning('WebSockets are experimental, expect them to change at any time.', {
- code: 'UNDICI-WS'
- })
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createHttpHeaders = createHttpHeaders;
+function normalizeName(name) {
+ return name.toLowerCase();
+}
+function* headerIterator(map) {
+ for (const entry of map.values()) {
+ yield [entry.name, entry.value];
}
-
- const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols)
-
- url = webidl.converters.USVString(url)
- protocols = options.protocols
-
- // 1. Let baseURL be this's relevant settings object's API base URL.
- const baseURL = getGlobalOrigin()
-
- // 1. Let urlRecord be the result of applying the URL parser to url with baseURL.
- let urlRecord
-
- try {
- urlRecord = new URL(url, baseURL)
- } catch (e) {
- // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException.
- throw new DOMException(e, 'SyntaxError')
+}
+class HttpHeadersImpl {
+ constructor(rawHeaders) {
+ this._headersMap = new Map();
+ if (rawHeaders) {
+ for (const headerName of Object.keys(rawHeaders)) {
+ this.set(headerName, rawHeaders[headerName]);
+ }
+ }
}
-
- // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws".
- if (urlRecord.protocol === 'http:') {
- urlRecord.protocol = 'ws:'
- } else if (urlRecord.protocol === 'https:') {
- // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss".
- urlRecord.protocol = 'wss:'
+ /**
+ * Set a header in this collection with the provided name and value. The name is
+ * case-insensitive.
+ * @param name - The name of the header to set. This value is case-insensitive.
+ * @param value - The value of the header to set.
+ */
+ set(name, value) {
+ this._headersMap.set(normalizeName(name), { name, value: String(value).trim() });
+ }
+ /**
+ * Get the header value for the provided header name, or undefined if no header exists in this
+ * collection with the provided name.
+ * @param name - The name of the header. This value is case-insensitive.
+ */
+ get(name) {
+ var _a;
+ return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value;
+ }
+ /**
+ * Get whether or not this header collection contains a header entry for the provided header name.
+ * @param name - The name of the header to set. This value is case-insensitive.
+ */
+ has(name) {
+ return this._headersMap.has(normalizeName(name));
+ }
+ /**
+ * Remove the header with the provided headerName.
+ * @param name - The name of the header to remove.
+ */
+ delete(name) {
+ this._headersMap.delete(normalizeName(name));
}
-
- // 6. 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: protocol, got ${urlRecord.protocol}`,
- 'SyntaxError'
- )
+ /**
+ * Get the JSON object representation of this HTTP header collection.
+ */
+ toJSON(options = {}) {
+ const result = {};
+ if (options.preserveCase) {
+ for (const entry of this._headersMap.values()) {
+ result[entry.name] = entry.value;
+ }
+ }
+ else {
+ for (const [normalizedName, entry] of this._headersMap) {
+ result[normalizedName] = entry.value;
+ }
+ }
+ return result;
}
-
- // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError"
- // DOMException.
- if (urlRecord.hash || urlRecord.href.endsWith('#')) {
- throw new DOMException('Got fragment', 'SyntaxError')
+ /**
+ * Get the string representation of this HTTP header collection.
+ */
+ toString() {
+ return JSON.stringify(this.toJSON({ preserveCase: true }));
}
-
- // 8. If protocols is a string, set protocols to a sequence consisting
- // of just that string.
- if (typeof protocols === 'string') {
- protocols = [protocols]
+ /**
+ * Iterate over tuples of header [name, value] pairs.
+ */
+ [Symbol.iterator]() {
+ return headerIterator(this._headersMap);
}
+}
+/**
+ * Creates an object that satisfies the `HttpHeaders` interface.
+ * @param rawHeaders - A simple object representing initial headers
+ */
+function createHttpHeaders(rawHeaders) {
+ return new HttpHeadersImpl(rawHeaders);
+}
+//# sourceMappingURL=httpHeaders.js.map
- // 9. 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')
- }
+/***/ 20778:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 10. Set this's url to urlRecord.
- this[kWebSocketURL] = new URL(urlRecord.href)
+"use strict";
- // 11. Let client be this's relevant settings object.
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createFileFromStream = exports.createFile = exports.auxiliaryAuthenticationHeaderPolicyName = exports.auxiliaryAuthenticationHeaderPolicy = exports.ndJsonPolicyName = exports.ndJsonPolicy = exports.bearerTokenAuthenticationPolicyName = exports.bearerTokenAuthenticationPolicy = exports.formDataPolicyName = exports.formDataPolicy = exports.tlsPolicyName = exports.tlsPolicy = exports.userAgentPolicyName = exports.userAgentPolicy = exports.defaultRetryPolicy = exports.tracingPolicyName = exports.tracingPolicy = exports.retryPolicy = exports.throttlingRetryPolicyName = exports.throttlingRetryPolicy = exports.systemErrorRetryPolicyName = exports.systemErrorRetryPolicy = exports.redirectPolicyName = exports.redirectPolicy = exports.getDefaultProxySettings = exports.proxyPolicyName = exports.proxyPolicy = exports.multipartPolicyName = exports.multipartPolicy = exports.logPolicyName = exports.logPolicy = exports.setClientRequestIdPolicyName = exports.setClientRequestIdPolicy = exports.exponentialRetryPolicyName = exports.exponentialRetryPolicy = exports.decompressResponsePolicyName = exports.decompressResponsePolicy = exports.isRestError = exports.RestError = exports.createPipelineRequest = exports.createHttpHeaders = exports.createDefaultHttpClient = exports.createPipelineFromOptions = exports.createEmptyPipeline = void 0;
+var pipeline_js_1 = __nccwpck_require__(29590);
+Object.defineProperty(exports, "createEmptyPipeline", ({ enumerable: true, get: function () { return pipeline_js_1.createEmptyPipeline; } }));
+var createPipelineFromOptions_js_1 = __nccwpck_require__(90862);
+Object.defineProperty(exports, "createPipelineFromOptions", ({ enumerable: true, get: function () { return createPipelineFromOptions_js_1.createPipelineFromOptions; } }));
+var defaultHttpClient_js_1 = __nccwpck_require__(7960);
+Object.defineProperty(exports, "createDefaultHttpClient", ({ enumerable: true, get: function () { return defaultHttpClient_js_1.createDefaultHttpClient; } }));
+var httpHeaders_js_1 = __nccwpck_require__(192);
+Object.defineProperty(exports, "createHttpHeaders", ({ enumerable: true, get: function () { return httpHeaders_js_1.createHttpHeaders; } }));
+var pipelineRequest_js_1 = __nccwpck_require__(95709);
+Object.defineProperty(exports, "createPipelineRequest", ({ enumerable: true, get: function () { return pipelineRequest_js_1.createPipelineRequest; } }));
+var restError_js_1 = __nccwpck_require__(8666);
+Object.defineProperty(exports, "RestError", ({ enumerable: true, get: function () { return restError_js_1.RestError; } }));
+Object.defineProperty(exports, "isRestError", ({ enumerable: true, get: function () { return restError_js_1.isRestError; } }));
+var decompressResponsePolicy_js_1 = __nccwpck_require__(39295);
+Object.defineProperty(exports, "decompressResponsePolicy", ({ enumerable: true, get: function () { return decompressResponsePolicy_js_1.decompressResponsePolicy; } }));
+Object.defineProperty(exports, "decompressResponsePolicyName", ({ enumerable: true, get: function () { return decompressResponsePolicy_js_1.decompressResponsePolicyName; } }));
+var exponentialRetryPolicy_js_1 = __nccwpck_require__(16708);
+Object.defineProperty(exports, "exponentialRetryPolicy", ({ enumerable: true, get: function () { return exponentialRetryPolicy_js_1.exponentialRetryPolicy; } }));
+Object.defineProperty(exports, "exponentialRetryPolicyName", ({ enumerable: true, get: function () { return exponentialRetryPolicy_js_1.exponentialRetryPolicyName; } }));
+var setClientRequestIdPolicy_js_1 = __nccwpck_require__(95686);
+Object.defineProperty(exports, "setClientRequestIdPolicy", ({ enumerable: true, get: function () { return setClientRequestIdPolicy_js_1.setClientRequestIdPolicy; } }));
+Object.defineProperty(exports, "setClientRequestIdPolicyName", ({ enumerable: true, get: function () { return setClientRequestIdPolicy_js_1.setClientRequestIdPolicyName; } }));
+var logPolicy_js_1 = __nccwpck_require__(53253);
+Object.defineProperty(exports, "logPolicy", ({ enumerable: true, get: function () { return logPolicy_js_1.logPolicy; } }));
+Object.defineProperty(exports, "logPolicyName", ({ enumerable: true, get: function () { return logPolicy_js_1.logPolicyName; } }));
+var multipartPolicy_js_1 = __nccwpck_require__(45807);
+Object.defineProperty(exports, "multipartPolicy", ({ enumerable: true, get: function () { return multipartPolicy_js_1.multipartPolicy; } }));
+Object.defineProperty(exports, "multipartPolicyName", ({ enumerable: true, get: function () { return multipartPolicy_js_1.multipartPolicyName; } }));
+var proxyPolicy_js_1 = __nccwpck_require__(32815);
+Object.defineProperty(exports, "proxyPolicy", ({ enumerable: true, get: function () { return proxyPolicy_js_1.proxyPolicy; } }));
+Object.defineProperty(exports, "proxyPolicyName", ({ enumerable: true, get: function () { return proxyPolicy_js_1.proxyPolicyName; } }));
+Object.defineProperty(exports, "getDefaultProxySettings", ({ enumerable: true, get: function () { return proxyPolicy_js_1.getDefaultProxySettings; } }));
+var redirectPolicy_js_1 = __nccwpck_require__(64087);
+Object.defineProperty(exports, "redirectPolicy", ({ enumerable: true, get: function () { return redirectPolicy_js_1.redirectPolicy; } }));
+Object.defineProperty(exports, "redirectPolicyName", ({ enumerable: true, get: function () { return redirectPolicy_js_1.redirectPolicyName; } }));
+var systemErrorRetryPolicy_js_1 = __nccwpck_require__(96518);
+Object.defineProperty(exports, "systemErrorRetryPolicy", ({ enumerable: true, get: function () { return systemErrorRetryPolicy_js_1.systemErrorRetryPolicy; } }));
+Object.defineProperty(exports, "systemErrorRetryPolicyName", ({ enumerable: true, get: function () { return systemErrorRetryPolicy_js_1.systemErrorRetryPolicyName; } }));
+var throttlingRetryPolicy_js_1 = __nccwpck_require__(97540);
+Object.defineProperty(exports, "throttlingRetryPolicy", ({ enumerable: true, get: function () { return throttlingRetryPolicy_js_1.throttlingRetryPolicy; } }));
+Object.defineProperty(exports, "throttlingRetryPolicyName", ({ enumerable: true, get: function () { return throttlingRetryPolicy_js_1.throttlingRetryPolicyName; } }));
+var retryPolicy_js_1 = __nccwpck_require__(56085);
+Object.defineProperty(exports, "retryPolicy", ({ enumerable: true, get: function () { return retryPolicy_js_1.retryPolicy; } }));
+var tracingPolicy_js_1 = __nccwpck_require__(93237);
+Object.defineProperty(exports, "tracingPolicy", ({ enumerable: true, get: function () { return tracingPolicy_js_1.tracingPolicy; } }));
+Object.defineProperty(exports, "tracingPolicyName", ({ enumerable: true, get: function () { return tracingPolicy_js_1.tracingPolicyName; } }));
+var defaultRetryPolicy_js_1 = __nccwpck_require__(48170);
+Object.defineProperty(exports, "defaultRetryPolicy", ({ enumerable: true, get: function () { return defaultRetryPolicy_js_1.defaultRetryPolicy; } }));
+var userAgentPolicy_js_1 = __nccwpck_require__(32799);
+Object.defineProperty(exports, "userAgentPolicy", ({ enumerable: true, get: function () { return userAgentPolicy_js_1.userAgentPolicy; } }));
+Object.defineProperty(exports, "userAgentPolicyName", ({ enumerable: true, get: function () { return userAgentPolicy_js_1.userAgentPolicyName; } }));
+var tlsPolicy_js_1 = __nccwpck_require__(75798);
+Object.defineProperty(exports, "tlsPolicy", ({ enumerable: true, get: function () { return tlsPolicy_js_1.tlsPolicy; } }));
+Object.defineProperty(exports, "tlsPolicyName", ({ enumerable: true, get: function () { return tlsPolicy_js_1.tlsPolicyName; } }));
+var formDataPolicy_js_1 = __nccwpck_require__(75497);
+Object.defineProperty(exports, "formDataPolicy", ({ enumerable: true, get: function () { return formDataPolicy_js_1.formDataPolicy; } }));
+Object.defineProperty(exports, "formDataPolicyName", ({ enumerable: true, get: function () { return formDataPolicy_js_1.formDataPolicyName; } }));
+var bearerTokenAuthenticationPolicy_js_1 = __nccwpck_require__(26925);
+Object.defineProperty(exports, "bearerTokenAuthenticationPolicy", ({ enumerable: true, get: function () { return bearerTokenAuthenticationPolicy_js_1.bearerTokenAuthenticationPolicy; } }));
+Object.defineProperty(exports, "bearerTokenAuthenticationPolicyName", ({ enumerable: true, get: function () { return bearerTokenAuthenticationPolicy_js_1.bearerTokenAuthenticationPolicyName; } }));
+var ndJsonPolicy_js_1 = __nccwpck_require__(36827);
+Object.defineProperty(exports, "ndJsonPolicy", ({ enumerable: true, get: function () { return ndJsonPolicy_js_1.ndJsonPolicy; } }));
+Object.defineProperty(exports, "ndJsonPolicyName", ({ enumerable: true, get: function () { return ndJsonPolicy_js_1.ndJsonPolicyName; } }));
+var auxiliaryAuthenticationHeaderPolicy_js_1 = __nccwpck_require__(42262);
+Object.defineProperty(exports, "auxiliaryAuthenticationHeaderPolicy", ({ enumerable: true, get: function () { return auxiliaryAuthenticationHeaderPolicy_js_1.auxiliaryAuthenticationHeaderPolicy; } }));
+Object.defineProperty(exports, "auxiliaryAuthenticationHeaderPolicyName", ({ enumerable: true, get: function () { return auxiliaryAuthenticationHeaderPolicy_js_1.auxiliaryAuthenticationHeaderPolicyName; } }));
+var file_js_1 = __nccwpck_require__(97073);
+Object.defineProperty(exports, "createFile", ({ enumerable: true, get: function () { return file_js_1.createFile; } }));
+Object.defineProperty(exports, "createFileFromStream", ({ enumerable: true, get: function () { return file_js_1.createFileFromStream; } }));
+//# sourceMappingURL=index.js.map
- // 12. Run this step in parallel:
+/***/ }),
- // 1. Establish a WebSocket connection given urlRecord, protocols,
- // and client.
- this[kController] = establishWebSocketConnection(
- urlRecord,
- protocols,
- this,
- (response) => this.#onConnectionEstablished(response),
- options
- )
+/***/ 80544:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 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[kReadyState] = WebSocket.CONNECTING
+"use strict";
- // The extensions attribute must initially return the empty string.
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.logger = void 0;
+const logger_1 = __nccwpck_require__(26515);
+exports.logger = (0, logger_1.createClientLogger)("core-rest-pipeline");
+//# sourceMappingURL=log.js.map
- // 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[kBinaryType] = 'blob'
- }
+/***/ 10195:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- /**
- * @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)
+"use strict";
- if (code !== undefined) {
- code = webidl.converters['unsigned short'](code, { clamp: true })
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getBodyLength = getBodyLength;
+exports.createNodeHttpClient = createNodeHttpClient;
+const tslib_1 = __nccwpck_require__(61860);
+const http = tslib_1.__importStar(__nccwpck_require__(37067));
+const https = tslib_1.__importStar(__nccwpck_require__(44708));
+const zlib = tslib_1.__importStar(__nccwpck_require__(38522));
+const node_stream_1 = __nccwpck_require__(57075);
+const abort_controller_1 = __nccwpck_require__(93287);
+const httpHeaders_js_1 = __nccwpck_require__(192);
+const restError_js_1 = __nccwpck_require__(8666);
+const log_js_1 = __nccwpck_require__(80544);
+const DEFAULT_TLS_SETTINGS = {};
+function isReadableStream(body) {
+ return body && typeof body.pipe === "function";
+}
+function isStreamComplete(stream) {
+ if (stream.readable === false) {
+ return Promise.resolve();
}
-
- if (reason !== undefined) {
- reason = webidl.converters.USVString(reason)
+ return new Promise((resolve) => {
+ const handler = () => {
+ resolve();
+ stream.removeListener("close", handler);
+ stream.removeListener("end", handler);
+ stream.removeListener("error", handler);
+ };
+ stream.on("close", handler);
+ stream.on("end", handler);
+ stream.on("error", handler);
+ });
+}
+function isArrayBuffer(body) {
+ return body && typeof body.byteLength === "number";
+}
+class ReportTransform extends node_stream_1.Transform {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
+ _transform(chunk, _encoding, callback) {
+ this.push(chunk);
+ this.loadedBytes += chunk.length;
+ try {
+ this.progressCallback({ loadedBytes: this.loadedBytes });
+ callback();
+ }
+ catch (e) {
+ callback(e);
+ }
}
-
- // 1. If code is present, but is neither an integer equal to 1000 nor an
- // integer in the range 3000 to 4999, inclusive, throw an
- // "InvalidAccessError" DOMException.
- if (code !== undefined) {
- if (code !== 1000 && (code < 3000 || code > 4999)) {
- throw new DOMException('invalid code', 'InvalidAccessError')
- }
+ constructor(progressCallback) {
+ super();
+ this.loadedBytes = 0;
+ this.progressCallback = progressCallback;
}
-
- let reasonByteLength = 0
-
- // 2. If reason is present, then run these substeps:
- if (reason !== undefined) {
- // 1. Let reasonBytes be the result of encoding reason.
- // 2. If reasonBytes is longer than 123 bytes, then throw a
- // "SyntaxError" DOMException.
- reasonByteLength = Buffer.byteLength(reason)
-
- if (reasonByteLength > 123) {
- throw new DOMException(
- `Reason must be less than 123 bytes; received ${reasonByteLength}`,
- 'SyntaxError'
- )
- }
+}
+/**
+ * A HttpClient implementation that uses Node's "https" module to send HTTPS requests.
+ * @internal
+ */
+class NodeHttpClient {
+ constructor() {
+ this.cachedHttpsAgents = new WeakMap();
}
-
- // 3. Run the first matching steps from the following list:
- if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) {
- // If this's ready state is CLOSING (2) or CLOSED (3)
- // Do nothing.
- } else if (!isEstablished(this)) {
- // If the WebSocket connection is not yet established
- // Fail the WebSocket connection and set this's ready state
- // to CLOSING (2).
- failWebsocketConnection(this, 'Connection was closed before it was established.')
- this[kReadyState] = WebSocket.CLOSING
- } else if (!isClosing(this)) {
- // If the WebSocket closing handshake has not yet been started
- // Start the WebSocket closing handshake and set this's ready
- // state to CLOSING (2).
- // - 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 reason is also present, then reasonBytes must be
- // provided in the Close message after the status code.
-
- 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 !== undefined && reason === undefined) {
- frame.frameData = Buffer.allocUnsafe(2)
- frame.frameData.writeUInt16BE(code, 0)
- } else if (code !== undefined && reason !== undefined) {
- // If reason is also present, then reasonBytes must be
- // provided in the Close message after the status code.
- frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength)
- 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
- }
-
- /** @type {import('stream').Duplex} */
- const socket = this[kResponse].socket
-
- socket.write(frame.createFrame(opcodes.CLOSE), (err) => {
- if (!err) {
- this[kSentClose] = true
+ /**
+ * Makes a request over an underlying transport layer and returns the response.
+ * @param request - The request to be made.
+ */
+ async sendRequest(request) {
+ var _a, _b, _c;
+ const abortController = new AbortController();
+ let abortListener;
+ if (request.abortSignal) {
+ if (request.abortSignal.aborted) {
+ throw new abort_controller_1.AbortError("The operation was aborted.");
+ }
+ abortListener = (event) => {
+ if (event.type === "abort") {
+ abortController.abort();
+ }
+ };
+ request.abortSignal.addEventListener("abort", abortListener);
+ }
+ if (request.timeout > 0) {
+ setTimeout(() => {
+ abortController.abort();
+ }, request.timeout);
+ }
+ const acceptEncoding = request.headers.get("Accept-Encoding");
+ const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate"));
+ let body = typeof request.body === "function" ? request.body() : request.body;
+ if (body && !request.headers.has("Content-Length")) {
+ const bodyLength = getBodyLength(body);
+ if (bodyLength !== null) {
+ request.headers.set("Content-Length", bodyLength);
+ }
+ }
+ let responseStream;
+ try {
+ if (body && request.onUploadProgress) {
+ const onUploadProgress = request.onUploadProgress;
+ const uploadReportStream = new ReportTransform(onUploadProgress);
+ uploadReportStream.on("error", (e) => {
+ log_js_1.logger.error("Error in upload progress", e);
+ });
+ if (isReadableStream(body)) {
+ body.pipe(uploadReportStream);
+ }
+ else {
+ uploadReportStream.end(body);
+ }
+ body = uploadReportStream;
+ }
+ const res = await this.makeRequest(request, abortController, body);
+ const headers = getResponseHeaders(res);
+ const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0;
+ const response = {
+ status,
+ headers,
+ request,
+ };
+ // Responses to HEAD must not have a body.
+ // If they do return a body, that body must be ignored.
+ if (request.method === "HEAD") {
+ // call resume() and not destroy() to avoid closing the socket
+ // and losing keep alive
+ res.resume();
+ return response;
+ }
+ responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res;
+ const onDownloadProgress = request.onDownloadProgress;
+ if (onDownloadProgress) {
+ const downloadReportStream = new ReportTransform(onDownloadProgress);
+ downloadReportStream.on("error", (e) => {
+ log_js_1.logger.error("Error in download progress", e);
+ });
+ responseStream.pipe(downloadReportStream);
+ responseStream = downloadReportStream;
+ }
+ if (
+ // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code
+ ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) ||
+ ((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status))) {
+ response.readableStreamBody = responseStream;
+ }
+ else {
+ response.bodyAsText = await streamToText(responseStream);
+ }
+ return response;
+ }
+ finally {
+ // clean up event listener
+ if (request.abortSignal && abortListener) {
+ let uploadStreamDone = Promise.resolve();
+ if (isReadableStream(body)) {
+ uploadStreamDone = isStreamComplete(body);
+ }
+ let downloadStreamDone = Promise.resolve();
+ if (isReadableStream(responseStream)) {
+ downloadStreamDone = isStreamComplete(responseStream);
+ }
+ Promise.all([uploadStreamDone, downloadStreamDone])
+ .then(() => {
+ var _a;
+ // eslint-disable-next-line promise/always-return
+ if (abortListener) {
+ (_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener);
+ }
+ })
+ .catch((e) => {
+ log_js_1.logger.warning("Error when cleaning up abortListener on httpRequest", e);
+ });
+ }
+ }
+ }
+ makeRequest(request, abortController, body) {
+ var _a;
+ const url = new URL(request.url);
+ const isInsecure = url.protocol !== "https:";
+ if (isInsecure && !request.allowInsecureConnection) {
+ throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);
+ }
+ const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure);
+ const options = {
+ agent,
+ hostname: url.hostname,
+ path: `${url.pathname}${url.search}`,
+ port: url.port,
+ method: request.method,
+ headers: request.headers.toJSON({ preserveCase: true }),
+ };
+ return new Promise((resolve, reject) => {
+ const req = isInsecure ? http.request(options, resolve) : https.request(options, resolve);
+ req.once("error", (err) => {
+ var _a;
+ reject(new restError_js_1.RestError(err.message, { code: (_a = err.code) !== null && _a !== void 0 ? _a : restError_js_1.RestError.REQUEST_SEND_ERROR, request }));
+ });
+ abortController.signal.addEventListener("abort", () => {
+ const abortError = new abort_controller_1.AbortError("The operation was aborted.");
+ req.destroy(abortError);
+ reject(abortError);
+ });
+ if (body && isReadableStream(body)) {
+ body.pipe(req);
+ }
+ else if (body) {
+ if (typeof body === "string" || Buffer.isBuffer(body)) {
+ req.end(body);
+ }
+ else if (isArrayBuffer(body)) {
+ req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body));
+ }
+ else {
+ log_js_1.logger.error("Unrecognized body type", body);
+ reject(new restError_js_1.RestError("Unrecognized body type"));
+ }
+ }
+ else {
+ // streams don't like "undefined" being passed as data
+ req.end();
+ }
+ });
+ }
+ getOrCreateAgent(request, isInsecure) {
+ var _a;
+ const disableKeepAlive = request.disableKeepAlive;
+ // Handle Insecure requests first
+ if (isInsecure) {
+ if (disableKeepAlive) {
+ // keepAlive:false is the default so we don't need a custom Agent
+ return http.globalAgent;
+ }
+ if (!this.cachedHttpAgent) {
+ // If there is no cached agent create a new one and cache it.
+ this.cachedHttpAgent = new http.Agent({ keepAlive: true });
+ }
+ return this.cachedHttpAgent;
+ }
+ else {
+ if (disableKeepAlive && !request.tlsSettings) {
+ // When there are no tlsSettings and keepAlive is false
+ // we don't need a custom agent
+ return https.globalAgent;
+ }
+ // We use the tlsSettings to index cached clients
+ const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS;
+ // Get the cached agent or create a new one with the
+ // provided values for keepAlive and tlsSettings
+ let agent = this.cachedHttpsAgents.get(tlsSettings);
+ if (agent && agent.options.keepAlive === !disableKeepAlive) {
+ return agent;
+ }
+ log_js_1.logger.info("No cached TLS Agent exist, creating a new Agent");
+ agent = new https.Agent(Object.assign({
+ // keepAlive is true if disableKeepAlive is false.
+ keepAlive: !disableKeepAlive }, tlsSettings));
+ this.cachedHttpsAgents.set(tlsSettings, agent);
+ return agent;
+ }
+ }
+}
+function getResponseHeaders(res) {
+ const headers = (0, httpHeaders_js_1.createHttpHeaders)();
+ for (const header of Object.keys(res.headers)) {
+ const value = res.headers[header];
+ if (Array.isArray(value)) {
+ if (value.length > 0) {
+ headers.set(header, value[0]);
+ }
+ }
+ else if (value) {
+ headers.set(header, value);
}
- })
-
- // 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[kReadyState] = states.CLOSING
- } else {
- // Otherwise
- // Set this's ready state to CLOSING (2).
- this[kReadyState] = WebSocket.CLOSING
}
- }
-
- /**
- * @see https://websockets.spec.whatwg.org/#dom-websocket-send
- * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data
- */
- send (data) {
- webidl.brandCheck(this, WebSocket)
-
- webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' })
-
- data = webidl.converters.WebSocketSendData(data)
-
- // 1. If this's ready state is CONNECTING, then throw an
- // "InvalidStateError" DOMException.
- if (this[kReadyState] === WebSocket.CONNECTING) {
- throw new DOMException('Sent before connected.', 'InvalidStateError')
+ return headers;
+}
+function getDecodedResponseStream(stream, headers) {
+ const contentEncoding = headers.get("Content-Encoding");
+ if (contentEncoding === "gzip") {
+ const unzip = zlib.createGunzip();
+ stream.pipe(unzip);
+ return unzip;
}
-
- // 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) || isClosing(this)) {
- return
+ else if (contentEncoding === "deflate") {
+ const inflate = zlib.createInflate();
+ stream.pipe(inflate);
+ return inflate;
}
-
- /** @type {import('stream').Duplex} */
- const socket = this[kResponse].socket
-
- // 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 value = Buffer.from(data)
- const frame = new WebsocketFrameSend(value)
- const buffer = frame.createFrame(opcodes.TEXT)
-
- this.#bufferedAmount += value.byteLength
- socket.write(buffer, () => {
- this.#bufferedAmount -= value.byteLength
- })
- } 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.
-
- const value = Buffer.from(data)
- const frame = new WebsocketFrameSend(value)
- const buffer = frame.createFrame(opcodes.BINARY)
-
- this.#bufferedAmount += value.byteLength
- socket.write(buffer, () => {
- this.#bufferedAmount -= value.byteLength
- })
- } 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.
-
- const ab = Buffer.from(data, data.byteOffset, data.byteLength)
-
- const frame = new WebsocketFrameSend(ab)
- const buffer = frame.createFrame(opcodes.BINARY)
-
- this.#bufferedAmount += ab.byteLength
- socket.write(buffer, () => {
- this.#bufferedAmount -= ab.byteLength
- })
- } else if (isBlobLike(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.
-
- const frame = new WebsocketFrameSend()
-
- data.arrayBuffer().then((ab) => {
- const value = Buffer.from(ab)
- frame.frameData = value
- const buffer = frame.createFrame(opcodes.BINARY)
-
- this.#bufferedAmount += value.byteLength
- socket.write(buffer, () => {
- this.#bufferedAmount -= value.byteLength
- })
- })
+ return stream;
+}
+function streamToText(stream) {
+ return new Promise((resolve, reject) => {
+ const buffer = [];
+ stream.on("data", (chunk) => {
+ if (Buffer.isBuffer(chunk)) {
+ buffer.push(chunk);
+ }
+ else {
+ buffer.push(Buffer.from(chunk));
+ }
+ });
+ stream.on("end", () => {
+ resolve(Buffer.concat(buffer).toString("utf8"));
+ });
+ stream.on("error", (e) => {
+ if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") {
+ reject(e);
+ }
+ else {
+ reject(new restError_js_1.RestError(`Error reading response as text: ${e.message}`, {
+ code: restError_js_1.RestError.PARSE_ERROR,
+ }));
+ }
+ });
+ });
+}
+/** @internal */
+function getBodyLength(body) {
+ if (!body) {
+ return 0;
}
- }
-
- get readyState () {
- webidl.brandCheck(this, WebSocket)
-
- // The readyState getter steps are to return this's ready state.
- return this[kReadyState]
- }
-
- 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[kWebSocketURL])
- }
-
- 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)
+ else if (Buffer.isBuffer(body)) {
+ return body.length;
}
-
- if (typeof fn === 'function') {
- this.#events.open = fn
- this.addEventListener('open', fn)
- } else {
- this.#events.open = null
+ else if (isReadableStream(body)) {
+ return 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)
+ else if (isArrayBuffer(body)) {
+ return body.byteLength;
}
-
- if (typeof fn === 'function') {
- this.#events.error = fn
- this.addEventListener('error', fn)
- } else {
- this.#events.error = null
+ else if (typeof body === "string") {
+ return Buffer.from(body).length;
}
- }
+ else {
+ return null;
+ }
+}
+/**
+ * Create a new HttpClient instance for the NodeJS environment.
+ * @internal
+ */
+function createNodeHttpClient() {
+ return new NodeHttpClient();
+}
+//# sourceMappingURL=nodeHttpClient.js.map
- get onclose () {
- webidl.brandCheck(this, WebSocket)
+/***/ }),
- return this.#events.close
- }
+/***/ 29590:
+/***/ ((__unused_webpack_module, exports) => {
- set onclose (fn) {
- webidl.brandCheck(this, WebSocket)
+"use strict";
- if (this.#events.close) {
- this.removeEventListener('close', this.#events.close)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createEmptyPipeline = createEmptyPipeline;
+const ValidPhaseNames = new Set(["Deserialize", "Serialize", "Retry", "Sign"]);
+/**
+ * A private implementation of Pipeline.
+ * Do not export this class from the package.
+ * @internal
+ */
+class HttpPipeline {
+ constructor(policies) {
+ var _a;
+ this._policies = [];
+ this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : [];
+ this._orderedPolicies = undefined;
}
-
- if (typeof fn === 'function') {
- this.#events.close = fn
- this.addEventListener('close', fn)
- } else {
- this.#events.close = null
+ addPolicy(policy, options = {}) {
+ if (options.phase && options.afterPhase) {
+ throw new Error("Policies inside a phase cannot specify afterPhase.");
+ }
+ if (options.phase && !ValidPhaseNames.has(options.phase)) {
+ throw new Error(`Invalid phase name: ${options.phase}`);
+ }
+ if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) {
+ throw new Error(`Invalid afterPhase name: ${options.afterPhase}`);
+ }
+ this._policies.push({
+ policy,
+ options,
+ });
+ this._orderedPolicies = undefined;
+ }
+ removePolicy(options) {
+ const removedPolicies = [];
+ this._policies = this._policies.filter((policyDescriptor) => {
+ if ((options.name && policyDescriptor.policy.name === options.name) ||
+ (options.phase && policyDescriptor.options.phase === options.phase)) {
+ removedPolicies.push(policyDescriptor.policy);
+ return false;
+ }
+ else {
+ return true;
+ }
+ });
+ this._orderedPolicies = undefined;
+ return removedPolicies;
+ }
+ sendRequest(httpClient, request) {
+ const policies = this.getOrderedPolicies();
+ const pipeline = policies.reduceRight((next, policy) => {
+ return (req) => {
+ return policy.sendRequest(req, next);
+ };
+ }, (req) => httpClient.sendRequest(req));
+ return pipeline(request);
+ }
+ getOrderedPolicies() {
+ if (!this._orderedPolicies) {
+ this._orderedPolicies = this.orderPolicies();
+ }
+ return this._orderedPolicies;
+ }
+ clone() {
+ return new HttpPipeline(this._policies);
+ }
+ static create() {
+ return new HttpPipeline();
+ }
+ orderPolicies() {
+ /**
+ * The goal of this method is to reliably order pipeline policies
+ * based on their declared requirements when they were added.
+ *
+ * Order is first determined by phase:
+ *
+ * 1. Serialize Phase
+ * 2. Policies not in a phase
+ * 3. Deserialize Phase
+ * 4. Retry Phase
+ * 5. Sign Phase
+ *
+ * Within each phase, policies are executed in the order
+ * they were added unless they were specified to execute
+ * before/after other policies or after a particular phase.
+ *
+ * To determine the final order, we will walk the policy list
+ * in phase order multiple times until all dependencies are
+ * satisfied.
+ *
+ * `afterPolicies` are the set of policies that must be
+ * executed before a given policy. This requirement is
+ * considered satisfied when each of the listed policies
+ * have been scheduled.
+ *
+ * `beforePolicies` are the set of policies that must be
+ * executed after a given policy. Since this dependency
+ * can be expressed by converting it into a equivalent
+ * `afterPolicies` declarations, they are normalized
+ * into that form for simplicity.
+ *
+ * An `afterPhase` dependency is considered satisfied when all
+ * policies in that phase have scheduled.
+ *
+ */
+ const result = [];
+ // Track all policies we know about.
+ const policyMap = new Map();
+ function createPhase(name) {
+ return {
+ name,
+ policies: new Set(),
+ hasRun: false,
+ hasAfterPolicies: false,
+ };
+ }
+ // Track policies for each phase.
+ const serializePhase = createPhase("Serialize");
+ const noPhase = createPhase("None");
+ const deserializePhase = createPhase("Deserialize");
+ const retryPhase = createPhase("Retry");
+ const signPhase = createPhase("Sign");
+ // a list of phases in order
+ const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase];
+ // Small helper function to map phase name to each Phase
+ function getPhase(phase) {
+ if (phase === "Retry") {
+ return retryPhase;
+ }
+ else if (phase === "Serialize") {
+ return serializePhase;
+ }
+ else if (phase === "Deserialize") {
+ return deserializePhase;
+ }
+ else if (phase === "Sign") {
+ return signPhase;
+ }
+ else {
+ return noPhase;
+ }
+ }
+ // First walk each policy and create a node to track metadata.
+ for (const descriptor of this._policies) {
+ const policy = descriptor.policy;
+ const options = descriptor.options;
+ const policyName = policy.name;
+ if (policyMap.has(policyName)) {
+ throw new Error("Duplicate policy names not allowed in pipeline");
+ }
+ const node = {
+ policy,
+ dependsOn: new Set(),
+ dependants: new Set(),
+ };
+ if (options.afterPhase) {
+ node.afterPhase = getPhase(options.afterPhase);
+ node.afterPhase.hasAfterPolicies = true;
+ }
+ policyMap.set(policyName, node);
+ const phase = getPhase(options.phase);
+ phase.policies.add(node);
+ }
+ // Now that each policy has a node, connect dependency references.
+ for (const descriptor of this._policies) {
+ const { policy, options } = descriptor;
+ const policyName = policy.name;
+ const node = policyMap.get(policyName);
+ if (!node) {
+ throw new Error(`Missing node for policy ${policyName}`);
+ }
+ if (options.afterPolicies) {
+ for (const afterPolicyName of options.afterPolicies) {
+ const afterNode = policyMap.get(afterPolicyName);
+ if (afterNode) {
+ // Linking in both directions helps later
+ // when we want to notify dependants.
+ node.dependsOn.add(afterNode);
+ afterNode.dependants.add(node);
+ }
+ }
+ }
+ if (options.beforePolicies) {
+ for (const beforePolicyName of options.beforePolicies) {
+ const beforeNode = policyMap.get(beforePolicyName);
+ if (beforeNode) {
+ // To execute before another node, make it
+ // depend on the current node.
+ beforeNode.dependsOn.add(node);
+ node.dependants.add(beforeNode);
+ }
+ }
+ }
+ }
+ function walkPhase(phase) {
+ phase.hasRun = true;
+ // Sets iterate in insertion order
+ for (const node of phase.policies) {
+ if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) {
+ // If this node is waiting on a phase to complete,
+ // we need to skip it for now.
+ // Even if the phase is empty, we should wait for it
+ // to be walked to avoid re-ordering policies.
+ continue;
+ }
+ if (node.dependsOn.size === 0) {
+ // If there's nothing else we're waiting for, we can
+ // add this policy to the result list.
+ result.push(node.policy);
+ // Notify anything that depends on this policy that
+ // the policy has been scheduled.
+ for (const dependant of node.dependants) {
+ dependant.dependsOn.delete(node);
+ }
+ policyMap.delete(node.policy.name);
+ phase.policies.delete(node);
+ }
+ }
+ }
+ function walkPhases() {
+ for (const phase of orderedPhases) {
+ walkPhase(phase);
+ // if the phase isn't complete
+ if (phase.policies.size > 0 && phase !== noPhase) {
+ if (!noPhase.hasRun) {
+ // Try running noPhase to see if that unblocks this phase next tick.
+ // This can happen if a phase that happens before noPhase
+ // is waiting on a noPhase policy to complete.
+ walkPhase(noPhase);
+ }
+ // Don't proceed to the next phase until this phase finishes.
+ return;
+ }
+ if (phase.hasAfterPolicies) {
+ // Run any policies unblocked by this phase
+ walkPhase(noPhase);
+ }
+ }
+ }
+ // Iterate until we've put every node in the result list.
+ let iteration = 0;
+ while (policyMap.size > 0) {
+ iteration++;
+ const initialResultLength = result.length;
+ // Keep walking each phase in order until we can order every node.
+ walkPhases();
+ // The result list *should* get at least one larger each time
+ // after the first full pass.
+ // Otherwise, we're going to loop forever.
+ if (result.length <= initialResultLength && iteration > 1) {
+ throw new Error("Cannot satisfy policy dependencies due to requirements cycle.");
+ }
+ }
+ return result;
}
- }
-
- get onmessage () {
- webidl.brandCheck(this, WebSocket)
+}
+/**
+ * Creates a totally empty pipeline.
+ * Useful for testing or creating a custom one.
+ */
+function createEmptyPipeline() {
+ return HttpPipeline.create();
+}
+//# sourceMappingURL=pipeline.js.map
- return this.#events.message
- }
+/***/ }),
- set onmessage (fn) {
- webidl.brandCheck(this, WebSocket)
+/***/ 95709:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (this.#events.message) {
- this.removeEventListener('message', this.#events.message)
- }
+"use strict";
- if (typeof fn === 'function') {
- this.#events.message = fn
- this.addEventListener('message', fn)
- } else {
- this.#events.message = null
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createPipelineRequest = createPipelineRequest;
+const httpHeaders_js_1 = __nccwpck_require__(192);
+const core_util_1 = __nccwpck_require__(87779);
+class PipelineRequestImpl {
+ constructor(options) {
+ var _a, _b, _c, _d, _e, _f, _g;
+ this.url = options.url;
+ this.body = options.body;
+ this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : (0, httpHeaders_js_1.createHttpHeaders)();
+ this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET";
+ this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0;
+ this.multipartBody = options.multipartBody;
+ this.formData = options.formData;
+ this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false;
+ this.proxySettings = options.proxySettings;
+ this.streamResponseStatusCodes = options.streamResponseStatusCodes;
+ this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false;
+ this.abortSignal = options.abortSignal;
+ this.tracingOptions = options.tracingOptions;
+ this.onUploadProgress = options.onUploadProgress;
+ this.onDownloadProgress = options.onDownloadProgress;
+ this.requestId = options.requestId || (0, core_util_1.randomUUID)();
+ this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false;
+ this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false;
}
- }
-
- get binaryType () {
- webidl.brandCheck(this, WebSocket)
-
- return this[kBinaryType]
- }
+}
+/**
+ * Creates a new pipeline request with the given options.
+ * This method is to allow for the easy setting of default values and not required.
+ * @param options - The options to create the request with.
+ */
+function createPipelineRequest(options) {
+ return new PipelineRequestImpl(options);
+}
+//# sourceMappingURL=pipelineRequest.js.map
- set binaryType (type) {
- webidl.brandCheck(this, WebSocket)
+/***/ }),
- if (type !== 'blob' && type !== 'arraybuffer') {
- this[kBinaryType] = 'blob'
- } else {
- this[kBinaryType] = type
- }
- }
+/***/ 42262:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- /**
- * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
- */
- #onConnectionEstablished (response) {
- // processResponse is called when the "response’s header list has been received and initialized."
- // once this happens, the connection is open
- this[kResponse] = response
+"use strict";
- const parser = new ByteParser(this)
- parser.on('drain', function onParserDrain () {
- this.ws[kResponse].socket.resume()
- })
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.auxiliaryAuthenticationHeaderPolicyName = void 0;
+exports.auxiliaryAuthenticationHeaderPolicy = auxiliaryAuthenticationHeaderPolicy;
+const tokenCycler_js_1 = __nccwpck_require__(39202);
+const log_js_1 = __nccwpck_require__(80544);
+/**
+ * The programmatic identifier of the auxiliaryAuthenticationHeaderPolicy.
+ */
+exports.auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy";
+const AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary";
+async function sendAuthorizeRequest(options) {
+ var _a, _b;
+ const { scopes, getAccessToken, request } = options;
+ const getTokenOptions = {
+ abortSignal: request.abortSignal,
+ tracingOptions: request.tracingOptions,
+ };
+ return (_b = (_a = (await getAccessToken(scopes, getTokenOptions))) === null || _a === void 0 ? void 0 : _a.token) !== null && _b !== void 0 ? _b : "";
+}
+/**
+ * A policy for external tokens to `x-ms-authorization-auxiliary` header.
+ * This header will be used when creating a cross-tenant application we may need to handle authentication requests
+ * for resources that are in different tenants.
+ * You could see [ARM docs](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/authenticate-multi-tenant) for a rundown of how this feature works
+ */
+function auxiliaryAuthenticationHeaderPolicy(options) {
+ const { credentials, scopes } = options;
+ const logger = options.logger || log_js_1.logger;
+ const tokenCyclerMap = new WeakMap();
+ return {
+ name: exports.auxiliaryAuthenticationHeaderPolicyName,
+ async sendRequest(request, next) {
+ if (!request.url.toLowerCase().startsWith("https://")) {
+ throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs.");
+ }
+ if (!credentials || credentials.length === 0) {
+ logger.info(`${exports.auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`);
+ return next(request);
+ }
+ const tokenPromises = [];
+ for (const credential of credentials) {
+ let getAccessToken = tokenCyclerMap.get(credential);
+ if (!getAccessToken) {
+ getAccessToken = (0, tokenCycler_js_1.createTokenCycler)(credential);
+ tokenCyclerMap.set(credential, getAccessToken);
+ }
+ tokenPromises.push(sendAuthorizeRequest({
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
+ request,
+ getAccessToken,
+ logger,
+ }));
+ }
+ const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token));
+ if (auxiliaryTokens.length === 0) {
+ logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`);
+ return next(request);
+ }
+ request.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", "));
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=auxiliaryAuthenticationHeaderPolicy.js.map
- response.socket.ws = this
- this[kByteParser] = parser
+/***/ }),
- // 1. Change the ready state to OPEN (1).
- this[kReadyState] = states.OPEN
+/***/ 26925:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 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')
+"use strict";
- if (extensions !== null) {
- this.#extensions = extensions
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.bearerTokenAuthenticationPolicyName = void 0;
+exports.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy;
+exports.parseChallenges = parseChallenges;
+const tokenCycler_js_1 = __nccwpck_require__(39202);
+const log_js_1 = __nccwpck_require__(80544);
+const restError_js_1 = __nccwpck_require__(8666);
+/**
+ * The programmatic identifier of the bearerTokenAuthenticationPolicy.
+ */
+exports.bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy";
+/**
+ * Try to send the given request.
+ *
+ * When a response is received, returns a tuple of the response received and, if the response was received
+ * inside a thrown RestError, the RestError that was thrown.
+ *
+ * Otherwise, if an error was thrown while sending the request that did not provide an underlying response, it
+ * will be rethrown.
+ */
+async function trySendRequest(request, next) {
+ try {
+ return [await next(request), undefined];
}
-
- // 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
+ catch (e) {
+ if ((0, restError_js_1.isRestError)(e) && e.response) {
+ return [e.response, e];
+ }
+ else {
+ throw e;
+ }
}
-
- // 4. Fire an event named open at the WebSocket object.
- fireEvent('open', this)
- }
-}
-
-// 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) {
- if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) {
- return webidl.converters['sequence'](V)
- }
-
- return webidl.converters.DOMString(V)
}
-
-// This implements the propsal made in https://github.com/whatwg/websockets/issues/42
-webidl.converters.WebSocketInit = webidl.dictionaryConverter([
- {
- key: 'protocols',
- converter: webidl.converters['DOMString or sequence'],
- get defaultValue () {
- return []
- }
- },
- {
- key: 'dispatcher',
- converter: (V) => V,
- get defaultValue () {
- return getGlobalDispatcher()
+/**
+ * Default authorize request handler
+ */
+async function defaultAuthorizeRequest(options) {
+ const { scopes, getAccessToken, request } = options;
+ // Enable CAE true by default
+ const getTokenOptions = {
+ abortSignal: request.abortSignal,
+ tracingOptions: request.tracingOptions,
+ enableCae: true,
+ };
+ const accessToken = await getAccessToken(scopes, getTokenOptions);
+ if (accessToken) {
+ options.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
}
- },
- {
- key: 'headers',
- converter: webidl.nullableConverter(webidl.converters.HeadersInit)
- }
-])
-
-webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) {
- if (webidl.util.Type(V) === '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) === 'Object') {
- if (isBlobLike(V)) {
- return webidl.converters.Blob(V, { strict: false })
+/**
+ * We will retrieve the challenge only if the response status code was 401,
+ * and if the response contained the header "WWW-Authenticate" with a non-empty value.
+ */
+function isChallengeResponse(response) {
+ return response.status === 401 && response.headers.has("WWW-Authenticate");
+}
+/**
+ * Re-authorize the request for CAE challenge.
+ * The response containing the challenge is `options.response`.
+ * If this method returns true, the underlying request will be sent once again.
+ */
+async function authorizeRequestOnCaeChallenge(onChallengeOptions, caeClaims) {
+ var _a;
+ const { scopes } = onChallengeOptions;
+ const accessToken = await onChallengeOptions.getAccessToken(scopes, {
+ enableCae: true,
+ claims: caeClaims,
+ });
+ if (!accessToken) {
+ return false;
}
-
- if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) {
- return webidl.converters.BufferSource(V)
+ onChallengeOptions.request.headers.set("Authorization", `${(_a = accessToken.tokenType) !== null && _a !== void 0 ? _a : "Bearer"} ${accessToken.token}`);
+ return true;
+}
+/**
+ * A policy that can request a token from a TokenCredential implementation and
+ * then apply it to the Authorization header of a request as a Bearer token.
+ */
+function bearerTokenAuthenticationPolicy(options) {
+ var _a, _b, _c;
+ const { credential, scopes, challengeCallbacks } = options;
+ const logger = options.logger || log_js_1.logger;
+ const callbacks = {
+ authorizeRequest: (_b = (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) === null || _a === void 0 ? void 0 : _a.bind(challengeCallbacks)) !== null && _b !== void 0 ? _b : defaultAuthorizeRequest,
+ authorizeRequestOnChallenge: (_c = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge) === null || _c === void 0 ? void 0 : _c.bind(challengeCallbacks),
+ };
+ // This function encapsulates the entire process of reliably retrieving the token
+ // The options are left out of the public API until there's demand to configure this.
+ // Remember to extend `BearerTokenAuthenticationPolicyOptions` with `TokenCyclerOptions`
+ // in order to pass through the `options` object.
+ const getAccessToken = credential
+ ? (0, tokenCycler_js_1.createTokenCycler)(credential /* , options */)
+ : () => Promise.resolve(null);
+ return {
+ name: exports.bearerTokenAuthenticationPolicyName,
+ /**
+ * If there's no challenge parameter:
+ * - It will try to retrieve the token using the cache, or the credential's getToken.
+ * - Then it will try the next policy with or without the retrieved token.
+ *
+ * It uses the challenge parameters to:
+ * - Skip a first attempt to get the token from the credential if there's no cached token,
+ * since it expects the token to be retrievable only after the challenge.
+ * - Prepare the outgoing request if the `prepareRequest` method has been provided.
+ * - Send an initial request to receive the challenge if it fails.
+ * - Process a challenge if the response contains it.
+ * - Retrieve a token with the challenge information, then re-send the request.
+ */
+ async sendRequest(request, next) {
+ if (!request.url.toLowerCase().startsWith("https://")) {
+ throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.");
+ }
+ await callbacks.authorizeRequest({
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
+ request,
+ getAccessToken,
+ logger,
+ });
+ let response;
+ let error;
+ let shouldSendRequest;
+ [response, error] = await trySendRequest(request, next);
+ if (isChallengeResponse(response)) {
+ let claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate"));
+ // Handle CAE by default when receive CAE claim
+ if (claims) {
+ let parsedClaim;
+ // Return the response immediately if claims is not a valid base64 encoded string
+ try {
+ parsedClaim = atob(claims);
+ }
+ catch (e) {
+ logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`);
+ return response;
+ }
+ shouldSendRequest = await authorizeRequestOnCaeChallenge({
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
+ response,
+ request,
+ getAccessToken,
+ logger,
+ }, parsedClaim);
+ // Send updated request and handle response for RestError
+ if (shouldSendRequest) {
+ [response, error] = await trySendRequest(request, next);
+ }
+ }
+ else if (callbacks.authorizeRequestOnChallenge) {
+ // Handle custom challenges when client provides custom callback
+ shouldSendRequest = await callbacks.authorizeRequestOnChallenge({
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
+ request,
+ response,
+ getAccessToken,
+ logger,
+ });
+ // Send updated request and handle response for RestError
+ if (shouldSendRequest) {
+ [response, error] = await trySendRequest(request, next);
+ }
+ // If we get another CAE Claim, we will handle it by default and return whatever value we receive for this
+ if (isChallengeResponse(response)) {
+ claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate"));
+ if (claims) {
+ let parsedClaim;
+ try {
+ parsedClaim = atob(claims);
+ }
+ catch (e) {
+ logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`);
+ return response;
+ }
+ shouldSendRequest = await authorizeRequestOnCaeChallenge({
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
+ response,
+ request,
+ getAccessToken,
+ logger,
+ }, parsedClaim);
+ // Send updated request and handle response for RestError
+ if (shouldSendRequest) {
+ [response, error] = await trySendRequest(request, next);
+ }
+ }
+ }
+ }
+ }
+ if (error) {
+ throw error;
+ }
+ else {
+ return response;
+ }
+ },
+ };
+}
+/**
+ * Converts: `Bearer a="b", c="d", Pop e="f", g="h"`.
+ * Into: `[ { scheme: 'Bearer', params: { a: 'b', c: 'd' } }, { scheme: 'Pop', params: { e: 'f', g: 'h' } } ]`.
+ *
+ * @internal
+ */
+function parseChallenges(challenges) {
+ // Challenge regex seperates the string to individual challenges with different schemes in the format `Scheme a="b", c=d`
+ // The challenge regex captures parameteres with either quotes values or unquoted values
+ const challengeRegex = /(\w+)\s+((?:\w+=(?:"[^"]*"|[^,]*),?\s*)+)/g;
+ // Parameter regex captures the claims group removed from the scheme in the format `a="b"` and `c="d"`
+ // CAE challenge always have quoted parameters. For more reference, https://learn.microsoft.com/entra/identity-platform/claims-challenge
+ const paramRegex = /(\w+)="([^"]*)"/g;
+ const parsedChallenges = [];
+ let match;
+ // Iterate over each challenge match
+ while ((match = challengeRegex.exec(challenges)) !== null) {
+ const scheme = match[1];
+ const paramsString = match[2];
+ const params = {};
+ let paramMatch;
+ // Iterate over each parameter match
+ while ((paramMatch = paramRegex.exec(paramsString)) !== null) {
+ params[paramMatch[1]] = paramMatch[2];
+ }
+ parsedChallenges.push({ scheme, params });
}
- }
-
- return webidl.converters.USVString(V)
+ return parsedChallenges;
}
-
-module.exports = {
- WebSocket
+/**
+ * Parse a pipeline response and look for a CAE challenge with "Bearer" scheme
+ * Return the value in the header without parsing the challenge
+ * @internal
+ */
+function getCaeChallengeClaims(challenges) {
+ var _a;
+ if (!challenges) {
+ return;
+ }
+ // Find all challenges present in the header
+ const parsedChallenges = parseChallenges(challenges);
+ return (_a = parsedChallenges.find((x) => x.scheme === "Bearer" && x.params.claims && x.params.error === "insufficient_claims")) === null || _a === void 0 ? void 0 : _a.params.claims;
}
-
+//# sourceMappingURL=bearerTokenAuthenticationPolicy.js.map
/***/ }),
-/***/ 7723:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-var v1 = __nccwpck_require__(6626);
-var v4 = __nccwpck_require__(9021);
-
-var uuid = v4;
-uuid.v1 = v1;
-uuid.v4 = v4;
-
-module.exports = uuid;
-
-
-/***/ }),
+/***/ 39295:
+/***/ ((__unused_webpack_module, exports) => {
-/***/ 8682:
-/***/ ((module) => {
+"use strict";
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.decompressResponsePolicyName = void 0;
+exports.decompressResponsePolicy = decompressResponsePolicy;
/**
- * Convert array of 16 byte values to UUID string format of the form:
- * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
+ * The programmatic identifier of the decompressResponsePolicy.
*/
-var byteToHex = [];
-for (var i = 0; i < 256; ++i) {
- byteToHex[i] = (i + 0x100).toString(16).substr(1);
-}
-
-function bytesToUuid(buf, offset) {
- var i = offset || 0;
- var bth = byteToHex;
- // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
- return ([
- bth[buf[i++]], bth[buf[i++]],
- bth[buf[i++]], bth[buf[i++]], '-',
- bth[buf[i++]], bth[buf[i++]], '-',
- bth[buf[i++]], bth[buf[i++]], '-',
- bth[buf[i++]], bth[buf[i++]], '-',
- bth[buf[i++]], bth[buf[i++]],
- bth[buf[i++]], bth[buf[i++]],
- bth[buf[i++]], bth[buf[i++]]
- ]).join('');
+exports.decompressResponsePolicyName = "decompressResponsePolicy";
+/**
+ * A policy to enable response decompression according to Accept-Encoding header
+ * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding
+ */
+function decompressResponsePolicy() {
+ return {
+ name: exports.decompressResponsePolicyName,
+ async sendRequest(request, next) {
+ // HEAD requests have no body
+ if (request.method !== "HEAD") {
+ request.headers.set("Accept-Encoding", "gzip,deflate");
+ }
+ return next(request);
+ },
+ };
}
-
-module.exports = bytesToUuid;
-
+//# sourceMappingURL=decompressResponsePolicy.js.map
/***/ }),
-/***/ 1694:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-// Unique ID creation requires a high quality random # generator. In node.js
-// this is pretty straight-forward - we use the crypto API.
-
-var crypto = __nccwpck_require__(6982);
+/***/ 48170:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-module.exports = function nodeRNG() {
- return crypto.randomBytes(16);
-};
+"use strict";
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.defaultRetryPolicyName = void 0;
+exports.defaultRetryPolicy = defaultRetryPolicy;
+const exponentialRetryStrategy_js_1 = __nccwpck_require__(50002);
+const throttlingRetryStrategy_js_1 = __nccwpck_require__(97084);
+const retryPolicy_js_1 = __nccwpck_require__(56085);
+const constants_js_1 = __nccwpck_require__(66427);
+/**
+ * Name of the {@link defaultRetryPolicy}
+ */
+exports.defaultRetryPolicyName = "defaultRetryPolicy";
+/**
+ * A policy that retries according to three strategies:
+ * - When the server sends a 429 response with a Retry-After header.
+ * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
+ * - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay.
+ */
+function defaultRetryPolicy(options = {}) {
+ var _a;
+ return {
+ name: exports.defaultRetryPolicyName,
+ sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)(), (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(options)], {
+ maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT,
+ }).sendRequest,
+ };
+}
+//# sourceMappingURL=defaultRetryPolicy.js.map
/***/ }),
-/***/ 6626:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-var rng = __nccwpck_require__(1694);
-var bytesToUuid = __nccwpck_require__(8682);
+/***/ 16708:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// **`v1()` - Generate time-based UUID**
-//
-// Inspired by https://github.com/LiosK/UUID.js
-// and http://docs.python.org/library/uuid.html
+"use strict";
-var _nodeId;
-var _clockseq;
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.exponentialRetryPolicyName = void 0;
+exports.exponentialRetryPolicy = exponentialRetryPolicy;
+const exponentialRetryStrategy_js_1 = __nccwpck_require__(50002);
+const retryPolicy_js_1 = __nccwpck_require__(56085);
+const constants_js_1 = __nccwpck_require__(66427);
+/**
+ * The programmatic identifier of the exponentialRetryPolicy.
+ */
+exports.exponentialRetryPolicyName = "exponentialRetryPolicy";
+/**
+ * A policy that attempts to retry requests while introducing an exponentially increasing delay.
+ * @param options - Options that configure retry logic.
+ */
+function exponentialRetryPolicy(options = {}) {
+ var _a;
+ return (0, retryPolicy_js_1.retryPolicy)([
+ (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreSystemErrors: true })),
+ ], {
+ maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT,
+ });
+}
+//# sourceMappingURL=exponentialRetryPolicy.js.map
-// Previous uuid creation time
-var _lastMSecs = 0;
-var _lastNSecs = 0;
+/***/ }),
-// See https://github.com/uuidjs/uuid for API details
-function v1(options, buf, offset) {
- var i = buf && offset || 0;
- var b = buf || [];
+/***/ 75497:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- options = options || {};
- var node = options.node || _nodeId;
- var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
+"use strict";
- // node and clockseq need to be initialized to random values if they're not
- // specified. We do this lazily to minimize issues related to insufficient
- // system entropy. See #189
- if (node == null || clockseq == null) {
- var seedBytes = rng();
- if (node == null) {
- // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
- node = _nodeId = [
- seedBytes[0] | 0x01,
- seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
- ];
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.formDataPolicyName = void 0;
+exports.formDataPolicy = formDataPolicy;
+const core_util_1 = __nccwpck_require__(87779);
+const httpHeaders_js_1 = __nccwpck_require__(192);
+/**
+ * The programmatic identifier of the formDataPolicy.
+ */
+exports.formDataPolicyName = "formDataPolicy";
+function formDataToFormDataMap(formData) {
+ var _a;
+ const formDataMap = {};
+ for (const [key, value] of formData.entries()) {
+ (_a = formDataMap[key]) !== null && _a !== void 0 ? _a : (formDataMap[key] = []);
+ formDataMap[key].push(value);
}
- if (clockseq == null) {
- // Per 4.2.2, randomize (14 bit) clockseq
- clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
+ return formDataMap;
+}
+/**
+ * A policy that encodes FormData on the request into the body.
+ */
+function formDataPolicy() {
+ return {
+ name: exports.formDataPolicyName,
+ async sendRequest(request, next) {
+ if (core_util_1.isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) {
+ request.formData = formDataToFormDataMap(request.body);
+ request.body = undefined;
+ }
+ if (request.formData) {
+ const contentType = request.headers.get("Content-Type");
+ if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) {
+ request.body = wwwFormUrlEncode(request.formData);
+ }
+ else {
+ await prepareFormData(request.formData, request);
+ }
+ request.formData = undefined;
+ }
+ return next(request);
+ },
+ };
+}
+function wwwFormUrlEncode(formData) {
+ const urlSearchParams = new URLSearchParams();
+ for (const [key, value] of Object.entries(formData)) {
+ if (Array.isArray(value)) {
+ for (const subValue of value) {
+ urlSearchParams.append(key, subValue.toString());
+ }
+ }
+ else {
+ urlSearchParams.append(key, value.toString());
+ }
}
- }
-
- // UUID timestamps are 100 nano-second units since the Gregorian epoch,
- // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
- // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
- // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
- var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
-
- // Per 4.2.1.2, use count of uuid's generated during the current clock
- // cycle to simulate higher resolution clock
- var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
-
- // Time since last uuid creation (in msecs)
- var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
-
- // Per 4.2.1.2, Bump clockseq on clock regression
- if (dt < 0 && options.clockseq === undefined) {
- clockseq = clockseq + 1 & 0x3fff;
- }
-
- // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
- // time interval
- if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
- nsecs = 0;
- }
-
- // Per 4.2.1.2 Throw error if too many uuids are requested
- if (nsecs >= 10000) {
- throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
- }
-
- _lastMSecs = msecs;
- _lastNSecs = nsecs;
- _clockseq = clockseq;
-
- // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
- msecs += 12219292800000;
-
- // `time_low`
- var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
- b[i++] = tl >>> 24 & 0xff;
- b[i++] = tl >>> 16 & 0xff;
- b[i++] = tl >>> 8 & 0xff;
- b[i++] = tl & 0xff;
-
- // `time_mid`
- var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
- b[i++] = tmh >>> 8 & 0xff;
- b[i++] = tmh & 0xff;
-
- // `time_high_and_version`
- b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
- b[i++] = tmh >>> 16 & 0xff;
-
- // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
- b[i++] = clockseq >>> 8 | 0x80;
-
- // `clock_seq_low`
- b[i++] = clockseq & 0xff;
-
- // `node`
- for (var n = 0; n < 6; ++n) {
- b[i + n] = node[n];
- }
-
- return buf ? buf : bytesToUuid(b);
+ return urlSearchParams.toString();
}
-
-module.exports = v1;
-
-
-/***/ }),
-
-/***/ 9021:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-var rng = __nccwpck_require__(1694);
-var bytesToUuid = __nccwpck_require__(8682);
-
-function v4(options, buf, offset) {
- var i = buf && offset || 0;
-
- if (typeof(options) == 'string') {
- buf = options === 'binary' ? new Array(16) : null;
- options = null;
- }
- options = options || {};
-
- var rnds = options.random || (options.rng || rng)();
-
- // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
- rnds[6] = (rnds[6] & 0x0f) | 0x40;
- rnds[8] = (rnds[8] & 0x3f) | 0x80;
-
- // Copy bytes to buffer, if provided
- if (buf) {
- for (var ii = 0; ii < 16; ++ii) {
- buf[i + ii] = rnds[ii];
+async function prepareFormData(formData, request) {
+ // validate content type (multipart/form-data)
+ const contentType = request.headers.get("Content-Type");
+ if (contentType && !contentType.startsWith("multipart/form-data")) {
+ // content type is specified and is not multipart/form-data. Exit.
+ return;
}
- }
-
- return buf || bytesToUuid(rnds);
+ request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data");
+ // set body to MultipartRequestBody using content from FormDataMap
+ const parts = [];
+ for (const [fieldName, values] of Object.entries(formData)) {
+ for (const value of Array.isArray(values) ? values : [values]) {
+ if (typeof value === "string") {
+ parts.push({
+ headers: (0, httpHeaders_js_1.createHttpHeaders)({
+ "Content-Disposition": `form-data; name="${fieldName}"`,
+ }),
+ body: (0, core_util_1.stringToUint8Array)(value, "utf-8"),
+ });
+ }
+ else if (value === undefined || value === null || typeof value !== "object") {
+ throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`);
+ }
+ else {
+ // using || instead of ?? here since if value.name is empty we should create a file name
+ const fileName = value.name || "blob";
+ const headers = (0, httpHeaders_js_1.createHttpHeaders)();
+ headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`);
+ // again, || is used since an empty value.type means the content type is unset
+ headers.set("Content-Type", value.type || "application/octet-stream");
+ parts.push({
+ headers,
+ body: value,
+ });
+ }
+ }
+ }
+ request.multipartBody = { parts };
}
-
-module.exports = v4;
-
+//# sourceMappingURL=formDataPolicy.js.map
/***/ }),
-/***/ 75:
-/***/ ((module) => {
+/***/ 53253:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-module.exports = eval("require")("supports-color");
+"use strict";
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.logPolicyName = void 0;
+exports.logPolicy = logPolicy;
+const log_js_1 = __nccwpck_require__(80544);
+const sanitizer_js_1 = __nccwpck_require__(35204);
+/**
+ * The programmatic identifier of the logPolicy.
+ */
+exports.logPolicyName = "logPolicy";
+/**
+ * A policy that logs all requests and responses.
+ * @param options - Options to configure logPolicy.
+ */
+function logPolicy(options = {}) {
+ var _a;
+ const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info;
+ const sanitizer = new sanitizer_js_1.Sanitizer({
+ additionalAllowedHeaderNames: options.additionalAllowedHeaderNames,
+ additionalAllowedQueryParameters: options.additionalAllowedQueryParameters,
+ });
+ return {
+ name: exports.logPolicyName,
+ async sendRequest(request, next) {
+ if (!logger.enabled) {
+ return next(request);
+ }
+ logger(`Request: ${sanitizer.sanitize(request)}`);
+ const response = await next(request);
+ logger(`Response status code: ${response.status}`);
+ logger(`Headers: ${sanitizer.sanitize(response.headers)}`);
+ return response;
+ },
+ };
+}
+//# sourceMappingURL=logPolicy.js.map
/***/ }),
-/***/ 2613:
-/***/ ((module) => {
+/***/ 45807:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-module.exports = require("assert");
-
-/***/ }),
-
-/***/ 290:
-/***/ ((module) => {
-"use strict";
-module.exports = require("async_hooks");
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.multipartPolicyName = void 0;
+exports.multipartPolicy = multipartPolicy;
+const core_util_1 = __nccwpck_require__(87779);
+const concat_js_1 = __nccwpck_require__(62471);
+const typeGuards_js_1 = __nccwpck_require__(22621);
+function generateBoundary() {
+ return `----AzSDKFormBoundary${(0, core_util_1.randomUUID)()}`;
+}
+function encodeHeaders(headers) {
+ let result = "";
+ for (const [key, value] of headers) {
+ result += `${key}: ${value}\r\n`;
+ }
+ return result;
+}
+function getLength(source) {
+ if (source instanceof Uint8Array) {
+ return source.byteLength;
+ }
+ else if ((0, typeGuards_js_1.isBlob)(source)) {
+ // if was created using createFile then -1 means we have an unknown size
+ return source.size === -1 ? undefined : source.size;
+ }
+ else {
+ return undefined;
+ }
+}
+function getTotalLength(sources) {
+ let total = 0;
+ for (const source of sources) {
+ const partLength = getLength(source);
+ if (partLength === undefined) {
+ return undefined;
+ }
+ else {
+ total += partLength;
+ }
+ }
+ return total;
+}
+async function buildRequestBody(request, parts, boundary) {
+ const sources = [
+ (0, core_util_1.stringToUint8Array)(`--${boundary}`, "utf-8"),
+ ...parts.flatMap((part) => [
+ (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"),
+ (0, core_util_1.stringToUint8Array)(encodeHeaders(part.headers), "utf-8"),
+ (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"),
+ part.body,
+ (0, core_util_1.stringToUint8Array)(`\r\n--${boundary}`, "utf-8"),
+ ]),
+ (0, core_util_1.stringToUint8Array)("--\r\n\r\n", "utf-8"),
+ ];
+ const contentLength = getTotalLength(sources);
+ if (contentLength) {
+ request.headers.set("Content-Length", contentLength);
+ }
+ request.body = await (0, concat_js_1.concat)(sources);
+}
+/**
+ * Name of multipart policy
+ */
+exports.multipartPolicyName = "multipartPolicy";
+const maxBoundaryLength = 70;
+const validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`);
+function assertValidBoundary(boundary) {
+ if (boundary.length > maxBoundaryLength) {
+ throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`);
+ }
+ if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) {
+ throw new Error(`Multipart boundary "${boundary}" contains invalid characters`);
+ }
+}
+/**
+ * Pipeline policy for multipart requests
+ */
+function multipartPolicy() {
+ return {
+ name: exports.multipartPolicyName,
+ async sendRequest(request, next) {
+ var _a;
+ if (!request.multipartBody) {
+ return next(request);
+ }
+ if (request.body) {
+ throw new Error("multipartBody and regular body cannot be set at the same time");
+ }
+ let boundary = request.multipartBody.boundary;
+ const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed";
+ const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/);
+ if (!parsedHeader) {
+ throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`);
+ }
+ const [, contentType, parsedBoundary] = parsedHeader;
+ if (parsedBoundary && boundary && parsedBoundary !== boundary) {
+ throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`);
+ }
+ boundary !== null && boundary !== void 0 ? boundary : (boundary = parsedBoundary);
+ if (boundary) {
+ assertValidBoundary(boundary);
+ }
+ else {
+ boundary = generateBoundary();
+ }
+ request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`);
+ await buildRequestBody(request, request.multipartBody.parts, boundary);
+ request.multipartBody = undefined;
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=multipartPolicy.js.map
/***/ }),
-/***/ 181:
-/***/ ((module) => {
+/***/ 36827:
+/***/ ((__unused_webpack_module, exports) => {
"use strict";
-module.exports = require("buffer");
-
-/***/ }),
-
-/***/ 5317:
-/***/ ((module) => {
-"use strict";
-module.exports = require("child_process");
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ndJsonPolicyName = void 0;
+exports.ndJsonPolicy = ndJsonPolicy;
+/**
+ * The programmatic identifier of the ndJsonPolicy.
+ */
+exports.ndJsonPolicyName = "ndJsonPolicy";
+/**
+ * ndJsonPolicy is a policy used to control keep alive settings for every request.
+ */
+function ndJsonPolicy() {
+ return {
+ name: exports.ndJsonPolicyName,
+ async sendRequest(request, next) {
+ // There currently isn't a good way to bypass the serializer
+ if (typeof request.body === "string" && request.body.startsWith("[")) {
+ const body = JSON.parse(request.body);
+ if (Array.isArray(body)) {
+ request.body = body.map((item) => JSON.stringify(item) + "\n").join("");
+ }
+ }
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=ndJsonPolicy.js.map
/***/ }),
-/***/ 4236:
-/***/ ((module) => {
+/***/ 32815:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-module.exports = require("console");
-
-/***/ }),
-
-/***/ 6982:
-/***/ ((module) => {
-"use strict";
-module.exports = require("crypto");
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.globalNoProxyList = exports.proxyPolicyName = void 0;
+exports.loadNoProxy = loadNoProxy;
+exports.getDefaultProxySettings = getDefaultProxySettings;
+exports.proxyPolicy = proxyPolicy;
+const https_proxy_agent_1 = __nccwpck_require__(3669);
+const http_proxy_agent_1 = __nccwpck_require__(81970);
+const log_js_1 = __nccwpck_require__(80544);
+const HTTPS_PROXY = "HTTPS_PROXY";
+const HTTP_PROXY = "HTTP_PROXY";
+const ALL_PROXY = "ALL_PROXY";
+const NO_PROXY = "NO_PROXY";
+/**
+ * The programmatic identifier of the proxyPolicy.
+ */
+exports.proxyPolicyName = "proxyPolicy";
+/**
+ * Stores the patterns specified in NO_PROXY environment variable.
+ * @internal
+ */
+exports.globalNoProxyList = [];
+let noProxyListLoaded = false;
+/** A cache of whether a host should bypass the proxy. */
+const globalBypassedMap = new Map();
+function getEnvironmentValue(name) {
+ if (process.env[name]) {
+ return process.env[name];
+ }
+ else if (process.env[name.toLowerCase()]) {
+ return process.env[name.toLowerCase()];
+ }
+ return undefined;
+}
+function loadEnvironmentProxyValue() {
+ if (!process) {
+ return undefined;
+ }
+ const httpsProxy = getEnvironmentValue(HTTPS_PROXY);
+ const allProxy = getEnvironmentValue(ALL_PROXY);
+ const httpProxy = getEnvironmentValue(HTTP_PROXY);
+ return httpsProxy || allProxy || httpProxy;
+}
+/**
+ * Check whether the host of a given `uri` matches any pattern in the no proxy list.
+ * If there's a match, any request sent to the same host shouldn't have the proxy settings set.
+ * This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210
+ */
+function isBypassed(uri, noProxyList, bypassedMap) {
+ if (noProxyList.length === 0) {
+ return false;
+ }
+ const host = new URL(uri).hostname;
+ if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) {
+ return bypassedMap.get(host);
+ }
+ let isBypassedFlag = false;
+ for (const pattern of noProxyList) {
+ if (pattern[0] === ".") {
+ // This should match either domain it self or any subdomain or host
+ // .foo.com will match foo.com it self or *.foo.com
+ if (host.endsWith(pattern)) {
+ isBypassedFlag = true;
+ }
+ else {
+ if (host.length === pattern.length - 1 && host === pattern.slice(1)) {
+ isBypassedFlag = true;
+ }
+ }
+ }
+ else {
+ if (host === pattern) {
+ isBypassedFlag = true;
+ }
+ }
+ }
+ bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag);
+ return isBypassedFlag;
+}
+function loadNoProxy() {
+ const noProxy = getEnvironmentValue(NO_PROXY);
+ noProxyListLoaded = true;
+ if (noProxy) {
+ return noProxy
+ .split(",")
+ .map((item) => item.trim())
+ .filter((item) => item.length);
+ }
+ return [];
+}
+/**
+ * This method converts a proxy url into `ProxySettings` for use with ProxyPolicy.
+ * If no argument is given, it attempts to parse a proxy URL from the environment
+ * variables `HTTPS_PROXY` or `HTTP_PROXY`.
+ * @param proxyUrl - The url of the proxy to use. May contain authentication information.
+ * @deprecated - Internally this method is no longer necessary when setting proxy information.
+ */
+function getDefaultProxySettings(proxyUrl) {
+ if (!proxyUrl) {
+ proxyUrl = loadEnvironmentProxyValue();
+ if (!proxyUrl) {
+ return undefined;
+ }
+ }
+ const parsedUrl = new URL(proxyUrl);
+ const schema = parsedUrl.protocol ? parsedUrl.protocol + "//" : "";
+ return {
+ host: schema + parsedUrl.hostname,
+ port: Number.parseInt(parsedUrl.port || "80"),
+ username: parsedUrl.username,
+ password: parsedUrl.password,
+ };
+}
+/**
+ * This method attempts to parse a proxy URL from the environment
+ * variables `HTTPS_PROXY` or `HTTP_PROXY`.
+ */
+function getDefaultProxySettingsInternal() {
+ const envProxy = loadEnvironmentProxyValue();
+ return envProxy ? new URL(envProxy) : undefined;
+}
+function getUrlFromProxySettings(settings) {
+ let parsedProxyUrl;
+ try {
+ parsedProxyUrl = new URL(settings.host);
+ }
+ catch (_a) {
+ throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`);
+ }
+ parsedProxyUrl.port = String(settings.port);
+ if (settings.username) {
+ parsedProxyUrl.username = settings.username;
+ }
+ if (settings.password) {
+ parsedProxyUrl.password = settings.password;
+ }
+ return parsedProxyUrl;
+}
+function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) {
+ // Custom Agent should take precedence so if one is present
+ // we should skip to avoid overwriting it.
+ if (request.agent) {
+ return;
+ }
+ const url = new URL(request.url);
+ const isInsecure = url.protocol !== "https:";
+ if (request.tlsSettings) {
+ log_js_1.logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored.");
+ }
+ const headers = request.headers.toJSON();
+ if (isInsecure) {
+ if (!cachedAgents.httpProxyAgent) {
+ cachedAgents.httpProxyAgent = new http_proxy_agent_1.HttpProxyAgent(proxyUrl, { headers });
+ }
+ request.agent = cachedAgents.httpProxyAgent;
+ }
+ else {
+ if (!cachedAgents.httpsProxyAgent) {
+ cachedAgents.httpsProxyAgent = new https_proxy_agent_1.HttpsProxyAgent(proxyUrl, { headers });
+ }
+ request.agent = cachedAgents.httpsProxyAgent;
+ }
+}
+/**
+ * A policy that allows one to apply proxy settings to all requests.
+ * If not passed static settings, they will be retrieved from the HTTPS_PROXY
+ * or HTTP_PROXY environment variables.
+ * @param proxySettings - ProxySettings to use on each request.
+ * @param options - additional settings, for example, custom NO_PROXY patterns
+ */
+function proxyPolicy(proxySettings, options) {
+ if (!noProxyListLoaded) {
+ exports.globalNoProxyList.push(...loadNoProxy());
+ }
+ const defaultProxy = proxySettings
+ ? getUrlFromProxySettings(proxySettings)
+ : getDefaultProxySettingsInternal();
+ const cachedAgents = {};
+ return {
+ name: exports.proxyPolicyName,
+ async sendRequest(request, next) {
+ var _a;
+ if (!request.proxySettings &&
+ defaultProxy &&
+ !isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : exports.globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? undefined : globalBypassedMap)) {
+ setProxyAgentOnRequest(request, cachedAgents, defaultProxy);
+ }
+ else if (request.proxySettings) {
+ setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings));
+ }
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=proxyPolicy.js.map
/***/ }),
-/***/ 1637:
-/***/ ((module) => {
+/***/ 64087:
+/***/ ((__unused_webpack_module, exports) => {
"use strict";
-module.exports = require("diagnostics_channel");
-
-/***/ }),
-
-/***/ 4434:
-/***/ ((module) => {
-"use strict";
-module.exports = require("events");
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.redirectPolicyName = void 0;
+exports.redirectPolicy = redirectPolicy;
+/**
+ * The programmatic identifier of the redirectPolicy.
+ */
+exports.redirectPolicyName = "redirectPolicy";
+/**
+ * Methods that are allowed to follow redirects 301 and 302
+ */
+const allowedRedirect = ["GET", "HEAD"];
+/**
+ * A policy to follow Location headers from the server in order
+ * to support server-side redirection.
+ * In the browser, this policy is not used.
+ * @param options - Options to control policy behavior.
+ */
+function redirectPolicy(options = {}) {
+ const { maxRetries = 20 } = options;
+ return {
+ name: exports.redirectPolicyName,
+ async sendRequest(request, next) {
+ const response = await next(request);
+ return handleRedirect(next, response, maxRetries);
+ },
+ };
+}
+async function handleRedirect(next, response, maxRetries, currentRetries = 0) {
+ const { request, status, headers } = response;
+ const locationHeader = headers.get("location");
+ if (locationHeader &&
+ (status === 300 ||
+ (status === 301 && allowedRedirect.includes(request.method)) ||
+ (status === 302 && allowedRedirect.includes(request.method)) ||
+ (status === 303 && request.method === "POST") ||
+ status === 307) &&
+ currentRetries < maxRetries) {
+ const url = new URL(locationHeader, request.url);
+ request.url = url.toString();
+ // POST request with Status code 303 should be converted into a
+ // redirected GET request if the redirect url is present in the location header
+ if (status === 303) {
+ request.method = "GET";
+ request.headers.delete("Content-Length");
+ delete request.body;
+ }
+ request.headers.delete("Authorization");
+ const res = await next(request);
+ return handleRedirect(next, res, maxRetries, currentRetries + 1);
+ }
+ return response;
+}
+//# sourceMappingURL=redirectPolicy.js.map
/***/ }),
-/***/ 9896:
-/***/ ((module) => {
+/***/ 56085:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-module.exports = require("fs");
-
-/***/ }),
-
-/***/ 1943:
-/***/ ((module) => {
-"use strict";
-module.exports = require("fs/promises");
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.retryPolicy = retryPolicy;
+const helpers_js_1 = __nccwpck_require__(653);
+const logger_1 = __nccwpck_require__(26515);
+const abort_controller_1 = __nccwpck_require__(93287);
+const constants_js_1 = __nccwpck_require__(66427);
+const retryPolicyLogger = (0, logger_1.createClientLogger)("core-rest-pipeline retryPolicy");
+/**
+ * The programmatic identifier of the retryPolicy.
+ */
+const retryPolicyName = "retryPolicy";
+/**
+ * retryPolicy is a generic policy to enable retrying requests when certain conditions are met
+ */
+function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_RETRY_POLICY_COUNT }) {
+ const logger = options.logger || retryPolicyLogger;
+ return {
+ name: retryPolicyName,
+ async sendRequest(request, next) {
+ var _a, _b;
+ let response;
+ let responseError;
+ let retryCount = -1;
+ // eslint-disable-next-line no-constant-condition
+ retryRequest: while (true) {
+ retryCount += 1;
+ response = undefined;
+ responseError = undefined;
+ try {
+ logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId);
+ response = await next(request);
+ logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId);
+ }
+ catch (e) {
+ logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId);
+ // RestErrors are valid targets for the retry strategies.
+ // If none of the retry strategies can work with them, they will be thrown later in this policy.
+ // If the received error is not a RestError, it is immediately thrown.
+ responseError = e;
+ if (!e || responseError.name !== "RestError") {
+ throw e;
+ }
+ response = responseError.response;
+ }
+ if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) {
+ logger.error(`Retry ${retryCount}: Request aborted.`);
+ const abortError = new abort_controller_1.AbortError();
+ throw abortError;
+ }
+ if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : constants_js_1.DEFAULT_RETRY_POLICY_COUNT)) {
+ logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`);
+ if (responseError) {
+ throw responseError;
+ }
+ else if (response) {
+ return response;
+ }
+ else {
+ throw new Error("Maximum retries reached with no response or error to throw");
+ }
+ }
+ logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`);
+ strategiesLoop: for (const strategy of strategies) {
+ const strategyLogger = strategy.logger || retryPolicyLogger;
+ strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`);
+ const modifiers = strategy.retry({
+ retryCount,
+ response,
+ responseError,
+ });
+ if (modifiers.skipStrategy) {
+ strategyLogger.info(`Retry ${retryCount}: Skipped.`);
+ continue strategiesLoop;
+ }
+ const { errorToThrow, retryAfterInMs, redirectTo } = modifiers;
+ if (errorToThrow) {
+ strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow);
+ throw errorToThrow;
+ }
+ if (retryAfterInMs || retryAfterInMs === 0) {
+ strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`);
+ await (0, helpers_js_1.delay)(retryAfterInMs, undefined, { abortSignal: request.abortSignal });
+ continue retryRequest;
+ }
+ if (redirectTo) {
+ strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`);
+ request.url = redirectTo;
+ continue retryRequest;
+ }
+ }
+ if (responseError) {
+ logger.info(`None of the retry strategies could work with the received error. Throwing it.`);
+ throw responseError;
+ }
+ if (response) {
+ logger.info(`None of the retry strategies could work with the received response. Returning it.`);
+ return response;
+ }
+ // If all the retries skip and there's no response,
+ // we're still in the retry loop, so a new request will be sent
+ // until `maxRetries` is reached.
+ }
+ },
+ };
+}
+//# sourceMappingURL=retryPolicy.js.map
/***/ }),
-/***/ 8611:
-/***/ ((module) => {
+/***/ 95686:
+/***/ ((__unused_webpack_module, exports) => {
"use strict";
-module.exports = require("http");
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.setClientRequestIdPolicyName = void 0;
+exports.setClientRequestIdPolicy = setClientRequestIdPolicy;
+/**
+ * The programmatic identifier of the setClientRequestIdPolicy.
+ */
+exports.setClientRequestIdPolicyName = "setClientRequestIdPolicy";
+/**
+ * Each PipelineRequest gets a unique id upon creation.
+ * This policy passes that unique id along via an HTTP header to enable better
+ * telemetry and tracing.
+ * @param requestIdHeaderName - The name of the header to pass the request ID to.
+ */
+function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") {
+ return {
+ name: exports.setClientRequestIdPolicyName,
+ async sendRequest(request, next) {
+ if (!request.headers.has(requestIdHeaderName)) {
+ request.headers.set(requestIdHeaderName, request.requestId);
+ }
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=setClientRequestIdPolicy.js.map
/***/ }),
-/***/ 5675:
-/***/ ((module) => {
+/***/ 96518:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-module.exports = require("http2");
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.systemErrorRetryPolicyName = void 0;
+exports.systemErrorRetryPolicy = systemErrorRetryPolicy;
+const exponentialRetryStrategy_js_1 = __nccwpck_require__(50002);
+const retryPolicy_js_1 = __nccwpck_require__(56085);
+const constants_js_1 = __nccwpck_require__(66427);
+/**
+ * Name of the {@link systemErrorRetryPolicy}
+ */
+exports.systemErrorRetryPolicyName = "systemErrorRetryPolicy";
+/**
+ * A retry policy that specifically seeks to handle errors in the
+ * underlying transport layer (e.g. DNS lookup failures) rather than
+ * retryable error codes from the server itself.
+ * @param options - Options that customize the policy.
+ */
+function systemErrorRetryPolicy(options = {}) {
+ var _a;
+ return {
+ name: exports.systemErrorRetryPolicyName,
+ sendRequest: (0, retryPolicy_js_1.retryPolicy)([
+ (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreHttpStatusCodes: true })),
+ ], {
+ maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT,
+ }).sendRequest,
+ };
+}
+//# sourceMappingURL=systemErrorRetryPolicy.js.map
/***/ }),
-/***/ 5692:
-/***/ ((module) => {
+/***/ 97540:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-module.exports = require("https");
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.throttlingRetryPolicyName = void 0;
+exports.throttlingRetryPolicy = throttlingRetryPolicy;
+const throttlingRetryStrategy_js_1 = __nccwpck_require__(97084);
+const retryPolicy_js_1 = __nccwpck_require__(56085);
+const constants_js_1 = __nccwpck_require__(66427);
+/**
+ * Name of the {@link throttlingRetryPolicy}
+ */
+exports.throttlingRetryPolicyName = "throttlingRetryPolicy";
+/**
+ * A policy that retries when the server sends a 429 response with a Retry-After header.
+ *
+ * To learn more, please refer to
+ * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits,
+ * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and
+ * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors
+ *
+ * @param options - Options that configure retry logic.
+ */
+function throttlingRetryPolicy(options = {}) {
+ var _a;
+ return {
+ name: exports.throttlingRetryPolicyName,
+ sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)()], {
+ maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT,
+ }).sendRequest,
+ };
+}
+//# sourceMappingURL=throttlingRetryPolicy.js.map
/***/ }),
-/***/ 9278:
-/***/ ((module) => {
+/***/ 75798:
+/***/ ((__unused_webpack_module, exports) => {
"use strict";
-module.exports = require("net");
-
-/***/ }),
-
-/***/ 8474:
-/***/ ((module) => {
-"use strict";
-module.exports = require("node:events");
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.tlsPolicyName = void 0;
+exports.tlsPolicy = tlsPolicy;
+/**
+ * Name of the TLS Policy
+ */
+exports.tlsPolicyName = "tlsPolicy";
+/**
+ * Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication.
+ */
+function tlsPolicy(tlsSettings) {
+ return {
+ name: exports.tlsPolicyName,
+ sendRequest: async (req, next) => {
+ // Users may define a request tlsSettings, honor those over the client level one
+ if (!req.tlsSettings) {
+ req.tlsSettings = tlsSettings;
+ }
+ return next(req);
+ },
+ };
+}
+//# sourceMappingURL=tlsPolicy.js.map
/***/ }),
-/***/ 7067:
-/***/ ((module) => {
+/***/ 93237:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-module.exports = require("node:http");
-
-/***/ }),
-/***/ 4708:
-/***/ ((module) => {
-
-"use strict";
-module.exports = require("node:https");
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.tracingPolicyName = void 0;
+exports.tracingPolicy = tracingPolicy;
+const core_tracing_1 = __nccwpck_require__(20623);
+const constants_js_1 = __nccwpck_require__(66427);
+const userAgent_js_1 = __nccwpck_require__(28431);
+const log_js_1 = __nccwpck_require__(80544);
+const core_util_1 = __nccwpck_require__(87779);
+const restError_js_1 = __nccwpck_require__(8666);
+const sanitizer_js_1 = __nccwpck_require__(35204);
+/**
+ * The programmatic identifier of the tracingPolicy.
+ */
+exports.tracingPolicyName = "tracingPolicy";
+/**
+ * A simple policy to create OpenTelemetry Spans for each request made by the pipeline
+ * that has SpanOptions with a parent.
+ * Requests made without a parent Span will not be recorded.
+ * @param options - Options to configure the telemetry logged by the tracing policy.
+ */
+function tracingPolicy(options = {}) {
+ const userAgentPromise = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix);
+ const sanitizer = new sanitizer_js_1.Sanitizer({
+ additionalAllowedQueryParameters: options.additionalAllowedQueryParameters,
+ });
+ const tracingClient = tryCreateTracingClient();
+ return {
+ name: exports.tracingPolicyName,
+ async sendRequest(request, next) {
+ var _a;
+ if (!tracingClient) {
+ return next(request);
+ }
+ const userAgent = await userAgentPromise;
+ const spanAttributes = {
+ "http.url": sanitizer.sanitizeUrl(request.url),
+ "http.method": request.method,
+ "http.user_agent": userAgent,
+ requestId: request.requestId,
+ };
+ if (userAgent) {
+ spanAttributes["http.user_agent"] = userAgent;
+ }
+ const { span, tracingContext } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {};
+ if (!span || !tracingContext) {
+ return next(request);
+ }
+ try {
+ const response = await tracingClient.withContext(tracingContext, next, request);
+ tryProcessResponse(span, response);
+ return response;
+ }
+ catch (err) {
+ tryProcessError(span, err);
+ throw err;
+ }
+ },
+ };
+}
+function tryCreateTracingClient() {
+ try {
+ return (0, core_tracing_1.createTracingClient)({
+ namespace: "",
+ packageName: "@azure/core-rest-pipeline",
+ packageVersion: constants_js_1.SDK_VERSION,
+ });
+ }
+ catch (e) {
+ log_js_1.logger.warning(`Error when creating the TracingClient: ${(0, core_util_1.getErrorMessage)(e)}`);
+ return undefined;
+ }
+}
+function tryCreateSpan(tracingClient, request, spanAttributes) {
+ try {
+ // As per spec, we do not need to differentiate between HTTP and HTTPS in span name.
+ const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, {
+ spanKind: "client",
+ spanAttributes,
+ });
+ // If the span is not recording, don't do any more work.
+ if (!span.isRecording()) {
+ span.end();
+ return undefined;
+ }
+ // set headers
+ const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext);
+ for (const [key, value] of Object.entries(headers)) {
+ request.headers.set(key, value);
+ }
+ return { span, tracingContext: updatedOptions.tracingOptions.tracingContext };
+ }
+ catch (e) {
+ log_js_1.logger.warning(`Skipping creating a tracing span due to an error: ${(0, core_util_1.getErrorMessage)(e)}`);
+ return undefined;
+ }
+}
+function tryProcessError(span, error) {
+ try {
+ span.setStatus({
+ status: "error",
+ error: (0, core_util_1.isError)(error) ? error : undefined,
+ });
+ if ((0, restError_js_1.isRestError)(error) && error.statusCode) {
+ span.setAttribute("http.status_code", error.statusCode);
+ }
+ span.end();
+ }
+ catch (e) {
+ log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`);
+ }
+}
+function tryProcessResponse(span, response) {
+ try {
+ span.setAttribute("http.status_code", response.status);
+ const serviceRequestId = response.headers.get("x-ms-request-id");
+ if (serviceRequestId) {
+ span.setAttribute("serviceRequestId", serviceRequestId);
+ }
+ span.setStatus({
+ status: "success",
+ });
+ span.end();
+ }
+ catch (e) {
+ log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`);
+ }
+}
+//# sourceMappingURL=tracingPolicy.js.map
/***/ }),
-/***/ 8161:
-/***/ ((module) => {
+/***/ 32799:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-module.exports = require("node:os");
-
-/***/ }),
-
-/***/ 1708:
-/***/ ((module) => {
-"use strict";
-module.exports = require("node:process");
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.userAgentPolicyName = void 0;
+exports.userAgentPolicy = userAgentPolicy;
+const userAgent_js_1 = __nccwpck_require__(28431);
+const UserAgentHeaderName = (0, userAgent_js_1.getUserAgentHeaderName)();
+/**
+ * The programmatic identifier of the userAgentPolicy.
+ */
+exports.userAgentPolicyName = "userAgentPolicy";
+/**
+ * A policy that sets the User-Agent header (or equivalent) to reflect
+ * the library version.
+ * @param options - Options to customize the user agent value.
+ */
+function userAgentPolicy(options = {}) {
+ const userAgentValue = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix);
+ return {
+ name: exports.userAgentPolicyName,
+ async sendRequest(request, next) {
+ if (!request.headers.has(UserAgentHeaderName)) {
+ request.headers.set(UserAgentHeaderName, await userAgentValue);
+ }
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=userAgentPolicy.js.map
/***/ }),
-/***/ 7075:
-/***/ ((module) => {
+/***/ 8666:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-module.exports = require("node:stream");
-
-/***/ }),
-/***/ 7975:
-/***/ ((module) => {
-
-"use strict";
-module.exports = require("node:util");
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.RestError = void 0;
+exports.isRestError = isRestError;
+const core_util_1 = __nccwpck_require__(87779);
+const inspect_js_1 = __nccwpck_require__(90995);
+const sanitizer_js_1 = __nccwpck_require__(35204);
+const errorSanitizer = new sanitizer_js_1.Sanitizer();
+/**
+ * A custom error type for failed pipeline requests.
+ */
+class RestError extends Error {
+ constructor(message, options = {}) {
+ super(message);
+ this.name = "RestError";
+ this.code = options.code;
+ this.statusCode = options.statusCode;
+ // The request and response may contain sensitive information in the headers or body.
+ // To help prevent this sensitive information being accidentally logged, the request and response
+ // properties are marked as non-enumerable here. This prevents them showing up in the output of
+ // JSON.stringify and console.log.
+ Object.defineProperty(this, "request", { value: options.request, enumerable: false });
+ Object.defineProperty(this, "response", { value: options.response, enumerable: false });
+ Object.setPrototypeOf(this, RestError.prototype);
+ }
+ /**
+ * Logging method for util.inspect in Node
+ */
+ [inspect_js_1.custom]() {
+ // Extract non-enumerable properties and add them back. This is OK since in this output the request and
+ // response get sanitized.
+ return `RestError: ${this.message} \n ${errorSanitizer.sanitize(Object.assign(Object.assign({}, this), { request: this.request, response: this.response }))}`;
+ }
+}
+exports.RestError = RestError;
+/**
+ * Something went wrong when making the request.
+ * This means the actual request failed for some reason,
+ * such as a DNS issue or the connection being lost.
+ */
+RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR";
+/**
+ * This means that parsing the response from the server failed.
+ * It may have been malformed.
+ */
+RestError.PARSE_ERROR = "PARSE_ERROR";
+/**
+ * Typeguard for RestError
+ * @param e - Something caught by a catch clause.
+ */
+function isRestError(e) {
+ if (e instanceof RestError) {
+ return true;
+ }
+ return (0, core_util_1.isError)(e) && e.name === "RestError";
+}
+//# sourceMappingURL=restError.js.map
/***/ }),
-/***/ 8522:
-/***/ ((module) => {
+/***/ 50002:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-module.exports = require("node:zlib");
-
-/***/ }),
-/***/ 857:
-/***/ ((module) => {
-
-"use strict";
-module.exports = require("os");
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.exponentialRetryStrategy = exponentialRetryStrategy;
+exports.isExponentialRetryResponse = isExponentialRetryResponse;
+exports.isSystemError = isSystemError;
+const core_util_1 = __nccwpck_require__(87779);
+const throttlingRetryStrategy_js_1 = __nccwpck_require__(97084);
+// intervals are in milliseconds
+const DEFAULT_CLIENT_RETRY_INTERVAL = 1000;
+const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64;
+/**
+ * A retry strategy that retries with an exponentially increasing delay in these two cases:
+ * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
+ * - Or otherwise if the outgoing request fails (408, greater or equal than 500, except for 501 and 505).
+ */
+function exponentialRetryStrategy(options = {}) {
+ var _a, _b;
+ const retryInterval = (_a = options.retryDelayInMs) !== null && _a !== void 0 ? _a : DEFAULT_CLIENT_RETRY_INTERVAL;
+ const maxRetryInterval = (_b = options.maxRetryDelayInMs) !== null && _b !== void 0 ? _b : DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
+ return {
+ name: "exponentialRetryStrategy",
+ retry({ retryCount, response, responseError }) {
+ const matchedSystemError = isSystemError(responseError);
+ const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors;
+ const isExponential = isExponentialRetryResponse(response);
+ const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes;
+ const unknownResponse = response && ((0, throttlingRetryStrategy_js_1.isThrottlingRetryResponse)(response) || !isExponential);
+ if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) {
+ return { skipStrategy: true };
+ }
+ if (responseError && !matchedSystemError && !isExponential) {
+ return { errorToThrow: responseError };
+ }
+ return (0, core_util_1.calculateRetryDelay)(retryCount, {
+ retryDelayInMs: retryInterval,
+ maxRetryDelayInMs: maxRetryInterval,
+ });
+ },
+ };
+}
+/**
+ * A response is a retry response if it has status codes:
+ * - 408, or
+ * - Greater or equal than 500, except for 501 and 505.
+ */
+function isExponentialRetryResponse(response) {
+ return Boolean(response &&
+ response.status !== undefined &&
+ (response.status >= 500 || response.status === 408) &&
+ response.status !== 501 &&
+ response.status !== 505);
+}
+/**
+ * Determines whether an error from a pipeline response was triggered in the network layer.
+ */
+function isSystemError(err) {
+ if (!err) {
+ return false;
+ }
+ return (err.code === "ETIMEDOUT" ||
+ err.code === "ESOCKETTIMEDOUT" ||
+ err.code === "ECONNREFUSED" ||
+ err.code === "ECONNRESET" ||
+ err.code === "ENOENT" ||
+ err.code === "ENOTFOUND");
+}
+//# sourceMappingURL=exponentialRetryStrategy.js.map
/***/ }),
-/***/ 6928:
-/***/ ((module) => {
+/***/ 97084:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-module.exports = require("path");
-
-/***/ }),
-
-/***/ 2987:
-/***/ ((module) => {
-"use strict";
-module.exports = require("perf_hooks");
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isThrottlingRetryResponse = isThrottlingRetryResponse;
+exports.throttlingRetryStrategy = throttlingRetryStrategy;
+const helpers_js_1 = __nccwpck_require__(653);
+/**
+ * The header that comes back from Azure services representing
+ * the amount of time (minimum) to wait to retry (in seconds or timestamp after which we can retry).
+ */
+const RetryAfterHeader = "Retry-After";
+/**
+ * The headers that come back from Azure services representing
+ * the amount of time (minimum) to wait to retry.
+ *
+ * "retry-after-ms", "x-ms-retry-after-ms" : milliseconds
+ * "Retry-After" : seconds or timestamp
+ */
+const AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader];
+/**
+ * A response is a throttling retry response if it has a throttling status code (429 or 503),
+ * as long as one of the [ "Retry-After" or "retry-after-ms" or "x-ms-retry-after-ms" ] headers has a valid value.
+ *
+ * Returns the `retryAfterInMs` value if the response is a throttling retry response.
+ * If not throttling retry response, returns `undefined`.
+ *
+ * @internal
+ */
+function getRetryAfterInMs(response) {
+ if (!(response && [429, 503].includes(response.status)))
+ return undefined;
+ try {
+ // Headers: "retry-after-ms", "x-ms-retry-after-ms", "Retry-After"
+ for (const header of AllRetryAfterHeaders) {
+ const retryAfterValue = (0, helpers_js_1.parseHeaderValueAsNumber)(response, header);
+ if (retryAfterValue === 0 || retryAfterValue) {
+ // "Retry-After" header ==> seconds
+ // "retry-after-ms", "x-ms-retry-after-ms" headers ==> milli-seconds
+ const multiplyingFactor = header === RetryAfterHeader ? 1000 : 1;
+ return retryAfterValue * multiplyingFactor; // in milli-seconds
+ }
+ }
+ // RetryAfterHeader ("Retry-After") has a special case where it might be formatted as a date instead of a number of seconds
+ const retryAfterHeader = response.headers.get(RetryAfterHeader);
+ if (!retryAfterHeader)
+ return;
+ const date = Date.parse(retryAfterHeader);
+ const diff = date - Date.now();
+ // negative diff would mean a date in the past, so retry asap with 0 milliseconds
+ return Number.isFinite(diff) ? Math.max(0, diff) : undefined;
+ }
+ catch (_a) {
+ return undefined;
+ }
+}
+/**
+ * A response is a retry response if it has a throttling status code (429 or 503),
+ * as long as one of the [ "Retry-After" or "retry-after-ms" or "x-ms-retry-after-ms" ] headers has a valid value.
+ */
+function isThrottlingRetryResponse(response) {
+ return Number.isFinite(getRetryAfterInMs(response));
+}
+function throttlingRetryStrategy() {
+ return {
+ name: "throttlingRetryStrategy",
+ retry({ response }) {
+ const retryAfterInMs = getRetryAfterInMs(response);
+ if (!Number.isFinite(retryAfterInMs)) {
+ return { skipStrategy: true };
+ }
+ return {
+ retryAfterInMs,
+ };
+ },
+ };
+}
+//# sourceMappingURL=throttlingRetryStrategy.js.map
/***/ }),
-/***/ 3480:
-/***/ ((module) => {
+/***/ 62471:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-module.exports = require("querystring");
-
-/***/ }),
-/***/ 2203:
-/***/ ((module) => {
-
-"use strict";
-module.exports = require("stream");
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.concat = concat;
+const tslib_1 = __nccwpck_require__(61860);
+const node_stream_1 = __nccwpck_require__(57075);
+const typeGuards_js_1 = __nccwpck_require__(22621);
+const file_js_1 = __nccwpck_require__(97073);
+function streamAsyncIterator() {
+ return tslib_1.__asyncGenerator(this, arguments, function* streamAsyncIterator_1() {
+ const reader = this.getReader();
+ try {
+ while (true) {
+ const { done, value } = yield tslib_1.__await(reader.read());
+ if (done) {
+ return yield tslib_1.__await(void 0);
+ }
+ yield yield tslib_1.__await(value);
+ }
+ }
+ finally {
+ reader.releaseLock();
+ }
+ });
+}
+function makeAsyncIterable(webStream) {
+ if (!webStream[Symbol.asyncIterator]) {
+ webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream);
+ }
+ if (!webStream.values) {
+ webStream.values = streamAsyncIterator.bind(webStream);
+ }
+}
+function ensureNodeStream(stream) {
+ if (stream instanceof ReadableStream) {
+ makeAsyncIterable(stream);
+ return node_stream_1.Readable.fromWeb(stream);
+ }
+ else {
+ return stream;
+ }
+}
+function toStream(source) {
+ if (source instanceof Uint8Array) {
+ return node_stream_1.Readable.from(Buffer.from(source));
+ }
+ else if ((0, typeGuards_js_1.isBlob)(source)) {
+ return toStream((0, file_js_1.getRawContent)(source));
+ }
+ else {
+ return ensureNodeStream(source);
+ }
+}
+/**
+ * Utility function that concatenates a set of binary inputs into one combined output.
+ *
+ * @param sources - array of sources for the concatenation
+ * @returns - in Node, a (() =\> NodeJS.ReadableStream) which, when read, produces a concatenation of all the inputs.
+ * In browser, returns a `Blob` representing all the concatenated inputs.
+ *
+ * @internal
+ */
+async function concat(sources) {
+ return function () {
+ const streams = sources.map((x) => (typeof x === "function" ? x() : x)).map(toStream);
+ return node_stream_1.Readable.from((function () {
+ return tslib_1.__asyncGenerator(this, arguments, function* () {
+ var _a, e_1, _b, _c;
+ for (const stream of streams) {
+ try {
+ for (var _d = true, stream_1 = (e_1 = void 0, tslib_1.__asyncValues(stream)), stream_1_1; stream_1_1 = yield tslib_1.__await(stream_1.next()), _a = stream_1_1.done, !_a; _d = true) {
+ _c = stream_1_1.value;
+ _d = false;
+ const chunk = _c;
+ yield yield tslib_1.__await(chunk);
+ }
+ }
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ finally {
+ try {
+ if (!_d && !_a && (_b = stream_1.return)) yield tslib_1.__await(_b.call(stream_1));
+ }
+ finally { if (e_1) throw e_1.error; }
+ }
+ }
+ });
+ })());
+ };
+}
+//# sourceMappingURL=concat.js.map
/***/ }),
-/***/ 3774:
-/***/ ((module) => {
+/***/ 97073:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-module.exports = require("stream/web");
-
-/***/ }),
-/***/ 3193:
-/***/ ((module) => {
-
-"use strict";
-module.exports = require("string_decoder");
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getRawContent = getRawContent;
+exports.createFileFromStream = createFileFromStream;
+exports.createFile = createFile;
+const core_util_1 = __nccwpck_require__(87779);
+const typeGuards_js_1 = __nccwpck_require__(22621);
+const unimplementedMethods = {
+ arrayBuffer: () => {
+ throw new Error("Not implemented");
+ },
+ slice: () => {
+ throw new Error("Not implemented");
+ },
+ text: () => {
+ throw new Error("Not implemented");
+ },
+};
+/**
+ * Private symbol used as key on objects created using createFile containing the
+ * original source of the file object.
+ *
+ * This is used in Node to access the original Node stream without using Blob#stream, which
+ * returns a web stream. This is done to avoid a couple of bugs to do with Blob#stream and
+ * Readable#to/fromWeb in Node versions we support:
+ * - https://github.com/nodejs/node/issues/42694 (fixed in Node 18.14)
+ * - https://github.com/nodejs/node/issues/48916 (fixed in Node 20.6)
+ *
+ * Once these versions are no longer supported, we may be able to stop doing this.
+ *
+ * @internal
+ */
+const rawContent = Symbol("rawContent");
+function hasRawContent(x) {
+ return typeof x[rawContent] === "function";
+}
+/**
+ * Extract the raw content from a given blob-like object. If the input was created using createFile
+ * or createFileFromStream, the exact content passed into createFile/createFileFromStream will be used.
+ * For true instances of Blob and File, returns the blob's content as a Web ReadableStream.
+ *
+ * @internal
+ */
+function getRawContent(blob) {
+ if (hasRawContent(blob)) {
+ return blob[rawContent]();
+ }
+ else {
+ return blob.stream();
+ }
+}
+/**
+ * Create an object that implements the File interface. This object is intended to be
+ * passed into RequestBodyType.formData, and is not guaranteed to work as expected in
+ * other situations.
+ *
+ * Use this function to:
+ * - Create a File object for use in RequestBodyType.formData in environments where the
+ * global File object is unavailable.
+ * - Create a File-like object from a readable stream without reading the stream into memory.
+ *
+ * @param stream - the content of the file as a callback returning a stream. When a File object made using createFile is
+ * passed in a request's form data map, the stream will not be read into memory
+ * and instead will be streamed when the request is made. In the event of a retry, the
+ * stream needs to be read again, so this callback SHOULD return a fresh stream if possible.
+ * @param name - the name of the file.
+ * @param options - optional metadata about the file, e.g. file name, file size, MIME type.
+ */
+function createFileFromStream(stream, name, options = {}) {
+ var _a, _b, _c, _d;
+ return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : new Date().getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: (_d = options.size) !== null && _d !== void 0 ? _d : -1, name, stream: () => {
+ const s = stream();
+ if ((0, typeGuards_js_1.isNodeReadableStream)(s)) {
+ throw new Error("Not supported: a Node stream was provided as input to createFileFromStream.");
+ }
+ return s;
+ }, [rawContent]: stream });
+}
+/**
+ * Create an object that implements the File interface. This object is intended to be
+ * passed into RequestBodyType.formData, and is not guaranteed to work as expected in
+ * other situations.
+ *
+ * Use this function create a File object for use in RequestBodyType.formData in environments where the global File object is unavailable.
+ *
+ * @param content - the content of the file as a Uint8Array in memory.
+ * @param name - the name of the file.
+ * @param options - optional metadata about the file, e.g. file name, file size, MIME type.
+ */
+function createFile(content, name, options = {}) {
+ var _a, _b, _c;
+ if (core_util_1.isNodeLike) {
+ return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : new Date().getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: content.byteLength, name, arrayBuffer: async () => content.buffer, stream: () => new Blob([content]).stream(), [rawContent]: () => content });
+ }
+ else {
+ return new File([content], name, options);
+ }
+}
+//# sourceMappingURL=file.js.map
/***/ }),
-/***/ 3557:
-/***/ ((module) => {
+/***/ 653:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-module.exports = require("timers");
-
-/***/ }),
-
-/***/ 4756:
-/***/ ((module) => {
-"use strict";
-module.exports = require("tls");
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.delay = delay;
+exports.parseHeaderValueAsNumber = parseHeaderValueAsNumber;
+const abort_controller_1 = __nccwpck_require__(93287);
+const StandardAbortMessage = "The operation was aborted.";
+/**
+ * A wrapper for setTimeout that resolves a promise after delayInMs milliseconds.
+ * @param delayInMs - The number of milliseconds to be delayed.
+ * @param value - The value to be resolved with after a timeout of t milliseconds.
+ * @param options - The options for delay - currently abort options
+ * - abortSignal - The abortSignal associated with containing operation.
+ * - abortErrorMsg - The abort error message associated with containing operation.
+ * @returns Resolved promise
+ */
+function delay(delayInMs, value, options) {
+ return new Promise((resolve, reject) => {
+ let timer = undefined;
+ let onAborted = undefined;
+ const rejectOnAbort = () => {
+ return reject(new abort_controller_1.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage));
+ };
+ const removeListeners = () => {
+ if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) {
+ options.abortSignal.removeEventListener("abort", onAborted);
+ }
+ };
+ onAborted = () => {
+ if (timer) {
+ clearTimeout(timer);
+ }
+ removeListeners();
+ return rejectOnAbort();
+ };
+ if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) {
+ return rejectOnAbort();
+ }
+ timer = setTimeout(() => {
+ removeListeners();
+ resolve(value);
+ }, delayInMs);
+ if (options === null || options === void 0 ? void 0 : options.abortSignal) {
+ options.abortSignal.addEventListener("abort", onAborted);
+ }
+ });
+}
+/**
+ * @internal
+ * @returns the parsed value or undefined if the parsed value is invalid.
+ */
+function parseHeaderValueAsNumber(response, headerName) {
+ const value = response.headers.get(headerName);
+ if (!value)
+ return;
+ const valueAsNum = Number(value);
+ if (Number.isNaN(valueAsNum))
+ return;
+ return valueAsNum;
+}
+//# sourceMappingURL=helpers.js.map
/***/ }),
-/***/ 2018:
-/***/ ((module) => {
+/***/ 90995:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-module.exports = require("tty");
-
-/***/ }),
-/***/ 7016:
-/***/ ((module) => {
-
-"use strict";
-module.exports = require("url");
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.custom = void 0;
+const node_util_1 = __nccwpck_require__(57975);
+exports.custom = node_util_1.inspect.custom;
+//# sourceMappingURL=inspect.js.map
/***/ }),
-/***/ 9023:
-/***/ ((module) => {
+/***/ 35204:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-module.exports = require("util");
-
-/***/ }),
-
-/***/ 8253:
-/***/ ((module) => {
-"use strict";
-module.exports = require("util/types");
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Sanitizer = void 0;
+const core_util_1 = __nccwpck_require__(87779);
+const RedactedString = "REDACTED";
+// Make sure this list is up-to-date with the one under core/logger/Readme#Keyconcepts
+const defaultAllowedHeaderNames = [
+ "x-ms-client-request-id",
+ "x-ms-return-client-request-id",
+ "x-ms-useragent",
+ "x-ms-correlation-request-id",
+ "x-ms-request-id",
+ "client-request-id",
+ "ms-cv",
+ "return-client-request-id",
+ "traceparent",
+ "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",
+ "Origin",
+ "Accept",
+ "Accept-Encoding",
+ "Cache-Control",
+ "Connection",
+ "Content-Length",
+ "Content-Type",
+ "Date",
+ "ETag",
+ "Expires",
+ "If-Match",
+ "If-Modified-Since",
+ "If-None-Match",
+ "If-Unmodified-Since",
+ "Last-Modified",
+ "Pragma",
+ "Request-Id",
+ "Retry-After",
+ "Server",
+ "Transfer-Encoding",
+ "User-Agent",
+ "WWW-Authenticate",
+];
+const defaultAllowedQueryParameters = ["api-version"];
+/**
+ * @internal
+ */
+class Sanitizer {
+ constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [], } = {}) {
+ allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames);
+ allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters);
+ this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase()));
+ this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase()));
+ }
+ sanitize(obj) {
+ const seen = new Set();
+ return JSON.stringify(obj, (key, value) => {
+ // Ensure Errors include their interesting non-enumerable members
+ if (value instanceof Error) {
+ return Object.assign(Object.assign({}, value), { name: value.name, message: value.message });
+ }
+ if (key === "headers") {
+ return this.sanitizeHeaders(value);
+ }
+ else if (key === "url") {
+ return this.sanitizeUrl(value);
+ }
+ else if (key === "query") {
+ return this.sanitizeQuery(value);
+ }
+ else if (key === "body") {
+ // Don't log the request body
+ return undefined;
+ }
+ else if (key === "response") {
+ // Don't log response again
+ return undefined;
+ }
+ else if (key === "operationSpec") {
+ // When using sendOperationRequest, the request carries a massive
+ // field with the autorest spec. No need to log it.
+ return undefined;
+ }
+ else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) {
+ if (seen.has(value)) {
+ return "[Circular]";
+ }
+ seen.add(value);
+ }
+ return value;
+ }, 2);
+ }
+ sanitizeUrl(value) {
+ if (typeof value !== "string" || value === null || value === "") {
+ return value;
+ }
+ const url = new URL(value);
+ if (!url.search) {
+ return value;
+ }
+ for (const [key] of url.searchParams) {
+ if (!this.allowedQueryParameters.has(key.toLowerCase())) {
+ url.searchParams.set(key, RedactedString);
+ }
+ }
+ return url.toString();
+ }
+ sanitizeHeaders(obj) {
+ const sanitized = {};
+ for (const key of Object.keys(obj)) {
+ if (this.allowedHeaderNames.has(key.toLowerCase())) {
+ sanitized[key] = obj[key];
+ }
+ else {
+ sanitized[key] = RedactedString;
+ }
+ }
+ return sanitized;
+ }
+ sanitizeQuery(value) {
+ if (typeof value !== "object" || value === null) {
+ return value;
+ }
+ const sanitized = {};
+ for (const k of Object.keys(value)) {
+ if (this.allowedQueryParameters.has(k.toLowerCase())) {
+ sanitized[k] = value[k];
+ }
+ else {
+ sanitized[k] = RedactedString;
+ }
+ }
+ return sanitized;
+ }
+}
+exports.Sanitizer = Sanitizer;
+//# sourceMappingURL=sanitizer.js.map
/***/ }),
-/***/ 8167:
-/***/ ((module) => {
+/***/ 39202:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-module.exports = require("worker_threads");
-
-/***/ }),
-
-/***/ 3106:
-/***/ ((module) => {
-"use strict";
-module.exports = require("zlib");
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.DEFAULT_CYCLER_OPTIONS = void 0;
+exports.createTokenCycler = createTokenCycler;
+const helpers_js_1 = __nccwpck_require__(653);
+// Default options for the cycler if none are provided
+exports.DEFAULT_CYCLER_OPTIONS = {
+ forcedRefreshWindowInMs: 1000, // Force waiting for a refresh 1s before the token expires
+ retryIntervalInMs: 3000, // Allow refresh attempts every 3s
+ refreshWindowInMs: 1000 * 60 * 2, // Start refreshing 2m before expiry
+};
+/**
+ * Converts an an unreliable access token getter (which may resolve with null)
+ * into an AccessTokenGetter by retrying the unreliable getter in a regular
+ * interval.
+ *
+ * @param getAccessToken - A function that produces a promise of an access token that may fail by returning null.
+ * @param retryIntervalInMs - The time (in milliseconds) to wait between retry attempts.
+ * @param refreshTimeout - The timestamp after which the refresh attempt will fail, throwing an exception.
+ * @returns - A promise that, if it resolves, will resolve with an access token.
+ */
+async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) {
+ // This wrapper handles exceptions gracefully as long as we haven't exceeded
+ // the timeout.
+ async function tryGetAccessToken() {
+ if (Date.now() < refreshTimeout) {
+ try {
+ return await getAccessToken();
+ }
+ catch (_a) {
+ return null;
+ }
+ }
+ else {
+ const finalToken = await getAccessToken();
+ // Timeout is up, so throw if it's still null
+ if (finalToken === null) {
+ throw new Error("Failed to refresh access token.");
+ }
+ return finalToken;
+ }
+ }
+ let token = await tryGetAccessToken();
+ while (token === null) {
+ await (0, helpers_js_1.delay)(retryIntervalInMs);
+ token = await tryGetAccessToken();
+ }
+ return token;
+}
+/**
+ * Creates a token cycler from a credential, scopes, and optional settings.
+ *
+ * A token cycler represents a way to reliably retrieve a valid access token
+ * from a TokenCredential. It will handle initializing the token, refreshing it
+ * when it nears expiration, and synchronizes refresh attempts to avoid
+ * concurrency hazards.
+ *
+ * @param credential - the underlying TokenCredential that provides the access
+ * token
+ * @param tokenCyclerOptions - optionally override default settings for the cycler
+ *
+ * @returns - a function that reliably produces a valid access token
+ */
+function createTokenCycler(credential, tokenCyclerOptions) {
+ let refreshWorker = null;
+ let token = null;
+ let tenantId;
+ const options = Object.assign(Object.assign({}, exports.DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions);
+ /**
+ * This little holder defines several predicates that we use to construct
+ * the rules of refreshing the token.
+ */
+ const cycler = {
+ /**
+ * Produces true if a refresh job is currently in progress.
+ */
+ get isRefreshing() {
+ return refreshWorker !== null;
+ },
+ /**
+ * Produces true if the cycler SHOULD refresh (we are within the refresh
+ * window and not already refreshing)
+ */
+ get shouldRefresh() {
+ var _a;
+ if (cycler.isRefreshing) {
+ return false;
+ }
+ if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) {
+ return true;
+ }
+ return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now();
+ },
+ /**
+ * Produces true if the cycler MUST refresh (null or nearly-expired
+ * token).
+ */
+ get mustRefresh() {
+ return (token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now());
+ },
+ };
+ /**
+ * Starts a refresh job or returns the existing job if one is already
+ * running.
+ */
+ function refresh(scopes, getTokenOptions) {
+ var _a;
+ if (!cycler.isRefreshing) {
+ // We bind `scopes` here to avoid passing it around a lot
+ const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions);
+ // Take advantage of promise chaining to insert an assignment to `token`
+ // before the refresh can be considered done.
+ refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs,
+ // If we don't have a token, then we should timeout immediately
+ (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now())
+ .then((_token) => {
+ refreshWorker = null;
+ token = _token;
+ tenantId = getTokenOptions.tenantId;
+ return token;
+ })
+ .catch((reason) => {
+ // We also should reset the refresher if we enter a failed state. All
+ // existing awaiters will throw, but subsequent requests will start a
+ // new retry chain.
+ refreshWorker = null;
+ token = null;
+ tenantId = undefined;
+ throw reason;
+ });
+ }
+ return refreshWorker;
+ }
+ return async (scopes, tokenOptions) => {
+ //
+ // Simple rules:
+ // - If we MUST refresh, then return the refresh task, blocking
+ // the pipeline until a token is available.
+ // - If we SHOULD refresh, then run refresh but don't return it
+ // (we can still use the cached token).
+ // - Return the token, since it's fine if we didn't return in
+ // step 1.
+ //
+ const hasClaimChallenge = Boolean(tokenOptions.claims);
+ const tenantIdChanged = tenantId !== tokenOptions.tenantId;
+ if (hasClaimChallenge) {
+ // If we've received a claim, we know the existing token isn't valid
+ // We want to clear it so that that refresh worker won't use the old expiration time as a timeout
+ token = null;
+ }
+ // If the tenantId passed in token options is different to the one we have
+ // Or if we are in claim challenge and the token was rejected and a new access token need to be issued, we need to
+ // refresh the token with the new tenantId or token.
+ const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh;
+ if (mustRefresh) {
+ return refresh(scopes, tokenOptions);
+ }
+ if (cycler.shouldRefresh) {
+ refresh(scopes, tokenOptions);
+ }
+ return token;
+ };
+}
+//# sourceMappingURL=tokenCycler.js.map
/***/ }),
-/***/ 198:
+/***/ 22621:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
@@ -74499,48 +120812,29 @@ module.exports = require("zlib");
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.AzureKeyCredential = void 0;
-/**
- * A static-key-based credential that supports updating
- * the underlying key value.
- */
-class AzureKeyCredential {
- /**
- * The value of the key to be used in authentication
- */
- get key() {
- return this._key;
- }
- /**
- * Create an instance of an AzureKeyCredential for use
- * with a service client.
- *
- * @param key - The initial value of the key to use in authentication
- */
- constructor(key) {
- if (!key) {
- throw new Error("key must be a non-empty string");
- }
- this._key = key;
- }
- /**
- * Change the value of the key.
- *
- * Updates will take effect upon the next request after
- * updating the key value.
- *
- * @param newKey - The new key value to be used
- */
- update(newKey) {
- this._key = newKey;
- }
+exports.isNodeReadableStream = isNodeReadableStream;
+exports.isWebReadableStream = isWebReadableStream;
+exports.isReadableStream = isReadableStream;
+exports.isBlob = isBlob;
+function isNodeReadableStream(x) {
+ return Boolean(x && typeof x["pipe"] === "function");
}
-exports.AzureKeyCredential = AzureKeyCredential;
-//# sourceMappingURL=azureKeyCredential.js.map
+function isWebReadableStream(x) {
+ return Boolean(x &&
+ typeof x.getReader === "function" &&
+ typeof x.tee === "function");
+}
+function isReadableStream(x) {
+ return isNodeReadableStream(x) || isWebReadableStream(x);
+}
+function isBlob(x) {
+ return typeof x.stream === "function";
+}
+//# sourceMappingURL=typeGuards.js.map
/***/ }),
-/***/ 1295:
+/***/ 28431:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
@@ -74548,73 +120842,40 @@ exports.AzureKeyCredential = AzureKeyCredential;
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.AzureNamedKeyCredential = void 0;
-exports.isNamedKeyCredential = isNamedKeyCredential;
-const core_util_1 = __nccwpck_require__(7779);
+exports.getUserAgentHeaderName = getUserAgentHeaderName;
+exports.getUserAgentValue = getUserAgentValue;
+const userAgentPlatform_js_1 = __nccwpck_require__(31848);
+const constants_js_1 = __nccwpck_require__(66427);
+function getUserAgentString(telemetryInfo) {
+ const parts = [];
+ for (const [key, value] of telemetryInfo) {
+ const token = value ? `${key}/${value}` : key;
+ parts.push(token);
+ }
+ return parts.join(" ");
+}
/**
- * A static name/key-based credential that supports updating
- * the underlying name and key values.
+ * @internal
*/
-class AzureNamedKeyCredential {
- /**
- * The value of the key to be used in authentication.
- */
- get key() {
- return this._key;
- }
- /**
- * The value of the name to be used in authentication.
- */
- get name() {
- return this._name;
- }
- /**
- * Create an instance of an AzureNamedKeyCredential for use
- * with a service client.
- *
- * @param name - The initial value of the name to use in authentication.
- * @param key - The initial value of the key to use in authentication.
- */
- constructor(name, key) {
- if (!name || !key) {
- throw new TypeError("name and key must be non-empty strings");
- }
- this._name = name;
- this._key = key;
- }
- /**
- * Change the value of the key.
- *
- * Updates will take effect upon the next request after
- * updating the key value.
- *
- * @param newName - The new name value to be used.
- * @param newKey - The new key value to be used.
- */
- update(newName, newKey) {
- if (!newName || !newKey) {
- throw new TypeError("newName and newKey must be non-empty strings");
- }
- this._name = newName;
- this._key = newKey;
- }
+function getUserAgentHeaderName() {
+ return (0, userAgentPlatform_js_1.getHeaderName)();
}
-exports.AzureNamedKeyCredential = AzureNamedKeyCredential;
/**
- * Tests an object to determine whether it implements NamedKeyCredential.
- *
- * @param credential - The assumed NamedKeyCredential to be tested.
+ * @internal
*/
-function isNamedKeyCredential(credential) {
- return ((0, core_util_1.isObjectWithProperties)(credential, ["name", "key"]) &&
- typeof credential.key === "string" &&
- typeof credential.name === "string");
+async function getUserAgentValue(prefix) {
+ const runtimeInfo = new Map();
+ runtimeInfo.set("core-rest-pipeline", constants_js_1.SDK_VERSION);
+ await (0, userAgentPlatform_js_1.setPlatformSpecificData)(runtimeInfo);
+ const defaultAgent = getUserAgentString(runtimeInfo);
+ const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent;
+ return userAgentValue;
}
-//# sourceMappingURL=azureNamedKeyCredential.js.map
+//# sourceMappingURL=userAgent.js.map
/***/ }),
-/***/ 6608:
+/***/ 31848:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
@@ -74622,84 +120883,93 @@ function isNamedKeyCredential(credential) {
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.AzureSASCredential = void 0;
-exports.isSASCredential = isSASCredential;
-const core_util_1 = __nccwpck_require__(7779);
+exports.getHeaderName = getHeaderName;
+exports.setPlatformSpecificData = setPlatformSpecificData;
+const tslib_1 = __nccwpck_require__(61860);
+const os = tslib_1.__importStar(__nccwpck_require__(48161));
+const process = tslib_1.__importStar(__nccwpck_require__(1708));
/**
- * A static-signature-based credential that supports updating
- * the underlying signature value.
+ * @internal
*/
-class AzureSASCredential {
- /**
- * The value of the shared access signature to be used in authentication
- */
- get signature() {
- return this._signature;
- }
- /**
- * Create an instance of an AzureSASCredential for use
- * with a service client.
- *
- * @param signature - The initial value of the shared access signature to use in authentication
- */
- constructor(signature) {
- if (!signature) {
- throw new Error("shared access signature must be a non-empty string");
+function getHeaderName() {
+ return "User-Agent";
+}
+/**
+ * @internal
+ */
+async function setPlatformSpecificData(map) {
+ if (process && process.versions) {
+ const versions = process.versions;
+ if (versions.bun) {
+ map.set("Bun", versions.bun);
}
- this._signature = signature;
- }
- /**
- * Change the value of the signature.
- *
- * Updates will take effect upon the next request after
- * updating the signature value.
- *
- * @param newSignature - The new shared access signature value to be used
- */
- update(newSignature) {
- if (!newSignature) {
- throw new Error("shared access signature must be a non-empty string");
+ else if (versions.deno) {
+ map.set("Deno", versions.deno);
+ }
+ else if (versions.node) {
+ map.set("Node", versions.node);
}
- this._signature = newSignature;
}
+ map.set("OS", `(${os.arch()}-${os.type()}-${os.release()})`);
}
-exports.AzureSASCredential = AzureSASCredential;
+//# sourceMappingURL=userAgentPlatform.js.map
+
+/***/ }),
+
+/***/ 45455:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AbortError = void 0;
/**
- * Tests an object to determine whether it implements SASCredential.
+ * 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"`.
*
- * @param credential - The assumed SASCredential to be tested.
+ * @example
+ * ```ts
+ * const controller = new AbortController();
+ * controller.abort();
+ * try {
+ * doAsyncWork(controller.signal)
+ * } catch (e) {
+ * if (e.name === 'AbortError') {
+ * // handle abort error here.
+ * }
+ * }
+ * ```
*/
-function isSASCredential(credential) {
- return ((0, core_util_1.isObjectWithProperties)(credential, ["signature"]) && typeof credential.signature === "string");
+class AbortError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "AbortError";
+ }
}
-//# sourceMappingURL=azureSASCredential.js.map
+exports.AbortError = AbortError;
+//# sourceMappingURL=AbortError.js.map
/***/ }),
-/***/ 417:
+/***/ 93287:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isTokenCredential = exports.isSASCredential = exports.AzureSASCredential = exports.isNamedKeyCredential = exports.AzureNamedKeyCredential = exports.isKeyCredential = exports.AzureKeyCredential = void 0;
-var azureKeyCredential_js_1 = __nccwpck_require__(198);
-Object.defineProperty(exports, "AzureKeyCredential", ({ enumerable: true, get: function () { return azureKeyCredential_js_1.AzureKeyCredential; } }));
-var keyCredential_js_1 = __nccwpck_require__(9155);
-Object.defineProperty(exports, "isKeyCredential", ({ enumerable: true, get: function () { return keyCredential_js_1.isKeyCredential; } }));
-var azureNamedKeyCredential_js_1 = __nccwpck_require__(1295);
-Object.defineProperty(exports, "AzureNamedKeyCredential", ({ enumerable: true, get: function () { return azureNamedKeyCredential_js_1.AzureNamedKeyCredential; } }));
-Object.defineProperty(exports, "isNamedKeyCredential", ({ enumerable: true, get: function () { return azureNamedKeyCredential_js_1.isNamedKeyCredential; } }));
-var azureSASCredential_js_1 = __nccwpck_require__(6608);
-Object.defineProperty(exports, "AzureSASCredential", ({ enumerable: true, get: function () { return azureSASCredential_js_1.AzureSASCredential; } }));
-Object.defineProperty(exports, "isSASCredential", ({ enumerable: true, get: function () { return azureSASCredential_js_1.isSASCredential; } }));
-var tokenCredential_js_1 = __nccwpck_require__(6881);
-Object.defineProperty(exports, "isTokenCredential", ({ enumerable: true, get: function () { return tokenCredential_js_1.isTokenCredential; } }));
+exports.AbortError = void 0;
+var AbortError_js_1 = __nccwpck_require__(45455);
+Object.defineProperty(exports, "AbortError", ({ enumerable: true, get: function () { return AbortError_js_1.AbortError; } }));
//# sourceMappingURL=index.js.map
/***/ }),
-/***/ 9155:
+/***/ 20623:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
@@ -74707,1016 +120977,778 @@ Object.defineProperty(exports, "isTokenCredential", ({ enumerable: true, get: fu
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isKeyCredential = isKeyCredential;
-const core_util_1 = __nccwpck_require__(7779);
-/**
- * Tests an object to determine whether it implements KeyCredential.
- *
- * @param credential - The assumed KeyCredential to be tested.
- */
-function isKeyCredential(credential) {
- return (0, core_util_1.isObjectWithProperties)(credential, ["key"]) && typeof credential.key === "string";
-}
-//# sourceMappingURL=keyCredential.js.map
+exports.createTracingClient = exports.useInstrumenter = void 0;
+var instrumenter_js_1 = __nccwpck_require__(48729);
+Object.defineProperty(exports, "useInstrumenter", ({ enumerable: true, get: function () { return instrumenter_js_1.useInstrumenter; } }));
+var tracingClient_js_1 = __nccwpck_require__(71057);
+Object.defineProperty(exports, "createTracingClient", ({ enumerable: true, get: function () { return tracingClient_js_1.createTracingClient; } }));
+//# sourceMappingURL=index.js.map
/***/ }),
-/***/ 6881:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 48729:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isBearerToken = isBearerToken;
-exports.isPopToken = isPopToken;
-exports.isTokenCredential = isTokenCredential;
+exports.createDefaultTracingSpan = createDefaultTracingSpan;
+exports.createDefaultInstrumenter = createDefaultInstrumenter;
+exports.useInstrumenter = useInstrumenter;
+exports.getInstrumenter = getInstrumenter;
+const tracingContext_js_1 = __nccwpck_require__(79186);
+const state_js_1 = __nccwpck_require__(38914);
+function createDefaultTracingSpan() {
+ return {
+ end: () => {
+ // noop
+ },
+ isRecording: () => false,
+ recordException: () => {
+ // noop
+ },
+ setAttribute: () => {
+ // noop
+ },
+ setStatus: () => {
+ // noop
+ },
+ addEvent: () => {
+ // noop
+ },
+ };
+}
+function createDefaultInstrumenter() {
+ return {
+ createRequestHeaders: () => {
+ return {};
+ },
+ parseTraceparentHeader: () => {
+ return undefined;
+ },
+ startSpan: (_name, spanOptions) => {
+ return {
+ span: createDefaultTracingSpan(),
+ tracingContext: (0, tracingContext_js_1.createTracingContext)({ parentContext: spanOptions.tracingContext }),
+ };
+ },
+ withContext(_context, callback, ...callbackArgs) {
+ return callback(...callbackArgs);
+ },
+ };
+}
/**
- * @internal
- * @param accessToken - Access token
- * @returns Whether a token is bearer type or not
+ * Extends the Azure SDK with support for a given instrumenter implementation.
+ *
+ * @param instrumenter - The instrumenter implementation to use.
*/
-function isBearerToken(accessToken) {
- return !accessToken.tokenType || accessToken.tokenType === "Bearer";
+function useInstrumenter(instrumenter) {
+ state_js_1.state.instrumenterImplementation = instrumenter;
}
/**
- * @internal
- * @param accessToken - Access token
- * @returns Whether a token is Pop token or not
+ * Gets the currently set instrumenter, a No-Op instrumenter by default.
+ *
+ * @returns The currently set instrumenter
*/
-function isPopToken(accessToken) {
- return accessToken.tokenType === "pop";
+function getInstrumenter() {
+ if (!state_js_1.state.instrumenterImplementation) {
+ state_js_1.state.instrumenterImplementation = createDefaultInstrumenter();
+ }
+ return state_js_1.state.instrumenterImplementation;
}
+//# sourceMappingURL=instrumenter.js.map
+
+/***/ }),
+
+/***/ 38914:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.state = void 0;
/**
- * Tests an object to determine whether it implements TokenCredential.
+ * @internal
*
- * @param credential - The assumed TokenCredential to be tested.
+ * Holds the singleton instrumenter, to be shared across CJS and ESM imports.
*/
-function isTokenCredential(credential) {
- // Check for an object with a 'getToken' function and possibly with
- // a 'signRequest' function. We do this check to make sure that
- // a ServiceClientCredentials implementor (like TokenClientCredentials
- // in ms-rest-nodeauth) doesn't get mistaken for a TokenCredential if
- // it doesn't actually implement TokenCredential also.
- const castCredential = credential;
- return (castCredential &&
- typeof castCredential.getToken === "function" &&
- (castCredential.signRequest === undefined || castCredential.getToken.length > 0));
-}
-//# sourceMappingURL=tokenCredential.js.map
+exports.state = {
+ instrumenterImplementation: undefined,
+};
+//# sourceMappingURL=state-cjs.cjs.map
/***/ }),
-/***/ 2460:
+/***/ 71057:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
+// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.authorizeRequestOnClaimChallenge = exports.parseCAEChallenge = void 0;
-const log_js_1 = __nccwpck_require__(9994);
-const base64_js_1 = __nccwpck_require__(741);
+exports.createTracingClient = createTracingClient;
+const instrumenter_js_1 = __nccwpck_require__(48729);
+const tracingContext_js_1 = __nccwpck_require__(79186);
/**
- * Converts: `Bearer a="b", c="d", Bearer d="e", f="g"`.
- * Into: `[ { a: 'b', c: 'd' }, { d: 'e', f: 'g' } ]`.
+ * Creates a new tracing client.
*
- * @internal
+ * @param options - Options used to configure the tracing client.
+ * @returns - An instance of {@link TracingClient}.
*/
-function parseCAEChallenge(challenges) {
- const bearerChallenges = `, ${challenges.trim()}`.split(", Bearer ").filter((x) => x);
- return bearerChallenges.map((challenge) => {
- const challengeParts = `${challenge.trim()}, `.split('", ').filter((x) => x);
- const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split('="')));
- // Key-value pairs to plain object:
- return keyValuePairs.reduce((a, b) => (Object.assign(Object.assign({}, a), b)), {});
- });
+function createTracingClient(options) {
+ const { namespace, packageName, packageVersion } = options;
+ function startSpan(name, operationOptions, spanOptions) {
+ var _a;
+ const startSpanResult = (0, instrumenter_js_1.getInstrumenter)().startSpan(name, Object.assign(Object.assign({}, spanOptions), { packageName: packageName, packageVersion: packageVersion, tracingContext: (_a = operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext }));
+ let tracingContext = startSpanResult.tracingContext;
+ const span = startSpanResult.span;
+ if (!tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)) {
+ tracingContext = tracingContext.setValue(tracingContext_js_1.knownContextKeys.namespace, namespace);
+ }
+ span.setAttribute("az.namespace", tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace));
+ const updatedOptions = Object.assign({}, operationOptions, {
+ tracingOptions: Object.assign(Object.assign({}, operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions), { tracingContext }),
+ });
+ return {
+ span,
+ updatedOptions,
+ };
+ }
+ async function withSpan(name, operationOptions, callback, spanOptions) {
+ const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions);
+ try {
+ const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span)));
+ span.setStatus({ status: "success" });
+ return result;
+ }
+ catch (err) {
+ span.setStatus({ status: "error", error: err });
+ throw err;
+ }
+ finally {
+ span.end();
+ }
+ }
+ function withContext(context, callback, ...callbackArgs) {
+ return (0, instrumenter_js_1.getInstrumenter)().withContext(context, callback, ...callbackArgs);
+ }
+ /**
+ * Parses a traceparent header value into a span identifier.
+ *
+ * @param traceparentHeader - The traceparent header to parse.
+ * @returns An implementation-specific identifier for the span.
+ */
+ function parseTraceparentHeader(traceparentHeader) {
+ return (0, instrumenter_js_1.getInstrumenter)().parseTraceparentHeader(traceparentHeader);
+ }
+ /**
+ * Creates a set of request headers to propagate tracing information to a backend.
+ *
+ * @param tracingContext - The context containing the span to serialize.
+ * @returns The set of headers to add to a request.
+ */
+ function createRequestHeaders(tracingContext) {
+ return (0, instrumenter_js_1.getInstrumenter)().createRequestHeaders(tracingContext);
+ }
+ return {
+ startSpan,
+ withSpan,
+ withContext,
+ parseTraceparentHeader,
+ createRequestHeaders,
+ };
}
-exports.parseCAEChallenge = parseCAEChallenge;
+//# sourceMappingURL=tracingClient.js.map
+
+/***/ }),
+
+/***/ 79186:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.TracingContextImpl = exports.knownContextKeys = void 0;
+exports.createTracingContext = createTracingContext;
+/** @internal */
+exports.knownContextKeys = {
+ span: Symbol.for("@azure/core-tracing span"),
+ namespace: Symbol.for("@azure/core-tracing namespace"),
+};
/**
- * This function can be used as a callback for the `bearerTokenAuthenticationPolicy` of `@azure/core-rest-pipeline`, to support CAE challenges:
- * [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation).
- *
- * Call the `bearerTokenAuthenticationPolicy` with the following options:
- *
- * ```ts
- * import { bearerTokenAuthenticationPolicy } from "@azure/core-rest-pipeline";
- * import { authorizeRequestOnClaimChallenge } from "@azure/core-client";
- *
- * const bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy({
- * authorizeRequestOnChallenge: authorizeRequestOnClaimChallenge
- * });
- * ```
- *
- * Once provided, the `bearerTokenAuthenticationPolicy` policy will internally handle Continuous Access Evaluation (CAE) challenges.
- * When it can't complete a challenge it will return the 401 (unauthorized) response from ARM.
- *
- * Example challenge with claims:
+ * Creates a new {@link TracingContext} with the given options.
+ * @param options - A set of known keys that may be set on the context.
+ * @returns A new {@link TracingContext} with the given options.
*
- * ```
- * Bearer authorization_uri="https://login.windows-ppe.net/", error="invalid_token",
- * error_description="User session has been revoked",
- * claims="eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwgInZhbHVlIjoiMTYwMzc0MjgwMCJ9fX0="
- * ```
+ * @internal
*/
-async function authorizeRequestOnClaimChallenge(onChallengeOptions) {
- const { scopes, response } = onChallengeOptions;
- const logger = onChallengeOptions.logger || log_js_1.logger;
- const challenge = response.headers.get("WWW-Authenticate");
- if (!challenge) {
- logger.info(`The WWW-Authenticate header was missing. Failed to perform the Continuous Access Evaluation authentication flow.`);
- return false;
+function createTracingContext(options = {}) {
+ let context = new TracingContextImpl(options.parentContext);
+ if (options.span) {
+ context = context.setValue(exports.knownContextKeys.span, options.span);
+ }
+ if (options.namespace) {
+ context = context.setValue(exports.knownContextKeys.namespace, options.namespace);
}
- const challenges = parseCAEChallenge(challenge) || [];
- const parsedChallenge = challenges.find((x) => x.claims);
- if (!parsedChallenge) {
- logger.info(`The WWW-Authenticate header was missing the necessary "claims" to perform the Continuous Access Evaluation authentication flow.`);
- return false;
+ return context;
+}
+/** @internal */
+class TracingContextImpl {
+ constructor(initialContext) {
+ this._contextMap =
+ initialContext instanceof TracingContextImpl
+ ? new Map(initialContext._contextMap)
+ : new Map();
}
- const accessToken = await onChallengeOptions.getAccessToken(parsedChallenge.scope ? [parsedChallenge.scope] : scopes, {
- claims: (0, base64_js_1.decodeStringToString)(parsedChallenge.claims),
- });
- if (!accessToken) {
- return false;
+ setValue(key, value) {
+ const newContext = new TracingContextImpl(this);
+ newContext._contextMap.set(key, value);
+ return newContext;
+ }
+ getValue(key) {
+ return this._contextMap.get(key);
+ }
+ deleteValue(key) {
+ const newContext = new TracingContextImpl(this);
+ newContext._contextMap.delete(key);
+ return newContext;
}
- onChallengeOptions.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
- return true;
}
-exports.authorizeRequestOnClaimChallenge = authorizeRequestOnClaimChallenge;
-//# sourceMappingURL=authorizeRequestOnClaimChallenge.js.map
+exports.TracingContextImpl = TracingContextImpl;
+//# sourceMappingURL=tracingContext.js.map
/***/ }),
-/***/ 7454:
+/***/ 95209:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
+// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.authorizeRequestOnTenantChallenge = void 0;
-/**
- * A set of constants used internally when processing requests.
- */
-const Constants = {
- DefaultScope: "/.default",
- /**
- * Defines constants for use with HTTP headers.
- */
- HeaderConstants: {
- /**
- * The Authorization header.
- */
- AUTHORIZATION: "authorization",
- },
-};
-function isUuid(text) {
- return /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(text);
-}
-/**
- * Defines a callback to handle auth challenge for Storage APIs.
- * This implements the bearer challenge process described here: https://docs.microsoft.com/rest/api/storageservices/authorize-with-azure-active-directory#bearer-challenge
- * Handling has specific features for storage that departs to the general AAD challenge docs.
- **/
-const authorizeRequestOnTenantChallenge = async (challengeOptions) => {
- const requestOptions = requestToOptions(challengeOptions.request);
- const challenge = getChallenge(challengeOptions.response);
- if (challenge) {
- const challengeInfo = parseChallenge(challenge);
- const challengeScopes = buildScopes(challengeOptions, challengeInfo);
- const tenantId = extractTenantId(challengeInfo);
- if (!tenantId) {
- return false;
- }
- const accessToken = await challengeOptions.getAccessToken(challengeScopes, Object.assign(Object.assign({}, requestOptions), { tenantId }));
- if (!accessToken) {
- return false;
- }
- challengeOptions.request.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${accessToken.token}`);
- return true;
- }
- return false;
-};
-exports.authorizeRequestOnTenantChallenge = authorizeRequestOnTenantChallenge;
-/**
- * Extracts the tenant id from the challenge information
- * The tenant id is contained in the authorization_uri as the first
- * path part.
- */
-function extractTenantId(challengeInfo) {
- const parsedAuthUri = new URL(challengeInfo.authorization_uri);
- const pathSegments = parsedAuthUri.pathname.split("/");
- const tenantId = pathSegments[1];
- if (tenantId && isUuid(tenantId)) {
- return tenantId;
- }
- return undefined;
-}
+exports.cancelablePromiseRace = cancelablePromiseRace;
/**
- * Builds the authentication scopes based on the information that comes in the
- * challenge information. Scopes url is present in the resource_id, if it is empty
- * we keep using the original scopes.
+ * promise.race() wrapper that aborts rest of promises as soon as the first promise settles.
*/
-function buildScopes(challengeOptions, challengeInfo) {
- if (!challengeInfo.resource_id) {
- return challengeOptions.scopes;
+async function cancelablePromiseRace(abortablePromiseBuilders, options) {
+ var _a, _b;
+ const aborter = new AbortController();
+ function abortHandler() {
+ aborter.abort();
}
- const challengeScopes = new URL(challengeInfo.resource_id);
- challengeScopes.pathname = Constants.DefaultScope;
- let scope = challengeScopes.toString();
- if (scope === "https://disk.azure.com/.default") {
- // the extra slash is required by the service
- scope = "https://disk.azure.com//.default";
+ (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler);
+ try {
+ return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal })));
}
- return [scope];
-}
-/**
- * We will retrieve the challenge only if the response status code was 401,
- * and if the response contained the header "WWW-Authenticate" with a non-empty value.
- */
-function getChallenge(response) {
- const challenge = response.headers.get("WWW-Authenticate");
- if (response.status === 401 && challenge) {
- return challenge;
+ finally {
+ aborter.abort();
+ (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler);
}
- return;
}
+//# sourceMappingURL=aborterUtils.js.map
+
+/***/ }),
+
+/***/ 2741:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.uint8ArrayToString = uint8ArrayToString;
+exports.stringToUint8Array = stringToUint8Array;
/**
- * Converts: `Bearer a="b" c="d"`.
- * Into: `[ { a: 'b', c: 'd' }]`.
- *
- * @internal
+ * The helper that transforms bytes with specific character encoding into string
+ * @param bytes - the uint8array bytes
+ * @param format - the format we use to encode the byte
+ * @returns a string of the encoded string
*/
-function parseChallenge(challenge) {
- const bearerChallenge = challenge.slice("Bearer ".length);
- const challengeParts = `${bearerChallenge.trim()} `.split(" ").filter((x) => x);
- const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split("=")));
- // Key-value pairs to plain object:
- return keyValuePairs.reduce((a, b) => (Object.assign(Object.assign({}, a), b)), {});
+function uint8ArrayToString(bytes, format) {
+ return Buffer.from(bytes).toString(format);
}
/**
- * Extracts the options form a Pipeline Request for later re-use
+ * The helper that transforms string to specific character encoded bytes array.
+ * @param value - the string to be converted
+ * @param format - the format we use to decode the value
+ * @returns a uint8array
*/
-function requestToOptions(request) {
- return {
- abortSignal: request.abortSignal,
- requestOptions: {
- timeout: request.timeout,
- },
- tracingOptions: request.tracingOptions,
- };
+function stringToUint8Array(value, format) {
+ return Buffer.from(value, format);
}
-//# sourceMappingURL=authorizeRequestOnTenantChallenge.js.map
+//# sourceMappingURL=bytesEncoding.js.map
/***/ }),
-/***/ 741:
+/***/ 8162:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
+// Licensed under the MIT License.
+var _a, _b, _c, _d;
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.decodeStringToString = exports.decodeString = exports.encodeByteArray = exports.encodeString = void 0;
+exports.isReactNative = exports.isNodeRuntime = exports.isNode = exports.isNodeLike = exports.isBun = exports.isDeno = exports.isWebWorker = exports.isBrowser = void 0;
/**
- * Encodes a string in base64 format.
- * @param value - the string to encode
- * @internal
+ * A constant that indicates whether the environment the code is running is a Web Browser.
*/
-function encodeString(value) {
- return Buffer.from(value).toString("base64");
-}
-exports.encodeString = encodeString;
+// eslint-disable-next-line @azure/azure-sdk/ts-no-window
+exports.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
/**
- * Encodes a byte array in base64 format.
- * @param value - the Uint8Aray to encode
- * @internal
+ * A constant that indicates whether the environment the code is running is a Web Worker.
*/
-function encodeByteArray(value) {
- const bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer);
- return bufferValue.toString("base64");
-}
-exports.encodeByteArray = encodeByteArray;
+exports.isWebWorker = typeof self === "object" &&
+ typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" &&
+ (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" ||
+ ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" ||
+ ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope");
/**
- * Decodes a base64 string into a byte array.
- * @param value - the base64 string to decode
- * @internal
+ * A constant that indicates whether the environment the code is running is Deno.
*/
-function decodeString(value) {
- return Buffer.from(value, "base64");
-}
-exports.decodeString = decodeString;
+exports.isDeno = typeof Deno !== "undefined" &&
+ typeof Deno.version !== "undefined" &&
+ typeof Deno.version.deno !== "undefined";
/**
- * Decodes a base64 string into a string.
- * @param value - the base64 string to decode
- * @internal
+ * A constant that indicates whether the environment the code is running is Bun.sh.
*/
-function decodeStringToString(value) {
- return Buffer.from(value, "base64").toString();
-}
-exports.decodeStringToString = decodeStringToString;
-//# sourceMappingURL=base64.js.map
+exports.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined";
+/**
+ * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
+ */
+exports.isNodeLike = typeof globalThis.process !== "undefined" &&
+ Boolean(globalThis.process.version) &&
+ Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node);
+/**
+ * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
+ * @deprecated Use `isNodeLike` instead.
+ */
+exports.isNode = exports.isNodeLike;
+/**
+ * A constant that indicates whether the environment the code is running is Node.JS.
+ */
+exports.isNodeRuntime = exports.isNodeLike && !exports.isBun && !exports.isDeno;
+/**
+ * A constant that indicates whether the environment the code is running is in React-Native.
+ */
+// https://github.com/facebook/react-native/blob/main/packages/react-native/Libraries/Core/setUpNavigator.js
+exports.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative";
+//# sourceMappingURL=checkEnvironment.js.map
/***/ }),
-/***/ 111:
+/***/ 63128:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
+// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.deserializationPolicy = exports.deserializationPolicyName = void 0;
-const interfaces_js_1 = __nccwpck_require__(6058);
-const core_rest_pipeline_1 = __nccwpck_require__(778);
-const serializer_js_1 = __nccwpck_require__(1530);
-const operationHelpers_js_1 = __nccwpck_require__(7307);
-const defaultJsonContentTypes = ["application/json", "text/json"];
-const defaultXmlContentTypes = ["application/xml", "application/atom+xml"];
-/**
- * The programmatic identifier of the deserializationPolicy.
- */
-exports.deserializationPolicyName = "deserializationPolicy";
+exports.createAbortablePromise = createAbortablePromise;
+const abort_controller_1 = __nccwpck_require__(16492);
/**
- * This policy handles parsing out responses according to OperationSpecs on the request.
+ * Creates an abortable promise.
+ * @param buildPromise - A function that takes the resolve and reject functions as parameters.
+ * @param options - The options for the abortable promise.
+ * @returns A promise that can be aborted.
*/
-function deserializationPolicy(options = {}) {
- var _a, _b, _c, _d, _e, _f, _g;
- const jsonContentTypes = (_b = (_a = options.expectedContentTypes) === null || _a === void 0 ? void 0 : _a.json) !== null && _b !== void 0 ? _b : defaultJsonContentTypes;
- const xmlContentTypes = (_d = (_c = options.expectedContentTypes) === null || _c === void 0 ? void 0 : _c.xml) !== null && _d !== void 0 ? _d : defaultXmlContentTypes;
- const parseXML = options.parseXML;
- const serializerOptions = options.serializerOptions;
- const updatedOptions = {
- xml: {
- rootName: (_e = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _e !== void 0 ? _e : "",
- includeRoot: (_f = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _f !== void 0 ? _f : false,
- xmlCharKey: (_g = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _g !== void 0 ? _g : interfaces_js_1.XML_CHARKEY,
- },
- };
- return {
- name: exports.deserializationPolicyName,
- async sendRequest(request, next) {
- const response = await next(request);
- return deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, updatedOptions, parseXML);
- },
- };
-}
-exports.deserializationPolicy = deserializationPolicy;
-function getOperationResponseMap(parsedResponse) {
- let result;
- const request = parsedResponse.request;
- const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
- const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
- if (operationSpec) {
- if (!(operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter)) {
- result = operationSpec.responses[parsedResponse.status];
- }
- else {
- result = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter(operationSpec, parsedResponse);
- }
- }
- return result;
-}
-function shouldDeserializeResponse(parsedResponse) {
- const request = parsedResponse.request;
- const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
- const shouldDeserialize = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.shouldDeserialize;
- let result;
- if (shouldDeserialize === undefined) {
- result = true;
- }
- else if (typeof shouldDeserialize === "boolean") {
- result = shouldDeserialize;
- }
- else {
- result = shouldDeserialize(parsedResponse);
- }
- return result;
-}
-async function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options, parseXML) {
- const parsedResponse = await parse(jsonContentTypes, xmlContentTypes, response, options, parseXML);
- if (!shouldDeserializeResponse(parsedResponse)) {
- return parsedResponse;
- }
- const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(parsedResponse.request);
- const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
- if (!operationSpec || !operationSpec.responses) {
- return parsedResponse;
- }
- const responseSpec = getOperationResponseMap(parsedResponse);
- const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec, options);
- if (error) {
- throw error;
- }
- else if (shouldReturnResponse) {
- return parsedResponse;
- }
- // An operation response spec does exist for current status code, so
- // use it to deserialize the response.
- if (responseSpec) {
- if (responseSpec.bodyMapper) {
- let valueToDeserialize = parsedResponse.parsedBody;
- if (operationSpec.isXML && responseSpec.bodyMapper.type.name === serializer_js_1.MapperTypeNames.Sequence) {
- valueToDeserialize =
- typeof valueToDeserialize === "object"
- ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName]
- : [];
- }
- try {
- parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options);
- }
- catch (deserializeError) {
- const restError = new core_rest_pipeline_1.RestError(`Error ${deserializeError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, {
- statusCode: parsedResponse.status,
- request: parsedResponse.request,
- response: parsedResponse,
- });
- throw restError;
- }
- }
- else if (operationSpec.httpMethod === "HEAD") {
- // head methods never have a body, but we return a boolean to indicate presence/absence of the resource
- parsedResponse.parsedBody = response.status >= 200 && response.status < 300;
- }
- if (responseSpec.headersMapper) {
- parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders", { xml: {}, ignoreUnknownProperties: true });
- }
- }
- return parsedResponse;
-}
-function isOperationSpecEmpty(operationSpec) {
- const expectedStatusCodes = Object.keys(operationSpec.responses);
- return (expectedStatusCodes.length === 0 ||
- (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"));
-}
-function handleErrorResponse(parsedResponse, operationSpec, responseSpec, options) {
- var _a;
- const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300;
- const isExpectedStatusCode = isOperationSpecEmpty(operationSpec)
- ? isSuccessByStatus
- : !!responseSpec;
- if (isExpectedStatusCode) {
- if (responseSpec) {
- if (!responseSpec.isError) {
- return { error: null, shouldReturnResponse: false };
- }
- }
- else {
- return { error: null, shouldReturnResponse: false };
- }
- }
- const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default;
- const initialErrorMessage = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status))
- ? `Unexpected status code: ${parsedResponse.status}`
- : parsedResponse.bodyAsText;
- const error = new core_rest_pipeline_1.RestError(initialErrorMessage, {
- statusCode: parsedResponse.status,
- request: parsedResponse.request,
- response: parsedResponse,
- });
- // If the item failed but there's no error spec or default spec to deserialize the error,
- // we should fail so we just throw the parsed response
- if (!errorResponseSpec) {
- throw error;
- }
- const defaultBodyMapper = errorResponseSpec.bodyMapper;
- const defaultHeadersMapper = errorResponseSpec.headersMapper;
- try {
- // If error response has a body, try to deserialize it using default body mapper.
- // Then try to extract error code & message from it
- if (parsedResponse.parsedBody) {
- const parsedBody = parsedResponse.parsedBody;
- let deserializedError;
- if (defaultBodyMapper) {
- let valueToDeserialize = parsedBody;
- if (operationSpec.isXML && defaultBodyMapper.type.name === serializer_js_1.MapperTypeNames.Sequence) {
- valueToDeserialize = [];
- const elementName = defaultBodyMapper.xmlElementName;
- if (typeof parsedBody === "object" && elementName) {
- valueToDeserialize = parsedBody[elementName];
- }
- }
- deserializedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody", options);
- }
- const internalError = parsedBody.error || deserializedError || parsedBody;
- error.code = internalError.code;
- if (internalError.message) {
- error.message = internalError.message;
- }
- if (defaultBodyMapper) {
- error.response.parsedBody = deserializedError;
- }
+function createAbortablePromise(buildPromise, options) {
+ const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {};
+ return new Promise((resolve, reject) => {
+ function rejectOnAbort() {
+ reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted."));
}
- // If error response has headers, try to deserialize it using default header mapper
- if (parsedResponse.headers && defaultHeadersMapper) {
- error.response.parsedHeaders =
- operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders");
+ function removeListeners() {
+ abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort);
}
- }
- catch (defaultError) {
- error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`;
- }
- return { error, shouldReturnResponse: false };
-}
-async function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts, parseXML) {
- var _a;
- if (!((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) &&
- operationResponse.bodyAsText) {
- const text = operationResponse.bodyAsText;
- const contentType = operationResponse.headers.get("Content-Type") || "";
- const contentComponents = !contentType
- ? []
- : contentType.split(";").map((component) => component.toLowerCase());
- try {
- if (contentComponents.length === 0 ||
- contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) {
- operationResponse.parsedBody = JSON.parse(text);
- return operationResponse;
- }
- else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) {
- if (!parseXML) {
- throw new Error("Parsing XML not supported.");
- }
- const body = await parseXML(text, opts.xml);
- operationResponse.parsedBody = body;
- return operationResponse;
- }
+ function onAbort() {
+ cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort();
+ removeListeners();
+ rejectOnAbort();
}
- catch (err) {
- const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`;
- const errCode = err.code || core_rest_pipeline_1.RestError.PARSE_ERROR;
- const e = new core_rest_pipeline_1.RestError(msg, {
- code: errCode,
- statusCode: operationResponse.status,
- request: operationResponse.request,
- response: operationResponse,
- });
- throw e;
+ if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) {
+ return rejectOnAbort();
}
- }
- return operationResponse;
-}
-//# sourceMappingURL=deserializationPolicy.js.map
-
-/***/ }),
-
-/***/ 6323:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getCachedDefaultHttpClient = void 0;
-const core_rest_pipeline_1 = __nccwpck_require__(778);
-let cachedHttpClient;
-function getCachedDefaultHttpClient() {
- if (!cachedHttpClient) {
- cachedHttpClient = (0, core_rest_pipeline_1.createDefaultHttpClient)();
- }
- return cachedHttpClient;
+ try {
+ buildPromise((x) => {
+ removeListeners();
+ resolve(x);
+ }, (x) => {
+ removeListeners();
+ reject(x);
+ });
+ }
+ catch (err) {
+ reject(err);
+ }
+ abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort);
+ });
}
-exports.getCachedDefaultHttpClient = getCachedDefaultHttpClient;
-//# sourceMappingURL=httpClientCache.js.map
+//# sourceMappingURL=createAbortablePromise.js.map
/***/ }),
-/***/ 160:
+/***/ 90636:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
+// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.authorizeRequestOnTenantChallenge = exports.authorizeRequestOnClaimChallenge = exports.serializationPolicyName = exports.serializationPolicy = exports.deserializationPolicyName = exports.deserializationPolicy = exports.XML_CHARKEY = exports.XML_ATTRKEY = exports.createClientPipeline = exports.ServiceClient = exports.MapperTypeNames = exports.createSerializer = void 0;
-var serializer_js_1 = __nccwpck_require__(1530);
-Object.defineProperty(exports, "createSerializer", ({ enumerable: true, get: function () { return serializer_js_1.createSerializer; } }));
-Object.defineProperty(exports, "MapperTypeNames", ({ enumerable: true, get: function () { return serializer_js_1.MapperTypeNames; } }));
-var serviceClient_js_1 = __nccwpck_require__(9544);
-Object.defineProperty(exports, "ServiceClient", ({ enumerable: true, get: function () { return serviceClient_js_1.ServiceClient; } }));
-var pipeline_js_1 = __nccwpck_require__(1755);
-Object.defineProperty(exports, "createClientPipeline", ({ enumerable: true, get: function () { return pipeline_js_1.createClientPipeline; } }));
-var interfaces_js_1 = __nccwpck_require__(6058);
-Object.defineProperty(exports, "XML_ATTRKEY", ({ enumerable: true, get: function () { return interfaces_js_1.XML_ATTRKEY; } }));
-Object.defineProperty(exports, "XML_CHARKEY", ({ enumerable: true, get: function () { return interfaces_js_1.XML_CHARKEY; } }));
-var deserializationPolicy_js_1 = __nccwpck_require__(111);
-Object.defineProperty(exports, "deserializationPolicy", ({ enumerable: true, get: function () { return deserializationPolicy_js_1.deserializationPolicy; } }));
-Object.defineProperty(exports, "deserializationPolicyName", ({ enumerable: true, get: function () { return deserializationPolicy_js_1.deserializationPolicyName; } }));
-var serializationPolicy_js_1 = __nccwpck_require__(6234);
-Object.defineProperty(exports, "serializationPolicy", ({ enumerable: true, get: function () { return serializationPolicy_js_1.serializationPolicy; } }));
-Object.defineProperty(exports, "serializationPolicyName", ({ enumerable: true, get: function () { return serializationPolicy_js_1.serializationPolicyName; } }));
-var authorizeRequestOnClaimChallenge_js_1 = __nccwpck_require__(2460);
-Object.defineProperty(exports, "authorizeRequestOnClaimChallenge", ({ enumerable: true, get: function () { return authorizeRequestOnClaimChallenge_js_1.authorizeRequestOnClaimChallenge; } }));
-var authorizeRequestOnTenantChallenge_js_1 = __nccwpck_require__(7454);
-Object.defineProperty(exports, "authorizeRequestOnTenantChallenge", ({ enumerable: true, get: function () { return authorizeRequestOnTenantChallenge_js_1.authorizeRequestOnTenantChallenge; } }));
-//# sourceMappingURL=index.js.map
+exports.delay = delay;
+exports.calculateRetryDelay = calculateRetryDelay;
+const createAbortablePromise_js_1 = __nccwpck_require__(63128);
+const random_js_1 = __nccwpck_require__(64196);
+const StandardAbortMessage = "The delay was aborted.";
+/**
+ * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds.
+ * @param timeInMs - The number of milliseconds to be delayed.
+ * @param options - The options for delay - currently abort options
+ * @returns Promise that is resolved after timeInMs
+ */
+function delay(timeInMs, options) {
+ let token;
+ const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {};
+ return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve) => {
+ token = setTimeout(resolve, timeInMs);
+ }, {
+ cleanupBeforeAbort: () => clearTimeout(token),
+ abortSignal,
+ abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage,
+ });
+}
+/**
+ * Calculates the delay interval for retry attempts using exponential delay with jitter.
+ * @param retryAttempt - The current retry attempt number.
+ * @param config - The exponential retry configuration.
+ * @returns An object containing the calculated retry delay.
+ */
+function calculateRetryDelay(retryAttempt, config) {
+ // Exponentially increase the delay each time
+ const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt);
+ // Don't let the delay exceed the maximum
+ const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay);
+ // Allow the final value to have some "jitter" (within 50% of the delay size) so
+ // that retries across multiple clients don't occur simultaneously.
+ const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2);
+ return { retryAfterInMs };
+}
+//# sourceMappingURL=delay.js.map
/***/ }),
-/***/ 2066:
+/***/ 99945:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
+// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getPathStringFromParameter = exports.getStreamingResponseStatusCodes = void 0;
-const serializer_js_1 = __nccwpck_require__(1530);
+exports.isError = isError;
+exports.getErrorMessage = getErrorMessage;
+const object_js_1 = __nccwpck_require__(17756);
/**
- * Gets the list of status codes for streaming responses.
- * @internal
+ * Typeguard for an error object shape (has name and message)
+ * @param e - Something caught by a catch clause.
*/
-function getStreamingResponseStatusCodes(operationSpec) {
- const result = new Set();
- for (const statusCode in operationSpec.responses) {
- const operationResponse = operationSpec.responses[statusCode];
- if (operationResponse.bodyMapper &&
- operationResponse.bodyMapper.type.name === serializer_js_1.MapperTypeNames.Stream) {
- result.add(Number(statusCode));
- }
+function isError(e) {
+ if ((0, object_js_1.isObject)(e)) {
+ const hasName = typeof e.name === "string";
+ const hasMessage = typeof e.message === "string";
+ return hasName && hasMessage;
}
- return result;
+ return false;
}
-exports.getStreamingResponseStatusCodes = getStreamingResponseStatusCodes;
/**
- * Get the path to this parameter's value as a dotted string (a.b.c).
- * @param parameter - The parameter to get the path string for.
- * @returns The path to this parameter's value as a dotted string.
- * @internal
+ * Given what is thought to be an error object, return the message if possible.
+ * If the message is missing, returns a stringified version of the input.
+ * @param e - Something thrown from a try block
+ * @returns The error message or a string of the input
*/
-function getPathStringFromParameter(parameter) {
- const { parameterPath, mapper } = parameter;
- let result;
- if (typeof parameterPath === "string") {
- result = parameterPath;
- }
- else if (Array.isArray(parameterPath)) {
- result = parameterPath.join(".");
+function getErrorMessage(e) {
+ if (isError(e)) {
+ return e.message;
}
else {
- result = mapper.serializedName;
+ let stringified;
+ try {
+ if (typeof e === "object" && e) {
+ stringified = JSON.stringify(e);
+ }
+ else {
+ stringified = String(e);
+ }
+ }
+ catch (err) {
+ stringified = "[unable to stringify input]";
+ }
+ return `Unknown error ${stringified}`;
}
- return result;
}
-exports.getPathStringFromParameter = getPathStringFromParameter;
-//# sourceMappingURL=interfaceHelpers.js.map
+//# sourceMappingURL=error.js.map
/***/ }),
-/***/ 6058:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 87779:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
+// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.XML_CHARKEY = exports.XML_ATTRKEY = void 0;
-/**
- * Default key used to access the XML attributes.
- */
-exports.XML_ATTRKEY = "$";
-/**
- * Default key used to access the XML value content.
- */
-exports.XML_CHARKEY = "_";
-//# sourceMappingURL=interfaces.js.map
+exports.stringToUint8Array = exports.uint8ArrayToString = exports.isWebWorker = exports.isReactNative = exports.isDeno = exports.isNodeRuntime = exports.isNodeLike = exports.isNode = exports.isBun = exports.isBrowser = exports.randomUUID = exports.objectHasProperty = exports.isObjectWithProperties = exports.isDefined = exports.computeSha256Hmac = exports.computeSha256Hash = exports.getErrorMessage = exports.isError = exports.isObject = exports.getRandomIntegerInclusive = exports.createAbortablePromise = exports.cancelablePromiseRace = exports.calculateRetryDelay = exports.delay = void 0;
+var delay_js_1 = __nccwpck_require__(90636);
+Object.defineProperty(exports, "delay", ({ enumerable: true, get: function () { return delay_js_1.delay; } }));
+Object.defineProperty(exports, "calculateRetryDelay", ({ enumerable: true, get: function () { return delay_js_1.calculateRetryDelay; } }));
+var aborterUtils_js_1 = __nccwpck_require__(95209);
+Object.defineProperty(exports, "cancelablePromiseRace", ({ enumerable: true, get: function () { return aborterUtils_js_1.cancelablePromiseRace; } }));
+var createAbortablePromise_js_1 = __nccwpck_require__(63128);
+Object.defineProperty(exports, "createAbortablePromise", ({ enumerable: true, get: function () { return createAbortablePromise_js_1.createAbortablePromise; } }));
+var random_js_1 = __nccwpck_require__(64196);
+Object.defineProperty(exports, "getRandomIntegerInclusive", ({ enumerable: true, get: function () { return random_js_1.getRandomIntegerInclusive; } }));
+var object_js_1 = __nccwpck_require__(17756);
+Object.defineProperty(exports, "isObject", ({ enumerable: true, get: function () { return object_js_1.isObject; } }));
+var error_js_1 = __nccwpck_require__(99945);
+Object.defineProperty(exports, "isError", ({ enumerable: true, get: function () { return error_js_1.isError; } }));
+Object.defineProperty(exports, "getErrorMessage", ({ enumerable: true, get: function () { return error_js_1.getErrorMessage; } }));
+var sha256_js_1 = __nccwpck_require__(19732);
+Object.defineProperty(exports, "computeSha256Hash", ({ enumerable: true, get: function () { return sha256_js_1.computeSha256Hash; } }));
+Object.defineProperty(exports, "computeSha256Hmac", ({ enumerable: true, get: function () { return sha256_js_1.computeSha256Hmac; } }));
+var typeGuards_js_1 = __nccwpck_require__(66277);
+Object.defineProperty(exports, "isDefined", ({ enumerable: true, get: function () { return typeGuards_js_1.isDefined; } }));
+Object.defineProperty(exports, "isObjectWithProperties", ({ enumerable: true, get: function () { return typeGuards_js_1.isObjectWithProperties; } }));
+Object.defineProperty(exports, "objectHasProperty", ({ enumerable: true, get: function () { return typeGuards_js_1.objectHasProperty; } }));
+var uuidUtils_js_1 = __nccwpck_require__(98795);
+Object.defineProperty(exports, "randomUUID", ({ enumerable: true, get: function () { return uuidUtils_js_1.randomUUID; } }));
+var checkEnvironment_js_1 = __nccwpck_require__(8162);
+Object.defineProperty(exports, "isBrowser", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isBrowser; } }));
+Object.defineProperty(exports, "isBun", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isBun; } }));
+Object.defineProperty(exports, "isNode", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isNode; } }));
+Object.defineProperty(exports, "isNodeLike", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isNodeLike; } }));
+Object.defineProperty(exports, "isNodeRuntime", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isNodeRuntime; } }));
+Object.defineProperty(exports, "isDeno", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isDeno; } }));
+Object.defineProperty(exports, "isReactNative", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isReactNative; } }));
+Object.defineProperty(exports, "isWebWorker", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isWebWorker; } }));
+var bytesEncoding_js_1 = __nccwpck_require__(2741);
+Object.defineProperty(exports, "uint8ArrayToString", ({ enumerable: true, get: function () { return bytesEncoding_js_1.uint8ArrayToString; } }));
+Object.defineProperty(exports, "stringToUint8Array", ({ enumerable: true, get: function () { return bytesEncoding_js_1.stringToUint8Array; } }));
+//# sourceMappingURL=index.js.map
/***/ }),
-/***/ 9994:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 17756:
+/***/ ((__unused_webpack_module, exports) => {
"use strict";
// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
+// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.logger = void 0;
-const logger_1 = __nccwpck_require__(6515);
-exports.logger = (0, logger_1.createClientLogger)("core-client");
-//# sourceMappingURL=log.js.map
+exports.isObject = isObject;
+/**
+ * Helper to determine when an input is a generic JS object.
+ * @returns true when input is an object type that is not null, Array, RegExp, or Date.
+ */
+function isObject(input) {
+ return (typeof input === "object" &&
+ input !== null &&
+ !Array.isArray(input) &&
+ !(input instanceof RegExp) &&
+ !(input instanceof Date));
+}
+//# sourceMappingURL=object.js.map
/***/ }),
-/***/ 7307:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 64196:
+/***/ ((__unused_webpack_module, exports) => {
"use strict";
// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
+// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getOperationRequestInfo = exports.getOperationArgumentValueFromParameter = void 0;
-const state_js_1 = __nccwpck_require__(3345);
+exports.getRandomIntegerInclusive = getRandomIntegerInclusive;
/**
- * @internal
- * Retrieves the value to use for a given operation argument
- * @param operationArguments - The arguments passed from the generated client
- * @param parameter - The parameter description
- * @param fallbackObject - If something isn't found in the arguments bag, look here.
- * Generally used to look at the service client properties.
+ * Returns a random integer value between a lower and upper bound,
+ * inclusive of both bounds.
+ * Note that this uses Math.random and isn't secure. If you need to use
+ * this for any kind of security purpose, find a better source of random.
+ * @param min - The smallest integer value allowed.
+ * @param max - The largest integer value allowed.
*/
-function getOperationArgumentValueFromParameter(operationArguments, parameter, fallbackObject) {
- let parameterPath = parameter.parameterPath;
- const parameterMapper = parameter.mapper;
- let value;
- if (typeof parameterPath === "string") {
- parameterPath = [parameterPath];
- }
- if (Array.isArray(parameterPath)) {
- if (parameterPath.length > 0) {
- if (parameterMapper.isConstant) {
- value = parameterMapper.defaultValue;
- }
- else {
- let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath);
- if (!propertySearchResult.propertyFound && fallbackObject) {
- propertySearchResult = getPropertyFromParameterPath(fallbackObject, parameterPath);
- }
- let useDefaultValue = false;
- if (!propertySearchResult.propertyFound) {
- useDefaultValue =
- parameterMapper.required ||
- (parameterPath[0] === "options" && parameterPath.length === 2);
- }
- value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue;
- }
- }
- }
- else {
- if (parameterMapper.required) {
- value = {};
- }
- for (const propertyName in parameterPath) {
- const propertyMapper = parameterMapper.type.modelProperties[propertyName];
- const propertyPath = parameterPath[propertyName];
- const propertyValue = getOperationArgumentValueFromParameter(operationArguments, {
- parameterPath: propertyPath,
- mapper: propertyMapper,
- }, fallbackObject);
- if (propertyValue !== undefined) {
- if (!value) {
- value = {};
- }
- value[propertyName] = propertyValue;
- }
- }
- }
- return value;
-}
-exports.getOperationArgumentValueFromParameter = getOperationArgumentValueFromParameter;
-function getPropertyFromParameterPath(parent, parameterPath) {
- const result = { propertyFound: false };
- let i = 0;
- for (; i < parameterPath.length; ++i) {
- const parameterPathPart = parameterPath[i];
- // Make sure to check inherited properties too, so don't use hasOwnProperty().
- if (parent && parameterPathPart in parent) {
- parent = parent[parameterPathPart];
- }
- else {
- break;
- }
- }
- if (i === parameterPath.length) {
- result.propertyValue = parent;
- result.propertyFound = true;
- }
- return result;
-}
-const originalRequestSymbol = Symbol.for("@azure/core-client original request");
-function hasOriginalRequest(request) {
- return originalRequestSymbol in request;
-}
-function getOperationRequestInfo(request) {
- if (hasOriginalRequest(request)) {
- return getOperationRequestInfo(request[originalRequestSymbol]);
- }
- let info = state_js_1.state.operationRequestMap.get(request);
- if (!info) {
- info = {};
- state_js_1.state.operationRequestMap.set(request, info);
- }
- return info;
+function getRandomIntegerInclusive(min, max) {
+ // Make sure inputs are integers.
+ min = Math.ceil(min);
+ max = Math.floor(max);
+ // Pick a random offset from zero to the size of the range.
+ // Since Math.random() can never return 1, we have to make the range one larger
+ // in order to be inclusive of the maximum value after we take the floor.
+ const offset = Math.floor(Math.random() * (max - min + 1));
+ return offset + min;
}
-exports.getOperationRequestInfo = getOperationRequestInfo;
-//# sourceMappingURL=operationHelpers.js.map
+//# sourceMappingURL=random.js.map
/***/ }),
-/***/ 1755:
+/***/ 19732:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
+// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createClientPipeline = void 0;
-const deserializationPolicy_js_1 = __nccwpck_require__(111);
-const core_rest_pipeline_1 = __nccwpck_require__(778);
-const serializationPolicy_js_1 = __nccwpck_require__(6234);
+exports.computeSha256Hmac = computeSha256Hmac;
+exports.computeSha256Hash = computeSha256Hash;
+const crypto_1 = __nccwpck_require__(76982);
/**
- * Creates a new Pipeline for use with a Service Client.
- * Adds in deserializationPolicy by default.
- * Also adds in bearerTokenAuthenticationPolicy if passed a TokenCredential.
- * @param options - Options to customize the created pipeline.
+ * Generates a SHA-256 HMAC signature.
+ * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash.
+ * @param stringToSign - The data to be signed.
+ * @param encoding - The textual encoding to use for the returned HMAC digest.
*/
-function createClientPipeline(options = {}) {
- const pipeline = (0, core_rest_pipeline_1.createPipelineFromOptions)(options !== null && options !== void 0 ? options : {});
- if (options.credentialOptions) {
- pipeline.addPolicy((0, core_rest_pipeline_1.bearerTokenAuthenticationPolicy)({
- credential: options.credentialOptions.credential,
- scopes: options.credentialOptions.credentialScopes,
- }));
- }
- pipeline.addPolicy((0, serializationPolicy_js_1.serializationPolicy)(options.serializationOptions), { phase: "Serialize" });
- pipeline.addPolicy((0, deserializationPolicy_js_1.deserializationPolicy)(options.deserializationOptions), {
- phase: "Deserialize",
- });
- return pipeline;
+async function computeSha256Hmac(key, stringToSign, encoding) {
+ const decodedKey = Buffer.from(key, "base64");
+ return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding);
}
-exports.createClientPipeline = createClientPipeline;
-//# sourceMappingURL=pipeline.js.map
+/**
+ * Generates a SHA-256 hash.
+ * @param content - The data to be included in the hash.
+ * @param encoding - The textual encoding to use for the returned hash.
+ */
+async function computeSha256Hash(content, encoding) {
+ return (0, crypto_1.createHash)("sha256").update(content).digest(encoding);
+}
+//# sourceMappingURL=sha256.js.map
/***/ }),
-/***/ 6234:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 66277:
+/***/ ((__unused_webpack_module, exports) => {
"use strict";
// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
+// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.serializeRequestBody = exports.serializeHeaders = exports.serializationPolicy = exports.serializationPolicyName = void 0;
-const interfaces_js_1 = __nccwpck_require__(6058);
-const operationHelpers_js_1 = __nccwpck_require__(7307);
-const serializer_js_1 = __nccwpck_require__(1530);
-const interfaceHelpers_js_1 = __nccwpck_require__(2066);
-/**
- * The programmatic identifier of the serializationPolicy.
- */
-exports.serializationPolicyName = "serializationPolicy";
+exports.isDefined = isDefined;
+exports.isObjectWithProperties = isObjectWithProperties;
+exports.objectHasProperty = objectHasProperty;
/**
- * This policy handles assembling the request body and headers using
- * an OperationSpec and OperationArguments on the request.
+ * Helper TypeGuard that checks if something is defined or not.
+ * @param thing - Anything
*/
-function serializationPolicy(options = {}) {
- const stringifyXML = options.stringifyXML;
- return {
- name: exports.serializationPolicyName,
- async sendRequest(request, next) {
- const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
- const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
- const operationArguments = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationArguments;
- if (operationSpec && operationArguments) {
- serializeHeaders(request, operationArguments, operationSpec);
- serializeRequestBody(request, operationArguments, operationSpec, stringifyXML);
- }
- return next(request);
- },
- };
+function isDefined(thing) {
+ return typeof thing !== "undefined" && thing !== null;
}
-exports.serializationPolicy = serializationPolicy;
/**
- * @internal
+ * Helper TypeGuard that checks if the input is an object with the specified properties.
+ * @param thing - Anything.
+ * @param properties - The name of the properties that should appear in the object.
*/
-function serializeHeaders(request, operationArguments, operationSpec) {
- var _a, _b;
- if (operationSpec.headerParameters) {
- for (const headerParameter of operationSpec.headerParameters) {
- let headerValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, headerParameter);
- if ((headerValue !== null && headerValue !== undefined) || headerParameter.mapper.required) {
- headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(headerParameter));
- const headerCollectionPrefix = headerParameter.mapper
- .headerCollectionPrefix;
- if (headerCollectionPrefix) {
- for (const key of Object.keys(headerValue)) {
- request.headers.set(headerCollectionPrefix + key, headerValue[key]);
- }
- }
- else {
- request.headers.set(headerParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(headerParameter), headerValue);
- }
- }
- }
+function isObjectWithProperties(thing, properties) {
+ if (!isDefined(thing) || typeof thing !== "object") {
+ return false;
}
- const customHeaders = (_b = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.requestOptions) === null || _b === void 0 ? void 0 : _b.customHeaders;
- if (customHeaders) {
- for (const customHeaderName of Object.keys(customHeaders)) {
- request.headers.set(customHeaderName, customHeaders[customHeaderName]);
+ for (const property of properties) {
+ if (!objectHasProperty(thing, property)) {
+ return false;
}
}
+ return true;
}
-exports.serializeHeaders = serializeHeaders;
/**
- * @internal
+ * Helper TypeGuard that checks if the input is an object with the specified property.
+ * @param thing - Any object.
+ * @param property - The name of the property that should appear in the object.
*/
-function serializeRequestBody(request, operationArguments, operationSpec, stringifyXML = function () {
- throw new Error("XML serialization unsupported!");
-}) {
- var _a, _b, _c, _d, _e;
- const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions;
- const updatedOptions = {
- xml: {
- rootName: (_b = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _b !== void 0 ? _b : "",
- includeRoot: (_c = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _c !== void 0 ? _c : false,
- xmlCharKey: (_d = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _d !== void 0 ? _d : interfaces_js_1.XML_CHARKEY,
- },
- };
- const xmlCharKey = updatedOptions.xml.xmlCharKey;
- if (operationSpec.requestBody && operationSpec.requestBody.mapper) {
- request.body = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, operationSpec.requestBody);
- const bodyMapper = operationSpec.requestBody.mapper;
- const { required, serializedName, xmlName, xmlElementName, xmlNamespace, xmlNamespacePrefix, nullable, } = bodyMapper;
- const typeName = bodyMapper.type.name;
- try {
- if ((request.body !== undefined && request.body !== null) ||
- (nullable && request.body === null) ||
- required) {
- const requestBodyParameterPathString = (0, interfaceHelpers_js_1.getPathStringFromParameter)(operationSpec.requestBody);
- request.body = operationSpec.serializer.serialize(bodyMapper, request.body, requestBodyParameterPathString, updatedOptions);
- const isStream = typeName === serializer_js_1.MapperTypeNames.Stream;
- if (operationSpec.isXML) {
- const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns";
- const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, request.body, updatedOptions);
- if (typeName === serializer_js_1.MapperTypeNames.Sequence) {
- request.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, xmlCharKey });
- }
- else if (!isStream) {
- request.body = stringifyXML(value, {
- rootName: xmlName || serializedName,
- xmlCharKey,
- });
- }
- }
- else if (typeName === serializer_js_1.MapperTypeNames.String &&
- (((_e = operationSpec.contentType) === null || _e === void 0 ? void 0 : _e.match("text/plain")) || operationSpec.mediaType === "text")) {
- // the String serializer has validated that request body is a string
- // so just send the string.
- return;
- }
- else if (!isStream) {
- request.body = JSON.stringify(request.body);
- }
- }
- }
- catch (error) {
- throw new Error(`Error "${error.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, undefined, " ")}.`);
- }
- }
- else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {
- request.formData = {};
- for (const formDataParameter of operationSpec.formDataParameters) {
- const formDataParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, formDataParameter);
- if (formDataParameterValue !== undefined && formDataParameterValue !== null) {
- const formDataParameterPropertyName = formDataParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(formDataParameter);
- request.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(formDataParameter), updatedOptions);
- }
- }
- }
+function objectHasProperty(thing, property) {
+ return (isDefined(thing) && typeof thing === "object" && property in thing);
}
-exports.serializeRequestBody = serializeRequestBody;
+//# sourceMappingURL=typeGuards.js.map
+
+/***/ }),
+
+/***/ 98795:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+var _a;
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.randomUUID = randomUUID;
+const crypto_1 = __nccwpck_require__(76982);
+// NOTE: This is a workaround until we can use `globalThis.crypto.randomUUID` in Node.js 19+.
+const uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function"
+ ? globalThis.crypto.randomUUID.bind(globalThis.crypto)
+ : crypto_1.randomUUID;
+/**
+ * Generated Universally Unique Identifier
+ *
+ * @returns RFC4122 v4 UUID.
+ */
+function randomUUID() {
+ return uuidFunction();
+}
+//# sourceMappingURL=uuidUtils.js.map
+
+/***/ }),
+
+/***/ 31658:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AbortError = void 0;
/**
- * Adds an xml namespace to the xml serialized object if needed, otherwise it just returns the value itself
+ * 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.
+ * }
+ * }
+ * ```
*/
-function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options) {
- // Composite and Sequence schemas already got their root namespace set during serialization
- // We just need to add xmlns to the other schema types
- if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) {
- const result = {};
- result[options.xml.xmlCharKey] = serializedValue;
- result[interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace };
- return result;
- }
- return serializedValue;
-}
-function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) {
- if (!Array.isArray(obj)) {
- obj = [obj];
- }
- if (!xmlNamespaceKey || !xmlNamespace) {
- return { [elementName]: obj };
+class AbortError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "AbortError";
}
- const result = { [elementName]: obj };
- result[interfaces_js_1.XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace };
- return result;
}
-//# sourceMappingURL=serializationPolicy.js.map
+exports.AbortError = AbortError;
+//# sourceMappingURL=AbortError.js.map
/***/ }),
-/***/ 1530:
+/***/ 16492:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
@@ -75724,9636 +121756,21277 @@ function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) {
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.MapperTypeNames = exports.createSerializer = void 0;
-const tslib_1 = __nccwpck_require__(1860);
-const base64 = tslib_1.__importStar(__nccwpck_require__(741));
-const interfaces_js_1 = __nccwpck_require__(6058);
-const utils_js_1 = __nccwpck_require__(1193);
-class SerializerImpl {
- constructor(modelMappers = {}, isXML = false) {
- this.modelMappers = modelMappers;
- this.isXML = isXML;
- }
- /**
- * @deprecated Removing the constraints validation on client side.
- */
- validateConstraints(mapper, value, objectName) {
- const failValidation = (constraintName, constraintValue) => {
- throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`);
- };
- if (mapper.constraints && value !== undefined && value !== null) {
- const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems, } = mapper.constraints;
- if (ExclusiveMaximum !== undefined && value >= ExclusiveMaximum) {
- failValidation("ExclusiveMaximum", ExclusiveMaximum);
- }
- if (ExclusiveMinimum !== undefined && value <= ExclusiveMinimum) {
- failValidation("ExclusiveMinimum", ExclusiveMinimum);
- }
- if (InclusiveMaximum !== undefined && value > InclusiveMaximum) {
- failValidation("InclusiveMaximum", InclusiveMaximum);
- }
- if (InclusiveMinimum !== undefined && value < InclusiveMinimum) {
- failValidation("InclusiveMinimum", InclusiveMinimum);
- }
- if (MaxItems !== undefined && value.length > MaxItems) {
- failValidation("MaxItems", MaxItems);
- }
- if (MaxLength !== undefined && value.length > MaxLength) {
- failValidation("MaxLength", MaxLength);
- }
- if (MinItems !== undefined && value.length < MinItems) {
- failValidation("MinItems", MinItems);
- }
- if (MinLength !== undefined && value.length < MinLength) {
- failValidation("MinLength", MinLength);
- }
- if (MultipleOf !== undefined && value % MultipleOf !== 0) {
- failValidation("MultipleOf", MultipleOf);
- }
- if (Pattern) {
- const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern;
- if (typeof value !== "string" || value.match(pattern) === null) {
- failValidation("Pattern", Pattern);
- }
- }
- if (UniqueItems &&
- value.some((item, i, ar) => ar.indexOf(item) !== i)) {
- failValidation("UniqueItems", UniqueItems);
- }
- }
- }
- /**
- * Serialize the given object based on its metadata defined in the mapper
- *
- * @param mapper - The mapper which defines the metadata of the serializable object
- *
- * @param object - A valid Javascript object to be serialized
- *
- * @param objectName - Name of the serialized object
- *
- * @param options - additional options to serialization
- *
- * @returns A valid serialized Javascript object
- */
- serialize(mapper, object, objectName, options = { xml: {} }) {
- var _a, _b, _c;
- const updatedOptions = {
- xml: {
- rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "",
- includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false,
- xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : interfaces_js_1.XML_CHARKEY,
- },
- };
- let payload = {};
- const mapperType = mapper.type.name;
- if (!objectName) {
- objectName = mapper.serializedName;
- }
- if (mapperType.match(/^Sequence$/i) !== null) {
- payload = [];
- }
- if (mapper.isConstant) {
- object = mapper.defaultValue;
- }
- // This table of allowed values should help explain
- // the mapper.required and mapper.nullable properties.
- // X means "neither undefined or null are allowed".
- // || required
- // || true | false
- // nullable || ==========================
- // true || null | undefined/null
- // false || X | undefined
- // undefined || X | undefined/null
- const { required, nullable } = mapper;
- if (required && nullable && object === undefined) {
- throw new Error(`${objectName} cannot be undefined.`);
- }
- if (required && !nullable && (object === undefined || object === null)) {
- throw new Error(`${objectName} cannot be null or undefined.`);
- }
- if (!required && nullable === false && object === null) {
- throw new Error(`${objectName} cannot be null.`);
- }
- if (object === undefined || object === null) {
- payload = object;
- }
- else {
- if (mapperType.match(/^any$/i) !== null) {
- payload = object;
- }
- else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) {
- payload = serializeBasicTypes(mapperType, objectName, object);
- }
- else if (mapperType.match(/^Enum$/i) !== null) {
- const enumMapper = mapper;
- payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object);
- }
- else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) {
- payload = serializeDateTypes(mapperType, object, objectName);
- }
- else if (mapperType.match(/^ByteArray$/i) !== null) {
- payload = serializeByteArrayType(objectName, object);
- }
- else if (mapperType.match(/^Base64Url$/i) !== null) {
- payload = serializeBase64UrlType(objectName, object);
- }
- else if (mapperType.match(/^Sequence$/i) !== null) {
- payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
- }
- else if (mapperType.match(/^Dictionary$/i) !== null) {
- payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
- }
- else if (mapperType.match(/^Composite$/i) !== null) {
- payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
- }
- }
- return payload;
- }
- /**
- * Deserialize the given object based on its metadata defined in the mapper
- *
- * @param mapper - The mapper which defines the metadata of the serializable object
- *
- * @param responseBody - A valid Javascript entity to be deserialized
- *
- * @param objectName - Name of the deserialized object
- *
- * @param options - Controls behavior of XML parser and builder.
- *
- * @returns A valid deserialized Javascript object
- */
- deserialize(mapper, responseBody, objectName, options = { xml: {} }) {
- var _a, _b, _c, _d;
- const updatedOptions = {
- xml: {
- rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "",
- includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false,
- xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : interfaces_js_1.XML_CHARKEY,
- },
- ignoreUnknownProperties: (_d = options.ignoreUnknownProperties) !== null && _d !== void 0 ? _d : false,
- };
- if (responseBody === undefined || responseBody === null) {
- if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) {
- // Edge case for empty XML non-wrapped lists. xml2js can't distinguish
- // between the list being empty versus being missing,
- // so let's do the more user-friendly thing and return an empty list.
- responseBody = [];
- }
- // specifically check for undefined as default value can be a falsey value `0, "", false, null`
- if (mapper.defaultValue !== undefined) {
- responseBody = mapper.defaultValue;
- }
- return responseBody;
- }
- let payload;
- const mapperType = mapper.type.name;
- if (!objectName) {
- objectName = mapper.serializedName;
- }
- if (mapperType.match(/^Composite$/i) !== null) {
- payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions);
- }
- else {
- if (this.isXML) {
- const xmlCharKey = updatedOptions.xml.xmlCharKey;
- /**
- * If the mapper specifies this as a non-composite type value but the responseBody contains
- * both header ("$" i.e., XML_ATTRKEY) and body ("#" i.e., XML_CHARKEY) properties,
- * then just reduce the responseBody value to the body ("#" i.e., XML_CHARKEY) property.
- */
- if (responseBody[interfaces_js_1.XML_ATTRKEY] !== undefined && responseBody[xmlCharKey] !== undefined) {
- responseBody = responseBody[xmlCharKey];
- }
- }
- if (mapperType.match(/^Number$/i) !== null) {
- payload = parseFloat(responseBody);
- if (isNaN(payload)) {
- payload = responseBody;
- }
- }
- else if (mapperType.match(/^Boolean$/i) !== null) {
- if (responseBody === "true") {
- payload = true;
- }
- else if (responseBody === "false") {
- payload = false;
- }
- else {
- payload = responseBody;
- }
- }
- else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) {
- payload = responseBody;
- }
- else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) {
- payload = new Date(responseBody);
- }
- else if (mapperType.match(/^UnixTime$/i) !== null) {
- payload = unixTimeToDate(responseBody);
- }
- else if (mapperType.match(/^ByteArray$/i) !== null) {
- payload = base64.decodeString(responseBody);
- }
- else if (mapperType.match(/^Base64Url$/i) !== null) {
- payload = base64UrlToByteArray(responseBody);
- }
- else if (mapperType.match(/^Sequence$/i) !== null) {
- payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions);
- }
- else if (mapperType.match(/^Dictionary$/i) !== null) {
- payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions);
- }
- }
- if (mapper.isConstant) {
- payload = mapper.defaultValue;
- }
- return payload;
- }
-}
+exports.AbortError = void 0;
+var AbortError_js_1 = __nccwpck_require__(31658);
+Object.defineProperty(exports, "AbortError", ({ enumerable: true, get: function () { return AbortError_js_1.AbortError; } }));
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 78756:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.XML_CHARKEY = exports.XML_ATTRKEY = exports.parseXML = exports.stringifyXML = void 0;
+var xml_js_1 = __nccwpck_require__(48133);
+Object.defineProperty(exports, "stringifyXML", ({ enumerable: true, get: function () { return xml_js_1.stringifyXML; } }));
+Object.defineProperty(exports, "parseXML", ({ enumerable: true, get: function () { return xml_js_1.parseXML; } }));
+var xml_common_js_1 = __nccwpck_require__(93406);
+Object.defineProperty(exports, "XML_ATTRKEY", ({ enumerable: true, get: function () { return xml_common_js_1.XML_ATTRKEY; } }));
+Object.defineProperty(exports, "XML_CHARKEY", ({ enumerable: true, get: function () { return xml_common_js_1.XML_CHARKEY; } }));
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 93406:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.XML_CHARKEY = exports.XML_ATTRKEY = void 0;
/**
- * Method that creates and returns a Serializer.
- * @param modelMappers - Known models to map
- * @param isXML - If XML should be supported
+ * Default key used to access the XML attributes.
*/
-function createSerializer(modelMappers = {}, isXML = false) {
- return new SerializerImpl(modelMappers, isXML);
+exports.XML_ATTRKEY = "$";
+/**
+ * Default key used to access the XML value content.
+ */
+exports.XML_CHARKEY = "_";
+//# sourceMappingURL=xml.common.js.map
+
+/***/ }),
+
+/***/ 48133:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.stringifyXML = stringifyXML;
+exports.parseXML = parseXML;
+const fast_xml_parser_1 = __nccwpck_require__(39741);
+const xml_common_js_1 = __nccwpck_require__(93406);
+function getCommonOptions(options) {
+ var _a;
+ return {
+ attributesGroupName: xml_common_js_1.XML_ATTRKEY,
+ textNodeName: (_a = options.xmlCharKey) !== null && _a !== void 0 ? _a : xml_common_js_1.XML_CHARKEY,
+ ignoreAttributes: false,
+ suppressBooleanAttributes: false,
+ };
}
-exports.createSerializer = createSerializer;
-function trimEnd(str, ch) {
- let len = str.length;
- while (len - 1 >= 0 && str[len - 1] === ch) {
- --len;
- }
- return str.substr(0, len);
+function getSerializerOptions(options = {}) {
+ var _a, _b;
+ return Object.assign(Object.assign({}, getCommonOptions(options)), { attributeNamePrefix: "@_", format: true, suppressEmptyNode: true, indentBy: "", rootNodeName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "root", cdataPropName: (_b = options.cdataPropName) !== null && _b !== void 0 ? _b : "__cdata" });
}
-function bufferToBase64Url(buffer) {
- if (!buffer) {
- return undefined;
- }
- if (!(buffer instanceof Uint8Array)) {
- throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`);
- }
- // Uint8Array to Base64.
- const str = base64.encodeByteArray(buffer);
- // Base64 to Base64Url.
- return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_");
+function getParserOptions(options = {}) {
+ return Object.assign(Object.assign({}, getCommonOptions(options)), { parseAttributeValue: false, parseTagValue: false, attributeNamePrefix: "", stopNodes: options.stopNodes, processEntities: true });
}
-function base64UrlToByteArray(str) {
+/**
+ * Converts given JSON object to XML string
+ * @param obj - JSON object to be converted into XML string
+ * @param opts - Options that govern the XML building of given JSON object
+ * `rootName` indicates the name of the root element in the resulting XML
+ */
+function stringifyXML(obj, opts = {}) {
+ const parserOptions = getSerializerOptions(opts);
+ const j2x = new fast_xml_parser_1.XMLBuilder(parserOptions);
+ const node = { [parserOptions.rootNodeName]: obj };
+ const xmlData = j2x.build(node);
+ return `${xmlData}`.replace(/\n/g, "");
+}
+/**
+ * Converts given XML string into JSON
+ * @param str - String containing the XML content to be parsed into JSON
+ * @param opts - Options that govern the parsing of given xml string
+ * `includeRoot` indicates whether the root element is to be included or not in the output
+ */
+async function parseXML(str, opts = {}) {
if (!str) {
- return undefined;
- }
- if (str && typeof str.valueOf() !== "string") {
- throw new Error("Please provide an input of type string for converting to Uint8Array");
+ throw new Error("Document is empty");
}
- // Base64Url to Base64.
- str = str.replace(/-/g, "+").replace(/_/g, "/");
- // Base64 to Uint8Array.
- return base64.decodeString(str);
-}
-function splitSerializeName(prop) {
- const classes = [];
- let partialclass = "";
- if (prop) {
- const subwords = prop.split(".");
- for (const item of subwords) {
- if (item.charAt(item.length - 1) === "\\") {
- partialclass += item.substr(0, item.length - 1) + ".";
- }
- else {
- partialclass += item;
- classes.push(partialclass);
- partialclass = "";
- }
- }
+ const validation = fast_xml_parser_1.XMLValidator.validate(str);
+ if (validation !== true) {
+ throw validation;
}
- return classes;
-}
-function dateToUnixTime(d) {
- if (!d) {
- return undefined;
+ const parser = new fast_xml_parser_1.XMLParser(getParserOptions(opts));
+ const parsedXml = parser.parse(str);
+ // Remove the node.
+ // This is a change in behavior on fxp v4. Issue #424
+ if (parsedXml["?xml"]) {
+ delete parsedXml["?xml"];
}
- if (typeof d.valueOf() === "string") {
- d = new Date(d);
+ if (!opts.includeRoot) {
+ for (const key of Object.keys(parsedXml)) {
+ const value = parsedXml[key];
+ return typeof value === "object" ? Object.assign({}, value) : value;
+ }
}
- return Math.floor(d.getTime() / 1000);
+ return parsedXml;
}
-function unixTimeToDate(n) {
- if (!n) {
- return undefined;
- }
- return new Date(n * 1000);
+//# sourceMappingURL=xml.js.map
+
+/***/ }),
+
+/***/ 1676:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+const log_js_1 = __nccwpck_require__(36757);
+const debugEnvVariable = (typeof process !== "undefined" && process.env && process.env.DEBUG) || undefined;
+let enabledString;
+let enabledNamespaces = [];
+let skippedNamespaces = [];
+const debuggers = [];
+if (debugEnvVariable) {
+ enable(debugEnvVariable);
}
-function serializeBasicTypes(typeName, objectName, value) {
- if (value !== null && value !== undefined) {
- if (typeName.match(/^Number$/i) !== null) {
- if (typeof value !== "number") {
- throw new Error(`${objectName} with value ${value} must be of type number.`);
- }
- }
- else if (typeName.match(/^String$/i) !== null) {
- if (typeof value.valueOf() !== "string") {
- throw new Error(`${objectName} with value "${value}" must be of type string.`);
- }
- }
- else if (typeName.match(/^Uuid$/i) !== null) {
- if (!(typeof value.valueOf() === "string" && (0, utils_js_1.isValidUuid)(value))) {
- throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`);
- }
- }
- else if (typeName.match(/^Boolean$/i) !== null) {
- if (typeof value !== "boolean") {
- throw new Error(`${objectName} with value ${value} must be of type boolean.`);
- }
+const debugObj = Object.assign((namespace) => {
+ return createDebugger(namespace);
+}, {
+ enable,
+ enabled,
+ disable,
+ log: log_js_1.log,
+});
+function enable(namespaces) {
+ enabledString = namespaces;
+ enabledNamespaces = [];
+ skippedNamespaces = [];
+ const wildcard = /\*/g;
+ const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?"));
+ for (const ns of namespaceList) {
+ if (ns.startsWith("-")) {
+ skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`));
}
- else if (typeName.match(/^Stream$/i) !== null) {
- const objectType = typeof value;
- if (objectType !== "string" &&
- typeof value.pipe !== "function" && // NodeJS.ReadableStream
- typeof value.tee !== "function" && // browser ReadableStream
- !(value instanceof ArrayBuffer) &&
- !ArrayBuffer.isView(value) &&
- // File objects count as a type of Blob, so we want to use instanceof explicitly
- !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob) &&
- objectType !== "function") {
- throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, ReadableStream, or () => ReadableStream.`);
- }
+ else {
+ enabledNamespaces.push(new RegExp(`^${ns}$`));
}
}
- return value;
+ for (const instance of debuggers) {
+ instance.enabled = enabled(instance.namespace);
+ }
}
-function serializeEnumType(objectName, allowedValues, value) {
- if (!allowedValues) {
- throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`);
+function enabled(namespace) {
+ if (namespace.endsWith("*")) {
+ return true;
}
- const isPresent = allowedValues.some((item) => {
- if (typeof item.valueOf() === "string") {
- return item.toLowerCase() === value.toLowerCase();
+ for (const skipped of skippedNamespaces) {
+ if (skipped.test(namespace)) {
+ return false;
}
- return item === value;
- });
- if (!isPresent) {
- throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`);
}
- return value;
-}
-function serializeByteArrayType(objectName, value) {
- if (value !== undefined && value !== null) {
- if (!(value instanceof Uint8Array)) {
- throw new Error(`${objectName} must be of type Uint8Array.`);
+ for (const enabledNamespace of enabledNamespaces) {
+ if (enabledNamespace.test(namespace)) {
+ return true;
}
- value = base64.encodeByteArray(value);
}
- return value;
+ return false;
}
-function serializeBase64UrlType(objectName, value) {
- if (value !== undefined && value !== null) {
- if (!(value instanceof Uint8Array)) {
- throw new Error(`${objectName} must be of type Uint8Array.`);
- }
- value = bufferToBase64Url(value);
- }
- return value;
+function disable() {
+ const result = enabledString || "";
+ enable("");
+ return result;
}
-function serializeDateTypes(typeName, value, objectName) {
- if (value !== undefined && value !== null) {
- if (typeName.match(/^Date$/i) !== null) {
- if (!(value instanceof Date ||
- (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
- throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
- }
- value =
- value instanceof Date
- ? value.toISOString().substring(0, 10)
- : new Date(value).toISOString().substring(0, 10);
- }
- else if (typeName.match(/^DateTime$/i) !== null) {
- if (!(value instanceof Date ||
- (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
- throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
- }
- value = value instanceof Date ? value.toISOString() : new Date(value).toISOString();
- }
- else if (typeName.match(/^DateTimeRfc1123$/i) !== null) {
- if (!(value instanceof Date ||
- (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
- throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`);
- }
- value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString();
- }
- else if (typeName.match(/^UnixTime$/i) !== null) {
- if (!(value instanceof Date ||
- (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
- throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format ` +
- `for it to be serialized in UnixTime/Epoch format.`);
- }
- value = dateToUnixTime(value);
+function createDebugger(namespace) {
+ const newDebugger = Object.assign(debug, {
+ enabled: enabled(namespace),
+ destroy,
+ log: debugObj.log,
+ namespace,
+ extend,
+ });
+ function debug(...args) {
+ if (!newDebugger.enabled) {
+ return;
}
- else if (typeName.match(/^TimeSpan$/i) !== null) {
- if (!(0, utils_js_1.isDuration)(value)) {
- throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`);
- }
+ if (args.length > 0) {
+ args[0] = `${namespace} ${args[0]}`;
}
+ newDebugger.log(...args);
}
- return value;
+ debuggers.push(newDebugger);
+ return newDebugger;
}
-function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) {
- var _a;
- if (!Array.isArray(object)) {
- throw new Error(`${objectName} must be of type Array.`);
- }
- let elementType = mapper.type.element;
- if (!elementType || typeof elementType !== "object") {
- throw new Error(`element" metadata for an Array must be defined in the ` +
- `mapper and it must of type "object" in ${objectName}.`);
- }
- // Quirk: Composite mappers referenced by `element` might
- // not have *all* properties declared (like uberParent),
- // so let's try to look up the full definition by name.
- if (elementType.type.name === "Composite" && elementType.type.className) {
- elementType = (_a = serializer.modelMappers[elementType.type.className]) !== null && _a !== void 0 ? _a : elementType;
- }
- const tempArray = [];
- for (let i = 0; i < object.length; i++) {
- const serializedValue = serializer.serialize(elementType, object[i], objectName, options);
- if (isXml && elementType.xmlNamespace) {
- const xmlnsKey = elementType.xmlNamespacePrefix
- ? `xmlns:${elementType.xmlNamespacePrefix}`
- : "xmlns";
- if (elementType.type.name === "Composite") {
- tempArray[i] = Object.assign({}, serializedValue);
- tempArray[i][interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
- }
- else {
- tempArray[i] = {};
- tempArray[i][options.xml.xmlCharKey] = serializedValue;
- tempArray[i][interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
- }
- }
- else {
- tempArray[i] = serializedValue;
- }
+function destroy() {
+ const index = debuggers.indexOf(this);
+ if (index >= 0) {
+ debuggers.splice(index, 1);
+ return true;
}
- return tempArray;
+ return false;
}
-function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) {
- if (typeof object !== "object") {
- throw new Error(`${objectName} must be of type object.`);
+function extend(namespace) {
+ const newDebugger = createDebugger(`${this.namespace}:${namespace}`);
+ newDebugger.log = this.log;
+ return newDebugger;
+}
+exports["default"] = debugObj;
+//# sourceMappingURL=debug.js.map
+
+/***/ }),
+
+/***/ 26515:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AzureLogger = void 0;
+exports.setLogLevel = setLogLevel;
+exports.getLogLevel = getLogLevel;
+exports.createClientLogger = createClientLogger;
+const tslib_1 = __nccwpck_require__(61860);
+const debug_js_1 = tslib_1.__importDefault(__nccwpck_require__(1676));
+const registeredLoggers = new Set();
+const logLevelFromEnv = (typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL) || undefined;
+let azureLogLevel;
+/**
+ * The AzureLogger provides a mechanism for overriding where logs are output to.
+ * By default, logs are sent to stderr.
+ * Override the `log` method to redirect logs to another location.
+ */
+exports.AzureLogger = (0, debug_js_1.default)("azure");
+exports.AzureLogger.log = (...args) => {
+ debug_js_1.default.log(...args);
+};
+const AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"];
+if (logLevelFromEnv) {
+ // avoid calling setLogLevel because we don't want a mis-set environment variable to crash
+ if (isAzureLogLevel(logLevelFromEnv)) {
+ setLogLevel(logLevelFromEnv);
}
- const valueType = mapper.type.value;
- if (!valueType || typeof valueType !== "object") {
- throw new Error(`"value" metadata for a Dictionary must be defined in the ` +
- `mapper and it must of type "object" in ${objectName}.`);
+ else {
+ console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`);
}
- const tempDictionary = {};
- for (const key of Object.keys(object)) {
- const serializedValue = serializer.serialize(valueType, object[key], objectName, options);
- // If the element needs an XML namespace we need to add it within the $ property
- tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options);
+}
+/**
+ * Immediately enables logging at the specified log level. If no level is specified, logging is disabled.
+ * @param level - The log level to enable for logging.
+ * Options from most verbose to least verbose are:
+ * - verbose
+ * - info
+ * - warning
+ * - error
+ */
+function setLogLevel(level) {
+ if (level && !isAzureLogLevel(level)) {
+ throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`);
}
- // Add the namespace to the root element if needed
- if (isXml && mapper.xmlNamespace) {
- const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns";
- const result = tempDictionary;
- result[interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace };
- return result;
+ azureLogLevel = level;
+ const enabledNamespaces = [];
+ for (const logger of registeredLoggers) {
+ if (shouldEnable(logger)) {
+ enabledNamespaces.push(logger.namespace);
+ }
}
- return tempDictionary;
+ debug_js_1.default.enable(enabledNamespaces.join(","));
}
/**
- * Resolves the additionalProperties property from a referenced mapper
- * @param serializer - the serializer containing the entire set of mappers
- * @param mapper - the composite mapper to resolve
- * @param objectName - name of the object being serialized
+ * Retrieves the currently specified log level.
*/
-function resolveAdditionalProperties(serializer, mapper, objectName) {
- const additionalProperties = mapper.type.additionalProperties;
- if (!additionalProperties && mapper.type.className) {
- const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
- return modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.additionalProperties;
- }
- return additionalProperties;
+function getLogLevel() {
+ return azureLogLevel;
}
+const levelMap = {
+ verbose: 400,
+ info: 300,
+ warning: 200,
+ error: 100,
+};
/**
- * Finds the mapper referenced by className
- * @param serializer - the serializer containing the entire set of mappers
- * @param mapper - the composite mapper to resolve
- * @param objectName - name of the object being serialized
+ * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`.
+ * @param namespace - The name of the SDK package.
+ * @hidden
*/
-function resolveReferencedMapper(serializer, mapper, objectName) {
- const className = mapper.type.className;
- if (!className) {
- throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, undefined, 2)}".`);
+function createClientLogger(namespace) {
+ const clientRootLogger = exports.AzureLogger.extend(namespace);
+ patchLogMethod(exports.AzureLogger, clientRootLogger);
+ return {
+ error: createLogger(clientRootLogger, "error"),
+ warning: createLogger(clientRootLogger, "warning"),
+ info: createLogger(clientRootLogger, "info"),
+ verbose: createLogger(clientRootLogger, "verbose"),
+ };
+}
+function patchLogMethod(parent, child) {
+ child.log = (...args) => {
+ parent.log(...args);
+ };
+}
+function createLogger(parent, level) {
+ const logger = Object.assign(parent.extend(level), {
+ level,
+ });
+ patchLogMethod(parent, logger);
+ if (shouldEnable(logger)) {
+ const enabledNamespaces = debug_js_1.default.disable();
+ debug_js_1.default.enable(enabledNamespaces + "," + logger.namespace);
}
- return serializer.modelMappers[className];
+ registeredLoggers.add(logger);
+ return logger;
+}
+function shouldEnable(logger) {
+ return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]);
+}
+function isAzureLogLevel(logLevel) {
+ return AZURE_LOG_LEVELS.includes(logLevel);
+}
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 36757:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.log = log;
+const tslib_1 = __nccwpck_require__(61860);
+const node_os_1 = __nccwpck_require__(48161);
+const node_util_1 = tslib_1.__importDefault(__nccwpck_require__(57975));
+const process = tslib_1.__importStar(__nccwpck_require__(1708));
+function log(message, ...args) {
+ process.stderr.write(`${node_util_1.default.format(message, ...args)}${node_os_1.EOL}`);
}
+//# sourceMappingURL=log.js.map
+
+/***/ }),
+
+/***/ 24841:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AbortError = void 0;
/**
- * Resolves a composite mapper's modelProperties.
- * @param serializer - the serializer containing the entire set of mappers
- * @param mapper - the composite mapper to resolve
+ * 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.
+ * }
+ * }
+ * ```
*/
-function resolveModelProperties(serializer, mapper, objectName) {
- let modelProps = mapper.type.modelProperties;
- if (!modelProps) {
- const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
- if (!modelMapper) {
- throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`);
- }
- modelProps = modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.modelProperties;
- if (!modelProps) {
- throw new Error(`modelProperties cannot be null or undefined in the ` +
- `mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`);
- }
+class AbortError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "AbortError";
}
- return modelProps;
}
-function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) {
- if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
- mapper = getPolymorphicMapper(serializer, mapper, object, "clientName");
- }
- if (object !== undefined && object !== null) {
- const payload = {};
- const modelProps = resolveModelProperties(serializer, mapper, objectName);
- for (const key of Object.keys(modelProps)) {
- const propertyMapper = modelProps[key];
- if (propertyMapper.readOnly) {
- continue;
- }
- let propName;
- let parentObject = payload;
- if (serializer.isXML) {
- if (propertyMapper.xmlIsWrapped) {
- propName = propertyMapper.xmlName;
- }
- else {
- propName = propertyMapper.xmlElementName || propertyMapper.xmlName;
- }
- }
- else {
- const paths = splitSerializeName(propertyMapper.serializedName);
- propName = paths.pop();
- for (const pathName of paths) {
- const childObject = parentObject[pathName];
- if ((childObject === undefined || childObject === null) &&
- ((object[key] !== undefined && object[key] !== null) ||
- propertyMapper.defaultValue !== undefined)) {
- parentObject[pathName] = {};
- }
- parentObject = parentObject[pathName];
- }
- }
- if (parentObject !== undefined && parentObject !== null) {
- if (isXml && mapper.xmlNamespace) {
- const xmlnsKey = mapper.xmlNamespacePrefix
- ? `xmlns:${mapper.xmlNamespacePrefix}`
- : "xmlns";
- parentObject[interfaces_js_1.XML_ATTRKEY] = Object.assign(Object.assign({}, parentObject[interfaces_js_1.XML_ATTRKEY]), { [xmlnsKey]: mapper.xmlNamespace });
- }
- const propertyObjectName = propertyMapper.serializedName !== ""
- ? objectName + "." + propertyMapper.serializedName
- : objectName;
- let toSerialize = object[key];
- const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
- if (polymorphicDiscriminator &&
- polymorphicDiscriminator.clientName === key &&
- (toSerialize === undefined || toSerialize === null)) {
- toSerialize = mapper.serializedName;
- }
- const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options);
- if (serializedValue !== undefined && propName !== undefined && propName !== null) {
- const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options);
- if (isXml && propertyMapper.xmlIsAttribute) {
- // XML_ATTRKEY, i.e., $ is the key attributes are kept under in xml2js.
- // This keeps things simple while preventing name collision
- // with names in user documents.
- parentObject[interfaces_js_1.XML_ATTRKEY] = parentObject[interfaces_js_1.XML_ATTRKEY] || {};
- parentObject[interfaces_js_1.XML_ATTRKEY][propName] = serializedValue;
- }
- else if (isXml && propertyMapper.xmlIsWrapped) {
- parentObject[propName] = { [propertyMapper.xmlElementName]: value };
- }
- else {
- parentObject[propName] = value;
- }
- }
- }
- }
- const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName);
- if (additionalPropertiesMapper) {
- const propNames = Object.keys(modelProps);
- for (const clientPropName in object) {
- const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName);
- if (isAdditionalProperty) {
- payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options);
- }
- }
+exports.AbortError = AbortError;
+//# sourceMappingURL=AbortError.js.map
+
+/***/ }),
+
+/***/ 24517:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AbortError = void 0;
+var AbortError_js_1 = __nccwpck_require__(24841);
+Object.defineProperty(exports, "AbortError", ({ enumerable: true, get: function () { return AbortError_js_1.AbortError; } }));
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 27182:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+const WritableStream = (__nccwpck_require__(57075).Writable)
+const inherits = (__nccwpck_require__(57975).inherits)
+
+const StreamSearch = __nccwpck_require__(84136)
+
+const PartStream = __nccwpck_require__(50612)
+const HeaderParser = __nccwpck_require__(62271)
+
+const DASH = 45
+const B_ONEDASH = Buffer.from('-')
+const B_CRLF = Buffer.from('\r\n')
+const EMPTY_FN = function () {}
+
+function Dicer (cfg) {
+ if (!(this instanceof Dicer)) { return new Dicer(cfg) }
+ WritableStream.call(this, cfg)
+
+ if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') }
+
+ if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined }
+
+ this._headerFirst = cfg.headerFirst
+
+ this._dashes = 0
+ this._parts = 0
+ this._finished = false
+ this._realFinish = false
+ this._isPreamble = true
+ this._justMatched = false
+ this._firstWrite = true
+ this._inHeader = true
+ this._part = undefined
+ this._cb = undefined
+ this._ignoreData = false
+ this._partOpts = { highWaterMark: cfg.partHwm }
+ this._pause = false
+
+ const self = this
+ this._hparser = new HeaderParser(cfg)
+ this._hparser.on('header', function (header) {
+ self._inHeader = false
+ self._part.emit('header', header)
+ })
+}
+inherits(Dicer, WritableStream)
+
+Dicer.prototype.emit = function (ev) {
+ if (ev === 'finish' && !this._realFinish) {
+ if (!this._finished) {
+ const self = this
+ process.nextTick(function () {
+ self.emit('error', new Error('Unexpected end of multipart data'))
+ if (self._part && !self._ignoreData) {
+ const type = (self._isPreamble ? 'Preamble' : 'Part')
+ self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data'))
+ self._part.push(null)
+ process.nextTick(function () {
+ self._realFinish = true
+ self.emit('finish')
+ self._realFinish = false
+ })
+ return
}
- return payload;
+ self._realFinish = true
+ self.emit('finish')
+ self._realFinish = false
+ })
}
- return object;
+ } else { WritableStream.prototype.emit.apply(this, arguments) }
}
-function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) {
- if (!isXml || !propertyMapper.xmlNamespace) {
- return serializedValue;
- }
- const xmlnsKey = propertyMapper.xmlNamespacePrefix
- ? `xmlns:${propertyMapper.xmlNamespacePrefix}`
- : "xmlns";
- const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace };
- if (["Composite"].includes(propertyMapper.type.name)) {
- if (serializedValue[interfaces_js_1.XML_ATTRKEY]) {
- return serializedValue;
- }
- else {
- const result = Object.assign({}, serializedValue);
- result[interfaces_js_1.XML_ATTRKEY] = xmlNamespace;
- return result;
- }
+
+Dicer.prototype._write = function (data, encoding, cb) {
+ // ignore unexpected data (e.g. extra trailer data after finished)
+ if (!this._hparser && !this._bparser) { return cb() }
+
+ if (this._headerFirst && this._isPreamble) {
+ if (!this._part) {
+ this._part = new PartStream(this._partOpts)
+ if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() }
}
- const result = {};
- result[options.xml.xmlCharKey] = serializedValue;
- result[interfaces_js_1.XML_ATTRKEY] = xmlNamespace;
- return result;
+ const r = this._hparser.push(data)
+ if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() }
+ }
+
+ // allows for "easier" testing
+ if (this._firstWrite) {
+ this._bparser.push(B_CRLF)
+ this._firstWrite = false
+ }
+
+ this._bparser.push(data)
+
+ if (this._pause) { this._cb = cb } else { cb() }
}
-function isSpecialXmlProperty(propertyName, options) {
- return [interfaces_js_1.XML_ATTRKEY, options.xml.xmlCharKey].includes(propertyName);
+
+Dicer.prototype.reset = function () {
+ this._part = undefined
+ this._bparser = undefined
+ this._hparser = undefined
}
-function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) {
- var _a, _b;
- const xmlCharKey = (_a = options.xml.xmlCharKey) !== null && _a !== void 0 ? _a : interfaces_js_1.XML_CHARKEY;
- if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
- mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName");
+
+Dicer.prototype.setBoundary = function (boundary) {
+ const self = this
+ this._bparser = new StreamSearch('\r\n--' + boundary)
+ this._bparser.on('info', function (isMatch, data, start, end) {
+ self._oninfo(isMatch, data, start, end)
+ })
+}
+
+Dicer.prototype._ignore = function () {
+ if (this._part && !this._ignoreData) {
+ this._ignoreData = true
+ this._part.on('error', EMPTY_FN)
+ // we must perform some kind of read on the stream even though we are
+ // ignoring the data, otherwise node's Readable stream will not emit 'end'
+ // after pushing null to the stream
+ this._part.resume()
+ }
+}
+
+Dicer.prototype._oninfo = function (isMatch, data, start, end) {
+ let buf; const self = this; let i = 0; let r; let shouldWriteMore = true
+
+ if (!this._part && this._justMatched && data) {
+ while (this._dashes < 2 && (start + i) < end) {
+ if (data[start + i] === DASH) {
+ ++i
+ ++this._dashes
+ } else {
+ if (this._dashes) { buf = B_ONEDASH }
+ this._dashes = 0
+ break
+ }
}
- const modelProps = resolveModelProperties(serializer, mapper, objectName);
- let instance = {};
- const handledPropertyNames = [];
- for (const key of Object.keys(modelProps)) {
- const propertyMapper = modelProps[key];
- const paths = splitSerializeName(modelProps[key].serializedName);
- handledPropertyNames.push(paths[0]);
- const { serializedName, xmlName, xmlElementName } = propertyMapper;
- let propertyObjectName = objectName;
- if (serializedName !== "" && serializedName !== undefined) {
- propertyObjectName = objectName + "." + serializedName;
- }
- const headerCollectionPrefix = propertyMapper.headerCollectionPrefix;
- if (headerCollectionPrefix) {
- const dictionary = {};
- for (const headerKey of Object.keys(responseBody)) {
- if (headerKey.startsWith(headerCollectionPrefix)) {
- dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options);
- }
- handledPropertyNames.push(headerKey);
- }
- instance[key] = dictionary;
- }
- else if (serializer.isXML) {
- if (propertyMapper.xmlIsAttribute && responseBody[interfaces_js_1.XML_ATTRKEY]) {
- instance[key] = serializer.deserialize(propertyMapper, responseBody[interfaces_js_1.XML_ATTRKEY][xmlName], propertyObjectName, options);
- }
- else if (propertyMapper.xmlIsMsText) {
- if (responseBody[xmlCharKey] !== undefined) {
- instance[key] = responseBody[xmlCharKey];
- }
- else if (typeof responseBody === "string") {
- // The special case where xml parser parses "content" into JSON of
- // `{ name: "content"}` instead of `{ name: { "_": "content" }}`
- instance[key] = responseBody;
- }
- }
- else {
- const propertyName = xmlElementName || xmlName || serializedName;
- if (propertyMapper.xmlIsWrapped) {
- /* a list of wrapped by
- For the xml example below
-
- ...
- ...
-
- the responseBody has
- {
- Cors: {
- CorsRule: [{...}, {...}]
- }
- }
- xmlName is "Cors" and xmlElementName is"CorsRule".
- */
- const wrapped = responseBody[xmlName];
- const elementList = (_b = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _b !== void 0 ? _b : [];
- instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options);
- handledPropertyNames.push(xmlName);
- }
- else {
- const property = responseBody[propertyName];
- instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options);
- handledPropertyNames.push(propertyName);
- }
- }
- }
- else {
- // deserialize the property if it is present in the provided responseBody instance
- let propertyInstance;
- let res = responseBody;
- // traversing the object step by step.
- let steps = 0;
- for (const item of paths) {
- if (!res)
- break;
- steps++;
- res = res[item];
- }
- // only accept null when reaching the last position of object otherwise it would be undefined
- if (res === null && steps < paths.length) {
- res = undefined;
- }
- propertyInstance = res;
- const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator;
- // checking that the model property name (key)(ex: "fishtype") and the
- // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype")
- // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type")
- // is a better approach. The generator is not consistent with escaping '\.' in the
- // serializedName of the property (ex: "fish\.type") that is marked as polymorphic discriminator
- // and the serializedName of the metadata polymorphicDiscriminator (ex: "fish.type"). However,
- // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and
- // the transformation of model property name (ex: "fishtype") is done consistently.
- // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator.
- if (polymorphicDiscriminator &&
- key === polymorphicDiscriminator.clientName &&
- (propertyInstance === undefined || propertyInstance === null)) {
- propertyInstance = mapper.serializedName;
- }
- let serializedValue;
- // paging
- if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") {
- propertyInstance = responseBody[key];
- const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options);
- // Copy over any properties that have already been added into the instance, where they do
- // not exist on the newly de-serialized array
- for (const [k, v] of Object.entries(instance)) {
- if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) {
- arrayInstance[k] = v;
- }
- }
- instance = arrayInstance;
- }
- else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) {
- serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options);
- instance[key] = serializedValue;
- }
- }
+ if (this._dashes === 2) {
+ if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) }
+ this.reset()
+ this._finished = true
+ // no more parts will be added
+ if (self._parts === 0) {
+ self._realFinish = true
+ self.emit('finish')
+ self._realFinish = false
+ }
}
- const additionalPropertiesMapper = mapper.type.additionalProperties;
- if (additionalPropertiesMapper) {
- const isAdditionalProperty = (responsePropName) => {
- for (const clientPropName in modelProps) {
- const paths = splitSerializeName(modelProps[clientPropName].serializedName);
- if (paths[0] === responsePropName) {
- return false;
- }
- }
- return true;
- };
- for (const responsePropName in responseBody) {
- if (isAdditionalProperty(responsePropName)) {
- instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options);
- }
- }
+ if (this._dashes) { return }
+ }
+ if (this._justMatched) { this._justMatched = false }
+ if (!this._part) {
+ this._part = new PartStream(this._partOpts)
+ this._part._read = function (n) {
+ self._unpause()
}
- else if (responseBody && !options.ignoreUnknownProperties) {
- for (const key of Object.keys(responseBody)) {
- if (instance[key] === undefined &&
- !handledPropertyNames.includes(key) &&
- !isSpecialXmlProperty(key, options)) {
- instance[key] = responseBody[key];
+ if (this._isPreamble && this.listenerCount('preamble') !== 0) {
+ this.emit('preamble', this._part)
+ } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) {
+ this.emit('part', this._part)
+ } else {
+ this._ignore()
+ }
+ if (!this._isPreamble) { this._inHeader = true }
+ }
+ if (data && start < end && !this._ignoreData) {
+ if (this._isPreamble || !this._inHeader) {
+ if (buf) { shouldWriteMore = this._part.push(buf) }
+ shouldWriteMore = this._part.push(data.slice(start, end))
+ if (!shouldWriteMore) { this._pause = true }
+ } else if (!this._isPreamble && this._inHeader) {
+ if (buf) { this._hparser.push(buf) }
+ r = this._hparser.push(data.slice(start, end))
+ if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) }
+ }
+ }
+ if (isMatch) {
+ this._hparser.reset()
+ if (this._isPreamble) { this._isPreamble = false } else {
+ if (start !== end) {
+ ++this._parts
+ this._part.on('end', function () {
+ if (--self._parts === 0) {
+ if (self._finished) {
+ self._realFinish = true
+ self.emit('finish')
+ self._realFinish = false
+ } else {
+ self._unpause()
}
- }
+ }
+ })
+ }
}
- return instance;
+ this._part.push(null)
+ this._part = undefined
+ this._ignoreData = false
+ this._justMatched = true
+ this._dashes = 0
+ }
+}
+
+Dicer.prototype._unpause = function () {
+ if (!this._pause) { return }
+
+ this._pause = false
+ if (this._cb) {
+ const cb = this._cb
+ this._cb = undefined
+ cb()
+ }
+}
+
+module.exports = Dicer
+
+
+/***/ }),
+
+/***/ 62271:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+const EventEmitter = (__nccwpck_require__(78474).EventEmitter)
+const inherits = (__nccwpck_require__(57975).inherits)
+const getLimit = __nccwpck_require__(22393)
+
+const StreamSearch = __nccwpck_require__(84136)
+
+const B_DCRLF = Buffer.from('\r\n\r\n')
+const RE_CRLF = /\r\n/g
+const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex
+
+function HeaderParser (cfg) {
+ EventEmitter.call(this)
+
+ cfg = cfg || {}
+ const self = this
+ this.nread = 0
+ this.maxed = false
+ this.npairs = 0
+ this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000)
+ this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024)
+ this.buffer = ''
+ this.header = {}
+ this.finished = false
+ this.ss = new StreamSearch(B_DCRLF)
+ this.ss.on('info', function (isMatch, data, start, end) {
+ if (data && !self.maxed) {
+ if (self.nread + end - start >= self.maxHeaderSize) {
+ end = self.maxHeaderSize - self.nread + start
+ self.nread = self.maxHeaderSize
+ self.maxed = true
+ } else { self.nread += (end - start) }
+
+ self.buffer += data.toString('binary', start, end)
+ }
+ if (isMatch) { self._finish() }
+ })
+}
+inherits(HeaderParser, EventEmitter)
+
+HeaderParser.prototype.push = function (data) {
+ const r = this.ss.push(data)
+ if (this.finished) { return r }
+}
+
+HeaderParser.prototype.reset = function () {
+ this.finished = false
+ this.buffer = ''
+ this.header = {}
+ this.ss.reset()
+}
+
+HeaderParser.prototype._finish = function () {
+ if (this.buffer) { this._parseHeader() }
+ this.ss.matches = this.ss.maxMatches
+ const header = this.header
+ this.header = {}
+ this.buffer = ''
+ this.finished = true
+ this.nread = this.npairs = 0
+ this.maxed = false
+ this.emit('header', header)
+}
+
+HeaderParser.prototype._parseHeader = function () {
+ if (this.npairs === this.maxHeaderPairs) { return }
+
+ const lines = this.buffer.split(RE_CRLF)
+ const len = lines.length
+ let m, h
+
+ for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
+ if (lines[i].length === 0) { continue }
+ if (lines[i][0] === '\t' || lines[i][0] === ' ') {
+ // folded header content
+ // RFC2822 says to just remove the CRLF and not the whitespace following
+ // it, so we follow the RFC and include the leading whitespace ...
+ if (h) {
+ this.header[h][this.header[h].length - 1] += lines[i]
+ continue
+ }
+ }
+
+ const posColon = lines[i].indexOf(':')
+ if (
+ posColon === -1 ||
+ posColon === 0
+ ) {
+ return
+ }
+ m = RE_HDR.exec(lines[i])
+ h = m[1].toLowerCase()
+ this.header[h] = this.header[h] || []
+ this.header[h].push((m[2] || ''))
+ if (++this.npairs === this.maxHeaderPairs) { break }
+ }
+}
+
+module.exports = HeaderParser
+
+
+/***/ }),
+
+/***/ 50612:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+const inherits = (__nccwpck_require__(57975).inherits)
+const ReadableStream = (__nccwpck_require__(57075).Readable)
+
+function PartStream (opts) {
+ ReadableStream.call(this, opts)
+}
+inherits(PartStream, ReadableStream)
+
+PartStream.prototype._read = function (n) {}
+
+module.exports = PartStream
+
+
+/***/ }),
+
+/***/ 84136:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+/**
+ * Copyright Brian White. All rights reserved.
+ *
+ * @see https://github.com/mscdex/streamsearch
+ *
+ * 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.
+ *
+ * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation
+ * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool
+ */
+const EventEmitter = (__nccwpck_require__(78474).EventEmitter)
+const inherits = (__nccwpck_require__(57975).inherits)
+
+function SBMH (needle) {
+ if (typeof needle === 'string') {
+ needle = Buffer.from(needle)
+ }
+
+ if (!Buffer.isBuffer(needle)) {
+ throw new TypeError('The needle has to be a String or a Buffer.')
+ }
+
+ const needleLength = needle.length
+
+ if (needleLength === 0) {
+ throw new Error('The needle cannot be an empty String/Buffer.')
+ }
+
+ if (needleLength > 256) {
+ throw new Error('The needle cannot have a length bigger than 256.')
+ }
+
+ this.maxMatches = Infinity
+ this.matches = 0
+
+ this._occ = new Array(256)
+ .fill(needleLength) // Initialize occurrence table.
+ this._lookbehind_size = 0
+ this._needle = needle
+ this._bufpos = 0
+
+ this._lookbehind = Buffer.alloc(needleLength)
+
+ // Populate occurrence table with analysis of the needle,
+ // ignoring last letter.
+ for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var
+ this._occ[needle[i]] = needleLength - 1 - i
+ }
+}
+inherits(SBMH, EventEmitter)
+
+SBMH.prototype.reset = function () {
+ this._lookbehind_size = 0
+ this.matches = 0
+ this._bufpos = 0
}
-function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) {
- /* jshint validthis: true */
- const value = mapper.type.value;
- if (!value || typeof value !== "object") {
- throw new Error(`"value" metadata for a Dictionary must be defined in the ` +
- `mapper and it must of type "object" in ${objectName}`);
- }
- if (responseBody) {
- const tempDictionary = {};
- for (const key of Object.keys(responseBody)) {
- tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options);
- }
- return tempDictionary;
- }
- return responseBody;
+
+SBMH.prototype.push = function (chunk, pos) {
+ if (!Buffer.isBuffer(chunk)) {
+ chunk = Buffer.from(chunk, 'binary')
+ }
+ const chlen = chunk.length
+ this._bufpos = pos || 0
+ let r
+ while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) }
+ return r
}
-function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) {
- var _a;
- let element = mapper.type.element;
- if (!element || typeof element !== "object") {
- throw new Error(`element" metadata for an Array must be defined in the ` +
- `mapper and it must of type "object" in ${objectName}`);
- }
- if (responseBody) {
- if (!Array.isArray(responseBody)) {
- // xml2js will interpret a single element array as just the element, so force it to be an array
- responseBody = [responseBody];
- }
- // Quirk: Composite mappers referenced by `element` might
- // not have *all* properties declared (like uberParent),
- // so let's try to look up the full definition by name.
- if (element.type.name === "Composite" && element.type.className) {
- element = (_a = serializer.modelMappers[element.type.className]) !== null && _a !== void 0 ? _a : element;
- }
- const tempArray = [];
- for (let i = 0; i < responseBody.length; i++) {
- tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options);
- }
- return tempArray;
+
+SBMH.prototype._sbmh_feed = function (data) {
+ const len = data.length
+ const needle = this._needle
+ const needleLength = needle.length
+ const lastNeedleChar = needle[needleLength - 1]
+
+ // Positive: points to a position in `data`
+ // pos == 3 points to data[3]
+ // Negative: points to a position in the lookbehind buffer
+ // pos == -2 points to lookbehind[lookbehind_size - 2]
+ let pos = -this._lookbehind_size
+ let ch
+
+ if (pos < 0) {
+ // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool
+ // search with character lookup code that considers both the
+ // lookbehind buffer and the current round's haystack data.
+ //
+ // Loop until
+ // there is a match.
+ // or until
+ // we've moved past the position that requires the
+ // lookbehind buffer. In this case we switch to the
+ // optimized loop.
+ // or until
+ // the character to look at lies outside the haystack.
+ while (pos < 0 && pos <= len - needleLength) {
+ ch = this._sbmh_lookup_char(data, pos + needleLength - 1)
+
+ if (
+ ch === lastNeedleChar &&
+ this._sbmh_memcmp(data, pos, needleLength - 1)
+ ) {
+ this._lookbehind_size = 0
+ ++this.matches
+ this.emit('info', true)
+
+ return (this._bufpos = pos + needleLength)
+ }
+ pos += this._occ[ch]
}
- return responseBody;
-}
-function getIndexDiscriminator(discriminators, discriminatorValue, typeName) {
- const typeNamesToCheck = [typeName];
- while (typeNamesToCheck.length) {
- const currentName = typeNamesToCheck.shift();
- const indexDiscriminator = discriminatorValue === currentName
- ? discriminatorValue
- : currentName + "." + discriminatorValue;
- if (Object.prototype.hasOwnProperty.call(discriminators, indexDiscriminator)) {
- return discriminators[indexDiscriminator];
- }
- else {
- for (const [name, mapper] of Object.entries(discriminators)) {
- if (name.startsWith(currentName + ".") &&
- mapper.type.uberParent === currentName &&
- mapper.type.className) {
- typeNamesToCheck.push(mapper.type.className);
- }
- }
- }
+
+ // No match.
+
+ if (pos < 0) {
+ // There's too few data for Boyer-Moore-Horspool to run,
+ // so let's use a different algorithm to skip as much as
+ // we can.
+ // Forward pos until
+ // the trailing part of lookbehind + data
+ // looks like the beginning of the needle
+ // or until
+ // pos == 0
+ while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos }
}
- return undefined;
-}
-function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) {
- var _a;
- const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
- if (polymorphicDiscriminator) {
- let discriminatorName = polymorphicDiscriminator[polymorphicPropertyName];
- if (discriminatorName) {
- // The serializedName might have \\, which we just want to ignore
- if (polymorphicPropertyName === "serializedName") {
- discriminatorName = discriminatorName.replace(/\\/gi, "");
- }
- const discriminatorValue = object[discriminatorName];
- const typeName = (_a = mapper.type.uberParent) !== null && _a !== void 0 ? _a : mapper.type.className;
- if (typeof discriminatorValue === "string" && typeName) {
- const polymorphicMapper = getIndexDiscriminator(serializer.modelMappers.discriminators, discriminatorValue, typeName);
- if (polymorphicMapper) {
- mapper = polymorphicMapper;
- }
- }
- }
+
+ if (pos >= 0) {
+ // Discard lookbehind buffer.
+ this.emit('info', false, this._lookbehind, 0, this._lookbehind_size)
+ this._lookbehind_size = 0
+ } else {
+ // Cut off part of the lookbehind buffer that has
+ // been processed and append the entire haystack
+ // into it.
+ const bytesToCutOff = this._lookbehind_size + pos
+ if (bytesToCutOff > 0) {
+ // The cut off data is guaranteed not to contain the needle.
+ this.emit('info', false, this._lookbehind, 0, bytesToCutOff)
+ }
+
+ this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff,
+ this._lookbehind_size - bytesToCutOff)
+ this._lookbehind_size -= bytesToCutOff
+
+ data.copy(this._lookbehind, this._lookbehind_size)
+ this._lookbehind_size += len
+
+ this._bufpos = len
+ return len
}
- return mapper;
+ }
+
+ pos += (pos >= 0) * this._bufpos
+
+ // Lookbehind buffer is now empty. We only need to check if the
+ // needle is in the haystack.
+ if (data.indexOf(needle, pos) !== -1) {
+ pos = data.indexOf(needle, pos)
+ ++this.matches
+ if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) }
+
+ return (this._bufpos = pos + needleLength)
+ } else {
+ pos = len - needleLength
+ }
+
+ // There was no match. If there's trailing haystack data that we cannot
+ // match yet using the Boyer-Moore-Horspool algorithm (because the trailing
+ // data is less than the needle size) then match using a modified
+ // algorithm that starts matching from the beginning instead of the end.
+ // Whatever trailing data is left after running this algorithm is added to
+ // the lookbehind buffer.
+ while (
+ pos < len &&
+ (
+ data[pos] !== needle[0] ||
+ (
+ (Buffer.compare(
+ data.subarray(pos, pos + len - pos),
+ needle.subarray(0, len - pos)
+ ) !== 0)
+ )
+ )
+ ) {
+ ++pos
+ }
+ if (pos < len) {
+ data.copy(this._lookbehind, 0, pos, pos + (len - pos))
+ this._lookbehind_size = len - pos
+ }
+
+ // Everything until pos is guaranteed not to contain needle data.
+ if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) }
+
+ this._bufpos = len
+ return len
}
-function getPolymorphicDiscriminatorRecursively(serializer, mapper) {
- return (mapper.type.polymorphicDiscriminator ||
- getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) ||
- getPolymorphicDiscriminatorSafely(serializer, mapper.type.className));
+
+SBMH.prototype._sbmh_lookup_char = function (data, pos) {
+ return (pos < 0)
+ ? this._lookbehind[this._lookbehind_size + pos]
+ : data[pos]
}
-function getPolymorphicDiscriminatorSafely(serializer, typeName) {
- return (typeName &&
- serializer.modelMappers[typeName] &&
- serializer.modelMappers[typeName].type.polymorphicDiscriminator);
+
+SBMH.prototype._sbmh_memcmp = function (data, pos, len) {
+ for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
+ if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false }
+ }
+ return true
}
-/**
- * Known types of Mappers
- */
-exports.MapperTypeNames = {
- Base64Url: "Base64Url",
- Boolean: "Boolean",
- ByteArray: "ByteArray",
- Composite: "Composite",
- Date: "Date",
- DateTime: "DateTime",
- DateTimeRfc1123: "DateTimeRfc1123",
- Dictionary: "Dictionary",
- Enum: "Enum",
- Number: "Number",
- Object: "Object",
- Sequence: "Sequence",
- String: "String",
- Stream: "Stream",
- TimeSpan: "TimeSpan",
- UnixTime: "UnixTime",
-};
-//# sourceMappingURL=serializer.js.map
+
+module.exports = SBMH
+
/***/ }),
-/***/ 9544:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 89581:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ServiceClient = void 0;
-const core_rest_pipeline_1 = __nccwpck_require__(778);
-const pipeline_js_1 = __nccwpck_require__(1755);
-const utils_js_1 = __nccwpck_require__(1193);
-const httpClientCache_js_1 = __nccwpck_require__(6323);
-const operationHelpers_js_1 = __nccwpck_require__(7307);
-const urlHelpers_js_1 = __nccwpck_require__(1752);
-const interfaceHelpers_js_1 = __nccwpck_require__(2066);
-const log_js_1 = __nccwpck_require__(9994);
-/**
- * Initializes a new instance of the ServiceClient.
- */
-class ServiceClient {
- /**
- * The ServiceClient constructor
- * @param credential - The credentials used for authentication with the service.
- * @param options - The service client options that govern the behavior of the client.
- */
- constructor(options = {}) {
- var _a, _b;
- this._requestContentType = options.requestContentType;
- this._endpoint = (_a = options.endpoint) !== null && _a !== void 0 ? _a : options.baseUri;
- if (options.baseUri) {
- log_js_1.logger.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead.");
- }
- this._allowInsecureConnection = options.allowInsecureConnection;
- this._httpClient = options.httpClient || (0, httpClientCache_js_1.getCachedDefaultHttpClient)();
- this.pipeline = options.pipeline || createDefaultPipeline(options);
- if ((_b = options.additionalPolicies) === null || _b === void 0 ? void 0 : _b.length) {
- for (const { policy, position } of options.additionalPolicies) {
- // Sign happens after Retry and is commonly needed to occur
- // before policies that intercept post-retry.
- const afterPhase = position === "perRetry" ? "Sign" : undefined;
- this.pipeline.addPolicy(policy, {
- afterPhase,
- });
- }
- }
- }
- /**
- * Send the provided httpRequest.
- */
- async sendRequest(request) {
- return this.pipeline.sendRequest(this._httpClient, request);
- }
- /**
- * Send an HTTP request that is populated using the provided OperationSpec.
- * @typeParam T - The typed result of the request, based on the OperationSpec.
- * @param operationArguments - The arguments that the HTTP request's templated values will be populated from.
- * @param operationSpec - The OperationSpec to use to populate the httpRequest.
- */
- async sendOperationRequest(operationArguments, operationSpec) {
- const endpoint = operationSpec.baseUrl || this._endpoint;
- if (!endpoint) {
- throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a endpoint string property that contains the base URL to use.");
- }
- // Templatized URLs sometimes reference properties on the ServiceClient child class,
- // so we have to pass `this` below in order to search these properties if they're
- // not part of OperationArguments
- const url = (0, urlHelpers_js_1.getRequestUrl)(endpoint, operationSpec, operationArguments, this);
- const request = (0, core_rest_pipeline_1.createPipelineRequest)({
- url,
- });
- request.method = operationSpec.httpMethod;
- const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
- operationInfo.operationSpec = operationSpec;
- operationInfo.operationArguments = operationArguments;
- const contentType = operationSpec.contentType || this._requestContentType;
- if (contentType && operationSpec.requestBody) {
- request.headers.set("Content-Type", contentType);
- }
- const options = operationArguments.options;
- if (options) {
- const requestOptions = options.requestOptions;
- if (requestOptions) {
- if (requestOptions.timeout) {
- request.timeout = requestOptions.timeout;
- }
- if (requestOptions.onUploadProgress) {
- request.onUploadProgress = requestOptions.onUploadProgress;
- }
- if (requestOptions.onDownloadProgress) {
- request.onDownloadProgress = requestOptions.onDownloadProgress;
- }
- if (requestOptions.shouldDeserialize !== undefined) {
- operationInfo.shouldDeserialize = requestOptions.shouldDeserialize;
- }
- if (requestOptions.allowInsecureConnection) {
- request.allowInsecureConnection = true;
- }
- }
- if (options.abortSignal) {
- request.abortSignal = options.abortSignal;
- }
- if (options.tracingOptions) {
- request.tracingOptions = options.tracingOptions;
- }
- }
- if (this._allowInsecureConnection) {
- request.allowInsecureConnection = true;
- }
- if (request.streamResponseStatusCodes === undefined) {
- request.streamResponseStatusCodes = (0, interfaceHelpers_js_1.getStreamingResponseStatusCodes)(operationSpec);
- }
- try {
- const rawResponse = await this.sendRequest(request);
- const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[rawResponse.status]);
- if (options === null || options === void 0 ? void 0 : options.onResponse) {
- options.onResponse(rawResponse, flatResponse);
- }
- return flatResponse;
- }
- catch (error) {
- if (typeof error === "object" && (error === null || error === void 0 ? void 0 : error.response)) {
- const rawResponse = error.response;
- const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[error.statusCode] || operationSpec.responses["default"]);
- error.details = flatResponse;
- if (options === null || options === void 0 ? void 0 : options.onResponse) {
- options.onResponse(rawResponse, flatResponse, error);
- }
- }
- throw error;
- }
+
+const WritableStream = (__nccwpck_require__(57075).Writable)
+const { inherits } = __nccwpck_require__(57975)
+const Dicer = __nccwpck_require__(27182)
+
+const MultipartParser = __nccwpck_require__(41192)
+const UrlencodedParser = __nccwpck_require__(80855)
+const parseParams = __nccwpck_require__(8929)
+
+function Busboy (opts) {
+ if (!(this instanceof Busboy)) { return new Busboy(opts) }
+
+ if (typeof opts !== 'object') {
+ throw new TypeError('Busboy expected an options-Object.')
+ }
+ if (typeof opts.headers !== 'object') {
+ throw new TypeError('Busboy expected an options-Object with headers-attribute.')
+ }
+ if (typeof opts.headers['content-type'] !== 'string') {
+ throw new TypeError('Missing Content-Type-header.')
+ }
+
+ const {
+ headers,
+ ...streamOptions
+ } = opts
+
+ this.opts = {
+ autoDestroy: false,
+ ...streamOptions
+ }
+ WritableStream.call(this, this.opts)
+
+ this._done = false
+ this._parser = this.getParserByHeaders(headers)
+ this._finished = false
+}
+inherits(Busboy, WritableStream)
+
+Busboy.prototype.emit = function (ev) {
+ if (ev === 'finish') {
+ if (!this._done) {
+ this._parser?.end()
+ return
+ } else if (this._finished) {
+ return
}
+ this._finished = true
+ }
+ WritableStream.prototype.emit.apply(this, arguments)
}
-exports.ServiceClient = ServiceClient;
-function createDefaultPipeline(options) {
- const credentialScopes = getCredentialScopes(options);
- const credentialOptions = options.credential && credentialScopes
- ? { credentialScopes, credential: options.credential }
- : undefined;
- return (0, pipeline_js_1.createClientPipeline)(Object.assign(Object.assign({}, options), { credentialOptions }));
+
+Busboy.prototype.getParserByHeaders = function (headers) {
+ const parsed = parseParams(headers['content-type'])
+
+ const cfg = {
+ defCharset: this.opts.defCharset,
+ fileHwm: this.opts.fileHwm,
+ headers,
+ highWaterMark: this.opts.highWaterMark,
+ isPartAFile: this.opts.isPartAFile,
+ limits: this.opts.limits,
+ parsedConType: parsed,
+ preservePath: this.opts.preservePath
+ }
+
+ if (MultipartParser.detect.test(parsed[0])) {
+ return new MultipartParser(this, cfg)
+ }
+ if (UrlencodedParser.detect.test(parsed[0])) {
+ return new UrlencodedParser(this, cfg)
+ }
+ throw new Error('Unsupported Content-Type.')
}
-function getCredentialScopes(options) {
- if (options.credentialScopes) {
- return options.credentialScopes;
+
+Busboy.prototype._write = function (chunk, encoding, cb) {
+ this._parser.write(chunk, cb)
+}
+
+module.exports = Busboy
+module.exports["default"] = Busboy
+module.exports.Busboy = Busboy
+
+module.exports.Dicer = Dicer
+
+
+/***/ }),
+
+/***/ 41192:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+// TODO:
+// * support 1 nested multipart level
+// (see second multipart example here:
+// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data)
+// * support limits.fieldNameSize
+// -- this will require modifications to utils.parseParams
+
+const { Readable } = __nccwpck_require__(57075)
+const { inherits } = __nccwpck_require__(57975)
+
+const Dicer = __nccwpck_require__(27182)
+
+const parseParams = __nccwpck_require__(8929)
+const decodeText = __nccwpck_require__(72747)
+const basename = __nccwpck_require__(20692)
+const getLimit = __nccwpck_require__(22393)
+
+const RE_BOUNDARY = /^boundary$/i
+const RE_FIELD = /^form-data$/i
+const RE_CHARSET = /^charset$/i
+const RE_FILENAME = /^filename$/i
+const RE_NAME = /^name$/i
+
+Multipart.detect = /^multipart\/form-data/i
+function Multipart (boy, cfg) {
+ let i
+ let len
+ const self = this
+ let boundary
+ const limits = cfg.limits
+ const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined))
+ const parsedConType = cfg.parsedConType || []
+ const defCharset = cfg.defCharset || 'utf8'
+ const preservePath = cfg.preservePath
+ const fileOpts = { highWaterMark: cfg.fileHwm }
+
+ for (i = 0, len = parsedConType.length; i < len; ++i) {
+ if (Array.isArray(parsedConType[i]) &&
+ RE_BOUNDARY.test(parsedConType[i][0])) {
+ boundary = parsedConType[i][1]
+ break
}
- if (options.endpoint) {
- return `${options.endpoint}/.default`;
+ }
+
+ function checkFinished () {
+ if (nends === 0 && finished && !boy._done) {
+ finished = false
+ self.end()
}
- if (options.baseUri) {
- return `${options.baseUri}/.default`;
+ }
+
+ if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') }
+
+ const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)
+ const fileSizeLimit = getLimit(limits, 'fileSize', Infinity)
+ const filesLimit = getLimit(limits, 'files', Infinity)
+ const fieldsLimit = getLimit(limits, 'fields', Infinity)
+ const partsLimit = getLimit(limits, 'parts', Infinity)
+ const headerPairsLimit = getLimit(limits, 'headerPairs', 2000)
+ const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024)
+
+ let nfiles = 0
+ let nfields = 0
+ let nends = 0
+ let curFile
+ let curField
+ let finished = false
+
+ this._needDrain = false
+ this._pause = false
+ this._cb = undefined
+ this._nparts = 0
+ this._boy = boy
+
+ const parserCfg = {
+ boundary,
+ maxHeaderPairs: headerPairsLimit,
+ maxHeaderSize: headerSizeLimit,
+ partHwm: fileOpts.highWaterMark,
+ highWaterMark: cfg.highWaterMark
+ }
+
+ this.parser = new Dicer(parserCfg)
+ this.parser.on('drain', function () {
+ self._needDrain = false
+ if (self._cb && !self._pause) {
+ const cb = self._cb
+ self._cb = undefined
+ cb()
}
- if (options.credential && !options.credentialScopes) {
- throw new Error(`When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`);
+ }).on('part', function onPart (part) {
+ if (++self._nparts > partsLimit) {
+ self.parser.removeListener('part', onPart)
+ self.parser.on('part', skipPart)
+ boy.hitPartsLimit = true
+ boy.emit('partsLimit')
+ return skipPart(part)
}
- return undefined;
-}
-//# sourceMappingURL=serviceClient.js.map
-/***/ }),
+ // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let
+ // us emit 'end' early since we know the part has ended if we are already
+ // seeing the next part
+ if (curField) {
+ const field = curField
+ field.emit('end')
+ field.removeAllListeners('end')
+ }
-/***/ 3345:
-/***/ ((__unused_webpack_module, exports) => {
+ part.on('header', function (header) {
+ let contype
+ let fieldname
+ let parsed
+ let charset
+ let encoding
+ let filename
+ let nsize = 0
-"use strict";
+ if (header['content-type']) {
+ parsed = parseParams(header['content-type'][0])
+ if (parsed[0]) {
+ contype = parsed[0].toLowerCase()
+ for (i = 0, len = parsed.length; i < len; ++i) {
+ if (RE_CHARSET.test(parsed[i][0])) {
+ charset = parsed[i][1].toLowerCase()
+ break
+ }
+ }
+ }
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.state = void 0;
-/**
- * Holds the singleton operationRequestMap, to be shared across CJS and ESM imports.
- */
-exports.state = {
- operationRequestMap: new WeakMap(),
-};
-//# sourceMappingURL=state-cjs.cjs.map
+ if (contype === undefined) { contype = 'text/plain' }
+ if (charset === undefined) { charset = defCharset }
-/***/ }),
+ if (header['content-disposition']) {
+ parsed = parseParams(header['content-disposition'][0])
+ if (!RE_FIELD.test(parsed[0])) { return skipPart(part) }
+ for (i = 0, len = parsed.length; i < len; ++i) {
+ if (RE_NAME.test(parsed[i][0])) {
+ fieldname = parsed[i][1]
+ } else if (RE_FILENAME.test(parsed[i][0])) {
+ filename = parsed[i][1]
+ if (!preservePath) { filename = basename(filename) }
+ }
+ }
+ } else { return skipPart(part) }
-/***/ 1752:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' }
-"use strict";
+ let onData,
+ onEnd
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.appendQueryParams = exports.getRequestUrl = void 0;
-const operationHelpers_js_1 = __nccwpck_require__(7307);
-const interfaceHelpers_js_1 = __nccwpck_require__(2066);
-const CollectionFormatToDelimiterMap = {
- CSV: ",",
- SSV: " ",
- Multi: "Multi",
- TSV: "\t",
- Pipes: "|",
-};
-function getRequestUrl(baseUri, operationSpec, operationArguments, fallbackObject) {
- const urlReplacements = calculateUrlReplacements(operationSpec, operationArguments, fallbackObject);
- let isAbsolutePath = false;
- let requestUrl = replaceAll(baseUri, urlReplacements);
- if (operationSpec.path) {
- let path = replaceAll(operationSpec.path, urlReplacements);
- // QUIRK: sometimes we get a path component like /{nextLink}
- // which may be a fully formed URL with a leading /. In that case, we should
- // remove the leading /
- if (operationSpec.path === "/{nextLink}" && path.startsWith("/")) {
- path = path.substring(1);
+ if (isPartAFile(fieldname, contype, filename)) {
+ // file/binary field
+ if (nfiles === filesLimit) {
+ if (!boy.hitFilesLimit) {
+ boy.hitFilesLimit = true
+ boy.emit('filesLimit')
+ }
+ return skipPart(part)
}
- // QUIRK: sometimes we get a path component like {nextLink}
- // which may be a fully formed URL. In that case, we should
- // ignore the baseUri.
- if (isAbsoluteUrl(path)) {
- requestUrl = path;
- isAbsolutePath = true;
+
+ ++nfiles
+
+ if (boy.listenerCount('file') === 0) {
+ self.parser._ignore()
+ return
}
- else {
- requestUrl = appendPath(requestUrl, path);
+
+ ++nends
+ const file = new FileStream(fileOpts)
+ curFile = file
+ file.on('end', function () {
+ --nends
+ self._pause = false
+ checkFinished()
+ if (self._cb && !self._needDrain) {
+ const cb = self._cb
+ self._cb = undefined
+ cb()
+ }
+ })
+ file._read = function (n) {
+ if (!self._pause) { return }
+ self._pause = false
+ if (self._cb && !self._needDrain) {
+ const cb = self._cb
+ self._cb = undefined
+ cb()
+ }
}
- }
- const { queryParams, sequenceParams } = calculateQueryParameters(operationSpec, operationArguments, fallbackObject);
- /**
- * Notice that this call sets the `noOverwrite` parameter to true if the `requestUrl`
- * is an absolute path. This ensures that existing query parameter values in `requestUrl`
- * do not get overwritten. On the other hand when `requestUrl` is not absolute path, it
- * is still being built so there is nothing to overwrite.
- */
- requestUrl = appendQueryParams(requestUrl, queryParams, sequenceParams, isAbsolutePath);
- return requestUrl;
-}
-exports.getRequestUrl = getRequestUrl;
-function replaceAll(input, replacements) {
- let result = input;
- for (const [searchValue, replaceValue] of replacements) {
- result = result.split(searchValue).join(replaceValue);
- }
- return result;
-}
-function calculateUrlReplacements(operationSpec, operationArguments, fallbackObject) {
- var _a;
- const result = new Map();
- if ((_a = operationSpec.urlParameters) === null || _a === void 0 ? void 0 : _a.length) {
- for (const urlParameter of operationSpec.urlParameters) {
- let urlParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, urlParameter, fallbackObject);
- const parameterPathString = (0, interfaceHelpers_js_1.getPathStringFromParameter)(urlParameter);
- urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, parameterPathString);
- if (!urlParameter.skipEncoding) {
- urlParameterValue = encodeURIComponent(urlParameterValue);
- }
- result.set(`{${urlParameter.mapper.serializedName || parameterPathString}}`, urlParameterValue);
+ boy.emit('file', fieldname, file, filename, encoding, contype)
+
+ onData = function (data) {
+ if ((nsize += data.length) > fileSizeLimit) {
+ const extralen = fileSizeLimit - nsize + data.length
+ if (extralen > 0) { file.push(data.slice(0, extralen)) }
+ file.truncated = true
+ file.bytesRead = fileSizeLimit
+ part.removeAllListeners('data')
+ file.emit('limit')
+ return
+ } else if (!file.push(data)) { self._pause = true }
+
+ file.bytesRead = nsize
}
- }
- return result;
-}
-function isAbsoluteUrl(url) {
- return url.includes("://");
-}
-function appendPath(url, pathToAppend) {
- if (!pathToAppend) {
- return url;
- }
- const parsedUrl = new URL(url);
- let newPath = parsedUrl.pathname;
- if (!newPath.endsWith("/")) {
- newPath = `${newPath}/`;
- }
- if (pathToAppend.startsWith("/")) {
- pathToAppend = pathToAppend.substring(1);
- }
- const searchStart = pathToAppend.indexOf("?");
- if (searchStart !== -1) {
- const path = pathToAppend.substring(0, searchStart);
- const search = pathToAppend.substring(searchStart + 1);
- newPath = newPath + path;
- if (search) {
- parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}&${search}` : search;
+
+ onEnd = function () {
+ curFile = undefined
+ file.push(null)
}
- }
- else {
- newPath = newPath + pathToAppend;
- }
- parsedUrl.pathname = newPath;
- return parsedUrl.toString();
-}
-function calculateQueryParameters(operationSpec, operationArguments, fallbackObject) {
- var _a;
- const result = new Map();
- const sequenceParams = new Set();
- if ((_a = operationSpec.queryParameters) === null || _a === void 0 ? void 0 : _a.length) {
- for (const queryParameter of operationSpec.queryParameters) {
- if (queryParameter.mapper.type.name === "Sequence" && queryParameter.mapper.serializedName) {
- sequenceParams.add(queryParameter.mapper.serializedName);
- }
- let queryParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, queryParameter, fallbackObject);
- if ((queryParameterValue !== undefined && queryParameterValue !== null) ||
- queryParameter.mapper.required) {
- queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(queryParameter));
- const delimiter = queryParameter.collectionFormat
- ? CollectionFormatToDelimiterMap[queryParameter.collectionFormat]
- : "";
- if (Array.isArray(queryParameterValue)) {
- // replace null and undefined
- queryParameterValue = queryParameterValue.map((item) => {
- if (item === null || item === undefined) {
- return "";
- }
- return item;
- });
- }
- if (queryParameter.collectionFormat === "Multi" && queryParameterValue.length === 0) {
- continue;
- }
- else if (Array.isArray(queryParameterValue) &&
- (queryParameter.collectionFormat === "SSV" || queryParameter.collectionFormat === "TSV")) {
- queryParameterValue = queryParameterValue.join(delimiter);
- }
- if (!queryParameter.skipEncoding) {
- if (Array.isArray(queryParameterValue)) {
- queryParameterValue = queryParameterValue.map((item) => {
- return encodeURIComponent(item);
- });
- }
- else {
- queryParameterValue = encodeURIComponent(queryParameterValue);
- }
- }
- // Join pipes and CSV *after* encoding, or the server will be upset.
- if (Array.isArray(queryParameterValue) &&
- (queryParameter.collectionFormat === "CSV" || queryParameter.collectionFormat === "Pipes")) {
- queryParameterValue = queryParameterValue.join(delimiter);
- }
- result.set(queryParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(queryParameter), queryParameterValue);
- }
+ } else {
+ // non-file field
+ if (nfields === fieldsLimit) {
+ if (!boy.hitFieldsLimit) {
+ boy.hitFieldsLimit = true
+ boy.emit('fieldsLimit')
+ }
+ return skipPart(part)
}
- }
- return {
- queryParams: result,
- sequenceParams,
- };
-}
-function simpleParseQueryParams(queryString) {
- const result = new Map();
- if (!queryString || queryString[0] !== "?") {
- return result;
- }
- // remove the leading ?
- queryString = queryString.slice(1);
- const pairs = queryString.split("&");
- for (const pair of pairs) {
- const [name, value] = pair.split("=", 2);
- const existingValue = result.get(name);
- if (existingValue) {
- if (Array.isArray(existingValue)) {
- existingValue.push(value);
- }
- else {
- result.set(name, [existingValue, value]);
- }
+
+ ++nfields
+ ++nends
+ let buffer = ''
+ let truncated = false
+ curField = part
+
+ onData = function (data) {
+ if ((nsize += data.length) > fieldSizeLimit) {
+ const extralen = (fieldSizeLimit - (nsize - data.length))
+ buffer += data.toString('binary', 0, extralen)
+ truncated = true
+ part.removeAllListeners('data')
+ } else { buffer += data.toString('binary') }
}
- else {
- result.set(name, value);
+
+ onEnd = function () {
+ curField = undefined
+ if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) }
+ boy.emit('field', fieldname, buffer, false, truncated, encoding, contype)
+ --nends
+ checkFinished()
}
- }
- return result;
+ }
+
+ /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become
+ broken. Streams2/streams3 is a huge black box of confusion, but
+ somehow overriding the sync state seems to fix things again (and still
+ seems to work for previous node versions).
+ */
+ part._readableState.sync = false
+
+ part.on('data', onData)
+ part.on('end', onEnd)
+ }).on('error', function (err) {
+ if (curFile) { curFile.emit('error', err) }
+ })
+ }).on('error', function (err) {
+ boy.emit('error', err)
+ }).on('finish', function () {
+ finished = true
+ checkFinished()
+ })
}
-/** @internal */
-function appendQueryParams(url, queryParams, sequenceParams, noOverwrite = false) {
- if (queryParams.size === 0) {
- return url;
+
+Multipart.prototype.write = function (chunk, cb) {
+ const r = this.parser.write(chunk)
+ if (r && !this._pause) {
+ cb()
+ } else {
+ this._needDrain = !r
+ this._cb = cb
+ }
+}
+
+Multipart.prototype.end = function () {
+ const self = this
+
+ if (self.parser.writable) {
+ self.parser.end()
+ } else if (!self._boy._done) {
+ process.nextTick(function () {
+ self._boy._done = true
+ self._boy.emit('finish')
+ })
+ }
+}
+
+function skipPart (part) {
+ part.resume()
+}
+
+function FileStream (opts) {
+ Readable.call(this, opts)
+
+ this.bytesRead = 0
+
+ this.truncated = false
+}
+
+inherits(FileStream, Readable)
+
+FileStream.prototype._read = function (n) {}
+
+module.exports = Multipart
+
+
+/***/ }),
+
+/***/ 80855:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+const Decoder = __nccwpck_require__(11496)
+const decodeText = __nccwpck_require__(72747)
+const getLimit = __nccwpck_require__(22393)
+
+const RE_CHARSET = /^charset$/i
+
+UrlEncoded.detect = /^application\/x-www-form-urlencoded/i
+function UrlEncoded (boy, cfg) {
+ const limits = cfg.limits
+ const parsedConType = cfg.parsedConType
+ this.boy = boy
+
+ this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)
+ this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100)
+ this.fieldsLimit = getLimit(limits, 'fields', Infinity)
+
+ let charset
+ for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var
+ if (Array.isArray(parsedConType[i]) &&
+ RE_CHARSET.test(parsedConType[i][0])) {
+ charset = parsedConType[i][1].toLowerCase()
+ break
}
- const parsedUrl = new URL(url);
- // QUIRK: parsedUrl.searchParams will have their name/value pairs decoded, which
- // can change their meaning to the server, such as in the case of a SAS signature.
- // To avoid accidentally un-encoding a query param, we parse the key/values ourselves
- const combinedParams = simpleParseQueryParams(parsedUrl.search);
- for (const [name, value] of queryParams) {
- const existingValue = combinedParams.get(name);
- if (Array.isArray(existingValue)) {
- if (Array.isArray(value)) {
- existingValue.push(...value);
- const valueSet = new Set(existingValue);
- combinedParams.set(name, Array.from(valueSet));
- }
- else {
- existingValue.push(value);
- }
- }
- else if (existingValue) {
- if (Array.isArray(value)) {
- value.unshift(existingValue);
- }
- else if (sequenceParams.has(name)) {
- combinedParams.set(name, [existingValue, value]);
- }
- if (!noOverwrite) {
- combinedParams.set(name, value);
- }
+ }
+
+ if (charset === undefined) { charset = cfg.defCharset || 'utf8' }
+
+ this.decoder = new Decoder()
+ this.charset = charset
+ this._fields = 0
+ this._state = 'key'
+ this._checkingBytes = true
+ this._bytesKey = 0
+ this._bytesVal = 0
+ this._key = ''
+ this._val = ''
+ this._keyTrunc = false
+ this._valTrunc = false
+ this._hitLimit = false
+}
+
+UrlEncoded.prototype.write = function (data, cb) {
+ if (this._fields === this.fieldsLimit) {
+ if (!this.boy.hitFieldsLimit) {
+ this.boy.hitFieldsLimit = true
+ this.boy.emit('fieldsLimit')
+ }
+ return cb()
+ }
+
+ let idxeq; let idxamp; let i; let p = 0; const len = data.length
+
+ while (p < len) {
+ if (this._state === 'key') {
+ idxeq = idxamp = undefined
+ for (i = p; i < len; ++i) {
+ if (!this._checkingBytes) { ++p }
+ if (data[i] === 0x3D/* = */) {
+ idxeq = i
+ break
+ } else if (data[i] === 0x26/* & */) {
+ idxamp = i
+ break
}
- else {
- combinedParams.set(name, value);
+ if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) {
+ this._hitLimit = true
+ break
+ } else if (this._checkingBytes) { ++this._bytesKey }
+ }
+
+ if (idxeq !== undefined) {
+ // key with assignment
+ if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) }
+ this._state = 'val'
+
+ this._hitLimit = false
+ this._checkingBytes = true
+ this._val = ''
+ this._bytesVal = 0
+ this._valTrunc = false
+ this.decoder.reset()
+
+ p = idxeq + 1
+ } else if (idxamp !== undefined) {
+ // key with no assignment
+ ++this._fields
+ let key; const keyTrunc = this._keyTrunc
+ if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key }
+
+ this._hitLimit = false
+ this._checkingBytes = true
+ this._key = ''
+ this._bytesKey = 0
+ this._keyTrunc = false
+ this.decoder.reset()
+
+ if (key.length) {
+ this.boy.emit('field', decodeText(key, 'binary', this.charset),
+ '',
+ keyTrunc,
+ false)
}
- }
- const searchPieces = [];
- for (const [name, value] of combinedParams) {
- if (typeof value === "string") {
- searchPieces.push(`${name}=${value}`);
+
+ p = idxamp + 1
+ if (this._fields === this.fieldsLimit) { return cb() }
+ } else if (this._hitLimit) {
+ // we may not have hit the actual limit if there are encoded bytes...
+ if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) }
+ p = i
+ if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) {
+ // yep, we actually did hit the limit
+ this._checkingBytes = false
+ this._keyTrunc = true
}
- else if (Array.isArray(value)) {
- // QUIRK: If we get an array of values, include multiple key/value pairs
- for (const subValue of value) {
- searchPieces.push(`${name}=${subValue}`);
- }
+ } else {
+ if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) }
+ p = len
+ }
+ } else {
+ idxamp = undefined
+ for (i = p; i < len; ++i) {
+ if (!this._checkingBytes) { ++p }
+ if (data[i] === 0x26/* & */) {
+ idxamp = i
+ break
}
- else {
- searchPieces.push(`${name}=${value}`);
+ if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) {
+ this._hitLimit = true
+ break
+ } else if (this._checkingBytes) { ++this._bytesVal }
+ }
+
+ if (idxamp !== undefined) {
+ ++this._fields
+ if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) }
+ this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
+ decodeText(this._val, 'binary', this.charset),
+ this._keyTrunc,
+ this._valTrunc)
+ this._state = 'key'
+
+ this._hitLimit = false
+ this._checkingBytes = true
+ this._key = ''
+ this._bytesKey = 0
+ this._keyTrunc = false
+ this.decoder.reset()
+
+ p = idxamp + 1
+ if (this._fields === this.fieldsLimit) { return cb() }
+ } else if (this._hitLimit) {
+ // we may not have hit the actual limit if there are encoded bytes...
+ if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) }
+ p = i
+ if ((this._val === '' && this.fieldSizeLimit === 0) ||
+ (this._bytesVal = this._val.length) === this.fieldSizeLimit) {
+ // yep, we actually did hit the limit
+ this._checkingBytes = false
+ this._valTrunc = true
}
+ } else {
+ if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) }
+ p = len
+ }
}
- // QUIRK: we have to set search manually as searchParams will encode comma when it shouldn't.
- parsedUrl.search = searchPieces.length ? `?${searchPieces.join("&")}` : "";
- return parsedUrl.toString();
+ }
+ cb()
}
-exports.appendQueryParams = appendQueryParams;
-//# sourceMappingURL=urlHelpers.js.map
+
+UrlEncoded.prototype.end = function () {
+ if (this.boy._done) { return }
+
+ if (this._state === 'key' && this._key.length > 0) {
+ this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
+ '',
+ this._keyTrunc,
+ false)
+ } else if (this._state === 'val') {
+ this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
+ decodeText(this._val, 'binary', this.charset),
+ this._keyTrunc,
+ this._valTrunc)
+ }
+ this.boy._done = true
+ this.boy.emit('finish')
+}
+
+module.exports = UrlEncoded
+
/***/ }),
-/***/ 1193:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 11496:
+/***/ ((module) => {
"use strict";
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.flattenResponse = exports.isValidUuid = exports.isDuration = exports.isPrimitiveBody = void 0;
-/**
- * A type guard for a primitive response body.
- * @param value - Value to test
- *
- * @internal
- */
-function isPrimitiveBody(value, mapperTypeName) {
- return (mapperTypeName !== "Composite" &&
- mapperTypeName !== "Dictionary" &&
- (typeof value === "string" ||
- typeof value === "number" ||
- typeof value === "boolean" ||
- (mapperTypeName === null || mapperTypeName === void 0 ? void 0 : mapperTypeName.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i)) !==
- null ||
- value === undefined ||
- value === null));
-}
-exports.isPrimitiveBody = isPrimitiveBody;
-const validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
-/**
- * Returns true if the given string is in ISO 8601 format.
- * @param value - The value to be validated for ISO 8601 duration format.
- * @internal
- */
-function isDuration(value) {
- return validateISODuration.test(value);
-}
-exports.isDuration = isDuration;
-const validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;
-/**
- * Returns true if the provided uuid is valid.
- *
- * @param uuid - The uuid that needs to be validated.
- *
- * @internal
- */
-function isValidUuid(uuid) {
- return validUuidRegex.test(uuid);
-}
-exports.isValidUuid = isValidUuid;
-/**
- * Maps the response as follows:
- * - wraps the response body if needed (typically if its type is primitive).
- * - returns null if the combination of the headers and the body is empty.
- * - otherwise, returns the combination of the headers and the body.
- *
- * @param responseObject - a representation of the parsed response
- * @returns the response that will be returned to the user which can be null and/or wrapped
- *
- * @internal
- */
-function handleNullableResponseAndWrappableBody(responseObject) {
- const combinedHeadersAndBody = Object.assign(Object.assign({}, responseObject.headers), responseObject.body);
- if (responseObject.hasNullableType &&
- Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0) {
- return responseObject.shouldWrapBody ? { body: null } : null;
- }
- else {
- return responseObject.shouldWrapBody
- ? Object.assign(Object.assign({}, responseObject.headers), { body: responseObject.body }) : combinedHeadersAndBody;
- }
+
+const RE_PLUS = /\+/g
+
+const HEX = [
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
+ 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+]
+
+function Decoder () {
+ this.buffer = undefined
}
-/**
- * Take a `FullOperationResponse` and turn it into a flat
- * response object to hand back to the consumer.
- * @param fullResponse - The processed response from the operation request
- * @param responseSpec - The response map from the OperationSpec
- *
- * @internal
- */
-function flattenResponse(fullResponse, responseSpec) {
- var _a, _b;
- const parsedHeaders = fullResponse.parsedHeaders;
- // head methods never have a body, but we return a boolean set to body property
- // to indicate presence/absence of the resource
- if (fullResponse.request.method === "HEAD") {
- return Object.assign(Object.assign({}, parsedHeaders), { body: fullResponse.parsedBody });
- }
- const bodyMapper = responseSpec && responseSpec.bodyMapper;
- const isNullable = Boolean(bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.nullable);
- const expectedBodyTypeName = bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.type.name;
- /** If the body is asked for, we look at the expected body type to handle it */
- if (expectedBodyTypeName === "Stream") {
- return Object.assign(Object.assign({}, parsedHeaders), { blobBody: fullResponse.blobBody, readableStreamBody: fullResponse.readableStreamBody });
- }
- const modelProperties = (expectedBodyTypeName === "Composite" &&
- bodyMapper.type.modelProperties) ||
- {};
- const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === "");
- if (expectedBodyTypeName === "Sequence" || isPageableResponse) {
- const arrayResponse = (_a = fullResponse.parsedBody) !== null && _a !== void 0 ? _a : [];
- for (const key of Object.keys(modelProperties)) {
- if (modelProperties[key].serializedName) {
- arrayResponse[key] = (_b = fullResponse.parsedBody) === null || _b === void 0 ? void 0 : _b[key];
- }
- }
- if (parsedHeaders) {
- for (const key of Object.keys(parsedHeaders)) {
- arrayResponse[key] = parsedHeaders[key];
- }
+Decoder.prototype.write = function (str) {
+ // Replace '+' with ' ' before decoding
+ str = str.replace(RE_PLUS, ' ')
+ let res = ''
+ let i = 0; let p = 0; const len = str.length
+ for (; i < len; ++i) {
+ if (this.buffer !== undefined) {
+ if (!HEX[str.charCodeAt(i)]) {
+ res += '%' + this.buffer
+ this.buffer = undefined
+ --i // retry character
+ } else {
+ this.buffer += str[i]
+ ++p
+ if (this.buffer.length === 2) {
+ res += String.fromCharCode(parseInt(this.buffer, 16))
+ this.buffer = undefined
}
- return isNullable &&
- !fullResponse.parsedBody &&
- !parsedHeaders &&
- Object.getOwnPropertyNames(modelProperties).length === 0
- ? null
- : arrayResponse;
+ }
+ } else if (str[i] === '%') {
+ if (i > p) {
+ res += str.substring(p, i)
+ p = i
+ }
+ this.buffer = ''
+ ++p
}
- return handleNullableResponseAndWrappableBody({
- body: fullResponse.parsedBody,
- headers: parsedHeaders,
- hasNullableType: isNullable,
- shouldWrapBody: isPrimitiveBody(fullResponse.parsedBody, expectedBodyTypeName),
- });
+ }
+ if (p < len && this.buffer === undefined) { res += str.substring(p) }
+ return res
+}
+Decoder.prototype.reset = function () {
+ this.buffer = undefined
}
-exports.flattenResponse = flattenResponse;
-//# sourceMappingURL=utils.js.map
+
+module.exports = Decoder
+
/***/ }),
-/***/ 5492:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 20692:
+/***/ ((module) => {
"use strict";
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ExtendedServiceClient = void 0;
-const disableKeepAlivePolicy_js_1 = __nccwpck_require__(2639);
-const core_rest_pipeline_1 = __nccwpck_require__(778);
-const core_client_1 = __nccwpck_require__(160);
-const response_js_1 = __nccwpck_require__(8153);
-/**
- * Client to provide compatability between core V1 & V2.
- */
-class ExtendedServiceClient extends core_client_1.ServiceClient {
- constructor(options) {
- var _a, _b;
- super(options);
- if (((_a = options.keepAliveOptions) === null || _a === void 0 ? void 0 : _a.enable) === false &&
- !(0, disableKeepAlivePolicy_js_1.pipelineContainsDisableKeepAlivePolicy)(this.pipeline)) {
- this.pipeline.addPolicy((0, disableKeepAlivePolicy_js_1.createDisableKeepAlivePolicy)());
- }
- if (((_b = options.redirectOptions) === null || _b === void 0 ? void 0 : _b.handleRedirects) === false) {
- this.pipeline.removePolicy({
- name: core_rest_pipeline_1.redirectPolicyName,
- });
- }
+
+module.exports = function basename (path) {
+ if (typeof path !== 'string') { return '' }
+ for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var
+ switch (path.charCodeAt(i)) {
+ case 0x2F: // '/'
+ case 0x5C: // '\'
+ path = path.slice(i + 1)
+ return (path === '..' || path === '.' ? '' : path)
}
- /**
- * Compatible send operation request function.
- *
- * @param operationArguments - Operation arguments
- * @param operationSpec - Operation Spec
- * @returns
- */
- async sendOperationRequest(operationArguments, operationSpec) {
- var _a;
- const userProvidedCallBack = (_a = operationArguments === null || operationArguments === void 0 ? void 0 : operationArguments.options) === null || _a === void 0 ? void 0 : _a.onResponse;
- let lastResponse;
- function onResponse(rawResponse, flatResponse, error) {
- lastResponse = rawResponse;
- if (userProvidedCallBack) {
- userProvidedCallBack(rawResponse, flatResponse, error);
- }
- }
- operationArguments.options = Object.assign(Object.assign({}, operationArguments.options), { onResponse });
- const result = await super.sendOperationRequest(operationArguments, operationSpec);
- if (lastResponse) {
- Object.defineProperty(result, "_response", {
- value: (0, response_js_1.toCompatResponse)(lastResponse),
- });
+ }
+ return (path === '..' || path === '.' ? '' : path)
+}
+
+
+/***/ }),
+
+/***/ 72747:
+/***/ (function(module) {
+
+"use strict";
+
+
+// Node has always utf-8
+const utf8Decoder = new TextDecoder('utf-8')
+const textDecoders = new Map([
+ ['utf-8', utf8Decoder],
+ ['utf8', utf8Decoder]
+])
+
+function getDecoder (charset) {
+ let lc
+ while (true) {
+ switch (charset) {
+ case 'utf-8':
+ case 'utf8':
+ return decoders.utf8
+ case 'latin1':
+ case 'ascii': // TODO: Make these a separate, strict decoder?
+ case 'us-ascii':
+ case 'iso-8859-1':
+ case 'iso8859-1':
+ case 'iso88591':
+ case 'iso_8859-1':
+ case 'windows-1252':
+ case 'iso_8859-1:1987':
+ case 'cp1252':
+ case 'x-cp1252':
+ return decoders.latin1
+ case 'utf16le':
+ case 'utf-16le':
+ case 'ucs2':
+ case 'ucs-2':
+ return decoders.utf16le
+ case 'base64':
+ return decoders.base64
+ default:
+ if (lc === undefined) {
+ lc = true
+ charset = charset.toLowerCase()
+ continue
}
- return result;
+ return decoders.other.bind(charset)
}
+ }
}
-exports.ExtendedServiceClient = ExtendedServiceClient;
-//# sourceMappingURL=extendedClient.js.map
-/***/ }),
+const decoders = {
+ utf8: (data, sourceEncoding) => {
+ if (data.length === 0) {
+ return ''
+ }
+ if (typeof data === 'string') {
+ data = Buffer.from(data, sourceEncoding)
+ }
+ return data.utf8Slice(0, data.length)
+ },
-/***/ 2078:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ latin1: (data, sourceEncoding) => {
+ if (data.length === 0) {
+ return ''
+ }
+ if (typeof data === 'string') {
+ return data
+ }
+ return data.latin1Slice(0, data.length)
+ },
+
+ utf16le: (data, sourceEncoding) => {
+ if (data.length === 0) {
+ return ''
+ }
+ if (typeof data === 'string') {
+ data = Buffer.from(data, sourceEncoding)
+ }
+ return data.ucs2Slice(0, data.length)
+ },
+
+ base64: (data, sourceEncoding) => {
+ if (data.length === 0) {
+ return ''
+ }
+ if (typeof data === 'string') {
+ data = Buffer.from(data, sourceEncoding)
+ }
+ return data.base64Slice(0, data.length)
+ },
+
+ other: (data, sourceEncoding) => {
+ if (data.length === 0) {
+ return ''
+ }
+ if (typeof data === 'string') {
+ data = Buffer.from(data, sourceEncoding)
+ }
+
+ if (textDecoders.has(this.toString())) {
+ try {
+ return textDecoders.get(this).decode(data)
+ } catch {}
+ }
+ return typeof data === 'string'
+ ? data
+ : data.toString()
+ }
+}
+
+function decodeText (text, sourceEncoding, destEncoding) {
+ if (text) {
+ return getDecoder(destEncoding)(text, sourceEncoding)
+ }
+ return text
+}
-"use strict";
+module.exports = decodeText
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.convertHttpClient = void 0;
-const response_js_1 = __nccwpck_require__(8153);
-const util_js_1 = __nccwpck_require__(3850);
-/**
- * Converts a RequestPolicy based HttpClient to a PipelineRequest based HttpClient.
- * @param requestPolicyClient - A HttpClient compatible with core-http
- * @returns A HttpClient compatible with core-rest-pipeline
- */
-function convertHttpClient(requestPolicyClient) {
- return {
- sendRequest: async (request) => {
- const response = await requestPolicyClient.sendRequest((0, util_js_1.toWebResourceLike)(request, { createProxy: true }));
- return (0, response_js_1.toPipelineResponse)(response);
- },
- };
-}
-exports.convertHttpClient = convertHttpClient;
-//# sourceMappingURL=httpClientAdapter.js.map
/***/ }),
-/***/ 1584:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 22393:
+/***/ ((module) => {
"use strict";
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.toHttpHeadersLike = exports.convertHttpClient = exports.disableKeepAlivePolicyName = exports.HttpPipelineLogLevel = exports.createRequestPolicyFactoryPolicy = exports.requestPolicyFactoryPolicyName = exports.ExtendedServiceClient = void 0;
-/**
- * A Shim Library that provides compatibility between Core V1 & V2 Packages.
- *
- * @packageDocumentation
- */
-var extendedClient_js_1 = __nccwpck_require__(5492);
-Object.defineProperty(exports, "ExtendedServiceClient", ({ enumerable: true, get: function () { return extendedClient_js_1.ExtendedServiceClient; } }));
-var requestPolicyFactoryPolicy_js_1 = __nccwpck_require__(3466);
-Object.defineProperty(exports, "requestPolicyFactoryPolicyName", ({ enumerable: true, get: function () { return requestPolicyFactoryPolicy_js_1.requestPolicyFactoryPolicyName; } }));
-Object.defineProperty(exports, "createRequestPolicyFactoryPolicy", ({ enumerable: true, get: function () { return requestPolicyFactoryPolicy_js_1.createRequestPolicyFactoryPolicy; } }));
-Object.defineProperty(exports, "HttpPipelineLogLevel", ({ enumerable: true, get: function () { return requestPolicyFactoryPolicy_js_1.HttpPipelineLogLevel; } }));
-var disableKeepAlivePolicy_js_1 = __nccwpck_require__(2639);
-Object.defineProperty(exports, "disableKeepAlivePolicyName", ({ enumerable: true, get: function () { return disableKeepAlivePolicy_js_1.disableKeepAlivePolicyName; } }));
-var httpClientAdapter_js_1 = __nccwpck_require__(2078);
-Object.defineProperty(exports, "convertHttpClient", ({ enumerable: true, get: function () { return httpClientAdapter_js_1.convertHttpClient; } }));
-var util_js_1 = __nccwpck_require__(3850);
-Object.defineProperty(exports, "toHttpHeadersLike", ({ enumerable: true, get: function () { return util_js_1.toHttpHeadersLike; } }));
-//# sourceMappingURL=index.js.map
-
-/***/ }),
-/***/ 2639:
-/***/ ((__unused_webpack_module, exports) => {
+module.exports = function getLimit (limits, name, defaultLimit) {
+ if (
+ !limits ||
+ limits[name] === undefined ||
+ limits[name] === null
+ ) { return defaultLimit }
-"use strict";
+ if (
+ typeof limits[name] !== 'number' ||
+ isNaN(limits[name])
+ ) { throw new TypeError('Limit ' + name + ' is not a valid number') }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.pipelineContainsDisableKeepAlivePolicy = exports.createDisableKeepAlivePolicy = exports.disableKeepAlivePolicyName = void 0;
-exports.disableKeepAlivePolicyName = "DisableKeepAlivePolicy";
-function createDisableKeepAlivePolicy() {
- return {
- name: exports.disableKeepAlivePolicyName,
- async sendRequest(request, next) {
- request.disableKeepAlive = true;
- return next(request);
- },
- };
-}
-exports.createDisableKeepAlivePolicy = createDisableKeepAlivePolicy;
-/**
- * @internal
- */
-function pipelineContainsDisableKeepAlivePolicy(pipeline) {
- return pipeline.getOrderedPolicies().some((policy) => policy.name === exports.disableKeepAlivePolicyName);
+ return limits[name]
}
-exports.pipelineContainsDisableKeepAlivePolicy = pipelineContainsDisableKeepAlivePolicy;
-//# sourceMappingURL=disableKeepAlivePolicy.js.map
+
/***/ }),
-/***/ 3466:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 8929:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
+/* eslint-disable object-property-newline */
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createRequestPolicyFactoryPolicy = exports.requestPolicyFactoryPolicyName = exports.HttpPipelineLogLevel = void 0;
-const util_js_1 = __nccwpck_require__(3850);
-const response_js_1 = __nccwpck_require__(8153);
-/**
- * An enum for compatibility with RequestPolicy
- */
-var HttpPipelineLogLevel;
-(function (HttpPipelineLogLevel) {
- HttpPipelineLogLevel[HttpPipelineLogLevel["ERROR"] = 1] = "ERROR";
- HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO";
- HttpPipelineLogLevel[HttpPipelineLogLevel["OFF"] = 0] = "OFF";
- HttpPipelineLogLevel[HttpPipelineLogLevel["WARNING"] = 2] = "WARNING";
-})(HttpPipelineLogLevel || (exports.HttpPipelineLogLevel = HttpPipelineLogLevel = {}));
-const mockRequestPolicyOptions = {
- log(_logLevel, _message) {
- /* do nothing */
- },
- shouldLog(_logLevel) {
- return false;
- },
-};
-/**
- * The name of the RequestPolicyFactoryPolicy
- */
-exports.requestPolicyFactoryPolicyName = "RequestPolicyFactoryPolicy";
-/**
- * A policy that wraps policies written for core-http.
- * @param factories - An array of `RequestPolicyFactory` objects from a core-http pipeline
- */
-function createRequestPolicyFactoryPolicy(factories) {
- const orderedFactories = factories.slice().reverse();
- return {
- name: exports.requestPolicyFactoryPolicyName,
- async sendRequest(request, next) {
- let httpPipeline = {
- async sendRequest(httpRequest) {
- const response = await next((0, util_js_1.toPipelineRequest)(httpRequest));
- return (0, response_js_1.toCompatResponse)(response, { createProxy: true });
- },
- };
- for (const factory of orderedFactories) {
- httpPipeline = factory.create(httpPipeline, mockRequestPolicyOptions);
- }
- const webResourceLike = (0, util_js_1.toWebResourceLike)(request, { createProxy: true });
- const response = await httpPipeline.sendRequest(webResourceLike);
- return (0, response_js_1.toPipelineResponse)(response);
- },
- };
-}
-exports.createRequestPolicyFactoryPolicy = createRequestPolicyFactoryPolicy;
-//# sourceMappingURL=requestPolicyFactoryPolicy.js.map
-
-/***/ }),
-/***/ 8153:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+const decodeText = __nccwpck_require__(72747)
-"use strict";
+const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.toPipelineResponse = exports.toCompatResponse = void 0;
-const core_rest_pipeline_1 = __nccwpck_require__(778);
-const util_js_1 = __nccwpck_require__(3850);
-const originalResponse = Symbol("Original FullOperationResponse");
-/**
- * A helper to convert response objects from the new pipeline back to the old one.
- * @param response - A response object from core-client.
- * @returns A response compatible with `HttpOperationResponse` from core-http.
- */
-function toCompatResponse(response, options) {
- let request = (0, util_js_1.toWebResourceLike)(response.request);
- let headers = (0, util_js_1.toHttpHeadersLike)(response.headers);
- if (options === null || options === void 0 ? void 0 : options.createProxy) {
- return new Proxy(response, {
- get(target, prop, receiver) {
- if (prop === "headers") {
- return headers;
- }
- else if (prop === "request") {
- return request;
- }
- else if (prop === originalResponse) {
- return response;
- }
- return Reflect.get(target, prop, receiver);
- },
- set(target, prop, value, receiver) {
- if (prop === "headers") {
- headers = value;
- }
- else if (prop === "request") {
- request = value;
- }
- return Reflect.set(target, prop, value, receiver);
- },
- });
- }
- else {
- return Object.assign(Object.assign({}, response), { request,
- headers });
- }
-}
-exports.toCompatResponse = toCompatResponse;
-/**
- * A helper to convert back to a PipelineResponse
- * @param compatResponse - A response compatible with `HttpOperationResponse` from core-http.
- */
-function toPipelineResponse(compatResponse) {
- const extendedCompatResponse = compatResponse;
- const response = extendedCompatResponse[originalResponse];
- const headers = (0, core_rest_pipeline_1.createHttpHeaders)(compatResponse.headers.toJson({ preserveCase: true }));
- if (response) {
- response.headers = headers;
- return response;
- }
- else {
- return Object.assign(Object.assign({}, compatResponse), { headers, request: (0, util_js_1.toPipelineRequest)(compatResponse.request) });
- }
+const EncodedLookup = {
+ '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04',
+ '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09',
+ '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c',
+ '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e',
+ '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12',
+ '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17',
+ '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b',
+ '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d',
+ '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20',
+ '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25',
+ '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a',
+ '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c',
+ '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f',
+ '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33',
+ '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38',
+ '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b',
+ '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e',
+ '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41',
+ '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46',
+ '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a',
+ '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d',
+ '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f',
+ '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54',
+ '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59',
+ '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c',
+ '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e',
+ '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62',
+ '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67',
+ '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b',
+ '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d',
+ '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70',
+ '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75',
+ '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a',
+ '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c',
+ '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f',
+ '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83',
+ '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88',
+ '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b',
+ '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e',
+ '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91',
+ '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96',
+ '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a',
+ '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d',
+ '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f',
+ '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2',
+ '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4',
+ '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7',
+ '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9',
+ '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab',
+ '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac',
+ '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad',
+ '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae',
+ '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0',
+ '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2',
+ '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5',
+ '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7',
+ '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba',
+ '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb',
+ '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc',
+ '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd',
+ '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf',
+ '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0',
+ '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3',
+ '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5',
+ '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8',
+ '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca',
+ '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb',
+ '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc',
+ '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce',
+ '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf',
+ '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1',
+ '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3',
+ '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6',
+ '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8',
+ '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda',
+ '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb',
+ '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd',
+ '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde',
+ '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf',
+ '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1',
+ '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4',
+ '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6',
+ '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9',
+ '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea',
+ '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec',
+ '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed',
+ '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee',
+ '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef',
+ '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2',
+ '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4',
+ '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7',
+ '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9',
+ '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb',
+ '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc',
+ '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd',
+ '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe',
+ '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff'
}
-exports.toPipelineResponse = toPipelineResponse;
-//# sourceMappingURL=response.js.map
-/***/ }),
+function encodedReplacer (match) {
+ return EncodedLookup[match]
+}
-/***/ 3850:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+const STATE_KEY = 0
+const STATE_VALUE = 1
+const STATE_CHARSET = 2
+const STATE_LANG = 3
-"use strict";
+function parseParams (str) {
+ const res = []
+ let state = STATE_KEY
+ let charset = ''
+ let inquote = false
+ let escaping = false
+ let p = 0
+ let tmp = ''
+ const len = str.length
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.HttpHeaders = exports.toHttpHeadersLike = exports.toWebResourceLike = exports.toPipelineRequest = void 0;
-const core_rest_pipeline_1 = __nccwpck_require__(778);
-// We use a custom symbol to cache a reference to the original request without
-// exposing it on the public interface.
-const originalRequestSymbol = Symbol("Original PipelineRequest");
-// Symbol.for() will return the same symbol if it's already been created
-// This particular one is used in core-client to handle the case of when a request is
-// cloned but we need to retrieve the OperationSpec and OperationArguments from the
-// original request.
-const originalClientRequestSymbol = Symbol.for("@azure/core-client original request");
-function toPipelineRequest(webResource, options = {}) {
- const compatWebResource = webResource;
- const request = compatWebResource[originalRequestSymbol];
- const headers = (0, core_rest_pipeline_1.createHttpHeaders)(webResource.headers.toJson({ preserveCase: true }));
- if (request) {
- request.headers = headers;
- return request;
- }
- else {
- const newRequest = (0, core_rest_pipeline_1.createPipelineRequest)({
- url: webResource.url,
- method: webResource.method,
- headers,
- withCredentials: webResource.withCredentials,
- timeout: webResource.timeout,
- requestId: webResource.requestId,
- abortSignal: webResource.abortSignal,
- body: webResource.body,
- formData: webResource.formData,
- disableKeepAlive: !!webResource.keepAlive,
- onDownloadProgress: webResource.onDownloadProgress,
- onUploadProgress: webResource.onUploadProgress,
- proxySettings: webResource.proxySettings,
- streamResponseStatusCodes: webResource.streamResponseStatusCodes,
- });
- if (options.originalRequest) {
- newRequest[originalClientRequestSymbol] =
- options.originalRequest;
+ for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
+ const char = str[i]
+ if (char === '\\' && inquote) {
+ if (escaping) { escaping = false } else {
+ escaping = true
+ continue
+ }
+ } else if (char === '"') {
+ if (!escaping) {
+ if (inquote) {
+ inquote = false
+ state = STATE_KEY
+ } else { inquote = true }
+ continue
+ } else { escaping = false }
+ } else {
+ if (escaping && inquote) { tmp += '\\' }
+ escaping = false
+ if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") {
+ if (state === STATE_CHARSET) {
+ state = STATE_LANG
+ charset = tmp.substring(1)
+ } else { state = STATE_VALUE }
+ tmp = ''
+ continue
+ } else if (state === STATE_KEY &&
+ (char === '*' || char === '=') &&
+ res.length) {
+ state = char === '*'
+ ? STATE_CHARSET
+ : STATE_VALUE
+ res[p] = [tmp, undefined]
+ tmp = ''
+ continue
+ } else if (!inquote && char === ';') {
+ state = STATE_KEY
+ if (charset) {
+ if (tmp.length) {
+ tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
+ 'binary',
+ charset)
+ }
+ charset = ''
+ } else if (tmp.length) {
+ tmp = decodeText(tmp, 'binary', 'utf8')
}
- return newRequest;
- }
-}
-exports.toPipelineRequest = toPipelineRequest;
-function toWebResourceLike(request, options) {
- var _a;
- const originalRequest = (_a = options === null || options === void 0 ? void 0 : options.originalRequest) !== null && _a !== void 0 ? _a : request;
- const webResource = {
- url: request.url,
- method: request.method,
- headers: toHttpHeadersLike(request.headers),
- withCredentials: request.withCredentials,
- timeout: request.timeout,
- requestId: request.headers.get("x-ms-client-request-id") || request.requestId,
- abortSignal: request.abortSignal,
- body: request.body,
- formData: request.formData,
- keepAlive: !!request.disableKeepAlive,
- onDownloadProgress: request.onDownloadProgress,
- onUploadProgress: request.onUploadProgress,
- proxySettings: request.proxySettings,
- streamResponseStatusCodes: request.streamResponseStatusCodes,
- clone() {
- throw new Error("Cannot clone a non-proxied WebResourceLike");
- },
- prepare() {
- throw new Error("WebResourceLike.prepare() is not supported by @azure/core-http-compat");
- },
- validateRequestProperties() {
- /** do nothing */
- },
- };
- if (options === null || options === void 0 ? void 0 : options.createProxy) {
- return new Proxy(webResource, {
- get(target, prop, receiver) {
- if (prop === originalRequestSymbol) {
- return request;
- }
- else if (prop === "clone") {
- return () => {
- return toWebResourceLike(toPipelineRequest(webResource, { originalRequest }), {
- createProxy: true,
- originalRequest,
- });
- };
- }
- return Reflect.get(target, prop, receiver);
- },
- set(target, prop, value, receiver) {
- if (prop === "keepAlive") {
- request.disableKeepAlive = !value;
- }
- const passThroughProps = [
- "url",
- "method",
- "withCredentials",
- "timeout",
- "requestId",
- "abortSignal",
- "body",
- "formData",
- "onDownloadProgress",
- "onUploadProgress",
- "proxySettings",
- "streamResponseStatusCodes",
- ];
- if (typeof prop === "string" && passThroughProps.includes(prop)) {
- request[prop] = value;
- }
- return Reflect.set(target, prop, value, receiver);
- },
- });
- }
- else {
- return webResource;
+ if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp }
+ tmp = ''
+ ++p
+ continue
+ } else if (!inquote && (char === ' ' || char === '\t')) { continue }
}
+ tmp += char
+ }
+ if (charset && tmp.length) {
+ tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
+ 'binary',
+ charset)
+ } else if (tmp) {
+ tmp = decodeText(tmp, 'binary', 'utf8')
+ }
+
+ if (res[p] === undefined) {
+ if (tmp) { res[p] = tmp }
+ } else { res[p][1] = tmp }
+
+ return res
}
-exports.toWebResourceLike = toWebResourceLike;
-/**
- * Converts HttpHeaders from core-rest-pipeline to look like
- * HttpHeaders from core-http.
- * @param headers - HttpHeaders from core-rest-pipeline
- * @returns HttpHeaders as they looked in core-http
- */
-function toHttpHeadersLike(headers) {
- return new HttpHeaders(headers.toJSON({ preserveCase: true }));
-}
-exports.toHttpHeadersLike = toHttpHeadersLike;
+
+module.exports = parseParams
+
+
+/***/ }),
+
+/***/ 76637:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// Copyright 2019 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AclRoleAccessorMethods = exports.Acl = void 0;
+const promisify_1 = __nccwpck_require__(60206);
/**
- * A collection of HttpHeaders that can be sent with a HTTP request.
+ * Attach functionality to a {@link Storage.acl} instance. This will add an
+ * object for each role group (owners, readers, and writers), with each object
+ * containing methods to add or delete a type of entity.
+ *
+ * As an example, here are a few methods that are created.
+ *
+ * myBucket.acl.readers.deleteGroup('groupId', function(err) {});
+ *
+ * myBucket.acl.owners.addUser('email@example.com', function(err, acl) {});
+ *
+ * myBucket.acl.writers.addDomain('example.com', function(err, acl) {});
+ *
+ * @private
*/
-function getHeaderKey(headerName) {
- return headerName.toLowerCase();
-}
+class AclRoleAccessorMethods {
+ constructor() {
+ this.owners = {};
+ this.readers = {};
+ this.writers = {};
+ /**
+ * An object of convenience methods to add or delete owner ACL permissions
+ * for a given entity.
+ *
+ * The supported methods include:
+ *
+ * - `myFile.acl.owners.addAllAuthenticatedUsers`
+ * - `myFile.acl.owners.deleteAllAuthenticatedUsers`
+ * - `myFile.acl.owners.addAllUsers`
+ * - `myFile.acl.owners.deleteAllUsers`
+ * - `myFile.acl.owners.addDomain`
+ * - `myFile.acl.owners.deleteDomain`
+ * - `myFile.acl.owners.addGroup`
+ * - `myFile.acl.owners.deleteGroup`
+ * - `myFile.acl.owners.addProject`
+ * - `myFile.acl.owners.deleteProject`
+ * - `myFile.acl.owners.addUser`
+ * - `myFile.acl.owners.deleteUser`
+ *
+ * @name Acl#owners
+ *
+ * @example
+ * ```
+ * const storage = require('@google-cloud/storage')();
+ * const myBucket = storage.bucket('my-bucket');
+ * const myFile = myBucket.file('my-file');
+ *
+ * //-
+ * // Add a user as an owner of a file.
+ * //-
+ * const myBucket = gcs.bucket('my-bucket');
+ * const myFile = myBucket.file('my-file');
+ * myFile.acl.owners.addUser('email@example.com', function(err, aclObject)
+ * {});
+ *
+ * //-
+ * // For reference, the above command is the same as running the following.
+ * //-
+ * myFile.acl.add({
+ * entity: 'user-email@example.com',
+ * role: gcs.acl.OWNER_ROLE
+ * }, function(err, aclObject) {});
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * myFile.acl.owners.addUser('email@example.com').then(function(data) {
+ * const aclObject = data[0];
+ * const apiResponse = data[1];
+ * });
+ * ```
+ */
+ this.owners = {};
+ /**
+ * An object of convenience methods to add or delete reader ACL permissions
+ * for a given entity.
+ *
+ * The supported methods include:
+ *
+ * - `myFile.acl.readers.addAllAuthenticatedUsers`
+ * - `myFile.acl.readers.deleteAllAuthenticatedUsers`
+ * - `myFile.acl.readers.addAllUsers`
+ * - `myFile.acl.readers.deleteAllUsers`
+ * - `myFile.acl.readers.addDomain`
+ * - `myFile.acl.readers.deleteDomain`
+ * - `myFile.acl.readers.addGroup`
+ * - `myFile.acl.readers.deleteGroup`
+ * - `myFile.acl.readers.addProject`
+ * - `myFile.acl.readers.deleteProject`
+ * - `myFile.acl.readers.addUser`
+ * - `myFile.acl.readers.deleteUser`
+ *
+ * @name Acl#readers
+ *
+ * @example
+ * ```
+ * const storage = require('@google-cloud/storage')();
+ * const myBucket = storage.bucket('my-bucket');
+ * const myFile = myBucket.file('my-file');
+ *
+ * //-
+ * // Add a user as a reader of a file.
+ * //-
+ * myFile.acl.readers.addUser('email@example.com', function(err, aclObject)
+ * {});
+ *
+ * //-
+ * // For reference, the above command is the same as running the following.
+ * //-
+ * myFile.acl.add({
+ * entity: 'user-email@example.com',
+ * role: gcs.acl.READER_ROLE
+ * }, function(err, aclObject) {});
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * myFile.acl.readers.addUser('email@example.com').then(function(data) {
+ * const aclObject = data[0];
+ * const apiResponse = data[1];
+ * });
+ * ```
+ */
+ this.readers = {};
+ /**
+ * An object of convenience methods to add or delete writer ACL permissions
+ * for a given entity.
+ *
+ * The supported methods include:
+ *
+ * - `myFile.acl.writers.addAllAuthenticatedUsers`
+ * - `myFile.acl.writers.deleteAllAuthenticatedUsers`
+ * - `myFile.acl.writers.addAllUsers`
+ * - `myFile.acl.writers.deleteAllUsers`
+ * - `myFile.acl.writers.addDomain`
+ * - `myFile.acl.writers.deleteDomain`
+ * - `myFile.acl.writers.addGroup`
+ * - `myFile.acl.writers.deleteGroup`
+ * - `myFile.acl.writers.addProject`
+ * - `myFile.acl.writers.deleteProject`
+ * - `myFile.acl.writers.addUser`
+ * - `myFile.acl.writers.deleteUser`
+ *
+ * @name Acl#writers
+ *
+ * @example
+ * ```
+ * const storage = require('@google-cloud/storage')();
+ * const myBucket = storage.bucket('my-bucket');
+ * const myFile = myBucket.file('my-file');
+ *
+ * //-
+ * // Add a user as a writer of a file.
+ * //-
+ * myFile.acl.writers.addUser('email@example.com', function(err, aclObject)
+ * {});
+ *
+ * //-
+ * // For reference, the above command is the same as running the following.
+ * //-
+ * myFile.acl.add({
+ * entity: 'user-email@example.com',
+ * role: gcs.acl.WRITER_ROLE
+ * }, function(err, aclObject) {});
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * myFile.acl.writers.addUser('email@example.com').then(function(data) {
+ * const aclObject = data[0];
+ * const apiResponse = data[1];
+ * });
+ * ```
+ */
+ this.writers = {};
+ AclRoleAccessorMethods.roles.forEach(this._assignAccessMethods.bind(this));
+ }
+ _assignAccessMethods(role) {
+ const accessMethods = AclRoleAccessorMethods.accessMethods;
+ const entities = AclRoleAccessorMethods.entities;
+ const roleGroup = role.toLowerCase() + 's';
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ this[roleGroup] = entities.reduce((acc, entity) => {
+ const isPrefix = entity.charAt(entity.length - 1) === '-';
+ accessMethods.forEach(accessMethod => {
+ let method = accessMethod + entity[0].toUpperCase() + entity.substring(1);
+ if (isPrefix) {
+ method = method.replace('-', '');
+ }
+ // Wrap the parent accessor method (e.g. `add` or `delete`) to avoid the
+ // more complex API of specifying an `entity` and `role`.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ acc[method] = (entityId, options, callback) => {
+ let apiEntity;
+ if (typeof options === 'function') {
+ callback = options;
+ options = {};
+ }
+ if (isPrefix) {
+ apiEntity = entity + entityId;
+ }
+ else {
+ // If the entity is not a prefix, it is a special entity group
+ // that does not require further details. The accessor methods
+ // only accept a callback.
+ apiEntity = entity;
+ callback = entityId;
+ }
+ options = Object.assign({
+ entity: apiEntity,
+ role,
+ }, options);
+ const args = [options];
+ if (typeof callback === 'function') {
+ args.push(callback);
+ }
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ return this[accessMethod].apply(this, args);
+ };
+ });
+ return acc;
+ }, {});
+ }
+}
+exports.AclRoleAccessorMethods = AclRoleAccessorMethods;
+AclRoleAccessorMethods.accessMethods = ['add', 'delete'];
+AclRoleAccessorMethods.entities = [
+ // Special entity groups that do not require further specification.
+ 'allAuthenticatedUsers',
+ 'allUsers',
+ // Entity groups that require specification, e.g. `user-email@example.com`.
+ 'domain-',
+ 'group-',
+ 'project-',
+ 'user-',
+];
+AclRoleAccessorMethods.roles = ['OWNER', 'READER', 'WRITER'];
/**
- * A collection of HTTP header key/value pairs.
+ * Cloud Storage uses access control lists (ACLs) to manage object and
+ * bucket access. ACLs are the mechanism you use to share objects with other
+ * users and allow other users to access your buckets and objects.
+ *
+ * An ACL consists of one or more entries, where each entry grants permissions
+ * to an entity. Permissions define the actions that can be performed against an
+ * object or bucket (for example, `READ` or `WRITE`); the entity defines who the
+ * permission applies to (for example, a specific user or group of users).
+ *
+ * Where an `entity` value is accepted, we follow the format the Cloud Storage
+ * API expects.
+ *
+ * Refer to
+ * https://cloud.google.com/storage/docs/json_api/v1/defaultObjectAccessControls
+ * for the most up-to-date values.
+ *
+ * - `user-userId`
+ * - `user-email`
+ * - `group-groupId`
+ * - `group-email`
+ * - `domain-domain`
+ * - `project-team-projectId`
+ * - `allUsers`
+ * - `allAuthenticatedUsers`
+ *
+ * Examples:
+ *
+ * - The user "liz@example.com" would be `user-liz@example.com`.
+ * - The group "example@googlegroups.com" would be
+ * `group-example@googlegroups.com`.
+ * - To refer to all members of the Google Apps for Business domain
+ * "example.com", the entity would be `domain-example.com`.
+ *
+ * For more detailed information, see
+ * {@link http://goo.gl/6qBBPO| About Access Control Lists}.
+ *
+ * @constructor Acl
+ * @mixin
+ * @param {object} options Configuration options.
*/
-class HttpHeaders {
- constructor(rawHeaders) {
- this._headersMap = {};
- if (rawHeaders) {
- for (const headerName in rawHeaders) {
- this.set(headerName, rawHeaders[headerName]);
- }
- }
+class Acl extends AclRoleAccessorMethods {
+ constructor(options) {
+ super();
+ this.pathPrefix = options.pathPrefix;
+ this.request_ = options.request;
}
/**
- * Set a header in this collection with the provided name and value. The name is
- * case-insensitive.
- * @param headerName - The name of the header to set. This value is case-insensitive.
- * @param headerValue - The value of the header to set.
+ * @typedef {array} AddAclResponse
+ * @property {object} 0 The Acl Objects.
+ * @property {object} 1 The full API response.
*/
- set(headerName, headerValue) {
- this._headersMap[getHeaderKey(headerName)] = {
- name: headerName,
- value: headerValue.toString(),
- };
- }
/**
- * Get the header value for the provided header name, or undefined if no header exists in this
- * collection with the provided name.
- * @param headerName - The name of the header.
+ * @callback AddAclCallback
+ * @param {?Error} err Request error, if any.
+ * @param {object} acl The Acl Objects.
+ * @param {object} apiResponse The full API response.
*/
- get(headerName) {
- const header = this._headersMap[getHeaderKey(headerName)];
- return !header ? undefined : header.value;
- }
/**
- * Get whether or not this header collection contains a header entry for the provided header name.
- */
- contains(headerName) {
- return !!this._headersMap[getHeaderKey(headerName)];
+ * Add access controls on a {@link Bucket} or {@link File}.
+ *
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/insert| BucketAccessControls: insert API Documentation}
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/insert| ObjectAccessControls: insert API Documentation}
+ *
+ * @param {object} options Configuration options.
+ * @param {string} options.entity Whose permissions will be added.
+ * @param {string} options.role Permissions allowed for the defined entity.
+ * See {@link https://cloud.google.com/storage/docs/access-control Access
+ * Control}.
+ * @param {number} [options.generation] **File Objects Only** Select a specific
+ * revision of this file (as opposed to the latest version, the default).
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {AddAclCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const storage = require('@google-cloud/storage')();
+ * const myBucket = storage.bucket('my-bucket');
+ * const myFile = myBucket.file('my-file');
+ *
+ * const options = {
+ * entity: 'user-useremail@example.com',
+ * role: gcs.acl.OWNER_ROLE
+ * };
+ *
+ * myBucket.acl.add(options, function(err, aclObject, apiResponse) {});
+ *
+ * //-
+ * // For file ACL operations, you can also specify a `generation` property.
+ * // Here is how you would grant ownership permissions to a user on a
+ * specific
+ * // revision of a file.
+ * //-
+ * myFile.acl.add({
+ * entity: 'user-useremail@example.com',
+ * role: gcs.acl.OWNER_ROLE,
+ * generation: 1
+ * }, function(err, aclObject, apiResponse) {});
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * myBucket.acl.add(options).then(function(data) {
+ * const aclObject = data[0];
+ * const apiResponse = data[1];
+ * });
+ *
+ * ```
+ * @example include:samples/acl.js
+ * region_tag:storage_add_file_owner
+ * Example of adding an owner to a file:
+ *
+ * @example include:samples/acl.js
+ * region_tag:storage_add_bucket_owner
+ * Example of adding an owner to a bucket:
+ *
+ * @example include:samples/acl.js
+ * region_tag:storage_add_bucket_default_owner
+ * Example of adding a default owner to a bucket:
+ */
+ add(options, callback) {
+ const query = {};
+ if (options.generation) {
+ query.generation = options.generation;
+ }
+ if (options.userProject) {
+ query.userProject = options.userProject;
+ }
+ this.request({
+ method: 'POST',
+ uri: '',
+ qs: query,
+ maxRetries: 0, //explicitly set this value since this is a non-idempotent function
+ json: {
+ entity: options.entity,
+ role: options.role.toUpperCase(),
+ },
+ }, (err, resp) => {
+ if (err) {
+ callback(err, null, resp);
+ return;
+ }
+ callback(null, this.makeAclObject_(resp), resp);
+ });
}
/**
- * Remove the header with the provided headerName. Return whether or not the header existed and
- * was removed.
- * @param headerName - The name of the header to remove.
+ * @typedef {array} RemoveAclResponse
+ * @property {object} 0 The full API response.
*/
- remove(headerName) {
- const result = this.contains(headerName);
- delete this._headersMap[getHeaderKey(headerName)];
- return result;
- }
/**
- * Get the headers that are contained this collection as an object.
+ * @callback RemoveAclCallback
+ * @param {?Error} err Request error, if any.
+ * @param {object} apiResponse The full API response.
*/
- rawHeaders() {
- return this.toJson({ preserveCase: true });
- }
/**
- * Get the headers that are contained in this collection as an array.
- */
- headersArray() {
- const headers = [];
- for (const headerKey in this._headersMap) {
- headers.push(this._headersMap[headerKey]);
- }
- return headers;
+ * Delete access controls on a {@link Bucket} or {@link File}.
+ *
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/delete| BucketAccessControls: delete API Documentation}
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/delete| ObjectAccessControls: delete API Documentation}
+ *
+ * @param {object} options Configuration object.
+ * @param {string} options.entity Whose permissions will be revoked.
+ * @param {int} [options.generation] **File Objects Only** Select a specific
+ * revision of this file (as opposed to the latest version, the default).
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {RemoveAclCallback} callback The callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const storage = require('@google-cloud/storage')();
+ * const myBucket = storage.bucket('my-bucket');
+ * const myFile = myBucket.file('my-file');
+ *
+ * myBucket.acl.delete({
+ * entity: 'user-useremail@example.com'
+ * }, function(err, apiResponse) {});
+ *
+ * //-
+ * // For file ACL operations, you can also specify a `generation` property.
+ * //-
+ * myFile.acl.delete({
+ * entity: 'user-useremail@example.com',
+ * generation: 1
+ * }, function(err, apiResponse) {});
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * myFile.acl.delete().then(function(data) {
+ * const apiResponse = data[0];
+ * });
+ *
+ * ```
+ * @example include:samples/acl.js
+ * region_tag:storage_remove_bucket_owner
+ * Example of removing an owner from a bucket:
+ *
+ * @example include:samples/acl.js
+ * region_tag:storage_remove_bucket_default_owner
+ * Example of removing a default owner from a bucket:
+ *
+ * @example include:samples/acl.js
+ * region_tag:storage_remove_file_owner
+ * Example of removing an owner from a bucket:
+ */
+ delete(options, callback) {
+ const query = {};
+ if (options.generation) {
+ query.generation = options.generation;
+ }
+ if (options.userProject) {
+ query.userProject = options.userProject;
+ }
+ this.request({
+ method: 'DELETE',
+ uri: '/' + encodeURIComponent(options.entity),
+ qs: query,
+ }, (err, resp) => {
+ callback(err, resp);
+ });
}
/**
- * Get the header names that are contained in this collection.
+ * @typedef {array} GetAclResponse
+ * @property {object|object[]} 0 Single or array of Acl Objects.
+ * @property {object} 1 The full API response.
*/
- headerNames() {
- const headerNames = [];
- const headers = this.headersArray();
- for (let i = 0; i < headers.length; ++i) {
- headerNames.push(headers[i].name);
- }
- return headerNames;
- }
/**
- * Get the header values that are contained in this collection.
+ * @callback GetAclCallback
+ * @param {?Error} err Request error, if any.
+ * @param {object|object[]} acl Single or array of Acl Objects.
+ * @param {object} apiResponse The full API response.
*/
- headerValues() {
- const headerValues = [];
- const headers = this.headersArray();
- for (let i = 0; i < headers.length; ++i) {
- headerValues.push(headers[i].value);
- }
- return headerValues;
- }
/**
- * Get the JSON object representation of this HTTP header collection.
- */
- toJson(options = {}) {
- const result = {};
- if (options.preserveCase) {
- for (const headerKey in this._headersMap) {
- const header = this._headersMap[headerKey];
- result[header.name] = header.value;
+ * Get access controls on a {@link Bucket} or {@link File}. If
+ * an entity is omitted, you will receive an array of all applicable access
+ * controls.
+ *
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/get| BucketAccessControls: get API Documentation}
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/get| ObjectAccessControls: get API Documentation}
+ *
+ * @param {object|function} [options] Configuration options. If you want to
+ * receive a list of all access controls, pass the callback function as
+ * the only argument.
+ * @param {string} options.entity Whose permissions will be fetched.
+ * @param {number} [options.generation] **File Objects Only** Select a specific
+ * revision of this file (as opposed to the latest version, the default).
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {GetAclCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const storage = require('@google-cloud/storage')();
+ * const myBucket = storage.bucket('my-bucket');
+ * const myFile = myBucket.file('my-file');
+ *
+ * myBucket.acl.get({
+ * entity: 'user-useremail@example.com'
+ * }, function(err, aclObject, apiResponse) {});
+ *
+ * //-
+ * // Get all access controls.
+ * //-
+ * myBucket.acl.get(function(err, aclObjects, apiResponse) {
+ * // aclObjects = [
+ * // {
+ * // entity: 'user-useremail@example.com',
+ * // role: 'owner'
+ * // }
+ * // ]
+ * });
+ *
+ * //-
+ * // For file ACL operations, you can also specify a `generation` property.
+ * //-
+ * myFile.acl.get({
+ * entity: 'user-useremail@example.com',
+ * generation: 1
+ * }, function(err, aclObject, apiResponse) {});
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * myBucket.acl.get().then(function(data) {
+ * const aclObject = data[0];
+ * const apiResponse = data[1];
+ * });
+ *
+ * ```
+ * @example include:samples/acl.js
+ * region_tag:storage_print_file_acl
+ * Example of printing a file's ACL:
+ *
+ * @example include:samples/acl.js
+ * region_tag:storage_print_file_acl_for_user
+ * Example of printing a file's ACL for a specific user:
+ *
+ * @example include:samples/acl.js
+ * region_tag:storage_print_bucket_acl
+ * Example of printing a bucket's ACL:
+ *
+ * @example include:samples/acl.js
+ * region_tag:storage_print_bucket_acl_for_user
+ * Example of printing a bucket's ACL for a specific user:
+ */
+ get(optionsOrCallback, cb) {
+ const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : null;
+ const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
+ let path = '';
+ const query = {};
+ if (options) {
+ path = '/' + encodeURIComponent(options.entity);
+ if (options.generation) {
+ query.generation = options.generation;
}
- }
- else {
- for (const headerKey in this._headersMap) {
- const header = this._headersMap[headerKey];
- result[getHeaderKey(header.name)] = header.value;
+ if (options.userProject) {
+ query.userProject = options.userProject;
}
}
- return result;
+ this.request({
+ uri: path,
+ qs: query,
+ }, (err, resp) => {
+ if (err) {
+ callback(err, null, resp);
+ return;
+ }
+ let results;
+ if (resp.items) {
+ results = resp.items.map(this.makeAclObject_);
+ }
+ else {
+ results = this.makeAclObject_(resp);
+ }
+ callback(null, results, resp);
+ });
}
/**
- * Get the string representation of this HTTP header collection.
+ * @typedef {array} UpdateAclResponse
+ * @property {object} 0 The updated Acl Objects.
+ * @property {object} 1 The full API response.
*/
- toString() {
- return JSON.stringify(this.toJson({ preserveCase: true }));
- }
/**
- * Create a deep clone/copy of this HttpHeaders collection.
+ * @callback UpdateAclCallback
+ * @param {?Error} err Request error, if any.
+ * @param {object} acl The updated Acl Objects.
+ * @param {object} apiResponse The full API response.
*/
- clone() {
- const resultPreservingCasing = {};
- for (const headerKey in this._headersMap) {
- const header = this._headersMap[headerKey];
- resultPreservingCasing[header.name] = header.value;
- }
- return new HttpHeaders(resultPreservingCasing);
- }
-}
-exports.HttpHeaders = HttpHeaders;
-//# sourceMappingURL=util.js.map
-
-/***/ }),
-
-/***/ 3878:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.pollHttpOperation = exports.isOperationError = exports.getResourceLocation = exports.getOperationStatus = exports.getOperationLocation = exports.initHttpOperation = exports.getStatusFromInitialResponse = exports.getErrorFromResponse = exports.parseRetryAfter = exports.inferLroMode = void 0;
-const operation_js_1 = __nccwpck_require__(736);
-const logger_js_1 = __nccwpck_require__(480);
-function getOperationLocationPollingUrl(inputs) {
- const { azureAsyncOperation, operationLocation } = inputs;
- return operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation;
-}
-function getLocationHeader(rawResponse) {
- return rawResponse.headers["location"];
-}
-function getOperationLocationHeader(rawResponse) {
- return rawResponse.headers["operation-location"];
-}
-function getAzureAsyncOperationHeader(rawResponse) {
- return rawResponse.headers["azure-asyncoperation"];
-}
-function findResourceLocation(inputs) {
- var _a;
- const { location, requestMethod, requestPath, resourceLocationConfig } = inputs;
- switch (requestMethod) {
- case "PUT": {
- return requestPath;
- }
- case "DELETE": {
- return undefined;
- }
- case "PATCH": {
- return (_a = getDefault()) !== null && _a !== void 0 ? _a : requestPath;
+ /**
+ * Update access controls on a {@link Bucket} or {@link File}.
+ *
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/update| BucketAccessControls: update API Documentation}
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/update| ObjectAccessControls: update API Documentation}
+ *
+ * @param {object} options Configuration options.
+ * @param {string} options.entity Whose permissions will be updated.
+ * @param {string} options.role Permissions allowed for the defined entity.
+ * See {@link Storage.acl}.
+ * @param {number} [options.generation] **File Objects Only** Select a specific
+ * revision of this file (as opposed to the latest version, the default).
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {UpdateAclCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const storage = require('@google-cloud/storage')();
+ * const myBucket = storage.bucket('my-bucket');
+ * const myFile = myBucket.file('my-file');
+ *
+ * const options = {
+ * entity: 'user-useremail@example.com',
+ * role: gcs.acl.WRITER_ROLE
+ * };
+ *
+ * myBucket.acl.update(options, function(err, aclObject, apiResponse) {});
+ *
+ * //-
+ * // For file ACL operations, you can also specify a `generation` property.
+ * //-
+ * myFile.acl.update({
+ * entity: 'user-useremail@example.com',
+ * role: gcs.acl.WRITER_ROLE,
+ * generation: 1
+ * }, function(err, aclObject, apiResponse) {});
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * myFile.acl.update(options).then(function(data) {
+ * const aclObject = data[0];
+ * const apiResponse = data[1];
+ * });
+ * ```
+ */
+ update(options, callback) {
+ const query = {};
+ if (options.generation) {
+ query.generation = options.generation;
}
- default: {
- return getDefault();
+ if (options.userProject) {
+ query.userProject = options.userProject;
}
- }
- function getDefault() {
- switch (resourceLocationConfig) {
- case "azure-async-operation": {
- return undefined;
- }
- case "original-uri": {
- return requestPath;
- }
- case "location":
- default: {
- return location;
+ this.request({
+ method: 'PUT',
+ uri: '/' + encodeURIComponent(options.entity),
+ qs: query,
+ json: {
+ role: options.role.toUpperCase(),
+ },
+ }, (err, resp) => {
+ if (err) {
+ callback(err, null, resp);
+ return;
}
- }
- }
-}
-function inferLroMode(inputs) {
- const { rawResponse, requestMethod, requestPath, resourceLocationConfig } = inputs;
- const operationLocation = getOperationLocationHeader(rawResponse);
- const azureAsyncOperation = getAzureAsyncOperationHeader(rawResponse);
- const pollingUrl = getOperationLocationPollingUrl({ operationLocation, azureAsyncOperation });
- const location = getLocationHeader(rawResponse);
- const normalizedRequestMethod = requestMethod === null || requestMethod === void 0 ? void 0 : requestMethod.toLocaleUpperCase();
- if (pollingUrl !== undefined) {
- return {
- mode: "OperationLocation",
- operationLocation: pollingUrl,
- resourceLocation: findResourceLocation({
- requestMethod: normalizedRequestMethod,
- location,
- requestPath,
- resourceLocationConfig,
- }),
- };
- }
- else if (location !== undefined) {
- return {
- mode: "ResourceLocation",
- operationLocation: location,
- };
- }
- else if (normalizedRequestMethod === "PUT" && requestPath) {
- return {
- mode: "Body",
- operationLocation: requestPath,
- };
- }
- else {
- return undefined;
- }
-}
-exports.inferLroMode = inferLroMode;
-function transformStatus(inputs) {
- const { status, statusCode } = inputs;
- if (typeof status !== "string" && status !== undefined) {
- throw new Error(`Polling was unsuccessful. Expected status to have a string value or no value but it has instead: ${status}. This doesn't necessarily indicate the operation has failed. Check your Azure subscription or resource status for more information.`);
- }
- switch (status === null || status === void 0 ? void 0 : status.toLocaleLowerCase()) {
- case undefined:
- return toOperationStatus(statusCode);
- case "succeeded":
- return "succeeded";
- case "failed":
- return "failed";
- case "running":
- case "accepted":
- case "started":
- case "canceling":
- case "cancelling":
- return "running";
- case "canceled":
- case "cancelled":
- return "canceled";
- default: {
- logger_js_1.logger.verbose(`LRO: unrecognized operation status: ${status}`);
- return status;
- }
- }
-}
-function getStatus(rawResponse) {
- var _a;
- const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
- return transformStatus({ status, statusCode: rawResponse.statusCode });
-}
-function getProvisioningState(rawResponse) {
- var _a, _b;
- const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
- const status = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState;
- return transformStatus({ status, statusCode: rawResponse.statusCode });
-}
-function toOperationStatus(statusCode) {
- if (statusCode === 202) {
- return "running";
- }
- else if (statusCode < 300) {
- return "succeeded";
- }
- else {
- return "failed";
- }
-}
-function parseRetryAfter({ rawResponse }) {
- const retryAfter = rawResponse.headers["retry-after"];
- if (retryAfter !== undefined) {
- // Retry-After header value is either in HTTP date format, or in seconds
- const retryAfterInSeconds = parseInt(retryAfter);
- return isNaN(retryAfterInSeconds)
- ? calculatePollingIntervalFromDate(new Date(retryAfter))
- : retryAfterInSeconds * 1000;
- }
- return undefined;
-}
-exports.parseRetryAfter = parseRetryAfter;
-function getErrorFromResponse(response) {
- const error = accessBodyProperty(response, "error");
- if (!error) {
- logger_js_1.logger.warning(`The long-running operation failed but there is no error property in the response's body`);
- return;
- }
- if (!error.code || !error.message) {
- logger_js_1.logger.warning(`The long-running operation failed but the error property in the response's body doesn't contain code or message`);
- return;
- }
- return error;
-}
-exports.getErrorFromResponse = getErrorFromResponse;
-function calculatePollingIntervalFromDate(retryAfterDate) {
- const timeNow = Math.floor(new Date().getTime());
- const retryAfterTime = retryAfterDate.getTime();
- if (timeNow < retryAfterTime) {
- return retryAfterTime - timeNow;
- }
- return undefined;
-}
-function getStatusFromInitialResponse(inputs) {
- const { response, state, operationLocation } = inputs;
- function helper() {
- var _a;
- const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
- switch (mode) {
- case undefined:
- return toOperationStatus(response.rawResponse.statusCode);
- case "Body":
- return getOperationStatus(response, state);
- default:
- return "running";
- }
- }
- const status = helper();
- return status === "running" && operationLocation === undefined ? "succeeded" : status;
-}
-exports.getStatusFromInitialResponse = getStatusFromInitialResponse;
-/**
- * Initiates the long-running operation.
- */
-async function initHttpOperation(inputs) {
- const { stateProxy, resourceLocationConfig, processResult, lro, setErrorAsResult } = inputs;
- return (0, operation_js_1.initOperation)({
- init: async () => {
- const response = await lro.sendInitialRequest();
- const config = inferLroMode({
- rawResponse: response.rawResponse,
- requestPath: lro.requestPath,
- requestMethod: lro.requestMethod,
- resourceLocationConfig,
- });
- return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}));
- },
- stateProxy,
- processResult: processResult
- ? ({ flatResponse }, state) => processResult(flatResponse, state)
- : ({ flatResponse }) => flatResponse,
- getOperationStatus: getStatusFromInitialResponse,
- setErrorAsResult,
- });
-}
-exports.initHttpOperation = initHttpOperation;
-function getOperationLocation({ rawResponse }, state) {
- var _a;
- const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
- switch (mode) {
- case "OperationLocation": {
- return getOperationLocationPollingUrl({
- operationLocation: getOperationLocationHeader(rawResponse),
- azureAsyncOperation: getAzureAsyncOperationHeader(rawResponse),
- });
- }
- case "ResourceLocation": {
- return getLocationHeader(rawResponse);
- }
- case "Body":
- default: {
- return undefined;
- }
- }
-}
-exports.getOperationLocation = getOperationLocation;
-function getOperationStatus({ rawResponse }, state) {
- var _a;
- const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
- switch (mode) {
- case "OperationLocation": {
- return getStatus(rawResponse);
- }
- case "ResourceLocation": {
- return toOperationStatus(rawResponse.statusCode);
- }
- case "Body": {
- return getProvisioningState(rawResponse);
- }
- default:
- throw new Error(`Internal error: Unexpected operation mode: ${mode}`);
- }
-}
-exports.getOperationStatus = getOperationStatus;
-function accessBodyProperty({ flatResponse, rawResponse }, prop) {
- var _a, _b;
- return (_a = flatResponse === null || flatResponse === void 0 ? void 0 : flatResponse[prop]) !== null && _a !== void 0 ? _a : (_b = rawResponse.body) === null || _b === void 0 ? void 0 : _b[prop];
-}
-function getResourceLocation(res, state) {
- const loc = accessBodyProperty(res, "resourceLocation");
- if (loc && typeof loc === "string") {
- state.config.resourceLocation = loc;
+ callback(null, this.makeAclObject_(resp), resp);
+ });
+ }
+ /**
+ * Transform API responses to a consistent object format.
+ *
+ * @private
+ */
+ makeAclObject_(accessControlObject) {
+ const obj = {
+ entity: accessControlObject.entity,
+ role: accessControlObject.role,
+ };
+ if (accessControlObject.projectTeam) {
+ obj.projectTeam = accessControlObject.projectTeam;
+ }
+ return obj;
+ }
+ /**
+ * Patch requests up to the bucket's request object.
+ *
+ * @private
+ *
+ * @param {string} method Action.
+ * @param {string} path Request path.
+ * @param {*} query Request query object.
+ * @param {*} body Request body contents.
+ * @param {function} callback Callback function.
+ */
+ request(reqOpts, callback) {
+ reqOpts.uri = this.pathPrefix + reqOpts.uri;
+ this.request_(reqOpts, callback);
}
- return state.config.resourceLocation;
-}
-exports.getResourceLocation = getResourceLocation;
-function isOperationError(e) {
- return e.name === "RestError";
-}
-exports.isOperationError = isOperationError;
-/** Polls the long-running operation. */
-async function pollHttpOperation(inputs) {
- const { lro, stateProxy, options, processResult, updateState, setDelay, state, setErrorAsResult, } = inputs;
- return (0, operation_js_1.pollOperation)({
- state,
- stateProxy,
- setDelay,
- processResult: processResult
- ? ({ flatResponse }, inputState) => processResult(flatResponse, inputState)
- : ({ flatResponse }) => flatResponse,
- getError: getErrorFromResponse,
- updateState,
- getPollingInterval: parseRetryAfter,
- getOperationLocation,
- getOperationStatus,
- isOperationError,
- getResourceLocation,
- options,
- /**
- * The expansion here is intentional because `lro` could be an object that
- * references an inner this, so we need to preserve a reference to it.
- */
- poll: async (location, inputOptions) => lro.sendPollRequest(location, inputOptions),
- setErrorAsResult,
- });
}
-exports.pollHttpOperation = pollHttpOperation;
-//# sourceMappingURL=operation.js.map
+exports.Acl = Acl;
+/*! Developer Documentation
+ *
+ * All async methods (except for streams) will return a Promise in the event
+ * that a callback is omitted.
+ */
+(0, promisify_1.promisifyAll)(Acl, {
+ exclude: ['request'],
+});
+
/***/ }),
-/***/ 7421:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 82887:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
+// Copyright 2019 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ 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.createHttpPoller = void 0;
-const operation_js_1 = __nccwpck_require__(3878);
-const poller_js_1 = __nccwpck_require__(8835);
+exports.Bucket = exports.BucketExceptionMessages = exports.AvailableServiceObjectMethods = exports.BucketActionToHTTPMethod = void 0;
+const index_js_1 = __nccwpck_require__(11325);
+const paginator_1 = __nccwpck_require__(99469);
+const promisify_1 = __nccwpck_require__(60206);
+const fs = __importStar(__nccwpck_require__(79896));
+const mime_1 = __importDefault(__nccwpck_require__(94900));
+const path = __importStar(__nccwpck_require__(16928));
+const p_limit_1 = __importDefault(__nccwpck_require__(58890));
+const util_1 = __nccwpck_require__(39023);
+const async_retry_1 = __importDefault(__nccwpck_require__(45195));
+const util_js_1 = __nccwpck_require__(74557);
+const acl_js_1 = __nccwpck_require__(76637);
+const file_js_1 = __nccwpck_require__(69975);
+const iam_js_1 = __nccwpck_require__(52880);
+const notification_js_1 = __nccwpck_require__(18598);
+const storage_js_1 = __nccwpck_require__(92848);
+const signer_js_1 = __nccwpck_require__(7319);
+const stream_1 = __nccwpck_require__(2203);
+const url_1 = __nccwpck_require__(87016);
+var BucketActionToHTTPMethod;
+(function (BucketActionToHTTPMethod) {
+ BucketActionToHTTPMethod["list"] = "GET";
+})(BucketActionToHTTPMethod || (exports.BucketActionToHTTPMethod = BucketActionToHTTPMethod = {}));
+var AvailableServiceObjectMethods;
+(function (AvailableServiceObjectMethods) {
+ AvailableServiceObjectMethods[AvailableServiceObjectMethods["setMetadata"] = 0] = "setMetadata";
+ AvailableServiceObjectMethods[AvailableServiceObjectMethods["delete"] = 1] = "delete";
+})(AvailableServiceObjectMethods || (exports.AvailableServiceObjectMethods = AvailableServiceObjectMethods = {}));
+var BucketExceptionMessages;
+(function (BucketExceptionMessages) {
+ BucketExceptionMessages["PROVIDE_SOURCE_FILE"] = "You must provide at least one source file.";
+ BucketExceptionMessages["DESTINATION_FILE_NOT_SPECIFIED"] = "A destination file must be specified.";
+ BucketExceptionMessages["CHANNEL_ID_REQUIRED"] = "An ID is required to create a channel.";
+ BucketExceptionMessages["TOPIC_NAME_REQUIRED"] = "A valid topic name is required.";
+ BucketExceptionMessages["CONFIGURATION_OBJECT_PREFIX_REQUIRED"] = "A configuration object with a prefix is required.";
+ BucketExceptionMessages["SPECIFY_FILE_NAME"] = "A file name must be specified.";
+ BucketExceptionMessages["METAGENERATION_NOT_PROVIDED"] = "A metageneration must be provided.";
+ BucketExceptionMessages["SUPPLY_NOTIFICATION_ID"] = "You must supply a notification ID.";
+})(BucketExceptionMessages || (exports.BucketExceptionMessages = BucketExceptionMessages = {}));
+/**
+ * @callback Crc32cGeneratorToStringCallback
+ * A method returning the CRC32C as a base64-encoded string.
+ *
+ * @returns {string}
+ *
+ * @example
+ * Hashing the string 'data' should return 'rth90Q=='
+ *
+ * ```js
+ * const buffer = Buffer.from('data');
+ * crc32c.update(buffer);
+ * crc32c.toString(); // 'rth90Q=='
+ * ```
+ **/
/**
- * Creates a poller that can be used to poll a long-running operation.
- * @param lro - Description of the long-running operation
- * @param options - options to configure the poller
- * @returns an initialized poller
+ * @callback Crc32cGeneratorValidateCallback
+ * A method validating a base64-encoded CRC32C string.
+ *
+ * @param {string} [value] base64-encoded CRC32C string to validate
+ * @returns {boolean}
+ *
+ * @example
+ * Should return `true` if the value matches, `false` otherwise
+ *
+ * ```js
+ * const buffer = Buffer.from('data');
+ * crc32c.update(buffer);
+ * crc32c.validate('DkjKuA=='); // false
+ * crc32c.validate('rth90Q=='); // true
+ * ```
+ **/
+/**
+ * @callback Crc32cGeneratorUpdateCallback
+ * A method for passing `Buffer`s for CRC32C generation.
+ *
+ * @param {Buffer} [data] data to update CRC32C value with
+ * @returns {undefined}
+ *
+ * @example
+ * Hashing buffers from 'some ' and 'text\n'
+ *
+ * ```js
+ * const buffer1 = Buffer.from('some ');
+ * crc32c.update(buffer1);
+ *
+ * const buffer2 = Buffer.from('text\n');
+ * crc32c.update(buffer2);
+ *
+ * crc32c.toString(); // 'DkjKuA=='
+ * ```
+ **/
+/**
+ * @typedef {object} CRC32CValidator
+ * @property {Crc32cGeneratorToStringCallback}
+ * @property {Crc32cGeneratorValidateCallback}
+ * @property {Crc32cGeneratorUpdateCallback}
*/
-async function createHttpPoller(lro, options) {
- const { resourceLocationConfig, intervalInMs, processResult, restoreFrom, updateState, withOperationLocation, resolveOnUnsuccessful = false, } = options || {};
- return (0, poller_js_1.buildCreatePoller)({
- getStatusFromInitialResponse: operation_js_1.getStatusFromInitialResponse,
- getStatusFromPollResponse: operation_js_1.getOperationStatus,
- isOperationError: operation_js_1.isOperationError,
- getOperationLocation: operation_js_1.getOperationLocation,
- getResourceLocation: operation_js_1.getResourceLocation,
- getPollingInterval: operation_js_1.parseRetryAfter,
- getError: operation_js_1.getErrorFromResponse,
- resolveOnUnsuccessful,
- })({
- init: async () => {
- const response = await lro.sendInitialRequest();
- const config = (0, operation_js_1.inferLroMode)({
- rawResponse: response.rawResponse,
- requestPath: lro.requestPath,
- requestMethod: lro.requestMethod,
- resourceLocationConfig,
- });
- return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}));
- },
- poll: lro.sendPollRequest,
- }, {
- intervalInMs,
- withOperationLocation,
- restoreFrom,
- updateState,
- processResult: processResult
- ? ({ flatResponse }, state) => processResult(flatResponse, state)
- : ({ flatResponse }) => flatResponse,
- });
-}
-exports.createHttpPoller = createHttpPoller;
-//# sourceMappingURL=poller.js.map
-
-/***/ }),
-
-/***/ 1754:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createHttpPoller = void 0;
-const tslib_1 = __nccwpck_require__(1860);
-var poller_js_1 = __nccwpck_require__(7421);
-Object.defineProperty(exports, "createHttpPoller", ({ enumerable: true, get: function () { return poller_js_1.createHttpPoller; } }));
/**
- * This can be uncommented to expose the protocol-agnostic poller
+ * A function that generates a CRC32C Validator. Defaults to {@link CRC32C}
+ *
+ * @name Bucket#crc32cGenerator
+ * @type {CRC32CValidator}
*/
-// export {
-// BuildCreatePollerOptions,
-// Operation,
-// CreatePollerOptions,
-// OperationConfig,
-// RestorableOperationState,
-// } from "./poller/models";
-// export { buildCreatePoller } from "./poller/poller";
-/** legacy */
-tslib_1.__exportStar(__nccwpck_require__(5454), exports);
-tslib_1.__exportStar(__nccwpck_require__(6272), exports);
-tslib_1.__exportStar(__nccwpck_require__(2670), exports);
-//# sourceMappingURL=index.js.map
-
-/***/ }),
-
-/***/ 5454:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.LroEngine = void 0;
-var lroEngine_js_1 = __nccwpck_require__(1607);
-Object.defineProperty(exports, "LroEngine", ({ enumerable: true, get: function () { return lroEngine_js_1.LroEngine; } }));
-//# sourceMappingURL=index.js.map
-
-/***/ }),
-
-/***/ 1607:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.LroEngine = void 0;
-const operation_js_1 = __nccwpck_require__(4267);
-const constants_js_1 = __nccwpck_require__(5044);
-const poller_js_1 = __nccwpck_require__(6272);
-const operation_js_2 = __nccwpck_require__(736);
/**
- * The LRO Engine, a class that performs polling.
+ * Get and set IAM policies for your bucket.
+ *
+ * @name Bucket#iam
+ * @mixes Iam
+ *
+ * See {@link https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management| Cloud Storage IAM Management}
+ * See {@link https://cloud.google.com/iam/docs/granting-changing-revoking-access| Granting, Changing, and Revoking Access}
+ * See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ *
+ * //-
+ * // Get the IAM policy for your bucket.
+ * //-
+ * bucket.iam.getPolicy(function(err, policy) {
+ * console.log(policy);
+ * });
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.iam.getPolicy().then(function(data) {
+ * const policy = data[0];
+ * const apiResponse = data[1];
+ * });
+ *
+ * ```
+ * @example include:samples/iam.js
+ * region_tag:storage_view_bucket_iam_members
+ * Example of retrieving a bucket's IAM policy:
+ *
+ * @example include:samples/iam.js
+ * region_tag:storage_add_bucket_iam_member
+ * Example of adding to a bucket's IAM policy:
+ *
+ * @example include:samples/iam.js
+ * region_tag:storage_remove_bucket_iam_member
+ * Example of removing from a bucket's IAM policy:
*/
-class LroEngine extends poller_js_1.Poller {
- constructor(lro, options) {
- const { intervalInMs = constants_js_1.POLL_INTERVAL_IN_MS, resumeFrom, resolveOnUnsuccessful = false, isDone, lroResourceLocationConfig, processResult, updateState, } = options || {};
- const state = resumeFrom
- ? (0, operation_js_2.deserializeState)(resumeFrom)
- : {};
- const operation = new operation_js_1.GenericPollOperation(state, lro, !resolveOnUnsuccessful, lroResourceLocationConfig, processResult, updateState, isDone);
- super(operation);
- this.resolveOnUnsuccessful = resolveOnUnsuccessful;
- this.config = { intervalInMs: intervalInMs };
- operation.setPollerConfig(this.config);
+/**
+ * Cloud Storage uses access control lists (ACLs) to manage object and
+ * bucket access. ACLs are the mechanism you use to share objects with other
+ * users and allow other users to access your buckets and objects.
+ *
+ * An ACL consists of one or more entries, where each entry grants permissions
+ * to an entity. Permissions define the actions that can be performed against
+ * an object or bucket (for example, `READ` or `WRITE`); the entity defines
+ * who the permission applies to (for example, a specific user or group of
+ * users).
+ *
+ * The `acl` object on a Bucket instance provides methods to get you a list of
+ * the ACLs defined on your bucket, as well as set, update, and delete them.
+ *
+ * Buckets also have
+ * {@link https://cloud.google.com/storage/docs/access-control/lists#default| default ACLs}
+ * for all created files. Default ACLs specify permissions that all new
+ * objects added to the bucket will inherit by default. You can add, delete,
+ * get, and update entities and permissions for these as well with
+ * {@link Bucket#acl.default}.
+ *
+ * See {@link http://goo.gl/6qBBPO| About Access Control Lists}
+ * See {@link https://cloud.google.com/storage/docs/access-control/lists#default| Default ACLs}
+ *
+ * @name Bucket#acl
+ * @mixes Acl
+ * @property {Acl} default Cloud Storage Buckets have
+ * {@link https://cloud.google.com/storage/docs/access-control/lists#default| default ACLs}
+ * for all created files. You can add, delete, get, and update entities and
+ * permissions for these as well. The method signatures and examples are all
+ * the same, after only prefixing the method call with `default`.
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ *
+ * //-
+ * // Make a bucket's contents publicly readable.
+ * //-
+ * const myBucket = storage.bucket('my-bucket');
+ *
+ * const options = {
+ * entity: 'allUsers',
+ * role: storage.acl.READER_ROLE
+ * };
+ *
+ * myBucket.acl.add(options, function(err, aclObject) {});
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * myBucket.acl.add(options).then(function(data) {
+ * const aclObject = data[0];
+ * const apiResponse = data[1];
+ * });
+ *
+ * ```
+ * @example include:samples/acl.js
+ * region_tag:storage_print_bucket_acl
+ * Example of printing a bucket's ACL:
+ *
+ * @example include:samples/acl.js
+ * region_tag:storage_print_bucket_acl_for_user
+ * Example of printing a bucket's ACL for a specific user:
+ *
+ * @example include:samples/acl.js
+ * region_tag:storage_add_bucket_owner
+ * Example of adding an owner to a bucket:
+ *
+ * @example include:samples/acl.js
+ * region_tag:storage_remove_bucket_owner
+ * Example of removing an owner from a bucket:
+ *
+ * @example include:samples/acl.js
+ * region_tag:storage_add_bucket_default_owner
+ * Example of adding a default owner to a bucket:
+ *
+ * @example include:samples/acl.js
+ * region_tag:storage_remove_bucket_default_owner
+ * Example of removing a default owner from a bucket:
+ */
+/**
+ * The API-formatted resource description of the bucket.
+ *
+ * Note: This is not guaranteed to be up-to-date when accessed. To get the
+ * latest record, call the `getMetadata()` method.
+ *
+ * @name Bucket#metadata
+ * @type {object}
+ */
+/**
+ * The bucket's name.
+ * @name Bucket#name
+ * @type {string}
+ */
+/**
+ * Get {@link File} objects for the files currently in the bucket as a
+ * readable object stream.
+ *
+ * @method Bucket#getFilesStream
+ * @param {GetFilesOptions} [query] Query object for listing files.
+ * @returns {ReadableStream} A readable stream that emits {@link File} instances.
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ *
+ * bucket.getFilesStream()
+ * .on('error', console.error)
+ * .on('data', function(file) {
+ * // file is a File object.
+ * })
+ * .on('end', function() {
+ * // All files retrieved.
+ * });
+ *
+ * //-
+ * // If you anticipate many results, you can end a stream early to prevent
+ * // unnecessary processing and API requests.
+ * //-
+ * bucket.getFilesStream()
+ * .on('data', function(file) {
+ * this.end();
+ * });
+ *
+ * //-
+ * // If you're filtering files with a delimiter, you should use
+ * // {@link Bucket#getFiles} and set `autoPaginate: false` in order to
+ * // preserve the `apiResponse` argument.
+ * //-
+ * const prefixes = [];
+ *
+ * function callback(err, files, nextQuery, apiResponse) {
+ * prefixes = prefixes.concat(apiResponse.prefixes);
+ *
+ * if (nextQuery) {
+ * bucket.getFiles(nextQuery, callback);
+ * } else {
+ * // prefixes = The finished array of prefixes.
+ * }
+ * }
+ *
+ * bucket.getFiles({
+ * autoPaginate: false,
+ * delimiter: '/'
+ * }, callback);
+ * ```
+ */
+/**
+ * Create a Bucket object to interact with a Cloud Storage bucket.
+ *
+ * @class
+ * @hideconstructor
+ *
+ * @param {Storage} storage A {@link Storage} instance.
+ * @param {string} name The name of the bucket.
+ * @param {object} [options] Configuration object.
+ * @param {string} [options.userProject] User project.
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ * ```
+ */
+class Bucket extends index_js_1.ServiceObject {
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ getFilesStream(query) {
+ // placeholder body, overwritten in constructor
+ return new stream_1.Readable();
+ }
+ constructor(storage, name, options) {
+ var _a, _b, _c, _d;
+ options = options || {};
+ // Allow for "gs://"-style input, and strip any trailing slashes.
+ name = name.replace(/^gs:\/\//, '').replace(/\/+$/, '');
+ const requestQueryObject = {};
+ if ((_a = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) {
+ requestQueryObject.ifGenerationMatch =
+ options.preconditionOpts.ifGenerationMatch;
+ }
+ if ((_b = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _b === void 0 ? void 0 : _b.ifGenerationNotMatch) {
+ requestQueryObject.ifGenerationNotMatch =
+ options.preconditionOpts.ifGenerationNotMatch;
+ }
+ if ((_c = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _c === void 0 ? void 0 : _c.ifMetagenerationMatch) {
+ requestQueryObject.ifMetagenerationMatch =
+ options.preconditionOpts.ifMetagenerationMatch;
+ }
+ if ((_d = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _d === void 0 ? void 0 : _d.ifMetagenerationNotMatch) {
+ requestQueryObject.ifMetagenerationNotMatch =
+ options.preconditionOpts.ifMetagenerationNotMatch;
+ }
+ const userProject = options.userProject;
+ if (typeof userProject === 'string') {
+ requestQueryObject.userProject = userProject;
+ }
+ const methods = {
+ /**
+ * Create a bucket.
+ *
+ * @method Bucket#create
+ * @param {CreateBucketRequest} [metadata] Metadata to set for the bucket.
+ * @param {CreateBucketCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ * bucket.create(function(err, bucket, apiResponse) {
+ * if (!err) {
+ * // The bucket was created successfully.
+ * }
+ * });
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.create().then(function(data) {
+ * const bucket = data[0];
+ * const apiResponse = data[1];
+ * });
+ * ```
+ */
+ create: {
+ reqOpts: {
+ qs: requestQueryObject,
+ },
+ },
+ /**
+ * IamDeleteBucketOptions Configuration options.
+ * @property {boolean} [ignoreNotFound = false] Ignore an error if
+ * the bucket does not exist.
+ * @property {string} [userProject] The ID of the project which will be
+ * billed for the request.
+ */
+ /**
+ * @typedef {array} DeleteBucketResponse
+ * @property {object} 0 The full API response.
+ */
+ /**
+ * @callback DeleteBucketCallback
+ * @param {?Error} err Request error, if any.
+ * @param {object} apiResponse The full API response.
+ */
+ /**
+ * Delete the bucket.
+ *
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/delete| Buckets: delete API Documentation}
+ *
+ * @method Bucket#delete
+ * @param {DeleteBucketOptions} [options] Configuration options.
+ * @param {boolean} [options.ignoreNotFound = false] Ignore an error if
+ * the bucket does not exist.
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {DeleteBucketCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ * bucket.delete(function(err, apiResponse) {});
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.delete().then(function(data) {
+ * const apiResponse = data[0];
+ * });
+ *
+ * ```
+ * @example include:samples/buckets.js
+ * region_tag:storage_delete_bucket
+ * Another example:
+ */
+ delete: {
+ reqOpts: {
+ qs: requestQueryObject,
+ },
+ },
+ /**
+ * @typedef {object} BucketExistsOptions Configuration options for Bucket#exists().
+ * @property {string} [userProject] The ID of the project which will be
+ * billed for the request.
+ */
+ /**
+ * @typedef {array} BucketExistsResponse
+ * @property {boolean} 0 Whether the {@link Bucket} exists.
+ */
+ /**
+ * @callback BucketExistsCallback
+ * @param {?Error} err Request error, if any.
+ * @param {boolean} exists Whether the {@link Bucket} exists.
+ */
+ /**
+ * Check if the bucket exists.
+ *
+ * @method Bucket#exists
+ * @param {BucketExistsOptions} [options] Configuration options.
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {BucketExistsCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ *
+ * bucket.exists(function(err, exists) {});
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.exists().then(function(data) {
+ * const exists = data[0];
+ * });
+ * ```
+ */
+ exists: {
+ reqOpts: {
+ qs: requestQueryObject,
+ },
+ },
+ /**
+ * @typedef {object} [GetBucketOptions] Configuration options for Bucket#get()
+ * @property {boolean} [autoCreate] Automatically create the object if
+ * it does not exist. Default: `false`
+ * @property {string} [userProject] The ID of the project which will be
+ * billed for the request.
+ */
+ /**
+ * @typedef {array} GetBucketResponse
+ * @property {Bucket} 0 The {@link Bucket}.
+ * @property {object} 1 The full API response.
+ */
+ /**
+ * @callback GetBucketCallback
+ * @param {?Error} err Request error, if any.
+ * @param {Bucket} bucket The {@link Bucket}.
+ * @param {object} apiResponse The full API response.
+ */
+ /**
+ * Get a bucket if it exists.
+ *
+ * You may optionally use this to "get or create" an object by providing
+ * an object with `autoCreate` set to `true`. Any extra configuration that
+ * is normally required for the `create` method must be contained within
+ * this object as well.
+ *
+ * @method Bucket#get
+ * @param {GetBucketOptions} [options] Configuration options.
+ * @param {boolean} [options.autoCreate] Automatically create the object if
+ * it does not exist. Default: `false`
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {GetBucketCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ *
+ * bucket.get(function(err, bucket, apiResponse) {
+ * // `bucket.metadata` has been populated.
+ * });
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.get().then(function(data) {
+ * const bucket = data[0];
+ * const apiResponse = data[1];
+ * });
+ * ```
+ */
+ get: {
+ reqOpts: {
+ qs: requestQueryObject,
+ },
+ },
+ /**
+ * @typedef {array} GetBucketMetadataResponse
+ * @property {object} 0 The bucket metadata.
+ * @property {object} 1 The full API response.
+ */
+ /**
+ * @callback GetBucketMetadataCallback
+ * @param {?Error} err Request error, if any.
+ * @param {object} metadata The bucket metadata.
+ * @param {object} apiResponse The full API response.
+ */
+ /**
+ * @typedef {object} GetBucketMetadataOptions Configuration options for Bucket#getMetadata().
+ * @property {string} [userProject] The ID of the project which will be
+ * billed for the request.
+ */
+ /**
+ * Get the bucket's metadata.
+ *
+ * To set metadata, see {@link Bucket#setMetadata}.
+ *
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/get| Buckets: get API Documentation}
+ *
+ * @method Bucket#getMetadata
+ * @param {GetBucketMetadataOptions} [options] Configuration options.
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {GetBucketMetadataCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ *
+ * bucket.getMetadata(function(err, metadata, apiResponse) {});
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.getMetadata().then(function(data) {
+ * const metadata = data[0];
+ * const apiResponse = data[1];
+ * });
+ *
+ * ```
+ * @example include:samples/requesterPays.js
+ * region_tag:storage_get_requester_pays_status
+ * Example of retrieving the requester pays status of a bucket:
+ */
+ getMetadata: {
+ reqOpts: {
+ qs: requestQueryObject,
+ },
+ },
+ /**
+ * @typedef {object} SetBucketMetadataOptions Configuration options for Bucket#setMetadata().
+ * @property {string} [userProject] The ID of the project which will be
+ * billed for the request.
+ */
+ /**
+ * @typedef {array} SetBucketMetadataResponse
+ * @property {object} apiResponse The full API response.
+ */
+ /**
+ * @callback SetBucketMetadataCallback
+ * @param {?Error} err Request error, if any.
+ * @param {object} metadata The bucket metadata.
+ */
+ /**
+ * Set the bucket's metadata.
+ *
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch| Buckets: patch API Documentation}
+ *
+ * @method Bucket#setMetadata
+ * @param {object} metadata The metadata you wish to set.
+ * @param {SetBucketMetadataOptions} [options] Configuration options.
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {SetBucketMetadataCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ *
+ * //-
+ * // Set website metadata field on the bucket.
+ * //-
+ * const metadata = {
+ * website: {
+ * mainPageSuffix: 'http://example.com',
+ * notFoundPage: 'http://example.com/404.html'
+ * }
+ * };
+ *
+ * bucket.setMetadata(metadata, function(err, apiResponse) {});
+ *
+ * //-
+ * // Enable versioning for your bucket.
+ * //-
+ * bucket.setMetadata({
+ * versioning: {
+ * enabled: true
+ * }
+ * }, function(err, apiResponse) {});
+ *
+ * //-
+ * // Enable KMS encryption for objects within this bucket.
+ * //-
+ * bucket.setMetadata({
+ * encryption: {
+ * defaultKmsKeyName: 'projects/grape-spaceship-123/...'
+ * }
+ * }, function(err, apiResponse) {});
+ *
+ * //-
+ * // Set the default event-based hold value for new objects in this
+ * // bucket.
+ * //-
+ * bucket.setMetadata({
+ * defaultEventBasedHold: true
+ * }, function(err, apiResponse) {});
+ *
+ * //-
+ * // Remove object lifecycle rules.
+ * //-
+ * bucket.setMetadata({
+ * lifecycle: null
+ * }, function(err, apiResponse) {});
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.setMetadata(metadata).then(function(data) {
+ * const apiResponse = data[0];
+ * });
+ * ```
+ */
+ setMetadata: {
+ reqOpts: {
+ qs: requestQueryObject,
+ },
+ },
+ };
+ super({
+ parent: storage,
+ baseUrl: '/b',
+ id: name,
+ createMethod: storage.createBucket.bind(storage),
+ methods,
+ });
+ this.name = name;
+ this.storage = storage;
+ this.userProject = options.userProject;
+ this.acl = new acl_js_1.Acl({
+ request: this.request.bind(this),
+ pathPrefix: '/acl',
+ });
+ this.acl.default = new acl_js_1.Acl({
+ request: this.request.bind(this),
+ pathPrefix: '/defaultObjectAcl',
+ });
+ this.crc32cGenerator =
+ options.crc32cGenerator || this.storage.crc32cGenerator;
+ this.iam = new iam_js_1.Iam(this);
+ this.getFilesStream = paginator_1.paginator.streamify('getFiles');
+ this.instanceRetryValue = storage.retryOptions.autoRetry;
+ this.instancePreconditionOpts = options === null || options === void 0 ? void 0 : options.preconditionOpts;
}
/**
- * The method used by the poller to wait before attempting to update its operation.
+ * The bucket's Cloud Storage URI (`gs://`)
+ *
+ * @example
+ * ```ts
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('my-bucket');
+ *
+ * // `gs://my-bucket`
+ * const href = bucket.cloudStorageURI.href;
+ * ```
*/
- delay() {
- return new Promise((resolve) => setTimeout(() => resolve(), this.config.intervalInMs));
+ get cloudStorageURI() {
+ const uri = new url_1.URL('gs://');
+ uri.host = this.name;
+ return uri;
+ }
+ /**
+ * @typedef {object} AddLifecycleRuleOptions Configuration options for Bucket#addLifecycleRule().
+ * @property {boolean} [append=true] The new rules will be appended to any
+ * pre-existing rules.
+ */
+ /**
+ *
+ * @typedef {object} LifecycleRule The new lifecycle rule to be added to objects
+ * in this bucket.
+ * @property {string|object} action The action to be taken upon matching of
+ * all the conditions 'delete', 'setStorageClass', or 'AbortIncompleteMultipartUpload'.
+ * **Note**: For configuring a raw-formatted rule object to be passed as `action`
+ * please refer to the [examples]{@link https://cloud.google.com/storage/docs/managing-lifecycles#configexamples}.
+ * @property {object} condition Condition a bucket must meet before the
+ * action occurs on the bucket. Refer to following supported [conditions]{@link https://cloud.google.com/storage/docs/lifecycle#conditions}.
+ * @property {string} [storageClass] When using the `setStorageClass`
+ * action, provide this option to dictate which storage class the object
+ * should update to. Please see
+ * [SetStorageClass option documentation]{@link https://cloud.google.com/storage/docs/lifecycle#setstorageclass} for supported transitions.
+ */
+ /**
+ * Add an object lifecycle management rule to the bucket.
+ *
+ * By default, an Object Lifecycle Management rule provided to this method
+ * will be included to the existing policy. To replace all existing rules,
+ * supply the `options` argument, setting `append` to `false`.
+ *
+ * To add multiple rules, pass a list to the `rule` parameter. Calling this
+ * function multiple times asynchronously does not guarantee that all rules
+ * are added correctly.
+ *
+ * See {@link https://cloud.google.com/storage/docs/lifecycle| Object Lifecycle Management}
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch| Buckets: patch API Documentation}
+ *
+ * @param {LifecycleRule|LifecycleRule[]} rule The new lifecycle rule or rules to be added to objects
+ * in this bucket.
+ * @param {string|object} rule.action The action to be taken upon matching of
+ * all the conditions 'delete', 'setStorageClass', or 'AbortIncompleteMultipartUpload'.
+ * **Note**: For configuring a raw-formatted rule object to be passed as `action`
+ * please refer to the [examples]{@link https://cloud.google.com/storage/docs/managing-lifecycles#configexamples}.
+ * @param {object} rule.condition Condition a bucket must meet before the
+ * action occurson the bucket. Refer to followitn supported [conditions]{@link https://cloud.google.com/storage/docs/lifecycle#conditions}.
+ * @param {string} [rule.storageClass] When using the `setStorageClass`
+ * action, provide this option to dictate which storage class the object
+ * should update to.
+ * @param {AddLifecycleRuleOptions} [options] Configuration object.
+ * @param {boolean} [options.append=true] Append the new rule to the existing
+ * policy.
+ * @param {SetBucketMetadataCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ *
+ * //-
+ * // Automatically have an object deleted from this bucket once it is 3 years
+ * // of age.
+ * //-
+ * bucket.addLifecycleRule({
+ * action: 'delete',
+ * condition: {
+ * age: 365 * 3 // Specified in days.
+ * }
+ * }, function(err, apiResponse) {
+ * if (err) {
+ * // Error handling omitted.
+ * }
+ *
+ * const lifecycleRules = bucket.metadata.lifecycle.rule;
+ *
+ * // Iterate over the Object Lifecycle Management rules on this bucket.
+ * lifecycleRules.forEach(lifecycleRule => {});
+ * });
+ *
+ * //-
+ * // By default, the rule you provide will be added to the existing policy.
+ * // Optionally, you can disable this behavior to replace all of the
+ * // pre-existing rules.
+ * //-
+ * const options = {
+ * append: false
+ * };
+ *
+ * bucket.addLifecycleRule({
+ * action: 'delete',
+ * condition: {
+ * age: 365 * 3 // Specified in days.
+ * }
+ * }, options, function(err, apiResponse) {
+ * if (err) {
+ * // Error handling omitted.
+ * }
+ *
+ * // All rules have been replaced with the new "delete" rule.
+ *
+ * // Iterate over the Object Lifecycle Management rules on this bucket.
+ * lifecycleRules.forEach(lifecycleRule => {});
+ * });
+ *
+ * //-
+ * // For objects created before 2018, "downgrade" the storage class.
+ * //-
+ * bucket.addLifecycleRule({
+ * action: 'setStorageClass',
+ * storageClass: 'COLDLINE',
+ * condition: {
+ * createdBefore: new Date('2018')
+ * }
+ * }, function(err, apiResponse) {});
+ *
+ * //-
+ * // Delete objects created before 2016 which have the Coldline storage
+ * // class.
+ * //-
+ * bucket.addLifecycleRule({
+ * action: 'delete',
+ * condition: {
+ * matchesStorageClass: [
+ * 'COLDLINE'
+ * ],
+ * createdBefore: new Date('2016')
+ * }
+ * }, function(err, apiResponse) {});
+ *
+ * //-
+ * // Delete object that has a noncurrent timestamp that is at least 100 days.
+ * //-
+ * bucket.addLifecycleRule({
+ * action: 'delete',
+ * condition: {
+ * daysSinceNoncurrentTime: 100
+ * }
+ * }, function(err, apiResponse) {});
+ *
+ * //-
+ * // Delete object that has a noncurrent timestamp before 2020-01-01.
+ * //-
+ * bucket.addLifecycleRule({
+ * action: 'delete',
+ * condition: {
+ * noncurrentTimeBefore: new Date('2020-01-01')
+ * }
+ * }, function(err, apiResponse) {});
+ *
+ * //-
+ * // Delete object that has a customTime that is at least 100 days.
+ * //-
+ * bucket.addLifecycleRule({
+ * action: 'delete',
+ * condition: {
+ * daysSinceCustomTime: 100
+ * }
+ * }, function(err, apiResponse) ());
+ *
+ * //-
+ * // Delete object that has a customTime before 2020-01-01.
+ * //-
+ * bucket.addLifecycleRule({
+ * action: 'delete',
+ * condition: {
+ * customTimeBefore: new Date('2020-01-01')
+ * }
+ * }, function(err, apiResponse) {});
+ * ```
+ */
+ addLifecycleRule(rule, optionsOrCallback, callback) {
+ let options = {};
+ if (typeof optionsOrCallback === 'function') {
+ callback = optionsOrCallback;
+ }
+ else if (optionsOrCallback) {
+ options = optionsOrCallback;
+ }
+ options = options || {};
+ const rules = Array.isArray(rule) ? rule : [rule];
+ for (const curRule of rules) {
+ if (curRule.condition.createdBefore instanceof Date) {
+ curRule.condition.createdBefore = curRule.condition.createdBefore
+ .toISOString()
+ .replace(/T.+$/, '');
+ }
+ if (curRule.condition.customTimeBefore instanceof Date) {
+ curRule.condition.customTimeBefore = curRule.condition.customTimeBefore
+ .toISOString()
+ .replace(/T.+$/, '');
+ }
+ if (curRule.condition.noncurrentTimeBefore instanceof Date) {
+ curRule.condition.noncurrentTimeBefore =
+ curRule.condition.noncurrentTimeBefore
+ .toISOString()
+ .replace(/T.+$/, '');
+ }
+ }
+ if (options.append === false) {
+ this.setMetadata({ lifecycle: { rule: rules } }, options, callback);
+ return;
+ }
+ // The default behavior appends the previously-defined lifecycle rules with
+ // the new ones just passed in by the user.
+ this.getMetadata((err, metadata) => {
+ var _a, _b;
+ if (err) {
+ callback(err);
+ return;
+ }
+ const currentLifecycleRules = Array.isArray((_a = metadata.lifecycle) === null || _a === void 0 ? void 0 : _a.rule)
+ ? (_b = metadata.lifecycle) === null || _b === void 0 ? void 0 : _b.rule
+ : [];
+ this.setMetadata({
+ lifecycle: { rule: currentLifecycleRules.concat(rules) },
+ }, options, callback);
+ });
}
-}
-exports.LroEngine = LroEngine;
-//# sourceMappingURL=lroEngine.js.map
-
-/***/ }),
-
-/***/ 4267:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.GenericPollOperation = void 0;
-const operation_js_1 = __nccwpck_require__(3878);
-const logger_js_1 = __nccwpck_require__(480);
-const createStateProxy = () => ({
- initState: (config) => ({ config, isStarted: true }),
- setCanceled: (state) => (state.isCancelled = true),
- setError: (state, error) => (state.error = error),
- setResult: (state, result) => (state.result = result),
- setRunning: (state) => (state.isStarted = true),
- setSucceeded: (state) => (state.isCompleted = true),
- setFailed: () => {
- /** empty body */
- },
- getError: (state) => state.error,
- getResult: (state) => state.result,
- isCanceled: (state) => !!state.isCancelled,
- isFailed: (state) => !!state.error,
- isRunning: (state) => !!state.isStarted,
- isSucceeded: (state) => Boolean(state.isCompleted && !state.isCancelled && !state.error),
-});
-class GenericPollOperation {
- constructor(state, lro, setErrorAsResult, lroResourceLocationConfig, processResult, updateState, isDone) {
- this.state = state;
- this.lro = lro;
- this.setErrorAsResult = setErrorAsResult;
- this.lroResourceLocationConfig = lroResourceLocationConfig;
- this.processResult = processResult;
- this.updateState = updateState;
- this.isDone = isDone;
+ /**
+ * @typedef {object} CombineOptions
+ * @property {string} [kmsKeyName] Resource name of the Cloud KMS key, of
+ * the form
+ * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`,
+ * that will be used to encrypt the object. Overwrites the object
+ * metadata's `kms_key_name` value, if any.
+ * @property {string} [userProject] The ID of the project which will be
+ * billed for the request.
+ */
+ /**
+ * @callback CombineCallback
+ * @param {?Error} err Request error, if any.
+ * @param {File} newFile The new {@link File}.
+ * @param {object} apiResponse The full API response.
+ */
+ /**
+ * @typedef {array} CombineResponse
+ * @property {File} 0 The new {@link File}.
+ * @property {object} 1 The full API response.
+ */
+ /**
+ * Combine multiple files into one new file.
+ *
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/compose| Objects: compose API Documentation}
+ *
+ * @throws {Error} if a non-array is provided as sources argument.
+ * @throws {Error} if no sources are provided.
+ * @throws {Error} if no destination is provided.
+ *
+ * @param {string[]|File[]} sources The source files that will be
+ * combined.
+ * @param {string|File} destination The file you would like the
+ * source files combined into.
+ * @param {CombineOptions} [options] Configuration options.
+ * @param {string} [options.kmsKeyName] Resource name of the Cloud KMS key, of
+ * the form
+ * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`,
+ * that will be used to encrypt the object. Overwrites the object
+ * metadata's `kms_key_name` value, if any.
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+
+ * @param {CombineCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const logBucket = storage.bucket('log-bucket');
+ *
+ * const sources = [
+ * logBucket.file('2013-logs.txt'),
+ * logBucket.file('2014-logs.txt')
+ * ];
+ *
+ * const allLogs = logBucket.file('all-logs.txt');
+ *
+ * logBucket.combine(sources, allLogs, function(err, newFile, apiResponse) {
+ * // newFile === allLogs
+ * });
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * logBucket.combine(sources, allLogs).then(function(data) {
+ * const newFile = data[0];
+ * const apiResponse = data[1];
+ * });
+ * ```
+ */
+ combine(sources, destination, optionsOrCallback, callback) {
+ var _a;
+ if (!Array.isArray(sources) || sources.length === 0) {
+ throw new Error(BucketExceptionMessages.PROVIDE_SOURCE_FILE);
+ }
+ if (!destination) {
+ throw new Error(BucketExceptionMessages.DESTINATION_FILE_NOT_SPECIFIED);
+ }
+ let options = {};
+ if (typeof optionsOrCallback === 'function') {
+ callback = optionsOrCallback;
+ }
+ else if (optionsOrCallback) {
+ options = optionsOrCallback;
+ }
+ this.disableAutoRetryConditionallyIdempotent_(this.methods.setMetadata, // Not relevant but param is required
+ AvailableServiceObjectMethods.setMetadata, // Same as above
+ options);
+ const convertToFile = (file) => {
+ if (file instanceof file_js_1.File) {
+ return file;
+ }
+ return this.file(file);
+ };
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ sources = sources.map(convertToFile);
+ const destinationFile = convertToFile(destination);
+ callback = callback || index_js_1.util.noop;
+ if (!destinationFile.metadata.contentType) {
+ const destinationContentType = mime_1.default.getType(destinationFile.name) || undefined;
+ if (destinationContentType) {
+ destinationFile.metadata.contentType = destinationContentType;
+ }
+ }
+ let maxRetries = this.storage.retryOptions.maxRetries;
+ if ((((_a = destinationFile === null || destinationFile === void 0 ? void 0 : destinationFile.instancePreconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) ===
+ undefined &&
+ options.ifGenerationMatch === undefined &&
+ this.storage.retryOptions.idempotencyStrategy ===
+ storage_js_1.IdempotencyStrategy.RetryConditional) ||
+ this.storage.retryOptions.idempotencyStrategy ===
+ storage_js_1.IdempotencyStrategy.RetryNever) {
+ maxRetries = 0;
+ }
+ if (options.ifGenerationMatch === undefined) {
+ Object.assign(options, destinationFile.instancePreconditionOpts, options);
+ }
+ // Make the request from the destination File object.
+ destinationFile.request({
+ method: 'POST',
+ uri: '/compose',
+ maxRetries,
+ json: {
+ destination: {
+ contentType: destinationFile.metadata.contentType,
+ contentEncoding: destinationFile.metadata.contentEncoding,
+ },
+ sourceObjects: sources.map(source => {
+ const sourceObject = {
+ name: source.name,
+ };
+ if (source.metadata && source.metadata.generation) {
+ sourceObject.generation = parseInt(source.metadata.generation.toString());
+ }
+ return sourceObject;
+ }),
+ },
+ qs: options,
+ }, (err, resp) => {
+ this.storage.retryOptions.autoRetry = this.instanceRetryValue;
+ if (err) {
+ callback(err, null, resp);
+ return;
+ }
+ callback(null, destinationFile, resp);
+ });
}
- setPollerConfig(pollerConfig) {
- this.pollerConfig = pollerConfig;
+ /**
+ * See a {@link https://cloud.google.com/storage/docs/json_api/v1/objects/watchAll| Objects: watchAll request body}.
+ *
+ * @typedef {object} CreateChannelConfig
+ * @property {string} address The address where notifications are
+ * delivered for this channel.
+ * @property {string} [delimiter] Returns results in a directory-like mode.
+ * @property {number} [maxResults] Maximum number of `items` plus `prefixes`
+ * to return in a single page of responses.
+ * @property {string} [pageToken] A previously-returned page token
+ * representing part of the larger set of results to view.
+ * @property {string} [prefix] Filter results to objects whose names begin
+ * with this prefix.
+ * @property {string} [projection=noAcl] Set of properties to return.
+ * @property {string} [userProject] The ID of the project which will be
+ * billed for the request.
+ * @property {boolean} [versions=false] If `true`, lists all versions of an object
+ * as distinct results.
+ */
+ /**
+ * @typedef {object} CreateChannelOptions
+ * @property {string} [userProject] The ID of the project which will be
+ * billed for the request.
+ */
+ /**
+ * @typedef {array} CreateChannelResponse
+ * @property {Channel} 0 The new {@link Channel}.
+ * @property {object} 1 The full API response.
+ */
+ /**
+ * @callback CreateChannelCallback
+ * @param {?Error} err Request error, if any.
+ * @param {Channel} channel The new {@link Channel}.
+ * @param {object} apiResponse The full API response.
+ */
+ /**
+ * Create a channel that will be notified when objects in this bucket changes.
+ *
+ * @throws {Error} If an ID is not provided.
+ * @throws {Error} If an address is not provided.
+ *
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/watchAll| Objects: watchAll API Documentation}
+ *
+ * @param {string} id The ID of the channel to create.
+ * @param {CreateChannelConfig} config Configuration for creating channel.
+ * @param {string} config.address The address where notifications are
+ * delivered for this channel.
+ * @param {string} [config.delimiter] Returns results in a directory-like mode.
+ * @param {number} [config.maxResults] Maximum number of `items` plus `prefixes`
+ * to return in a single page of responses.
+ * @param {string} [config.pageToken] A previously-returned page token
+ * representing part of the larger set of results to view.
+ * @param {string} [config.prefix] Filter results to objects whose names begin
+ * with this prefix.
+ * @param {string} [config.projection=noAcl] Set of properties to return.
+ * @param {string} [config.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {boolean} [config.versions=false] If `true`, lists all versions of an object
+ * as distinct results.
+ * @param {CreateChannelOptions} [options] Configuration options.
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {CreateChannelCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ * const id = 'new-channel-id';
+ *
+ * const config = {
+ * address: 'https://...'
+ * };
+ *
+ * bucket.createChannel(id, config, function(err, channel, apiResponse) {
+ * if (!err) {
+ * // Channel created successfully.
+ * }
+ * });
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.createChannel(id, config).then(function(data) {
+ * const channel = data[0];
+ * const apiResponse = data[1];
+ * });
+ * ```
+ */
+ createChannel(id, config, optionsOrCallback, callback) {
+ if (typeof id !== 'string') {
+ throw new Error(BucketExceptionMessages.CHANNEL_ID_REQUIRED);
+ }
+ let options = {};
+ if (typeof optionsOrCallback === 'function') {
+ callback = optionsOrCallback;
+ }
+ else if (optionsOrCallback) {
+ options = optionsOrCallback;
+ }
+ this.request({
+ method: 'POST',
+ uri: '/o/watch',
+ json: Object.assign({
+ id,
+ type: 'web_hook',
+ }, config),
+ qs: options,
+ }, (err, apiResponse) => {
+ if (err) {
+ callback(err, null, apiResponse);
+ return;
+ }
+ const resourceId = apiResponse.resourceId;
+ const channel = this.storage.channel(id, resourceId);
+ channel.metadata = apiResponse;
+ callback(null, channel, apiResponse);
+ });
}
- async update(options) {
- var _a;
- const stateProxy = createStateProxy();
- if (!this.state.isStarted) {
- this.state = Object.assign(Object.assign({}, this.state), (await (0, operation_js_1.initHttpOperation)({
- lro: this.lro,
- stateProxy,
- resourceLocationConfig: this.lroResourceLocationConfig,
- processResult: this.processResult,
- setErrorAsResult: this.setErrorAsResult,
- })));
+ /**
+ * Metadata to set for the Notification.
+ *
+ * @typedef {object} CreateNotificationOptions
+ * @property {object} [customAttributes] An optional list of additional
+ * attributes to attach to each Cloud PubSub message published for this
+ * notification subscription.
+ * @property {string[]} [eventTypes] If present, only send notifications about
+ * listed event types. If empty, sent notifications for all event types.
+ * @property {string} [objectNamePrefix] If present, only apply this
+ * notification configuration to object names that begin with this prefix.
+ * @property {string} [payloadFormat] The desired content of the Payload.
+ * Defaults to `JSON_API_V1`.
+ *
+ * Acceptable values are:
+ * - `JSON_API_V1`
+ *
+ * - `NONE`
+ * @property {string} [userProject] The ID of the project which will be
+ * billed for the request.
+ */
+ /**
+ * @callback CreateNotificationCallback
+ * @param {?Error} err Request error, if any.
+ * @param {Notification} notification The new {@link Notification}.
+ * @param {object} apiResponse The full API response.
+ */
+ /**
+ * @typedef {array} CreateNotificationResponse
+ * @property {Notification} 0 The new {@link Notification}.
+ * @property {object} 1 The full API response.
+ */
+ /**
+ * Creates a notification subscription for the bucket.
+ *
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/insert| Notifications: insert}
+ *
+ * @param {Topic|string} topic The Cloud PubSub topic to which this
+ * subscription publishes. If the project ID is omitted, the current
+ * project ID will be used.
+ *
+ * Acceptable formats are:
+ * - `projects/grape-spaceship-123/topics/my-topic`
+ *
+ * - `my-topic`
+ * @param {CreateNotificationOptions} [options] Metadata to set for the
+ * notification.
+ * @param {object} [options.customAttributes] An optional list of additional
+ * attributes to attach to each Cloud PubSub message published for this
+ * notification subscription.
+ * @param {string[]} [options.eventTypes] If present, only send notifications about
+ * listed event types. If empty, sent notifications for all event types.
+ * @param {string} [options.objectNamePrefix] If present, only apply this
+ * notification configuration to object names that begin with this prefix.
+ * @param {string} [options.payloadFormat] The desired content of the Payload.
+ * Defaults to `JSON_API_V1`.
+ *
+ * Acceptable values are:
+ * - `JSON_API_V1`
+ *
+ * - `NONE`
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {CreateNotificationCallback} [callback] Callback function.
+ * @returns {Promise}
+ * @throws {Error} If a valid topic is not provided.
+ * @see Notification#create
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const myBucket = storage.bucket('my-bucket');
+ *
+ * const callback = function(err, notification, apiResponse) {
+ * if (!err) {
+ * // The notification was created successfully.
+ * }
+ * };
+ *
+ * myBucket.createNotification('my-topic', callback);
+ *
+ * //-
+ * // Configure the nofiication by providing Notification metadata.
+ * //-
+ * const metadata = {
+ * objectNamePrefix: 'prefix-'
+ * };
+ *
+ * myBucket.createNotification('my-topic', metadata, callback);
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * myBucket.createNotification('my-topic').then(function(data) {
+ * const notification = data[0];
+ * const apiResponse = data[1];
+ * });
+ *
+ * ```
+ * @example include:samples/createNotification.js
+ * region_tag:storage_create_bucket_notifications
+ * Another example:
+ */
+ createNotification(topic, optionsOrCallback, callback) {
+ let options = {};
+ if (typeof optionsOrCallback === 'function') {
+ callback = optionsOrCallback;
+ }
+ else if (optionsOrCallback) {
+ options = optionsOrCallback;
+ }
+ const topicIsObject = topic !== null && typeof topic === 'object';
+ if (topicIsObject && index_js_1.util.isCustomType(topic, 'pubsub/topic')) {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ topic = topic.name;
+ }
+ if (typeof topic !== 'string') {
+ throw new Error(BucketExceptionMessages.TOPIC_NAME_REQUIRED);
+ }
+ const body = Object.assign({ topic }, options);
+ if (body.topic.indexOf('projects') !== 0) {
+ body.topic = 'projects/{{projectId}}/topics/' + body.topic;
+ }
+ body.topic = `//pubsub.${this.storage.universeDomain}/` + body.topic;
+ if (!body.payloadFormat) {
+ body.payloadFormat = 'JSON_API_V1';
+ }
+ const query = {};
+ if (body.userProject) {
+ query.userProject = body.userProject;
+ delete body.userProject;
+ }
+ this.request({
+ method: 'POST',
+ uri: '/notificationConfigs',
+ json: (0, util_js_1.convertObjKeysToSnakeCase)(body),
+ qs: query,
+ maxRetries: 0, //explicitly set this value since this is a non-idempotent function
+ }, (err, apiResponse) => {
+ if (err) {
+ callback(err, null, apiResponse);
+ return;
+ }
+ const notification = this.notification(apiResponse.id);
+ notification.metadata = apiResponse;
+ callback(null, notification, apiResponse);
+ });
+ }
+ /**
+ * @typedef {object} DeleteFilesOptions Query object. See {@link Bucket#getFiles}
+ * for all of the supported properties.
+ * @property {boolean} [force] Suppress errors until all files have been
+ * processed.
+ */
+ /**
+ * @callback DeleteFilesCallback
+ * @param {?Error|?Error[]} err Request error, if any, or array of errors from
+ * files that were not able to be deleted.
+ * @param {object} [apiResponse] The full API response.
+ */
+ /**
+ * Iterate over the bucket's files, calling `file.delete()` on each.
+ *
+ * This is not an atomic request. A delete attempt will be
+ * made for each file individually. Any one can fail, in which case only a
+ * portion of the files you intended to be deleted would have.
+ *
+ * Operations are performed in parallel, up to 10 at once. The first error
+ * breaks the loop and will execute the provided callback with it. Specify
+ * `{ force: true }` to suppress the errors until all files have had a chance
+ * to be processed.
+ *
+ * File preconditions cannot be passed to this function. It will not retry unless
+ * the idempotency strategy is set to retry always.
+ *
+ * The `query` object passed as the first argument will also be passed to
+ * {@link Bucket#getFiles}.
+ *
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/delete| Objects: delete API Documentation}
+ *
+ * @param {DeleteFilesOptions} [query] Query object. See {@link Bucket#getFiles}
+ * @param {boolean} [query.force] Suppress errors until all files have been
+ * processed.
+ * @param {DeleteFilesCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ *
+ * //-
+ * // Delete all of the files in the bucket.
+ * //-
+ * bucket.deleteFiles(function(err) {});
+ *
+ * //-
+ * // By default, if a file cannot be deleted, this method will stop deleting
+ * // files from your bucket. You can override this setting with `force:
+ * // true`.
+ * //-
+ * bucket.deleteFiles({
+ * force: true
+ * }, function(errors) {
+ * // `errors`:
+ * // Array of errors if any occurred, otherwise null.
+ * });
+ *
+ * //-
+ * // The first argument to this method acts as a query to
+ * // {@link Bucket#getFiles}. As an example, you can delete files
+ * // which match a prefix.
+ * //-
+ * bucket.deleteFiles({
+ * prefix: 'images/'
+ * }, function(err) {
+ * if (!err) {
+ * // All files in the `images` directory have been deleted.
+ * }
+ * });
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.deleteFiles().then(function() {});
+ * ```
+ */
+ deleteFiles(queryOrCallback, callback) {
+ let query = {};
+ if (typeof queryOrCallback === 'function') {
+ callback = queryOrCallback;
+ }
+ else if (queryOrCallback) {
+ query = queryOrCallback;
+ }
+ const MAX_PARALLEL_LIMIT = 10;
+ const MAX_QUEUE_SIZE = 1000;
+ const errors = [];
+ const deleteFile = (file) => {
+ return file.delete(query).catch(err => {
+ if (!query.force) {
+ throw err;
+ }
+ errors.push(err);
+ });
+ };
+ (async () => {
+ try {
+ let promises = [];
+ const limit = (0, p_limit_1.default)(MAX_PARALLEL_LIMIT);
+ const filesStream = this.getFilesStream(query);
+ for await (const curFile of filesStream) {
+ if (promises.length >= MAX_QUEUE_SIZE) {
+ await Promise.all(promises);
+ promises = [];
+ }
+ promises.push(limit(() => deleteFile(curFile)).catch(e => {
+ filesStream.destroy();
+ throw e;
+ }));
+ }
+ await Promise.all(promises);
+ callback(errors.length > 0 ? errors : null);
+ }
+ catch (e) {
+ callback(e);
+ return;
+ }
+ })();
+ }
+ /**
+ * @deprecated
+ * @typedef {array} DeleteLabelsResponse
+ * @property {object} 0 The full API response.
+ */
+ /**
+ * @deprecated
+ * @callback DeleteLabelsCallback
+ * @param {?Error} err Request error, if any.
+ * @param {object} metadata Bucket's metadata.
+ */
+ /**
+ * @deprecated Use setMetadata directly
+ * Delete one or more labels from this bucket.
+ *
+ * @param {string|string[]} [labels] The labels to delete. If no labels are
+ * provided, all of the labels are removed.
+ * @param {DeleteLabelsCallback} [callback] Callback function.
+ * @param {DeleteLabelsOptions} [options] Options, including precondition options
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ *
+ * //-
+ * // Delete all of the labels from this bucket.
+ * //-
+ * bucket.deleteLabels(function(err, apiResponse) {});
+ *
+ * //-
+ * // Delete a single label.
+ * //-
+ * bucket.deleteLabels('labelone', function(err, apiResponse) {});
+ *
+ * //-
+ * // Delete a specific set of labels.
+ * //-
+ * bucket.deleteLabels([
+ * 'labelone',
+ * 'labeltwo'
+ * ], function(err, apiResponse) {});
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.deleteLabels().then(function(data) {
+ * const apiResponse = data[0];
+ * });
+ * ```
+ */
+ deleteLabels(labelsOrCallbackOrOptions, optionsOrCallback, callback) {
+ let labels = new Array();
+ let options = {};
+ if (typeof labelsOrCallbackOrOptions === 'function') {
+ callback = labelsOrCallbackOrOptions;
}
- const updateState = this.updateState;
- const isDone = this.isDone;
- if (!this.state.isCompleted && this.state.error === undefined) {
- await (0, operation_js_1.pollHttpOperation)({
- lro: this.lro,
- state: this.state,
- stateProxy,
- processResult: this.processResult,
- updateState: updateState
- ? (state, { rawResponse }) => updateState(state, rawResponse)
- : undefined,
- isDone: isDone
- ? ({ flatResponse }, state) => isDone(flatResponse, state)
- : undefined,
- options,
- setDelay: (intervalInMs) => {
- this.pollerConfig.intervalInMs = intervalInMs;
- },
- setErrorAsResult: this.setErrorAsResult,
+ else if (typeof labelsOrCallbackOrOptions === 'string') {
+ labels = [labelsOrCallbackOrOptions];
+ }
+ else if (Array.isArray(labelsOrCallbackOrOptions)) {
+ labels = labelsOrCallbackOrOptions;
+ }
+ else if (labelsOrCallbackOrOptions) {
+ options = labelsOrCallbackOrOptions;
+ }
+ if (typeof optionsOrCallback === 'function') {
+ callback = optionsOrCallback;
+ }
+ else if (optionsOrCallback) {
+ options = optionsOrCallback;
+ }
+ const deleteLabels = (labels) => {
+ const nullLabelMap = labels.reduce((nullLabelMap, labelKey) => {
+ nullLabelMap[labelKey] = null;
+ return nullLabelMap;
+ }, {});
+ if ((options === null || options === void 0 ? void 0 : options.ifMetagenerationMatch) !== undefined) {
+ this.setLabels(nullLabelMap, options, callback);
+ }
+ else {
+ this.setLabels(nullLabelMap, callback);
+ }
+ };
+ if (labels.length === 0) {
+ this.getLabels((err, labels) => {
+ if (err) {
+ callback(err);
+ return;
+ }
+ deleteLabels(Object.keys(labels));
});
}
- (_a = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _a === void 0 ? void 0 : _a.call(options, this.state);
- return this;
- }
- async cancel() {
- logger_js_1.logger.error("`cancelOperation` is deprecated because it wasn't implemented");
- return this;
+ else {
+ deleteLabels(labels);
+ }
}
/**
- * Serializes the Poller operation.
+ * @typedef {array} DisableRequesterPaysResponse
+ * @property {object} 0 The full API response.
*/
- toString() {
- return JSON.stringify({
- state: this.state,
- });
- }
-}
-exports.GenericPollOperation = GenericPollOperation;
-//# sourceMappingURL=operation.js.map
-
-/***/ }),
-
-/***/ 2670:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-//# sourceMappingURL=pollOperation.js.map
-
-/***/ }),
-
-/***/ 6272:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Poller = exports.PollerCancelledError = exports.PollerStoppedError = void 0;
-/**
- * When a poller is manually stopped through the `stopPolling` method,
- * the poller will be rejected with an instance of the PollerStoppedError.
- */
-class PollerStoppedError extends Error {
- constructor(message) {
- super(message);
- this.name = "PollerStoppedError";
- Object.setPrototypeOf(this, PollerStoppedError.prototype);
- }
-}
-exports.PollerStoppedError = PollerStoppedError;
-/**
- * When the operation is cancelled, the poller will be rejected with an instance
- * of the PollerCancelledError.
- */
-class PollerCancelledError extends Error {
- constructor(message) {
- super(message);
- this.name = "PollerCancelledError";
- Object.setPrototypeOf(this, PollerCancelledError.prototype);
+ /**
+ * @callback DisableRequesterPaysCallback
+ * @param {?Error} err Request error, if any.
+ * @param {object} apiResponse The full API response.
+ */
+ /**
+ *
+ *
Early Access Testers Only
+ *
+ * This feature is not yet widely-available.
+ *
+ *
+ *
+ * Disable `requesterPays` functionality from this bucket.
+ *
+ * @param {DisableRequesterPaysCallback} [callback] Callback function.
+ * @param {DisableRequesterPaysOptions} [options] Options, including precondition options
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ *
+ * bucket.disableRequesterPays(function(err, apiResponse) {
+ * if (!err) {
+ * // requesterPays functionality disabled successfully.
+ * }
+ * });
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.disableRequesterPays().then(function(data) {
+ * const apiResponse = data[0];
+ * });
+ *
+ * ```
+ * @example include:samples/requesterPays.js
+ * region_tag:storage_disable_requester_pays
+ * Example of disabling requester pays:
+ */
+ disableRequesterPays(optionsOrCallback, callback) {
+ let options = {};
+ if (typeof optionsOrCallback === 'function') {
+ callback = optionsOrCallback;
+ }
+ else if (optionsOrCallback) {
+ options = optionsOrCallback;
+ }
+ this.setMetadata({
+ billing: {
+ requesterPays: false,
+ },
+ }, options, callback);
}
-}
-exports.PollerCancelledError = PollerCancelledError;
-/**
- * A class that represents the definition of a program that polls through consecutive requests
- * until it reaches a state of completion.
- *
- * A poller can be executed manually, by polling request by request by calling to the `poll()` method repeatedly, until its operation is completed.
- * It also provides a way to wait until the operation completes, by calling `pollUntilDone()` and waiting until the operation finishes.
- * Pollers can also request the cancellation of the ongoing process to whom is providing the underlying long running operation.
- *
- * ```ts
- * const poller = new MyPoller();
- *
- * // Polling just once:
- * await poller.poll();
- *
- * // We can try to cancel the request here, by calling:
- * //
- * // await poller.cancelOperation();
- * //
- *
- * // Getting the final result:
- * const result = await poller.pollUntilDone();
- * ```
- *
- * The Poller is defined by two types, a type representing the state of the poller, which
- * must include a basic set of properties from `PollOperationState`,
- * and a return type defined by `TResult`, which can be anything.
- *
- * The Poller class implements the `PollerLike` interface, which allows poller implementations to avoid having
- * to export the Poller's class directly, and instead only export the already instantiated poller with the PollerLike type.
- *
- * ```ts
- * class Client {
- * public async makePoller: PollerLike {
- * const poller = new MyPoller({});
- * // It might be preferred to return the poller after the first request is made,
- * // so that some information can be obtained right away.
- * await poller.poll();
- * return poller;
- * }
- * }
- *
- * const poller: PollerLike = myClient.makePoller();
- * ```
- *
- * A poller can be created through its constructor, then it can be polled until it's completed.
- * At any point in time, the state of the poller can be obtained without delay through the getOperationState method.
- * At any point in time, the intermediate forms of the result type can be requested without delay.
- * Once the underlying operation is marked as completed, the poller will stop and the final value will be returned.
- *
- * ```ts
- * const poller = myClient.makePoller();
- * const state: MyOperationState = poller.getOperationState();
- *
- * // The intermediate result can be obtained at any time.
- * const result: MyResult | undefined = poller.getResult();
- *
- * // The final result can only be obtained after the poller finishes.
- * const result: MyResult = await poller.pollUntilDone();
- * ```
- *
- */
-// eslint-disable-next-line no-use-before-define
-class Poller {
/**
- * A poller needs to be initialized by passing in at least the basic properties of the `PollOperation`.
+ * Configuration object for enabling logging.
*
- * When writing an implementation of a Poller, this implementation needs to deal with the initialization
- * of any custom state beyond the basic definition of the poller. The basic poller assumes that the poller's
- * operation has already been defined, at least its basic properties. The code below shows how to approach
- * the definition of the constructor of a new custom poller.
+ * @typedef {object} EnableLoggingOptions
+ * @property {string|Bucket} [bucket] The bucket for the log entries. By
+ * default, the current bucket is used.
+ * @property {string} prefix A unique prefix for log object names.
+ */
+ /**
+ * Enable logging functionality for this bucket. This will make two API
+ * requests, first to grant Cloud Storage WRITE permission to the bucket, then
+ * to set the appropriate configuration on the Bucket's metadata.
*
- * ```ts
- * export class MyPoller extends Poller {
- * constructor({
- * // Anything you might need outside of the basics
- * }) {
- * let state: MyOperationState = {
- * privateProperty: private,
- * publicProperty: public,
- * };
+ * @param {EnableLoggingOptions} config Configuration options.
+ * @param {string|Bucket} [config.bucket] The bucket for the log entries. By
+ * default, the current bucket is used.
+ * @param {string} config.prefix A unique prefix for log object names.
+ * @param {SetBucketMetadataCallback} [callback] Callback function.
+ * @returns {Promise}
*
- * const operation = {
- * state,
- * update,
- * cancel,
- * toString
- * }
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
*
- * // Sending the operation to the parent's constructor.
- * super(operation);
+ * const config = {
+ * prefix: 'log'
+ * };
*
- * // You can assign more local properties here.
+ * bucket.enableLogging(config, function(err, apiResponse) {
+ * if (!err) {
+ * // Logging functionality enabled successfully.
* }
- * }
+ * });
+ *
+ * ```
+ * @example
+ * Optionally, provide a destination bucket.
* ```
+ * const config = {
+ * prefix: 'log',
+ * bucket: 'destination-bucket'
+ * };
*
- * Inside of this constructor, a new promise is created. This will be used to
- * tell the user when the poller finishes (see `pollUntilDone()`). The promise's
- * resolve and reject methods are also used internally to control when to resolve
- * or reject anyone waiting for the poller to finish.
+ * bucket.enableLogging(config, function(err, apiResponse) {});
+ * ```
*
- * The constructor of a custom implementation of a poller is where any serialized version of
- * a previous poller's operation should be deserialized into the operation sent to the
- * base constructor. For example:
+ * @example
+ * If the callback is omitted, we'll return a Promise.
+ * ```
+ * bucket.enableLogging(config).then(function(data) {
+ * const apiResponse = data[0];
+ * });
+ * ```
+ */
+ enableLogging(config, callback) {
+ if (!config ||
+ typeof config === 'function' ||
+ typeof config.prefix === 'undefined') {
+ throw new Error(BucketExceptionMessages.CONFIGURATION_OBJECT_PREFIX_REQUIRED);
+ }
+ let logBucket = this.id;
+ if (config.bucket && config.bucket instanceof Bucket) {
+ logBucket = config.bucket.id;
+ }
+ else if (config.bucket && typeof config.bucket === 'string') {
+ logBucket = config.bucket;
+ }
+ const options = {};
+ if (config === null || config === void 0 ? void 0 : config.ifMetagenerationMatch) {
+ options.ifMetagenerationMatch = config.ifMetagenerationMatch;
+ }
+ if (config === null || config === void 0 ? void 0 : config.ifMetagenerationNotMatch) {
+ options.ifMetagenerationNotMatch = config.ifMetagenerationNotMatch;
+ }
+ (async () => {
+ try {
+ const [policy] = await this.iam.getPolicy();
+ policy.bindings.push({
+ members: ['group:cloud-storage-analytics@google.com'],
+ role: 'roles/storage.objectCreator',
+ });
+ await this.iam.setPolicy(policy);
+ this.setMetadata({
+ logging: {
+ logBucket,
+ logObjectPrefix: config.prefix,
+ },
+ }, options, callback);
+ }
+ catch (e) {
+ callback(e);
+ return;
+ }
+ })();
+ }
+ /**
+ * @typedef {array} EnableRequesterPaysResponse
+ * @property {object} 0 The full API response.
+ */
+ /**
+ * @callback EnableRequesterPaysCallback
+ * @param {?Error} err Request error, if any.
+ * @param {object} apiResponse The full API response.
+ */
+ /**
+ *
+ *
Early Access Testers Only
+ *
+ * This feature is not yet widely-available.
+ *
+ *
*
- * ```ts
- * export class MyPoller extends Poller {
- * constructor(
- * baseOperation: string | undefined
- * ) {
- * let state: MyOperationState = {};
- * if (baseOperation) {
- * state = {
- * ...JSON.parse(baseOperation).state,
- * ...state
- * };
- * }
- * const operation = {
- * state,
- * // ...
- * }
- * super(operation);
- * }
- * }
+ * Enable `requesterPays` functionality for this bucket. This enables you, the
+ * bucket owner, to have the requesting user assume the charges for the access
+ * to your bucket and its contents.
+ *
+ * @param {EnableRequesterPaysCallback | EnableRequesterPaysOptions} [optionsOrCallback]
+ * Callback function or precondition options.
+ * @returns {Promise}
+ *
+ * @example
* ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
*
- * @param operation - Must contain the basic properties of `PollOperation`.
+ * bucket.enableRequesterPays(function(err, apiResponse) {
+ * if (!err) {
+ * // requesterPays functionality enabled successfully.
+ * }
+ * });
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.enableRequesterPays().then(function(data) {
+ * const apiResponse = data[0];
+ * });
+ *
+ * ```
+ * @example include:samples/requesterPays.js
+ * region_tag:storage_enable_requester_pays
+ * Example of enabling requester pays:
+ */
+ enableRequesterPays(optionsOrCallback, cb) {
+ let options = {};
+ if (typeof optionsOrCallback === 'function') {
+ cb = optionsOrCallback;
+ }
+ else if (optionsOrCallback) {
+ options = optionsOrCallback;
+ }
+ this.setMetadata({
+ billing: {
+ requesterPays: true,
+ },
+ }, options, cb);
+ }
+ /**
+ * Create a {@link File} object. See {@link File} to see how to handle
+ * the different use cases you may have.
+ *
+ * @param {string} name The name of the file in this bucket.
+ * @param {FileOptions} [options] Configuration options.
+ * @param {string|number} [options.generation] Only use a specific revision of
+ * this file.
+ * @param {string} [options.encryptionKey] A custom encryption key. See
+ * {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}.
+ * @param {string} [options.kmsKeyName] The name of the Cloud KMS key that will
+ * be used to encrypt the object. Must be in the format:
+ * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`.
+ * KMS key ring must use the same location as the bucket.
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for all requests made from File object.
+ * @returns {File}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ * const file = bucket.file('my-existing-file.png');
+ * ```
*/
- constructor(operation) {
- /** controls whether to throw an error if the operation failed or was canceled. */
- this.resolveOnUnsuccessful = false;
- this.stopped = true;
- this.pollProgressCallbacks = [];
- this.operation = operation;
- this.promise = new Promise((resolve, reject) => {
- this.resolve = resolve;
- this.reject = reject;
- });
- // This prevents the UnhandledPromiseRejectionWarning in node.js from being thrown.
- // The above warning would get thrown if `poller.poll` is called, it returns an error,
- // and pullUntilDone did not have a .catch or await try/catch on it's return value.
- this.promise.catch(() => {
- /* intentionally blank */
+ file(name, options) {
+ if (!name) {
+ throw Error(BucketExceptionMessages.SPECIFY_FILE_NAME);
+ }
+ return new file_js_1.File(this, name, options);
+ }
+ /**
+ * @typedef {array} GetFilesResponse
+ * @property {File[]} 0 Array of {@link File} instances.
+ * @param {object} nextQuery 1 A query object to receive more results.
+ * @param {object} apiResponse 2 The full API response.
+ */
+ /**
+ * @callback GetFilesCallback
+ * @param {?Error} err Request error, if any.
+ * @param {File[]} files Array of {@link File} instances.
+ * @param {object} nextQuery A query object to receive more results.
+ * @param {object} apiResponse The full API response.
+ */
+ /**
+ * Query object for listing files.
+ *
+ * @typedef {object} GetFilesOptions
+ * @property {boolean} [autoPaginate=true] Have pagination handled
+ * automatically.
+ * @property {string} [delimiter] Results will contain only objects whose
+ * names, aside from the prefix, do not contain delimiter. Objects whose
+ * names, aside from the prefix, contain delimiter will have their name
+ * truncated after the delimiter, returned in `apiResponse.prefixes`.
+ * Duplicate prefixes are omitted.
+ * @property {string} [endOffset] Filter results to objects whose names are
+ * lexicographically before endOffset. If startOffset is also set, the objects
+ * listed have names between startOffset (inclusive) and endOffset (exclusive).
+ * @property {boolean} [includeFoldersAsPrefixes] If true, includes folders and
+ * managed folders in the set of prefixes returned by the query. Only applicable if
+ * delimiter is set to / and autoPaginate is set to false.
+ * See: https://cloud.google.com/storage/docs/managed-folders
+ * @property {boolean} [includeTrailingDelimiter] If true, objects that end in
+ * exactly one instance of delimiter have their metadata included in items[]
+ * in addition to the relevant part of the object name appearing in prefixes[].
+ * @property {string} [prefix] Filter results to objects whose names begin
+ * with this prefix.
+ * @property {string} [matchGlob] A glob pattern used to filter results,
+ * for example foo*bar
+ * @property {number} [maxApiCalls] Maximum number of API calls to make.
+ * @property {number} [maxResults] Maximum number of items plus prefixes to
+ * return per call.
+ * Note: By default will handle pagination automatically
+ * if more than 1 page worth of results are requested per call.
+ * When `autoPaginate` is set to `false` the smaller of `maxResults`
+ * or 1 page of results will be returned per call.
+ * @property {string} [pageToken] A previously-returned page token
+ * representing part of the larger set of results to view.
+ * @property {boolean} [softDeleted] If true, only soft-deleted object versions will be
+ * listed as distinct results in order of generation number. Note `soft_deleted` and
+ * `versions` cannot be set to true simultaneously.
+ * @property {string} [startOffset] Filter results to objects whose names are
+ * lexicographically equal to or after startOffset. If endOffset is also set,
+ * the objects listed have names between startOffset (inclusive) and endOffset (exclusive).
+ * @property {string} [userProject] The ID of the project which will be
+ * billed for the request.
+ * @property {boolean} [versions] If true, returns File objects scoped to
+ * their versions.
+ */
+ /**
+ * Get {@link File} objects for the files currently in the bucket.
+ *
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/list| Objects: list API Documentation}
+ *
+ * @param {GetFilesOptions} [query] Query object for listing files.
+ * @param {boolean} [query.autoPaginate=true] Have pagination handled
+ * automatically.
+ * @param {string} [query.delimiter] Results will contain only objects whose
+ * names, aside from the prefix, do not contain delimiter. Objects whose
+ * names, aside from the prefix, contain delimiter will have their name
+ * truncated after the delimiter, returned in `apiResponse.prefixes`.
+ * Duplicate prefixes are omitted.
+ * @param {string} [query.endOffset] Filter results to objects whose names are
+ * lexicographically before endOffset. If startOffset is also set, the objects
+ * listed have names between startOffset (inclusive) and endOffset (exclusive).
+ * @param {boolean} [query.includeFoldersAsPrefixes] If true, includes folders and
+ * managed folders in the set of prefixes returned by the query. Only applicable if
+ * delimiter is set to / and autoPaginate is set to false.
+ * See: https://cloud.google.com/storage/docs/managed-folders
+ * @param {boolean} [query.includeTrailingDelimiter] If true, objects that end in
+ * exactly one instance of delimiter have their metadata included in items[]
+ * in addition to the relevant part of the object name appearing in prefixes[].
+ * @param {string} [query.prefix] Filter results to objects whose names begin
+ * with this prefix.
+ * @param {number} [query.maxApiCalls] Maximum number of API calls to make.
+ * @param {number} [query.maxResults] Maximum number of items plus prefixes to
+ * return per call.
+ * Note: By default will handle pagination automatically
+ * if more than 1 page worth of results are requested per call.
+ * When `autoPaginate` is set to `false` the smaller of `maxResults`
+ * or 1 page of results will be returned per call.
+ * @param {string} [query.pageToken] A previously-returned page token
+ * representing part of the larger set of results to view.
+ * @param {boolean} [query.softDeleted] If true, only soft-deleted object versions will be
+ * listed as distinct results in order of generation number. Note `soft_deleted` and
+ * `versions` cannot be set to true simultaneously.
+ * @param {string} [query.startOffset] Filter results to objects whose names are
+ * lexicographically equal to or after startOffset. If endOffset is also set,
+ * the objects listed have names between startOffset (inclusive) and endOffset (exclusive).
+ * @param {string} [query.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {boolean} [query.versions] If true, returns File objects scoped to
+ * their versions.
+ * @param {GetFilesCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ *
+ * bucket.getFiles(function(err, files) {
+ * if (!err) {
+ * // files is an array of File objects.
+ * }
+ * });
+ *
+ * //-
+ * // If your bucket has versioning enabled, you can get all of your files
+ * // scoped to their generation.
+ * //-
+ * bucket.getFiles({
+ * versions: true
+ * }, function(err, files) {
+ * // Each file is scoped to its generation.
+ * });
+ *
+ * //-
+ * // To control how many API requests are made and page through the results
+ * // manually, set `autoPaginate` to `false`.
+ * //-
+ * const callback = function(err, files, nextQuery, apiResponse) {
+ * if (nextQuery) {
+ * // More results exist.
+ * bucket.getFiles(nextQuery, callback);
+ * }
+ *
+ * // The `metadata` property is populated for you with the metadata at the
+ * // time of fetching.
+ * files[0].metadata;
+ *
+ * // However, in cases where you are concerned the metadata could have
+ * // changed, use the `getMetadata` method.
+ * files[0].getMetadata(function(err, metadata) {});
+ * };
+ *
+ * bucket.getFiles({
+ * autoPaginate: false
+ * }, callback);
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.getFiles().then(function(data) {
+ * const files = data[0];
+ * });
+ *
+ * ```
+ * @example
+ * Simulating a File System
With `autoPaginate: false`, it's possible to iterate over files which incorporate a common structure using a delimiter.
Consider the following remote objects:
- "a"
- "a/b/c/d"
- "b/d/e"
Using a delimiter of `/` will return a single file, "a".
`apiResponse.prefixes` will return the "sub-directories" that were found:
- "a/"
- "b/"
+ * ```
+ * bucket.getFiles({
+ * autoPaginate: false,
+ * delimiter: '/'
+ * }, function(err, files, nextQuery, apiResponse) {
+ * // files = [
+ * // {File} // File object for file "a"
+ * // ]
+ *
+ * // apiResponse.prefixes = [
+ * // 'a/',
+ * // 'b/'
+ * // ]
+ * });
+ * ```
+ *
+ * @example
+ * Using prefixes, it's now possible to simulate a file system with follow-up requests.
+ * ```
+ * bucket.getFiles({
+ * autoPaginate: false,
+ * delimiter: '/',
+ * prefix: 'a/'
+ * }, function(err, files, nextQuery, apiResponse) {
+ * // No files found within "directory" a.
+ * // files = []
+ *
+ * // However, a "sub-directory" was found.
+ * // This prefix can be used to continue traversing the "file system".
+ * // apiResponse.prefixes = [
+ * // 'a/b/'
+ * // ]
+ * });
+ * ```
+ *
+ * @example include:samples/files.js
+ * region_tag:storage_list_files
+ * Another example:
+ *
+ * @example include:samples/files.js
+ * region_tag:storage_list_files_with_prefix
+ * Example of listing files, filtered by a prefix:
+ */
+ getFiles(queryOrCallback, callback) {
+ let query = typeof queryOrCallback === 'object' ? queryOrCallback : {};
+ if (!callback) {
+ callback = queryOrCallback;
+ }
+ query = Object.assign({}, query);
+ if (query.fields &&
+ query.autoPaginate &&
+ !query.fields.includes('nextPageToken')) {
+ query.fields = `${query.fields},nextPageToken`;
+ }
+ this.request({
+ uri: '/o',
+ qs: query,
+ }, (err, resp) => {
+ if (err) {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ callback(err, null, null, resp);
+ return;
+ }
+ const itemsArray = resp.items ? resp.items : [];
+ const files = itemsArray.map((file) => {
+ const options = {};
+ if (query.fields) {
+ const fileInstance = file;
+ return fileInstance;
+ }
+ if (query.versions) {
+ options.generation = file.generation;
+ }
+ if (file.kmsKeyName) {
+ options.kmsKeyName = file.kmsKeyName;
+ }
+ const fileInstance = this.file(file.name, options);
+ fileInstance.metadata = file;
+ return fileInstance;
+ });
+ let nextQuery = null;
+ if (resp.nextPageToken) {
+ nextQuery = Object.assign({}, query, {
+ pageToken: resp.nextPageToken,
+ });
+ }
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ callback(null, files, nextQuery, resp);
});
}
/**
- * Starts a loop that will break only if the poller is done
- * or if the poller is stopped.
+ * @deprecated
+ * @typedef {object} GetLabelsOptions Configuration options for Bucket#getLabels().
+ * @param {string} [userProject] The ID of the project which will be
+ * billed for the request.
*/
- async startPolling(pollOptions = {}) {
- if (this.stopped) {
- this.stopped = false;
+ /**
+ * @deprecated
+ * @typedef {array} GetLabelsResponse
+ * @property {object} 0 Object of labels currently set on this bucket.
+ */
+ /**
+ * @deprecated
+ * @callback GetLabelsCallback
+ * @param {?Error} err Request error, if any.
+ * @param {object} labels Object of labels currently set on this bucket.
+ */
+ /**
+ * @deprecated Use getMetadata directly.
+ * Get the labels currently set on this bucket.
+ *
+ * @param {object} [options] Configuration options.
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {GetLabelsCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ *
+ * bucket.getLabels(function(err, labels) {
+ * if (err) {
+ * // Error handling omitted.
+ * }
+ *
+ * // labels = {
+ * // label: 'labelValue',
+ * // ...
+ * // }
+ * });
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.getLabels().then(function(data) {
+ * const labels = data[0];
+ * });
+ * ```
+ */
+ getLabels(optionsOrCallback, callback) {
+ let options = {};
+ if (typeof optionsOrCallback === 'function') {
+ callback = optionsOrCallback;
}
- while (!this.isStopped() && !this.isDone()) {
- await this.poll(pollOptions);
- await this.delay();
+ else if (optionsOrCallback) {
+ options = optionsOrCallback;
}
+ this.getMetadata(options, (err, metadata) => {
+ if (err) {
+ callback(err, null);
+ return;
+ }
+ callback(null, (metadata === null || metadata === void 0 ? void 0 : metadata.labels) || {});
+ });
}
/**
- * pollOnce does one polling, by calling to the update method of the underlying
- * poll operation to make any relevant change effective.
+ * @typedef {object} GetNotificationsOptions Configuration options for Bucket#getNotification().
+ * @property {string} [userProject] The ID of the project which will be
+ * billed for the request.
+ */
+ /**
+ * @callback GetNotificationsCallback
+ * @param {?Error} err Request error, if any.
+ * @param {Notification[]} notifications Array of {@link Notification}
+ * instances.
+ * @param {object} apiResponse The full API response.
+ */
+ /**
+ * @typedef {array} GetNotificationsResponse
+ * @property {Notification[]} 0 Array of {@link Notification} instances.
+ * @property {object} 1 The full API response.
+ */
+ /**
+ * Retrieves a list of notification subscriptions for a given bucket.
*
- * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/list| Notifications: list}
*
- * @param options - Optional properties passed to the operation's update method.
- */
- async pollOnce(options = {}) {
- if (!this.isDone()) {
- this.operation = await this.operation.update({
- abortSignal: options.abortSignal,
- fireProgress: this.fireProgress.bind(this),
+ * @param {GetNotificationsOptions} [options] Configuration options.
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {GetNotificationsCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('my-bucket');
+ *
+ * bucket.getNotifications(function(err, notifications, apiResponse) {
+ * if (!err) {
+ * // notifications is an array of Notification objects.
+ * }
+ * });
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.getNotifications().then(function(data) {
+ * const notifications = data[0];
+ * const apiResponse = data[1];
+ * });
+ *
+ * ```
+ * @example include:samples/listNotifications.js
+ * region_tag:storage_list_bucket_notifications
+ * Another example:
+ */
+ getNotifications(optionsOrCallback, callback) {
+ let options = {};
+ if (typeof optionsOrCallback === 'function') {
+ callback = optionsOrCallback;
+ }
+ else if (optionsOrCallback) {
+ options = optionsOrCallback;
+ }
+ this.request({
+ uri: '/notificationConfigs',
+ qs: options,
+ }, (err, resp) => {
+ if (err) {
+ callback(err, null, resp);
+ return;
+ }
+ const itemsArray = resp.items ? resp.items : [];
+ const notifications = itemsArray.map((notification) => {
+ const notificationInstance = this.notification(notification.id);
+ notificationInstance.metadata = notification;
+ return notificationInstance;
});
+ callback(null, notifications, resp);
+ });
+ }
+ /**
+ * @typedef {array} GetSignedUrlResponse
+ * @property {object} 0 The signed URL.
+ */
+ /**
+ * @callback GetSignedUrlCallback
+ * @param {?Error} err Request error, if any.
+ * @param {object} url The signed URL.
+ */
+ /**
+ * @typedef {object} GetBucketSignedUrlConfig
+ * @property {string} action Only listing objects within a bucket (HTTP: GET) is supported for bucket-level signed URLs.
+ * @property {*} expires A timestamp when this link will expire. Any value
+ * given is passed to `new Date()`.
+ * Note: 'v4' supports maximum duration of 7 days (604800 seconds) from now.
+ * @property {string} [version='v2'] The signing version to use, either
+ * 'v2' or 'v4'.
+ * @property {boolean} [virtualHostedStyle=false] Use virtual hosted-style
+ * URLs ('https://mybucket.storage.googleapis.com/...') instead of path-style
+ * ('https://storage.googleapis.com/mybucket/...'). Virtual hosted-style URLs
+ * should generally be preferred instaed of path-style URL.
+ * Currently defaults to `false` for path-style, although this may change in a
+ * future major-version release.
+ * @property {string} [cname] The cname for this bucket, i.e.,
+ * "https://cdn.example.com".
+ * See [reference]{@link https://cloud.google.com/storage/docs/access-control/signed-urls#example}
+ * @property {object} [extensionHeaders] If these headers are used, the
+ * server will check to make sure that the client provides matching
+ * values. See {@link https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers| Canonical extension headers}
+ * for the requirements of this feature, most notably:
+ * - The header name must be prefixed with `x-goog-`
+ * - The header name must be all lowercase
+ *
+ * Note: Multi-valued header passed as an array in the extensionHeaders
+ * object is converted into a string, delimited by `,` with
+ * no space. Requests made using the signed URL will need to
+ * delimit multi-valued headers using a single `,` as well, or
+ * else the server will report a mismatched signature.
+ * @property {object} [queryParams] Additional query parameters to include
+ * in the signed URL.
+ */
+ /**
+ * Get a signed URL to allow limited time access to a bucket.
+ *
+ * In Google Cloud Platform environments, such as Cloud Functions and App
+ * Engine, you usually don't provide a `keyFilename` or `credentials` during
+ * instantiation. In those environments, we call the
+ * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob| signBlob API}
+ * to create a signed URL. That API requires either the
+ * `https://www.googleapis.com/auth/iam` or
+ * `https://www.googleapis.com/auth/cloud-platform` scope, so be sure they are
+ * enabled.
+ *
+ * See {@link https://cloud.google.com/storage/docs/access-control/signed-urls| Signed URLs Reference}
+ *
+ * @throws {Error} if an expiration timestamp from the past is given.
+ *
+ * @param {GetBucketSignedUrlConfig} config Configuration object.
+ * @param {string} config.action Currently only supports "list" (HTTP: GET).
+ * @param {*} config.expires A timestamp when this link will expire. Any value
+ * given is passed to `new Date()`.
+ * Note: 'v4' supports maximum duration of 7 days (604800 seconds) from now.
+ * @param {string} [config.version='v2'] The signing version to use, either
+ * 'v2' or 'v4'.
+ * @param {boolean} [config.virtualHostedStyle=false] Use virtual hosted-style
+ * URLs ('https://mybucket.storage.googleapis.com/...') instead of path-style
+ * ('https://storage.googleapis.com/mybucket/...'). Virtual hosted-style URLs
+ * should generally be preferred instaed of path-style URL.
+ * Currently defaults to `false` for path-style, although this may change in a
+ * future major-version release.
+ * @param {string} [config.cname] The cname for this bucket, i.e.,
+ * "https://cdn.example.com".
+ * See [reference]{@link https://cloud.google.com/storage/docs/access-control/signed-urls#example}
+ * @param {object} [config.extensionHeaders] If these headers are used, the
+ * server will check to make sure that the client provides matching
+ * values. See {@link https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers| Canonical extension headers}
+ * for the requirements of this feature, most notably:
+ * - The header name must be prefixed with `x-goog-`
+ * - The header name must be all lowercase
+ *
+ * Note: Multi-valued header passed as an array in the extensionHeaders
+ * object is converted into a string, delimited by `,` with
+ * no space. Requests made using the signed URL will need to
+ * delimit multi-valued headers using a single `,` as well, or
+ * else the server will report a mismatched signature.
+ * @property {object} [config.queryParams] Additional query parameters to include
+ * in the signed URL.
+ * @param {GetSignedUrlCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const myBucket = storage.bucket('my-bucket');
+ *
+ * //-
+ * // Generate a URL that allows temporary access to list files in a bucket.
+ * //-
+ * const request = require('request');
+ *
+ * const config = {
+ * action: 'list',
+ * expires: '03-17-2025'
+ * };
+ *
+ * bucket.getSignedUrl(config, function(err, url) {
+ * if (err) {
+ * console.error(err);
+ * return;
+ * }
+ *
+ * // The bucket is now available to be listed from this URL.
+ * request(url, function(err, resp) {
+ * // resp.statusCode = 200
+ * });
+ * });
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.getSignedUrl(config).then(function(data) {
+ * const url = data[0];
+ * });
+ * ```
+ */
+ getSignedUrl(cfg, callback) {
+ const method = BucketActionToHTTPMethod[cfg.action];
+ const signConfig = {
+ method,
+ expires: cfg.expires,
+ version: cfg.version,
+ cname: cfg.cname,
+ extensionHeaders: cfg.extensionHeaders || {},
+ queryParams: cfg.queryParams || {},
+ host: cfg.host,
+ signingEndpoint: cfg.signingEndpoint,
+ };
+ if (!this.signer) {
+ this.signer = new signer_js_1.URLSigner(this.storage.authClient, this, undefined, this.storage);
}
- this.processUpdatedState();
+ this.signer
+ .getSignedUrl(signConfig)
+ .then(signedUrl => callback(null, signedUrl), callback);
}
/**
- * fireProgress calls the functions passed in via onProgress the method of the poller.
+ * @callback BucketLockCallback
+ * @param {?Error} err Request error, if any.
+ * @param {object} apiResponse The full API response.
+ */
+ /**
+ * Lock a previously-defined retention policy. This will prevent changes to
+ * the policy.
*
- * It loops over all of the callbacks received from onProgress, and executes them, sending them
- * the current operation state.
+ * @throws {Error} if a metageneration is not provided.
*
- * @param state - The current operation state.
+ * @param {number|string} metageneration The bucket's metageneration. This is
+ * accesssible from calling {@link File#getMetadata}.
+ * @param {BucketLockCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const storage = require('@google-cloud/storage')();
+ * const bucket = storage.bucket('albums');
+ *
+ * const metageneration = 2;
+ *
+ * bucket.lock(metageneration, function(err, apiResponse) {});
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.lock(metageneration).then(function(data) {
+ * const apiResponse = data[0];
+ * });
+ * ```
*/
- fireProgress(state) {
- for (const callback of this.pollProgressCallbacks) {
- callback(state);
+ lock(metageneration, callback) {
+ const metatype = typeof metageneration;
+ if (metatype !== 'number' && metatype !== 'string') {
+ throw new Error(BucketExceptionMessages.METAGENERATION_NOT_PROVIDED);
}
+ this.request({
+ method: 'POST',
+ uri: '/lockRetentionPolicy',
+ qs: {
+ ifMetagenerationMatch: metageneration,
+ },
+ }, callback);
}
/**
- * Invokes the underlying operation's cancel method.
+ * @typedef {object} RestoreOptions Options for Bucket#restore(). See an
+ * {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/restore#resource| Object resource}.
+ * @param {number} [generation] If present, selects a specific revision of this object.
+ * @param {string} [projection] Specifies the set of properties to return. If used, must be 'full' or 'noAcl'.
*/
- async cancelOnce(options = {}) {
- this.operation = await this.operation.cancel(options);
+ /**
+ * Restores a soft-deleted bucket
+ * @param {RestoreOptions} options Restore options.
+ * @returns {Promise}
+ */
+ async restore(options) {
+ const [bucket] = await this.request({
+ method: 'POST',
+ uri: '/restore',
+ qs: options,
+ });
+ return bucket;
}
/**
- * Returns a promise that will resolve once a single polling request finishes.
- * It does this by calling the update method of the Poller's operation.
+ * @typedef {array} MakeBucketPrivateResponse
+ * @property {File[]} 0 List of files made private.
+ */
+ /**
+ * @callback MakeBucketPrivateCallback
+ * @param {?Error} err Request error, if any.
+ * @param {File[]} files List of files made private.
+ */
+ /**
+ * @typedef {object} MakeBucketPrivateOptions
+ * @property {boolean} [includeFiles=false] Make each file in the bucket
+ * private.
+ * @property {Metadata} [metadata] Define custom metadata properties to define
+ * along with the operation.
+ * @property {boolean} [force] Queue errors occurred while making files
+ * private until all files have been processed.
+ * @property {string} [userProject] The ID of the project which will be
+ * billed for the request.
+ */
+ /**
+ * Make the bucket listing private.
*
- * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
+ * You may also choose to make the contents of the bucket private by
+ * specifying `includeFiles: true`. This will automatically run
+ * {@link File#makePrivate} for every file in the bucket.
*
- * @param options - Optional properties passed to the operation's update method.
+ * When specifying `includeFiles: true`, use `force: true` to delay execution
+ * of your callback until all files have been processed. By default, the
+ * callback is executed after the first error. Use `force` to queue such
+ * errors until all files have been processed, after which they will be
+ * returned as an array as the first argument to your callback.
+ *
+ * NOTE: This may cause the process to be long-running and use a high number
+ * of requests. Use with caution.
+ *
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch| Buckets: patch API Documentation}
+ *
+ * @param {MakeBucketPrivateOptions} [options] Configuration options.
+ * @param {boolean} [options.includeFiles=false] Make each file in the bucket
+ * private.
+ * @param {Metadata} [options.metadata] Define custom metadata properties to define
+ * along with the operation.
+ * @param {boolean} [options.force] Queue errors occurred while making files
+ * private until all files have been processed.
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {MakeBucketPrivateCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ *
+ * //-
+ * // Make the bucket private.
+ * //-
+ * bucket.makePrivate(function(err) {});
+ *
+ * //-
+ * // Make the bucket and its contents private.
+ * //-
+ * const opts = {
+ * includeFiles: true
+ * };
+ *
+ * bucket.makePrivate(opts, function(err, files) {
+ * // `err`:
+ * // The first error to occur, otherwise null.
+ * //
+ * // `files`:
+ * // Array of files successfully made private in the bucket.
+ * });
+ *
+ * //-
+ * // Make the bucket and its contents private, using force to suppress errors
+ * // until all files have been processed.
+ * //-
+ * const opts = {
+ * includeFiles: true,
+ * force: true
+ * };
+ *
+ * bucket.makePrivate(opts, function(errors, files) {
+ * // `errors`:
+ * // Array of errors if any occurred, otherwise null.
+ * //
+ * // `files`:
+ * // Array of files successfully made private in the bucket.
+ * });
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.makePrivate(opts).then(function(data) {
+ * const files = data[0];
+ * });
+ * ```
*/
- poll(options = {}) {
- if (!this.pollOncePromise) {
- this.pollOncePromise = this.pollOnce(options);
- const clearPollOncePromise = () => {
- this.pollOncePromise = undefined;
- };
- this.pollOncePromise.then(clearPollOncePromise, clearPollOncePromise).catch(this.reject);
+ makePrivate(optionsOrCallback, callback) {
+ var _a, _b, _c, _d;
+ const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
+ callback =
+ typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
+ options.private = true;
+ const query = {
+ predefinedAcl: 'projectPrivate',
+ };
+ if (options.userProject) {
+ query.userProject = options.userProject;
}
- return this.pollOncePromise;
- }
- processUpdatedState() {
- if (this.operation.state.error) {
- this.stopped = true;
- if (!this.resolveOnUnsuccessful) {
- this.reject(this.operation.state.error);
- throw this.operation.state.error;
- }
+ if ((_a = options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) {
+ query.ifGenerationMatch = options.preconditionOpts.ifGenerationMatch;
}
- if (this.operation.state.isCancelled) {
- this.stopped = true;
- if (!this.resolveOnUnsuccessful) {
- const error = new PollerCancelledError("Operation was canceled");
- this.reject(error);
- throw error;
- }
+ if ((_b = options.preconditionOpts) === null || _b === void 0 ? void 0 : _b.ifGenerationNotMatch) {
+ query.ifGenerationNotMatch =
+ options.preconditionOpts.ifGenerationNotMatch;
}
- if (this.isDone() && this.resolve) {
- // If the poller has finished polling, this means we now have a result.
- // However, it can be the case that TResult is instantiated to void, so
- // we are not expecting a result anyway. To assert that we might not
- // have a result eventually after finishing polling, we cast the result
- // to TResult.
- this.resolve(this.getResult());
+ if ((_c = options.preconditionOpts) === null || _c === void 0 ? void 0 : _c.ifMetagenerationMatch) {
+ query.ifMetagenerationMatch =
+ options.preconditionOpts.ifMetagenerationMatch;
+ }
+ if ((_d = options.preconditionOpts) === null || _d === void 0 ? void 0 : _d.ifMetagenerationNotMatch) {
+ query.ifMetagenerationNotMatch =
+ options.preconditionOpts.ifMetagenerationNotMatch;
}
+ // You aren't allowed to set both predefinedAcl & acl properties on a bucket
+ // so acl must explicitly be nullified.
+ const metadata = { ...options.metadata, acl: null };
+ this.setMetadata(metadata, query, (err) => {
+ if (err) {
+ callback(err);
+ }
+ const internalCall = () => {
+ if (options.includeFiles) {
+ return (0, util_1.promisify)(this.makeAllFilesPublicPrivate_).call(this, options);
+ }
+ return Promise.resolve([]);
+ };
+ internalCall()
+ .then(files => callback(null, files))
+ .catch(callback);
+ });
+ }
+ /**
+ * @typedef {object} MakeBucketPublicOptions
+ * @property {boolean} [includeFiles=false] Make each file in the bucket
+ * private.
+ * @property {boolean} [force] Queue errors occurred while making files
+ * private until all files have been processed.
+ */
+ /**
+ * @callback MakeBucketPublicCallback
+ * @param {?Error} err Request error, if any.
+ * @param {File[]} files List of files made public.
+ */
+ /**
+ * @typedef {array} MakeBucketPublicResponse
+ * @property {File[]} 0 List of files made public.
+ */
+ /**
+ * Make the bucket publicly readable.
+ *
+ * You may also choose to make the contents of the bucket publicly readable by
+ * specifying `includeFiles: true`. This will automatically run
+ * {@link File#makePublic} for every file in the bucket.
+ *
+ * When specifying `includeFiles: true`, use `force: true` to delay execution
+ * of your callback until all files have been processed. By default, the
+ * callback is executed after the first error. Use `force` to queue such
+ * errors until all files have been processed, after which they will be
+ * returned as an array as the first argument to your callback.
+ *
+ * NOTE: This may cause the process to be long-running and use a high number
+ * of requests. Use with caution.
+ *
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch| Buckets: patch API Documentation}
+ *
+ * @param {MakeBucketPublicOptions} [options] Configuration options.
+ * @param {boolean} [options.includeFiles=false] Make each file in the bucket
+ * private.
+ * @param {boolean} [options.force] Queue errors occurred while making files
+ * private until all files have been processed.
+ * @param {MakeBucketPublicCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ *
+ * //-
+ * // Make the bucket publicly readable.
+ * //-
+ * bucket.makePublic(function(err) {});
+ *
+ * //-
+ * // Make the bucket and its contents publicly readable.
+ * //-
+ * const opts = {
+ * includeFiles: true
+ * };
+ *
+ * bucket.makePublic(opts, function(err, files) {
+ * // `err`:
+ * // The first error to occur, otherwise null.
+ * //
+ * // `files`:
+ * // Array of files successfully made public in the bucket.
+ * });
+ *
+ * //-
+ * // Make the bucket and its contents publicly readable, using force to
+ * // suppress errors until all files have been processed.
+ * //-
+ * const opts = {
+ * includeFiles: true,
+ * force: true
+ * };
+ *
+ * bucket.makePublic(opts, function(errors, files) {
+ * // `errors`:
+ * // Array of errors if any occurred, otherwise null.
+ * //
+ * // `files`:
+ * // Array of files successfully made public in the bucket.
+ * });
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.makePublic(opts).then(function(data) {
+ * const files = data[0];
+ * });
+ * ```
+ */
+ makePublic(optionsOrCallback, callback) {
+ const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
+ callback =
+ typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
+ const req = { public: true, ...options };
+ this.acl
+ .add({
+ entity: 'allUsers',
+ role: 'READER',
+ })
+ .then(() => {
+ return this.acl.default.add({
+ entity: 'allUsers',
+ role: 'READER',
+ });
+ })
+ .then(() => {
+ if (req.includeFiles) {
+ return (0, util_1.promisify)(this.makeAllFilesPublicPrivate_).call(this, req);
+ }
+ return [];
+ })
+ .then(files => callback(null, files), callback);
}
/**
- * Returns a promise that will resolve once the underlying operation is completed.
+ * Get a reference to a Cloud Pub/Sub Notification.
+ *
+ * @param {string} id ID of notification.
+ * @returns {Notification}
+ * @see Notification
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('my-bucket');
+ * const notification = bucket.notification('1');
+ * ```
*/
- async pollUntilDone(pollOptions = {}) {
- if (this.stopped) {
- this.startPolling(pollOptions).catch(this.reject);
+ notification(id) {
+ if (!id) {
+ throw new Error(BucketExceptionMessages.SUPPLY_NOTIFICATION_ID);
}
- // This is needed because the state could have been updated by
- // `cancelOperation`, e.g. the operation is canceled or an error occurred.
- this.processUpdatedState();
- return this.promise;
+ return new notification_js_1.Notification(this, id);
}
/**
- * Invokes the provided callback after each polling is completed,
- * sending the current state of the poller's operation.
+ * Remove an already-existing retention policy from this bucket, if it is not
+ * locked.
*
- * It returns a method that can be used to stop receiving updates on the given callback function.
+ * @param {SetBucketMetadataCallback} [callback] Callback function.
+ * @param {SetBucketMetadataOptions} [options] Options, including precondition options
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const storage = require('@google-cloud/storage')();
+ * const bucket = storage.bucket('albums');
+ *
+ * bucket.removeRetentionPeriod(function(err, apiResponse) {});
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.removeRetentionPeriod().then(function(data) {
+ * const apiResponse = data[0];
+ * });
+ * ```
*/
- onProgress(callback) {
- this.pollProgressCallbacks.push(callback);
- return () => {
- this.pollProgressCallbacks = this.pollProgressCallbacks.filter((c) => c !== callback);
- };
+ removeRetentionPeriod(optionsOrCallback, callback) {
+ const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
+ callback =
+ typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
+ this.setMetadata({
+ retentionPolicy: null,
+ }, options, callback);
}
/**
- * Returns true if the poller has finished polling.
+ * Makes request and applies userProject query parameter if necessary.
+ *
+ * @private
+ *
+ * @param {object} reqOpts - The request options.
+ * @param {function} callback - The callback function.
*/
- isDone() {
- const state = this.operation.state;
- return Boolean(state.isCompleted || state.isCancelled || state.error);
+ request(reqOpts, callback) {
+ if (this.userProject && (!reqOpts.qs || !reqOpts.qs.userProject)) {
+ reqOpts.qs = { ...reqOpts.qs, userProject: this.userProject };
+ }
+ return super.request(reqOpts, callback);
}
/**
- * Stops the poller from continuing to poll.
+ * @deprecated
+ * @typedef {array} SetLabelsResponse
+ * @property {object} 0 The bucket metadata.
*/
- stopPolling() {
- if (!this.stopped) {
- this.stopped = true;
- if (this.reject) {
- this.reject(new PollerStoppedError("This poller is already stopped"));
- }
- }
- }
/**
- * Returns true if the poller is stopped.
+ * @deprecated
+ * @callback SetLabelsCallback
+ * @param {?Error} err Request error, if any.
+ * @param {object} metadata The bucket metadata.
*/
- isStopped() {
- return this.stopped;
- }
/**
- * Attempts to cancel the underlying operation.
+ * @deprecated
+ * @typedef {object} SetLabelsOptions Configuration options for Bucket#setLabels().
+ * @property {string} [userProject] The ID of the project which will be
+ * billed for the request.
+ */
+ /**
+ * @deprecated Use setMetadata directly.
+ * Set labels on the bucket.
*
- * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
+ * This makes an underlying call to {@link Bucket#setMetadata}, which
+ * is a PATCH request. This means an individual label can be overwritten, but
+ * unmentioned labels will not be touched.
*
- * If it's called again before it finishes, it will throw an error.
+ * @param {object} labels Labels to set on the bucket.
+ * @param {SetLabelsOptions} [options] Configuration options.
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {SetLabelsCallback} [callback] Callback function.
+ * @returns {Promise}
*
- * @param options - Optional properties passed to the operation's update method.
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ *
+ * const labels = {
+ * labelone: 'labelonevalue',
+ * labeltwo: 'labeltwovalue'
+ * };
+ *
+ * bucket.setLabels(labels, function(err, metadata) {
+ * if (!err) {
+ * // Labels set successfully.
+ * }
+ * });
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.setLabels(labels).then(function(data) {
+ * const metadata = data[0];
+ * });
+ * ```
*/
- cancelOperation(options = {}) {
- if (!this.cancelPromise) {
- this.cancelPromise = this.cancelOnce(options);
- }
- else if (options.abortSignal) {
- throw new Error("A cancel request is currently pending");
- }
- return this.cancelPromise;
+ setLabels(labels, optionsOrCallback, callback) {
+ const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
+ callback =
+ typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
+ callback = callback || index_js_1.util.noop;
+ this.setMetadata({ labels }, options, callback);
+ }
+ setMetadata(metadata, optionsOrCallback, cb) {
+ const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
+ cb =
+ typeof optionsOrCallback === 'function'
+ ? optionsOrCallback
+ : cb;
+ this.disableAutoRetryConditionallyIdempotent_(this.methods.setMetadata, AvailableServiceObjectMethods.setMetadata, options);
+ super
+ .setMetadata(metadata, options)
+ .then(resp => cb(null, ...resp))
+ .catch(cb)
+ .finally(() => {
+ this.storage.retryOptions.autoRetry = this.instanceRetryValue;
+ });
}
/**
- * Returns the state of the operation.
+ * Lock all objects contained in the bucket, based on their creation time. Any
+ * attempt to overwrite or delete objects younger than the retention period
+ * will result in a `PERMISSION_DENIED` error.
*
- * Even though TState will be the same type inside any of the methods of any extension of the Poller class,
- * implementations of the pollers can customize what's shared with the public by writing their own
- * version of the `getOperationState` method, and by defining two types, one representing the internal state of the poller
- * and a public type representing a safe to share subset of the properties of the internal state.
- * Their definition of getOperationState can then return their public type.
+ * An unlocked retention policy can be modified or removed from the bucket via
+ * {@link File#removeRetentionPeriod} and {@link File#setRetentionPeriod}. A
+ * locked retention policy cannot be removed or shortened in duration for the
+ * lifetime of the bucket. Attempting to remove or decrease period of a locked
+ * retention policy will result in a `PERMISSION_DENIED` error. You can still
+ * increase the policy.
*
- * Example:
+ * @param {*} duration In seconds, the minimum retention time for all objects
+ * contained in this bucket.
+ * @param {SetBucketMetadataCallback} [callback] Callback function.
+ * @param {SetBucketMetadataCallback} [options] Options, including precondition options.
+ * @returns {Promise}
*
- * ```ts
- * // Let's say we have our poller's operation state defined as:
- * interface MyOperationState extends PollOperationState {
- * privateProperty?: string;
- * publicProperty?: string;
- * }
+ * @example
+ * ```
+ * const storage = require('@google-cloud/storage')();
+ * const bucket = storage.bucket('albums');
*
- * // To allow us to have a true separation of public and private state, we have to define another interface:
- * interface PublicState extends PollOperationState {
- * publicProperty?: string;
- * }
+ * const DURATION_SECONDS = 15780000; // 6 months.
*
- * // Then, we define our Poller as follows:
- * export class MyPoller extends Poller {
- * // ... More content is needed here ...
+ * //-
+ * // Lock the objects in this bucket for 6 months.
+ * //-
+ * bucket.setRetentionPeriod(DURATION_SECONDS, function(err, apiResponse) {});
*
- * public getOperationState(): PublicState {
- * const state: PublicState = this.operation.state;
- * return {
- * // Properties from PollOperationState
- * isStarted: state.isStarted,
- * isCompleted: state.isCompleted,
- * isCancelled: state.isCancelled,
- * error: state.error,
- * result: state.result,
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.setRetentionPeriod(DURATION_SECONDS).then(function(data) {
+ * const apiResponse = data[0];
+ * });
+ * ```
+ */
+ setRetentionPeriod(duration, optionsOrCallback, callback) {
+ const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
+ callback =
+ typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
+ this.setMetadata({
+ retentionPolicy: {
+ retentionPeriod: duration.toString(),
+ },
+ }, options, callback);
+ }
+ /**
*
- * // The only other property needed by PublicState.
- * publicProperty: state.publicProperty
- * }
- * }
- * }
+ * @typedef {object} Cors
+ * @property {number} [maxAgeSeconds] The number of seconds the browser is
+ * allowed to make requests before it must repeat the preflight request.
+ * @property {string[]} [method] HTTP method allowed for cross origin resource
+ * sharing with this bucket.
+ * @property {string[]} [origin] an origin allowed for cross origin resource
+ * sharing with this bucket.
+ * @property {string[]} [responseHeader] A header allowed for cross origin
+ * resource sharing with this bucket.
+ */
+ /**
+ * This can be used to set the CORS configuration on the bucket.
+ *
+ * The configuration will be overwritten with the value passed into this.
+ *
+ * @param {Cors[]} corsConfiguration The new CORS configuration to set
+ * @param {number} [corsConfiguration.maxAgeSeconds] The number of seconds the browser is
+ * allowed to make requests before it must repeat the preflight request.
+ * @param {string[]} [corsConfiguration.method] HTTP method allowed for cross origin resource
+ * sharing with this bucket.
+ * @param {string[]} [corsConfiguration.origin] an origin allowed for cross origin resource
+ * sharing with this bucket.
+ * @param {string[]} [corsConfiguration.responseHeader] A header allowed for cross origin
+ * resource sharing with this bucket.
+ * @param {SetBucketMetadataCallback} [callback] Callback function.
+ * @param {SetBucketMetadataOptions} [options] Options, including precondition options.
+ * @returns {Promise}
+ *
+ * @example
* ```
+ * const storage = require('@google-cloud/storage')();
+ * const bucket = storage.bucket('albums');
*
- * You can see this in the tests of this repository, go to the file:
- * `../test/utils/testPoller.ts`
- * and look for the getOperationState implementation.
+ * const corsConfiguration = [{maxAgeSeconds: 3600}]; // 1 hour
+ * bucket.setCorsConfiguration(corsConfiguration);
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.setCorsConfiguration(corsConfiguration).then(function(data) {
+ * const apiResponse = data[0];
+ * });
+ * ```
*/
- getOperationState() {
- return this.operation.state;
+ setCorsConfiguration(corsConfiguration, optionsOrCallback, callback) {
+ const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
+ callback =
+ typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
+ this.setMetadata({
+ cors: corsConfiguration,
+ }, options, callback);
}
/**
- * Returns the result value of the operation,
- * regardless of the state of the poller.
- * It can return undefined or an incomplete form of the final TResult value
- * depending on the implementation.
+ * @typedef {object} SetBucketStorageClassOptions
+ * @property {string} [userProject] - The ID of the project which will be
+ * billed for the request.
*/
- getResult() {
- const state = this.operation.state;
- return state.result;
- }
/**
- * Returns a serialized version of the poller's operation
- * by invoking the operation's toString method.
+ * @callback SetBucketStorageClassCallback
+ * @param {?Error} err Request error, if any.
*/
- toString() {
- return this.operation.toString();
- }
-}
-exports.Poller = Poller;
-//# sourceMappingURL=poller.js.map
-
-/***/ }),
-
-/***/ 480:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.logger = void 0;
-const logger_1 = __nccwpck_require__(6515);
-/**
- * The `@azure/logger` configuration for this package.
- * @internal
- */
-exports.logger = (0, logger_1.createClientLogger)("core-lro");
-//# sourceMappingURL=logger.js.map
-
-/***/ }),
-
-/***/ 5044:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.terminalStates = exports.POLL_INTERVAL_IN_MS = void 0;
-/**
- * The default time interval to wait before sending the next polling request.
- */
-exports.POLL_INTERVAL_IN_MS = 2000;
-/**
- * The closed set of terminal states.
- */
-exports.terminalStates = ["succeeded", "canceled", "failed"];
-//# sourceMappingURL=constants.js.map
-
-/***/ }),
-
-/***/ 736:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.pollOperation = exports.initOperation = exports.deserializeState = void 0;
-const logger_js_1 = __nccwpck_require__(480);
-const constants_js_1 = __nccwpck_require__(5044);
-/**
- * Deserializes the state
- */
-function deserializeState(serializedState) {
- try {
- return JSON.parse(serializedState).state;
- }
- catch (e) {
- throw new Error(`Unable to deserialize input state: ${serializedState}`);
- }
-}
-exports.deserializeState = deserializeState;
-function setStateError(inputs) {
- const { state, stateProxy, isOperationError } = inputs;
- return (error) => {
- if (isOperationError(error)) {
- stateProxy.setError(state, error);
- stateProxy.setFailed(state);
- }
- throw error;
- };
-}
-function appendReadableErrorMessage(currentMessage, innerMessage) {
- let message = currentMessage;
- if (message.slice(-1) !== ".") {
- message = message + ".";
- }
- return message + " " + innerMessage;
-}
-function simplifyError(err) {
- let message = err.message;
- let code = err.code;
- let curErr = err;
- while (curErr.innererror) {
- curErr = curErr.innererror;
- code = curErr.code;
- message = appendReadableErrorMessage(message, curErr.message);
- }
- return {
- code,
- message,
- };
-}
-function processOperationStatus(result) {
- const { state, stateProxy, status, isDone, processResult, getError, response, setErrorAsResult } = result;
- switch (status) {
- case "succeeded": {
- stateProxy.setSucceeded(state);
- break;
- }
- case "failed": {
- const err = getError === null || getError === void 0 ? void 0 : getError(response);
- let postfix = "";
- if (err) {
- const { code, message } = simplifyError(err);
- postfix = `. ${code}. ${message}`;
- }
- const errStr = `The long-running operation has failed${postfix}`;
- stateProxy.setError(state, new Error(errStr));
- stateProxy.setFailed(state);
- logger_js_1.logger.warning(errStr);
- break;
- }
- case "canceled": {
- stateProxy.setCanceled(state);
- break;
- }
- }
- if ((isDone === null || isDone === void 0 ? void 0 : isDone(response, state)) ||
- (isDone === undefined &&
- ["succeeded", "canceled"].concat(setErrorAsResult ? [] : ["failed"]).includes(status))) {
- stateProxy.setResult(state, buildResult({
- response,
- state,
- processResult,
- }));
- }
-}
-function buildResult(inputs) {
- const { processResult, response, state } = inputs;
- return processResult ? processResult(response, state) : response;
-}
-/**
- * Initiates the long-running operation.
- */
-async function initOperation(inputs) {
- const { init, stateProxy, processResult, getOperationStatus, withOperationLocation, setErrorAsResult, } = inputs;
- const { operationLocation, resourceLocation, metadata, response } = await init();
- if (operationLocation)
- withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false);
- const config = {
- metadata,
- operationLocation,
- resourceLocation,
- };
- logger_js_1.logger.verbose(`LRO: Operation description:`, config);
- const state = stateProxy.initState(config);
- const status = getOperationStatus({ response, state, operationLocation });
- processOperationStatus({ state, status, stateProxy, response, setErrorAsResult, processResult });
- return state;
-}
-exports.initOperation = initOperation;
-async function pollOperationHelper(inputs) {
- const { poll, state, stateProxy, operationLocation, getOperationStatus, getResourceLocation, isOperationError, options, } = inputs;
- const response = await poll(operationLocation, options).catch(setStateError({
- state,
- stateProxy,
- isOperationError,
- }));
- const status = getOperationStatus(response, state);
- logger_js_1.logger.verbose(`LRO: Status:\n\tPolling from: ${state.config.operationLocation}\n\tOperation status: ${status}\n\tPolling status: ${constants_js_1.terminalStates.includes(status) ? "Stopped" : "Running"}`);
- if (status === "succeeded") {
- const resourceLocation = getResourceLocation(response, state);
- if (resourceLocation !== undefined) {
- return {
- response: await poll(resourceLocation).catch(setStateError({ state, stateProxy, isOperationError })),
- status,
- };
- }
- }
- return { response, status };
-}
-/** Polls the long-running operation. */
-async function pollOperation(inputs) {
- const { poll, state, stateProxy, options, getOperationStatus, getResourceLocation, getOperationLocation, isOperationError, withOperationLocation, getPollingInterval, processResult, getError, updateState, setDelay, isDone, setErrorAsResult, } = inputs;
- const { operationLocation } = state.config;
- if (operationLocation !== undefined) {
- const { response, status } = await pollOperationHelper({
- poll,
- getOperationStatus,
- state,
- stateProxy,
- operationLocation,
- getResourceLocation,
- isOperationError,
- options,
- });
- processOperationStatus({
- status,
- response,
- state,
- stateProxy,
- isDone,
- processResult,
- getError,
- setErrorAsResult,
- });
- if (!constants_js_1.terminalStates.includes(status)) {
- const intervalInMs = getPollingInterval === null || getPollingInterval === void 0 ? void 0 : getPollingInterval(response);
- if (intervalInMs)
- setDelay(intervalInMs);
- const location = getOperationLocation === null || getOperationLocation === void 0 ? void 0 : getOperationLocation(response, state);
- if (location !== undefined) {
- const isUpdated = operationLocation !== location;
- state.config.operationLocation = location;
- withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(location, isUpdated);
- }
- else
- withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false);
- }
- updateState === null || updateState === void 0 ? void 0 : updateState(state, response);
+ /**
+ * Set the default storage class for new files in this bucket.
+ *
+ * See {@link https://cloud.google.com/storage/docs/storage-classes| Storage Classes}
+ *
+ * @param {string} storageClass The new storage class. (`standard`,
+ * `nearline`, `coldline`, or `archive`).
+ * **Note:** The storage classes `multi_regional`, `regional`, and
+ * `durable_reduced_availability` are now legacy and will be deprecated in
+ * the future.
+ * @param {object} [options] Configuration options.
+ * @param {string} [options.userProject] - The ID of the project which will be
+ * billed for the request.
+ * @param {SetStorageClassCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ *
+ * bucket.setStorageClass('nearline', function(err, apiResponse) {
+ * if (err) {
+ * // Error handling omitted.
+ * }
+ *
+ * // The storage class was updated successfully.
+ * });
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.setStorageClass('nearline').then(function() {});
+ * ```
+ */
+ setStorageClass(storageClass, optionsOrCallback, callback) {
+ const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
+ callback =
+ typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
+ // In case we get input like `storageClass`, convert to `storage_class`.
+ storageClass = storageClass
+ .replace(/-/g, '_')
+ .replace(/([a-z])([A-Z])/g, (_, low, up) => {
+ return low + '_' + up;
+ })
+ .toUpperCase();
+ this.setMetadata({ storageClass }, options, callback);
}
-}
-exports.pollOperation = pollOperation;
-//# sourceMappingURL=operation.js.map
-
-/***/ }),
-
-/***/ 8835:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.buildCreatePoller = void 0;
-const operation_js_1 = __nccwpck_require__(736);
-const constants_js_1 = __nccwpck_require__(5044);
-const core_util_1 = __nccwpck_require__(7779);
-const createStateProxy = () => ({
/**
- * The state at this point is created to be of type OperationState.
- * It will be updated later to be of type TState when the
- * customer-provided callback, `updateState`, is called during polling.
+ * Set a user project to be billed for all requests made from this Bucket
+ * object and any files referenced from this Bucket object.
+ *
+ * @param {string} userProject The user project.
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ *
+ * bucket.setUserProject('grape-spaceship-123');
+ * ```
*/
- initState: (config) => ({ status: "running", config }),
- setCanceled: (state) => (state.status = "canceled"),
- setError: (state, error) => (state.error = error),
- setResult: (state, result) => (state.result = result),
- setRunning: (state) => (state.status = "running"),
- setSucceeded: (state) => (state.status = "succeeded"),
- setFailed: (state) => (state.status = "failed"),
- getError: (state) => state.error,
- getResult: (state) => state.result,
- isCanceled: (state) => state.status === "canceled",
- isFailed: (state) => state.status === "failed",
- isRunning: (state) => state.status === "running",
- isSucceeded: (state) => state.status === "succeeded",
-});
-/**
- * Returns a poller factory.
- */
-function buildCreatePoller(inputs) {
- const { getOperationLocation, getStatusFromInitialResponse, getStatusFromPollResponse, isOperationError, getResourceLocation, getPollingInterval, getError, resolveOnUnsuccessful, } = inputs;
- return async ({ init, poll }, options) => {
- const { processResult, updateState, withOperationLocation: withOperationLocationCallback, intervalInMs = constants_js_1.POLL_INTERVAL_IN_MS, restoreFrom, } = options || {};
- const stateProxy = createStateProxy();
- const withOperationLocation = withOperationLocationCallback
- ? (() => {
- let called = false;
- return (operationLocation, isUpdated) => {
- if (isUpdated)
- withOperationLocationCallback(operationLocation);
- else if (!called)
- withOperationLocationCallback(operationLocation);
- called = true;
- };
- })()
- : undefined;
- const state = restoreFrom
- ? (0, operation_js_1.deserializeState)(restoreFrom)
- : await (0, operation_js_1.initOperation)({
- init,
- stateProxy,
- processResult,
- getOperationStatus: getStatusFromInitialResponse,
- withOperationLocation,
- setErrorAsResult: !resolveOnUnsuccessful,
- });
- let resultPromise;
- const abortController = new AbortController();
- const handlers = new Map();
- const handleProgressEvents = async () => handlers.forEach((h) => h(state));
- const cancelErrMsg = "Operation was canceled";
- let currentPollIntervalInMs = intervalInMs;
- const poller = {
- getOperationState: () => state,
- getResult: () => state.result,
- isDone: () => ["succeeded", "failed", "canceled"].includes(state.status),
- isStopped: () => resultPromise === undefined,
- stopPolling: () => {
- abortController.abort();
- },
- toString: () => JSON.stringify({
- state,
- }),
- onProgress: (callback) => {
- const s = Symbol();
- handlers.set(s, callback);
- return () => handlers.delete(s);
- },
- pollUntilDone: (pollOptions) => (resultPromise !== null && resultPromise !== void 0 ? resultPromise : (resultPromise = (async () => {
- const { abortSignal: inputAbortSignal } = pollOptions || {};
- // In the future we can use AbortSignal.any() instead
- function abortListener() {
- abortController.abort();
- }
- const abortSignal = abortController.signal;
- if (inputAbortSignal === null || inputAbortSignal === void 0 ? void 0 : inputAbortSignal.aborted) {
- abortController.abort();
- }
- else if (!abortSignal.aborted) {
- inputAbortSignal === null || inputAbortSignal === void 0 ? void 0 : inputAbortSignal.addEventListener("abort", abortListener, { once: true });
- }
- try {
- if (!poller.isDone()) {
- await poller.poll({ abortSignal });
- while (!poller.isDone()) {
- await (0, core_util_1.delay)(currentPollIntervalInMs, { abortSignal });
- await poller.poll({ abortSignal });
- }
- }
- }
- finally {
- inputAbortSignal === null || inputAbortSignal === void 0 ? void 0 : inputAbortSignal.removeEventListener("abort", abortListener);
- }
- if (resolveOnUnsuccessful) {
- return poller.getResult();
+ setUserProject(userProject) {
+ this.userProject = userProject;
+ const methods = [
+ 'create',
+ 'delete',
+ 'exists',
+ 'get',
+ 'getMetadata',
+ 'setMetadata',
+ ];
+ methods.forEach(method => {
+ const methodConfig = this.methods[method];
+ if (typeof methodConfig === 'object') {
+ if (typeof methodConfig.reqOpts === 'object') {
+ Object.assign(methodConfig.reqOpts.qs, { userProject });
}
else {
- switch (state.status) {
- case "succeeded":
- return poller.getResult();
- case "canceled":
- throw new Error(cancelErrMsg);
- case "failed":
- throw state.error;
- case "notStarted":
- case "running":
- throw new Error(`Polling completed without succeeding or failing`);
+ methodConfig.reqOpts = {
+ qs: { userProject },
+ };
+ }
+ }
+ });
+ }
+ /**
+ * @typedef {object} UploadOptions Configuration options for Bucket#upload().
+ * @property {string|File} [destination] The place to save
+ * your file. If given a string, the file will be uploaded to the bucket
+ * using the string as a filename. When given a File object, your local
+ * file will be uploaded to the File object's bucket and under the File
+ * object's name. Lastly, when this argument is omitted, the file is uploaded
+ * to your bucket using the name of the local file.
+ * @property {string} [encryptionKey] A custom encryption key. See
+ * {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}.
+ * @property {boolean} [gzip] Automatically gzip the file. This will set
+ * `options.metadata.contentEncoding` to `gzip`.
+ * @property {string} [kmsKeyName] The name of the Cloud KMS key that will
+ * be used to encrypt the object. Must be in the format:
+ * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`.
+ * @property {object} [metadata] See an
+ * {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON| Objects: insert request body}.
+ * @property {string} [offset] The starting byte of the upload stream, for
+ * resuming an interrupted upload. Defaults to 0.
+ * @property {string} [predefinedAcl] Apply a predefined set of access
+ * controls to this object.
+ *
+ * Acceptable values are:
+ * - **`authenticatedRead`** - Object owner gets `OWNER` access, and
+ * `allAuthenticatedUsers` get `READER` access.
+ *
+ * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and
+ * project team owners get `OWNER` access.
+ *
+ * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project
+ * team owners get `READER` access.
+ *
+ * - **`private`** - Object owner gets `OWNER` access.
+ *
+ * - **`projectPrivate`** - Object owner gets `OWNER` access, and project
+ * team members get access according to their roles.
+ *
+ * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers`
+ * get `READER` access.
+ * @property {boolean} [private] Make the uploaded file private. (Alias for
+ * `options.predefinedAcl = 'private'`)
+ * @property {boolean} [public] Make the uploaded file public. (Alias for
+ * `options.predefinedAcl = 'publicRead'`)
+ * @property {boolean} [resumable=true] Resumable uploads are automatically
+ * enabled and must be shut off explicitly by setting to false.
+ * @property {number} [timeout=60000] Set the HTTP request timeout in
+ * milliseconds. This option is not available for resumable uploads.
+ * Default: `60000`
+ * @property {string} [uri] The URI for an already-created resumable
+ * upload. See {@link File#createResumableUpload}.
+ * @property {string} [userProject] The ID of the project which will be
+ * billed for the request.
+ * @property {string|boolean} [validation] Possible values: `"md5"`,
+ * `"crc32c"`, or `false`. By default, data integrity is validated with an
+ * MD5 checksum for maximum reliability. CRC32c will provide better
+ * performance with less reliability. You may also choose to skip
+ * validation completely, however this is **not recommended**.
+ */
+ /**
+ * @typedef {array} UploadResponse
+ * @property {object} 0 The uploaded {@link File}.
+ * @property {object} 1 The full API response.
+ */
+ /**
+ * @callback UploadCallback
+ * @param {?Error} err Request error, if any.
+ * @param {object} file The uploaded {@link File}.
+ * @param {object} apiResponse The full API response.
+ */
+ /**
+ * Upload a file to the bucket. This is a convenience method that wraps
+ * {@link File#createWriteStream}.
+ *
+ * Resumable uploads are enabled by default
+ *
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload#uploads| Upload Options (Simple or Resumable)}
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert| Objects: insert API Documentation}
+ *
+ * @param {string} pathString The fully qualified path to the file you
+ * wish to upload to your bucket.
+ * @param {UploadOptions} [options] Configuration options.
+ * @param {string|File} [options.destination] The place to save
+ * your file. If given a string, the file will be uploaded to the bucket
+ * using the string as a filename. When given a File object, your local
+ * file will be uploaded to the File object's bucket and under the File
+ * object's name. Lastly, when this argument is omitted, the file is uploaded
+ * to your bucket using the name of the local file.
+ * @param {string} [options.encryptionKey] A custom encryption key. See
+ * {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}.
+ * @param {boolean} [options.gzip] Automatically gzip the file. This will set
+ * `options.metadata.contentEncoding` to `gzip`.
+ * @param {string} [options.kmsKeyName] The name of the Cloud KMS key that will
+ * be used to encrypt the object. Must be in the format:
+ * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`.
+ * @param {object} [options.metadata] See an
+ * {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON| Objects: insert request body}.
+ * @param {string} [options.offset] The starting byte of the upload stream, for
+ * resuming an interrupted upload. Defaults to 0.
+ * @param {string} [options.predefinedAcl] Apply a predefined set of access
+ * controls to this object.
+ * Acceptable values are:
+ * - **`authenticatedRead`** - Object owner gets `OWNER` access, and
+ * `allAuthenticatedUsers` get `READER` access.
+ *
+ * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and
+ * project team owners get `OWNER` access.
+ *
+ * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project
+ * team owners get `READER` access.
+ *
+ * - **`private`** - Object owner gets `OWNER` access.
+ *
+ * - **`projectPrivate`** - Object owner gets `OWNER` access, and project
+ * team members get access according to their roles.
+ *
+ * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers`
+ * get `READER` access.
+ * @param {boolean} [options.private] Make the uploaded file private. (Alias for
+ * `options.predefinedAcl = 'private'`)
+ * @param {boolean} [options.public] Make the uploaded file public. (Alias for
+ * `options.predefinedAcl = 'publicRead'`)
+ * @param {boolean} [options.resumable=true] Resumable uploads are automatically
+ * enabled and must be shut off explicitly by setting to false.
+ * @param {number} [options.timeout=60000] Set the HTTP request timeout in
+ * milliseconds. This option is not available for resumable uploads.
+ * Default: `60000`
+ * @param {string} [options.uri] The URI for an already-created resumable
+ * upload. See {@link File#createResumableUpload}.
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {string|boolean} [options.validation] Possible values: `"md5"`,
+ * `"crc32c"`, or `false`. By default, data integrity is validated with an
+ * MD5 checksum for maximum reliability. CRC32c will provide better
+ * performance with less reliability. You may also choose to skip
+ * validation completely, however this is **not recommended**.
+ * @param {UploadCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const bucket = storage.bucket('albums');
+ *
+ * //-
+ * // Upload a file from a local path.
+ * //-
+ * bucket.upload('/local/path/image.png', function(err, file, apiResponse) {
+ * // Your bucket now contains:
+ * // - "image.png" (with the contents of `/local/path/image.png')
+ *
+ * // `file` is an instance of a File object that refers to your new file.
+ * });
+ *
+ *
+ * //-
+ * // It's not always that easy. You will likely want to specify the filename
+ * // used when your new file lands in your bucket.
+ * //
+ * // You may also want to set metadata or customize other options.
+ * //-
+ * const options = {
+ * destination: 'new-image.png',
+ * validation: 'crc32c',
+ * metadata: {
+ * metadata: {
+ * event: 'Fall trip to the zoo'
+ * }
+ * }
+ * };
+ *
+ * bucket.upload('local-image.png', options, function(err, file) {
+ * // Your bucket now contains:
+ * // - "new-image.png" (with the contents of `local-image.png')
+ *
+ * // `file` is an instance of a File object that refers to your new file.
+ * });
+ *
+ * //-
+ * // You can also have a file gzip'd on the fly.
+ * //-
+ * bucket.upload('index.html', { gzip: true }, function(err, file) {
+ * // Your bucket now contains:
+ * // - "index.html" (automatically compressed with gzip)
+ *
+ * // Downloading the file with `file.download` will automatically decode
+ * the
+ * // file.
+ * });
+ *
+ * //-
+ * // You may also re-use a File object, {File}, that references
+ * // the file you wish to create or overwrite.
+ * //-
+ * const options = {
+ * destination: bucket.file('existing-file.png'),
+ * resumable: false
+ * };
+ *
+ * bucket.upload('local-img.png', options, function(err, newFile) {
+ * // Your bucket now contains:
+ * // - "existing-file.png" (with the contents of `local-img.png')
+ *
+ * // Note:
+ * // The `newFile` parameter is equal to `file`.
+ * });
+ *
+ * //-
+ * // To use
+ * //
+ * // Customer-supplied Encryption Keys, provide the `encryptionKey`
+ * option.
+ * //-
+ * const crypto = require('crypto');
+ * const encryptionKey = crypto.randomBytes(32);
+ *
+ * bucket.upload('img.png', {
+ * encryptionKey: encryptionKey
+ * }, function(err, newFile) {
+ * // `img.png` was uploaded with your custom encryption key.
+ *
+ * // `newFile` is already configured to use the encryption key when making
+ * // operations on the remote object.
+ *
+ * // However, to use your encryption key later, you must create a `File`
+ * // instance with the `key` supplied:
+ * const file = bucket.file('img.png', {
+ * encryptionKey: encryptionKey
+ * });
+ *
+ * // Or with `file#setEncryptionKey`:
+ * const file = bucket.file('img.png');
+ * file.setEncryptionKey(encryptionKey);
+ * });
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * bucket.upload('local-image.png').then(function(data) {
+ * const file = data[0];
+ * });
+ *
+ * To upload a file from a URL, use {@link File#createWriteStream}.
+ *
+ * ```
+ * @example include:samples/files.js
+ * region_tag:storage_upload_file
+ * Another example:
+ *
+ * @example include:samples/encryption.js
+ * region_tag:storage_upload_encrypted_file
+ * Example of uploading an encrypted file:
+ */
+ upload(pathString, optionsOrCallback, callback) {
+ var _a, _b;
+ const upload = (numberOfRetries) => {
+ const returnValue = (0, async_retry_1.default)(async (bail) => {
+ await new Promise((resolve, reject) => {
+ var _a, _b;
+ if (numberOfRetries === 0 &&
+ ((_b = (_a = newFile === null || newFile === void 0 ? void 0 : newFile.storage) === null || _a === void 0 ? void 0 : _a.retryOptions) === null || _b === void 0 ? void 0 : _b.autoRetry)) {
+ newFile.storage.retryOptions.autoRetry = false;
}
- }
- })().finally(() => {
- resultPromise = undefined;
- }))),
- async poll(pollOptions) {
- if (resolveOnUnsuccessful) {
- if (poller.isDone())
- return;
- }
- else {
- switch (state.status) {
- case "succeeded":
- return;
- case "canceled":
- throw new Error(cancelErrMsg);
- case "failed":
- throw state.error;
+ const writable = newFile.createWriteStream(options);
+ if (options.onUploadProgress) {
+ writable.on('progress', options.onUploadProgress);
}
- }
- await (0, operation_js_1.pollOperation)({
- poll,
- state,
- stateProxy,
- getOperationLocation,
- isOperationError,
- withOperationLocation,
- getPollingInterval,
- getOperationStatus: getStatusFromPollResponse,
- getResourceLocation,
- processResult,
- getError,
- updateState,
- options: pollOptions,
- setDelay: (pollIntervalInMs) => {
- currentPollIntervalInMs = pollIntervalInMs;
- },
- setErrorAsResult: !resolveOnUnsuccessful,
+ fs.createReadStream(pathString)
+ .on('error', bail)
+ .pipe(writable)
+ .on('error', err => {
+ if (this.storage.retryOptions.autoRetry &&
+ this.storage.retryOptions.retryableErrorFn(err)) {
+ return reject(err);
+ }
+ else {
+ return bail(err);
+ }
+ })
+ .on('finish', () => {
+ return resolve();
+ });
});
- await handleProgressEvents();
- if (!resolveOnUnsuccessful) {
- switch (state.status) {
- case "canceled":
- throw new Error(cancelErrMsg);
- case "failed":
- throw state.error;
+ }, {
+ retries: numberOfRetries,
+ factor: this.storage.retryOptions.retryDelayMultiplier,
+ maxTimeout: this.storage.retryOptions.maxRetryDelay * 1000, //convert to milliseconds
+ maxRetryTime: this.storage.retryOptions.totalTimeout * 1000, //convert to milliseconds
+ });
+ if (!callback) {
+ return returnValue;
+ }
+ else {
+ return returnValue
+ .then(() => {
+ if (callback) {
+ return callback(null, newFile, newFile.metadata);
}
+ })
+ .catch(callback);
+ }
+ };
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ if (global['GCLOUD_SANDBOX_ENV']) {
+ return;
+ }
+ let options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
+ callback =
+ typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
+ options = Object.assign({
+ metadata: {},
+ }, options);
+ // Do not retry if precondition option ifGenerationMatch is not set
+ // because this is a file operation
+ let maxRetries = this.storage.retryOptions.maxRetries;
+ if ((((_a = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) === undefined &&
+ ((_b = this.instancePreconditionOpts) === null || _b === void 0 ? void 0 : _b.ifGenerationMatch) === undefined &&
+ this.storage.retryOptions.idempotencyStrategy ===
+ storage_js_1.IdempotencyStrategy.RetryConditional) ||
+ this.storage.retryOptions.idempotencyStrategy ===
+ storage_js_1.IdempotencyStrategy.RetryNever) {
+ maxRetries = 0;
+ }
+ let newFile;
+ if (options.destination instanceof file_js_1.File) {
+ newFile = options.destination;
+ }
+ else if (options.destination !== null &&
+ typeof options.destination === 'string') {
+ // Use the string as the name of the file.
+ newFile = this.file(options.destination, {
+ encryptionKey: options.encryptionKey,
+ kmsKeyName: options.kmsKeyName,
+ preconditionOpts: this.instancePreconditionOpts,
+ });
+ }
+ else {
+ // Resort to using the name of the incoming file.
+ const destination = path.basename(pathString);
+ newFile = this.file(destination, {
+ encryptionKey: options.encryptionKey,
+ kmsKeyName: options.kmsKeyName,
+ preconditionOpts: this.instancePreconditionOpts,
+ });
+ }
+ upload(maxRetries);
+ }
+ /**
+ * @private
+ *
+ * @typedef {object} MakeAllFilesPublicPrivateOptions
+ * @property {boolean} [force] Suppress errors until all files have been
+ * processed.
+ * @property {boolean} [private] Make files private.
+ * @property {boolean} [public] Make files public.
+ * @property {string} [userProject] The ID of the project which will be
+ * billed for the request.
+ */
+ /**
+ * @private
+ *
+ * @callback SetBucketMetadataCallback
+ * @param {?Error} err Request error, if any.
+ * @param {File[]} files Files that were updated.
+ */
+ /**
+ * @typedef {array} MakeAllFilesPublicPrivateResponse
+ * @property {File[]} 0 List of files affected.
+ */
+ /**
+ * Iterate over all of a bucket's files, calling `file.makePublic()` (public)
+ * or `file.makePrivate()` (private) on each.
+ *
+ * Operations are performed in parallel, up to 10 at once. The first error
+ * breaks the loop, and will execute the provided callback with it. Specify
+ * `{ force: true }` to suppress the errors.
+ *
+ * @private
+ *
+ * @param {MakeAllFilesPublicPrivateOptions} [options] Configuration options.
+ * @param {boolean} [options.force] Suppress errors until all files have been
+ * processed.
+ * @param {boolean} [options.private] Make files private.
+ * @param {boolean} [options.public] Make files public.
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+
+ * @param {MakeAllFilesPublicPrivateCallback} callback Callback function.
+ *
+ * @return {Promise}
+ */
+ makeAllFilesPublicPrivate_(optionsOrCallback, callback) {
+ const MAX_PARALLEL_LIMIT = 10;
+ const errors = [];
+ const updatedFiles = [];
+ const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
+ callback =
+ typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
+ const processFile = async (file) => {
+ try {
+ await (options.public ? file.makePublic() : file.makePrivate(options));
+ updatedFiles.push(file);
+ }
+ catch (e) {
+ if (!options.force) {
+ throw e;
}
- },
+ errors.push(e);
+ }
};
- return poller;
- };
+ this.getFiles(options)
+ .then(([files]) => {
+ const limit = (0, p_limit_1.default)(MAX_PARALLEL_LIMIT);
+ const promises = files.map(file => {
+ return limit(() => processFile(file));
+ });
+ return Promise.all(promises);
+ })
+ .then(() => callback(errors.length > 0 ? errors : null, updatedFiles), err => callback(err, updatedFiles));
+ }
+ getId() {
+ return this.id;
+ }
+ disableAutoRetryConditionallyIdempotent_(
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ coreOpts,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ methodType, localPreconditionOptions) {
+ var _a, _b;
+ if (typeof coreOpts === 'object' &&
+ ((_b = (_a = coreOpts === null || coreOpts === void 0 ? void 0 : coreOpts.reqOpts) === null || _a === void 0 ? void 0 : _a.qs) === null || _b === void 0 ? void 0 : _b.ifMetagenerationMatch) === undefined &&
+ (localPreconditionOptions === null || localPreconditionOptions === void 0 ? void 0 : localPreconditionOptions.ifMetagenerationMatch) === undefined &&
+ (methodType === AvailableServiceObjectMethods.setMetadata ||
+ methodType === AvailableServiceObjectMethods.delete) &&
+ this.storage.retryOptions.idempotencyStrategy ===
+ storage_js_1.IdempotencyStrategy.RetryConditional) {
+ this.storage.retryOptions.autoRetry = false;
+ }
+ else if (this.storage.retryOptions.idempotencyStrategy ===
+ storage_js_1.IdempotencyStrategy.RetryNever) {
+ this.storage.retryOptions.autoRetry = false;
+ }
+ }
}
-exports.buildCreatePoller = buildCreatePoller;
-//# sourceMappingURL=poller.js.map
-
-/***/ }),
-
-/***/ 6427:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
+exports.Bucket = Bucket;
+/*! Developer Documentation
+ *
+ * These methods can be auto-paginated.
+ */
+paginator_1.paginator.extend(Bucket, 'getFiles');
+/*! Developer Documentation
+ *
+ * All async methods (except for streams) will return a Promise in the event
+ * that a callback is omitted.
+ */
+(0, promisify_1.promisifyAll)(Bucket, {
+ exclude: ['cloudStorageURI', 'request', 'file', 'notification', 'restore'],
+});
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.DEFAULT_RETRY_POLICY_COUNT = exports.SDK_VERSION = void 0;
-exports.SDK_VERSION = "1.18.1";
-exports.DEFAULT_RETRY_POLICY_COUNT = 3;
-//# sourceMappingURL=constants.js.map
/***/ }),
-/***/ 862:
+/***/ 12658:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
+// Copyright 2019 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createPipelineFromOptions = createPipelineFromOptions;
-const logPolicy_js_1 = __nccwpck_require__(3253);
-const pipeline_js_1 = __nccwpck_require__(9590);
-const redirectPolicy_js_1 = __nccwpck_require__(4087);
-const userAgentPolicy_js_1 = __nccwpck_require__(2799);
-const multipartPolicy_js_1 = __nccwpck_require__(5807);
-const decompressResponsePolicy_js_1 = __nccwpck_require__(9295);
-const defaultRetryPolicy_js_1 = __nccwpck_require__(8170);
-const formDataPolicy_js_1 = __nccwpck_require__(5497);
-const core_util_1 = __nccwpck_require__(7779);
-const proxyPolicy_js_1 = __nccwpck_require__(2815);
-const setClientRequestIdPolicy_js_1 = __nccwpck_require__(5686);
-const tlsPolicy_js_1 = __nccwpck_require__(5798);
-const tracingPolicy_js_1 = __nccwpck_require__(3237);
+exports.Channel = void 0;
+const index_js_1 = __nccwpck_require__(11325);
+const promisify_1 = __nccwpck_require__(60206);
/**
- * Create a new pipeline with a default set of customizable policies.
- * @param options - Options to configure a custom pipeline.
+ * Create a channel object to interact with a Cloud Storage channel.
+ *
+ * See {@link https://cloud.google.com/storage/docs/object-change-notification| Object Change Notification}
+ *
+ * @class
+ *
+ * @param {string} id The ID of the channel.
+ * @param {string} resourceId The resource ID of the channel.
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const channel = storage.channel('id', 'resource-id');
+ * ```
*/
-function createPipelineFromOptions(options) {
- var _a;
- const pipeline = (0, pipeline_js_1.createEmptyPipeline)();
- if (core_util_1.isNodeLike) {
- if (options.tlsOptions) {
- pipeline.addPolicy((0, tlsPolicy_js_1.tlsPolicy)(options.tlsOptions));
- }
- pipeline.addPolicy((0, proxyPolicy_js_1.proxyPolicy)(options.proxyOptions));
- pipeline.addPolicy((0, decompressResponsePolicy_js_1.decompressResponsePolicy)());
+class Channel extends index_js_1.ServiceObject {
+ constructor(storage, id, resourceId) {
+ const config = {
+ parent: storage,
+ baseUrl: '/channels',
+ // An ID shouldn't be included in the API requests.
+ // RE:
+ // https://github.com/GoogleCloudPlatform/google-cloud-node/issues/1145
+ id: '',
+ methods: {
+ // Only need `request`.
+ },
+ };
+ super(config);
+ this.metadata.id = id;
+ this.metadata.resourceId = resourceId;
}
- pipeline.addPolicy((0, formDataPolicy_js_1.formDataPolicy)(), { beforePolicies: [multipartPolicy_js_1.multipartPolicyName] });
- pipeline.addPolicy((0, userAgentPolicy_js_1.userAgentPolicy)(options.userAgentOptions));
- pipeline.addPolicy((0, setClientRequestIdPolicy_js_1.setClientRequestIdPolicy)((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.clientRequestIdHeaderName));
- // The multipart policy is added after policies with no phase, so that
- // policies can be added between it and formDataPolicy to modify
- // properties (e.g., making the boundary constant in recorded tests).
- pipeline.addPolicy((0, multipartPolicy_js_1.multipartPolicy)(), { afterPhase: "Deserialize" });
- pipeline.addPolicy((0, defaultRetryPolicy_js_1.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" });
- pipeline.addPolicy((0, tracingPolicy_js_1.tracingPolicy)(Object.assign(Object.assign({}, options.userAgentOptions), options.loggingOptions)), {
- afterPhase: "Retry",
- });
- if (core_util_1.isNodeLike) {
- // Both XHR and Fetch expect to handle redirects automatically,
- // so only include this policy when we're in Node.
- pipeline.addPolicy((0, redirectPolicy_js_1.redirectPolicy)(options.redirectOptions), { afterPhase: "Retry" });
+ /**
+ * @typedef {array} StopResponse
+ * @property {object} 0 The full API response.
+ */
+ /**
+ * @callback StopCallback
+ * @param {?Error} err Request error, if any.
+ * @param {object} apiResponse The full API response.
+ */
+ /**
+ * Stop this channel.
+ *
+ * @param {StopCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const channel = storage.channel('id', 'resource-id');
+ * channel.stop(function(err, apiResponse) {
+ * if (!err) {
+ * // Channel stopped successfully.
+ * }
+ * });
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * channel.stop().then(function(data) {
+ * const apiResponse = data[0];
+ * });
+ * ```
+ */
+ stop(callback) {
+ callback = callback || index_js_1.util.noop;
+ this.request({
+ method: 'POST',
+ uri: '/stop',
+ json: this.metadata,
+ }, (err, apiResponse) => {
+ callback(err, apiResponse);
+ });
}
- pipeline.addPolicy((0, logPolicy_js_1.logPolicy)(options.loggingOptions), { afterPhase: "Sign" });
- return pipeline;
}
-//# sourceMappingURL=createPipelineFromOptions.js.map
-
-/***/ }),
-
-/***/ 7960:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createDefaultHttpClient = createDefaultHttpClient;
-const nodeHttpClient_js_1 = __nccwpck_require__(195);
-/**
- * Create the correct HttpClient for the current environment.
+exports.Channel = Channel;
+/*! Developer Documentation
+ *
+ * All async methods (except for streams) will return a Promise in the event
+ * that a callback is omitted.
*/
-function createDefaultHttpClient() {
- return (0, nodeHttpClient_js_1.createNodeHttpClient)();
-}
-//# sourceMappingURL=defaultHttpClient.js.map
+(0, promisify_1.promisifyAll)(Channel);
+
/***/ }),
-/***/ 192:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 34317:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
+// Copyright 2022 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
+ if (kind === "m") throw new TypeError("Private method is not writable");
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
+};
+var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
+};
+var _CRC32C_crc32c;
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createHttpHeaders = createHttpHeaders;
-function normalizeName(name) {
- return name.toLowerCase();
-}
-function* headerIterator(map) {
- for (const entry of map.values()) {
- yield [entry.name, entry.value];
+exports.CRC32C_EXTENSION_TABLE = exports.CRC32C_EXTENSIONS = exports.CRC32C_EXCEPTION_MESSAGES = exports.CRC32C_DEFAULT_VALIDATOR_GENERATOR = exports.CRC32C = void 0;
+const fs_1 = __nccwpck_require__(79896);
+/**
+ * Ported from {@link https://github.com/google/crc32c/blob/21fc8ef30415a635e7351ffa0e5d5367943d4a94/src/crc32c_portable.cc#L16-L59 github.com/google/crc32c}
+ */
+const CRC32C_EXTENSIONS = [
+ 0x00000000, 0xf26b8303, 0xe13b70f7, 0x1350f3f4, 0xc79a971f, 0x35f1141c,
+ 0x26a1e7e8, 0xd4ca64eb, 0x8ad958cf, 0x78b2dbcc, 0x6be22838, 0x9989ab3b,
+ 0x4d43cfd0, 0xbf284cd3, 0xac78bf27, 0x5e133c24, 0x105ec76f, 0xe235446c,
+ 0xf165b798, 0x030e349b, 0xd7c45070, 0x25afd373, 0x36ff2087, 0xc494a384,
+ 0x9a879fa0, 0x68ec1ca3, 0x7bbcef57, 0x89d76c54, 0x5d1d08bf, 0xaf768bbc,
+ 0xbc267848, 0x4e4dfb4b, 0x20bd8ede, 0xd2d60ddd, 0xc186fe29, 0x33ed7d2a,
+ 0xe72719c1, 0x154c9ac2, 0x061c6936, 0xf477ea35, 0xaa64d611, 0x580f5512,
+ 0x4b5fa6e6, 0xb93425e5, 0x6dfe410e, 0x9f95c20d, 0x8cc531f9, 0x7eaeb2fa,
+ 0x30e349b1, 0xc288cab2, 0xd1d83946, 0x23b3ba45, 0xf779deae, 0x05125dad,
+ 0x1642ae59, 0xe4292d5a, 0xba3a117e, 0x4851927d, 0x5b016189, 0xa96ae28a,
+ 0x7da08661, 0x8fcb0562, 0x9c9bf696, 0x6ef07595, 0x417b1dbc, 0xb3109ebf,
+ 0xa0406d4b, 0x522bee48, 0x86e18aa3, 0x748a09a0, 0x67dafa54, 0x95b17957,
+ 0xcba24573, 0x39c9c670, 0x2a993584, 0xd8f2b687, 0x0c38d26c, 0xfe53516f,
+ 0xed03a29b, 0x1f682198, 0x5125dad3, 0xa34e59d0, 0xb01eaa24, 0x42752927,
+ 0x96bf4dcc, 0x64d4cecf, 0x77843d3b, 0x85efbe38, 0xdbfc821c, 0x2997011f,
+ 0x3ac7f2eb, 0xc8ac71e8, 0x1c661503, 0xee0d9600, 0xfd5d65f4, 0x0f36e6f7,
+ 0x61c69362, 0x93ad1061, 0x80fde395, 0x72966096, 0xa65c047d, 0x5437877e,
+ 0x4767748a, 0xb50cf789, 0xeb1fcbad, 0x197448ae, 0x0a24bb5a, 0xf84f3859,
+ 0x2c855cb2, 0xdeeedfb1, 0xcdbe2c45, 0x3fd5af46, 0x7198540d, 0x83f3d70e,
+ 0x90a324fa, 0x62c8a7f9, 0xb602c312, 0x44694011, 0x5739b3e5, 0xa55230e6,
+ 0xfb410cc2, 0x092a8fc1, 0x1a7a7c35, 0xe811ff36, 0x3cdb9bdd, 0xceb018de,
+ 0xdde0eb2a, 0x2f8b6829, 0x82f63b78, 0x709db87b, 0x63cd4b8f, 0x91a6c88c,
+ 0x456cac67, 0xb7072f64, 0xa457dc90, 0x563c5f93, 0x082f63b7, 0xfa44e0b4,
+ 0xe9141340, 0x1b7f9043, 0xcfb5f4a8, 0x3dde77ab, 0x2e8e845f, 0xdce5075c,
+ 0x92a8fc17, 0x60c37f14, 0x73938ce0, 0x81f80fe3, 0x55326b08, 0xa759e80b,
+ 0xb4091bff, 0x466298fc, 0x1871a4d8, 0xea1a27db, 0xf94ad42f, 0x0b21572c,
+ 0xdfeb33c7, 0x2d80b0c4, 0x3ed04330, 0xccbbc033, 0xa24bb5a6, 0x502036a5,
+ 0x4370c551, 0xb11b4652, 0x65d122b9, 0x97baa1ba, 0x84ea524e, 0x7681d14d,
+ 0x2892ed69, 0xdaf96e6a, 0xc9a99d9e, 0x3bc21e9d, 0xef087a76, 0x1d63f975,
+ 0x0e330a81, 0xfc588982, 0xb21572c9, 0x407ef1ca, 0x532e023e, 0xa145813d,
+ 0x758fe5d6, 0x87e466d5, 0x94b49521, 0x66df1622, 0x38cc2a06, 0xcaa7a905,
+ 0xd9f75af1, 0x2b9cd9f2, 0xff56bd19, 0x0d3d3e1a, 0x1e6dcdee, 0xec064eed,
+ 0xc38d26c4, 0x31e6a5c7, 0x22b65633, 0xd0ddd530, 0x0417b1db, 0xf67c32d8,
+ 0xe52cc12c, 0x1747422f, 0x49547e0b, 0xbb3ffd08, 0xa86f0efc, 0x5a048dff,
+ 0x8ecee914, 0x7ca56a17, 0x6ff599e3, 0x9d9e1ae0, 0xd3d3e1ab, 0x21b862a8,
+ 0x32e8915c, 0xc083125f, 0x144976b4, 0xe622f5b7, 0xf5720643, 0x07198540,
+ 0x590ab964, 0xab613a67, 0xb831c993, 0x4a5a4a90, 0x9e902e7b, 0x6cfbad78,
+ 0x7fab5e8c, 0x8dc0dd8f, 0xe330a81a, 0x115b2b19, 0x020bd8ed, 0xf0605bee,
+ 0x24aa3f05, 0xd6c1bc06, 0xc5914ff2, 0x37faccf1, 0x69e9f0d5, 0x9b8273d6,
+ 0x88d28022, 0x7ab90321, 0xae7367ca, 0x5c18e4c9, 0x4f48173d, 0xbd23943e,
+ 0xf36e6f75, 0x0105ec76, 0x12551f82, 0xe03e9c81, 0x34f4f86a, 0xc69f7b69,
+ 0xd5cf889d, 0x27a40b9e, 0x79b737ba, 0x8bdcb4b9, 0x988c474d, 0x6ae7c44e,
+ 0xbe2da0a5, 0x4c4623a6, 0x5f16d052, 0xad7d5351,
+];
+exports.CRC32C_EXTENSIONS = CRC32C_EXTENSIONS;
+const CRC32C_EXTENSION_TABLE = new Int32Array(CRC32C_EXTENSIONS);
+exports.CRC32C_EXTENSION_TABLE = CRC32C_EXTENSION_TABLE;
+const CRC32C_DEFAULT_VALIDATOR_GENERATOR = () => new CRC32C();
+exports.CRC32C_DEFAULT_VALIDATOR_GENERATOR = CRC32C_DEFAULT_VALIDATOR_GENERATOR;
+const CRC32C_EXCEPTION_MESSAGES = {
+ INVALID_INIT_BASE64_RANGE: (l) => `base64-encoded data expected to equal 4 bytes, not ${l}`,
+ INVALID_INIT_BUFFER_LENGTH: (l) => `Buffer expected to equal 4 bytes, not ${l}`,
+ INVALID_INIT_INTEGER: (l) => `Number expected to be a safe, unsigned 32-bit integer, not ${l}`,
+};
+exports.CRC32C_EXCEPTION_MESSAGES = CRC32C_EXCEPTION_MESSAGES;
+class CRC32C {
+ /**
+ * Constructs a new `CRC32C` object.
+ *
+ * Reconstruction is recommended via the `CRC32C.from` static method.
+ *
+ * @param initialValue An initial CRC32C value - a signed 32-bit integer.
+ */
+ constructor(initialValue = 0) {
+ /** Current CRC32C value */
+ _CRC32C_crc32c.set(this, 0);
+ __classPrivateFieldSet(this, _CRC32C_crc32c, initialValue, "f");
}
-}
-class HttpHeadersImpl {
- constructor(rawHeaders) {
- this._headersMap = new Map();
- if (rawHeaders) {
- for (const headerName of Object.keys(rawHeaders)) {
- this.set(headerName, rawHeaders[headerName]);
- }
+ /**
+ * Calculates a CRC32C from a provided buffer.
+ *
+ * Implementation inspired from:
+ * - {@link https://github.com/google/crc32c/blob/21fc8ef30415a635e7351ffa0e5d5367943d4a94/src/crc32c_portable.cc github.com/google/crc32c}
+ * - {@link https://github.com/googleapis/python-crc32c/blob/a595e758c08df445a99c3bf132ee8e80a3ec4308/src/google_crc32c/python.py github.com/googleapis/python-crc32c}
+ * - {@link https://github.com/googleapis/java-storage/pull/1376/files github.com/googleapis/java-storage}
+ *
+ * @param data The `Buffer` to generate the CRC32C from
+ */
+ update(data) {
+ let current = __classPrivateFieldGet(this, _CRC32C_crc32c, "f") ^ 0xffffffff;
+ for (const d of data) {
+ const tablePoly = CRC32C.CRC32C_EXTENSION_TABLE[(d ^ current) & 0xff];
+ current = tablePoly ^ (current >>> 8);
}
+ __classPrivateFieldSet(this, _CRC32C_crc32c, current ^ 0xffffffff, "f");
}
/**
- * Set a header in this collection with the provided name and value. The name is
- * case-insensitive.
- * @param name - The name of the header to set. This value is case-insensitive.
- * @param value - The value of the header to set.
+ * Validates a provided input to the current CRC32C value.
+ *
+ * @param input A Buffer, `CRC32C`-compatible object, base64-encoded data (string), or signed 32-bit integer
*/
- set(name, value) {
- this._headersMap.set(normalizeName(name), { name, value: String(value).trim() });
+ validate(input) {
+ if (typeof input === 'number') {
+ return input === __classPrivateFieldGet(this, _CRC32C_crc32c, "f");
+ }
+ else if (typeof input === 'string') {
+ return input === this.toString();
+ }
+ else if (Buffer.isBuffer(input)) {
+ return Buffer.compare(input, this.toBuffer()) === 0;
+ }
+ else {
+ // `CRC32C`-like object
+ return input.toString() === this.toString();
+ }
}
/**
- * Get the header value for the provided header name, or undefined if no header exists in this
- * collection with the provided name.
- * @param name - The name of the header. This value is case-insensitive.
+ * Returns a `Buffer` representation of the CRC32C value
*/
- get(name) {
- var _a;
- return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value;
+ toBuffer() {
+ const buffer = Buffer.alloc(4);
+ buffer.writeInt32BE(__classPrivateFieldGet(this, _CRC32C_crc32c, "f"));
+ return buffer;
}
/**
- * Get whether or not this header collection contains a header entry for the provided header name.
- * @param name - The name of the header to set. This value is case-insensitive.
+ * Returns a JSON-compatible, base64-encoded representation of the CRC32C value.
+ *
+ * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify `JSON#stringify`}
*/
- has(name) {
- return this._headersMap.has(normalizeName(name));
+ toJSON() {
+ return this.toString();
}
/**
- * Remove the header with the provided headerName.
- * @param name - The name of the header to remove.
+ * Returns a base64-encoded representation of the CRC32C value.
+ *
+ * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString `Object#toString`}
*/
- delete(name) {
- this._headersMap.delete(normalizeName(name));
+ toString() {
+ return this.toBuffer().toString('base64');
}
/**
- * Get the JSON object representation of this HTTP header collection.
+ * Returns the `number` representation of the CRC32C value as a signed 32-bit integer
+ *
+ * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf `Object#valueOf`}
*/
- toJSON(options = {}) {
- const result = {};
- if (options.preserveCase) {
- for (const entry of this._headersMap.values()) {
- result[entry.name] = entry.value;
- }
+ valueOf() {
+ return __classPrivateFieldGet(this, _CRC32C_crc32c, "f");
+ }
+ /**
+ * Generates a `CRC32C` from a compatible buffer format.
+ *
+ * @param value 4-byte `ArrayBufferView`/`Buffer`/`TypedArray`
+ */
+ static fromBuffer(value) {
+ let buffer;
+ if (Buffer.isBuffer(value)) {
+ buffer = value;
+ }
+ else if ('buffer' in value) {
+ // `ArrayBufferView`
+ buffer = Buffer.from(value.buffer);
}
else {
- for (const [normalizedName, entry] of this._headersMap) {
- result[normalizedName] = entry.value;
- }
+ // `ArrayBuffer`
+ buffer = Buffer.from(value);
}
- return result;
+ if (buffer.byteLength !== 4) {
+ throw new RangeError(CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_BUFFER_LENGTH(buffer.byteLength));
+ }
+ return new CRC32C(buffer.readInt32BE());
+ }
+ static async fromFile(file) {
+ const crc32c = new CRC32C();
+ await new Promise((resolve, reject) => {
+ (0, fs_1.createReadStream)(file)
+ .on('data', (d) => {
+ if (typeof d === 'string') {
+ crc32c.update(Buffer.from(d));
+ }
+ else {
+ crc32c.update(d);
+ }
+ })
+ .on('end', () => resolve())
+ .on('error', reject);
+ });
+ return crc32c;
}
/**
- * Get the string representation of this HTTP header collection.
+ * Generates a `CRC32C` from 4-byte base64-encoded data (string).
+ *
+ * @param value 4-byte base64-encoded data (string)
*/
- toString() {
- return JSON.stringify(this.toJSON({ preserveCase: true }));
+ static fromString(value) {
+ const buffer = Buffer.from(value, 'base64');
+ if (buffer.byteLength !== 4) {
+ throw new RangeError(CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_BASE64_RANGE(buffer.byteLength));
+ }
+ return this.fromBuffer(buffer);
}
/**
- * Iterate over tuples of header [name, value] pairs.
+ * Generates a `CRC32C` from a safe, unsigned 32-bit integer.
+ *
+ * @param value an unsigned 32-bit integer
*/
- [Symbol.iterator]() {
- return headerIterator(this._headersMap);
+ static fromNumber(value) {
+ if (!Number.isSafeInteger(value) || value > 2 ** 32 || value < -(2 ** 32)) {
+ throw new RangeError(CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_INTEGER(value));
+ }
+ return new CRC32C(value);
+ }
+ /**
+ * Generates a `CRC32C` from a variety of compatable types.
+ * Note: strings are treated as input, not as file paths to read from.
+ *
+ * @param value A number, 4-byte `ArrayBufferView`/`Buffer`/`TypedArray`, or 4-byte base64-encoded data (string)
+ */
+ static from(value) {
+ if (typeof value === 'number') {
+ return this.fromNumber(value);
+ }
+ else if (typeof value === 'string') {
+ return this.fromString(value);
+ }
+ else if ('byteLength' in value) {
+ // `ArrayBuffer` | `Buffer` | `ArrayBufferView`
+ return this.fromBuffer(value);
+ }
+ else {
+ // `CRC32CValidator`/`CRC32C`-like
+ return this.fromString(value.toString());
+ }
}
}
-/**
- * Creates an object that satisfies the `HttpHeaders` interface.
- * @param rawHeaders - A simple object representing initial headers
- */
-function createHttpHeaders(rawHeaders) {
- return new HttpHeadersImpl(rawHeaders);
-}
-//# sourceMappingURL=httpHeaders.js.map
-
-/***/ }),
-
-/***/ 778:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createFileFromStream = exports.createFile = exports.auxiliaryAuthenticationHeaderPolicyName = exports.auxiliaryAuthenticationHeaderPolicy = exports.ndJsonPolicyName = exports.ndJsonPolicy = exports.bearerTokenAuthenticationPolicyName = exports.bearerTokenAuthenticationPolicy = exports.formDataPolicyName = exports.formDataPolicy = exports.tlsPolicyName = exports.tlsPolicy = exports.userAgentPolicyName = exports.userAgentPolicy = exports.defaultRetryPolicy = exports.tracingPolicyName = exports.tracingPolicy = exports.retryPolicy = exports.throttlingRetryPolicyName = exports.throttlingRetryPolicy = exports.systemErrorRetryPolicyName = exports.systemErrorRetryPolicy = exports.redirectPolicyName = exports.redirectPolicy = exports.getDefaultProxySettings = exports.proxyPolicyName = exports.proxyPolicy = exports.multipartPolicyName = exports.multipartPolicy = exports.logPolicyName = exports.logPolicy = exports.setClientRequestIdPolicyName = exports.setClientRequestIdPolicy = exports.exponentialRetryPolicyName = exports.exponentialRetryPolicy = exports.decompressResponsePolicyName = exports.decompressResponsePolicy = exports.isRestError = exports.RestError = exports.createPipelineRequest = exports.createHttpHeaders = exports.createDefaultHttpClient = exports.createPipelineFromOptions = exports.createEmptyPipeline = void 0;
-var pipeline_js_1 = __nccwpck_require__(9590);
-Object.defineProperty(exports, "createEmptyPipeline", ({ enumerable: true, get: function () { return pipeline_js_1.createEmptyPipeline; } }));
-var createPipelineFromOptions_js_1 = __nccwpck_require__(862);
-Object.defineProperty(exports, "createPipelineFromOptions", ({ enumerable: true, get: function () { return createPipelineFromOptions_js_1.createPipelineFromOptions; } }));
-var defaultHttpClient_js_1 = __nccwpck_require__(7960);
-Object.defineProperty(exports, "createDefaultHttpClient", ({ enumerable: true, get: function () { return defaultHttpClient_js_1.createDefaultHttpClient; } }));
-var httpHeaders_js_1 = __nccwpck_require__(192);
-Object.defineProperty(exports, "createHttpHeaders", ({ enumerable: true, get: function () { return httpHeaders_js_1.createHttpHeaders; } }));
-var pipelineRequest_js_1 = __nccwpck_require__(5709);
-Object.defineProperty(exports, "createPipelineRequest", ({ enumerable: true, get: function () { return pipelineRequest_js_1.createPipelineRequest; } }));
-var restError_js_1 = __nccwpck_require__(8666);
-Object.defineProperty(exports, "RestError", ({ enumerable: true, get: function () { return restError_js_1.RestError; } }));
-Object.defineProperty(exports, "isRestError", ({ enumerable: true, get: function () { return restError_js_1.isRestError; } }));
-var decompressResponsePolicy_js_1 = __nccwpck_require__(9295);
-Object.defineProperty(exports, "decompressResponsePolicy", ({ enumerable: true, get: function () { return decompressResponsePolicy_js_1.decompressResponsePolicy; } }));
-Object.defineProperty(exports, "decompressResponsePolicyName", ({ enumerable: true, get: function () { return decompressResponsePolicy_js_1.decompressResponsePolicyName; } }));
-var exponentialRetryPolicy_js_1 = __nccwpck_require__(6708);
-Object.defineProperty(exports, "exponentialRetryPolicy", ({ enumerable: true, get: function () { return exponentialRetryPolicy_js_1.exponentialRetryPolicy; } }));
-Object.defineProperty(exports, "exponentialRetryPolicyName", ({ enumerable: true, get: function () { return exponentialRetryPolicy_js_1.exponentialRetryPolicyName; } }));
-var setClientRequestIdPolicy_js_1 = __nccwpck_require__(5686);
-Object.defineProperty(exports, "setClientRequestIdPolicy", ({ enumerable: true, get: function () { return setClientRequestIdPolicy_js_1.setClientRequestIdPolicy; } }));
-Object.defineProperty(exports, "setClientRequestIdPolicyName", ({ enumerable: true, get: function () { return setClientRequestIdPolicy_js_1.setClientRequestIdPolicyName; } }));
-var logPolicy_js_1 = __nccwpck_require__(3253);
-Object.defineProperty(exports, "logPolicy", ({ enumerable: true, get: function () { return logPolicy_js_1.logPolicy; } }));
-Object.defineProperty(exports, "logPolicyName", ({ enumerable: true, get: function () { return logPolicy_js_1.logPolicyName; } }));
-var multipartPolicy_js_1 = __nccwpck_require__(5807);
-Object.defineProperty(exports, "multipartPolicy", ({ enumerable: true, get: function () { return multipartPolicy_js_1.multipartPolicy; } }));
-Object.defineProperty(exports, "multipartPolicyName", ({ enumerable: true, get: function () { return multipartPolicy_js_1.multipartPolicyName; } }));
-var proxyPolicy_js_1 = __nccwpck_require__(2815);
-Object.defineProperty(exports, "proxyPolicy", ({ enumerable: true, get: function () { return proxyPolicy_js_1.proxyPolicy; } }));
-Object.defineProperty(exports, "proxyPolicyName", ({ enumerable: true, get: function () { return proxyPolicy_js_1.proxyPolicyName; } }));
-Object.defineProperty(exports, "getDefaultProxySettings", ({ enumerable: true, get: function () { return proxyPolicy_js_1.getDefaultProxySettings; } }));
-var redirectPolicy_js_1 = __nccwpck_require__(4087);
-Object.defineProperty(exports, "redirectPolicy", ({ enumerable: true, get: function () { return redirectPolicy_js_1.redirectPolicy; } }));
-Object.defineProperty(exports, "redirectPolicyName", ({ enumerable: true, get: function () { return redirectPolicy_js_1.redirectPolicyName; } }));
-var systemErrorRetryPolicy_js_1 = __nccwpck_require__(6518);
-Object.defineProperty(exports, "systemErrorRetryPolicy", ({ enumerable: true, get: function () { return systemErrorRetryPolicy_js_1.systemErrorRetryPolicy; } }));
-Object.defineProperty(exports, "systemErrorRetryPolicyName", ({ enumerable: true, get: function () { return systemErrorRetryPolicy_js_1.systemErrorRetryPolicyName; } }));
-var throttlingRetryPolicy_js_1 = __nccwpck_require__(7540);
-Object.defineProperty(exports, "throttlingRetryPolicy", ({ enumerable: true, get: function () { return throttlingRetryPolicy_js_1.throttlingRetryPolicy; } }));
-Object.defineProperty(exports, "throttlingRetryPolicyName", ({ enumerable: true, get: function () { return throttlingRetryPolicy_js_1.throttlingRetryPolicyName; } }));
-var retryPolicy_js_1 = __nccwpck_require__(6085);
-Object.defineProperty(exports, "retryPolicy", ({ enumerable: true, get: function () { return retryPolicy_js_1.retryPolicy; } }));
-var tracingPolicy_js_1 = __nccwpck_require__(3237);
-Object.defineProperty(exports, "tracingPolicy", ({ enumerable: true, get: function () { return tracingPolicy_js_1.tracingPolicy; } }));
-Object.defineProperty(exports, "tracingPolicyName", ({ enumerable: true, get: function () { return tracingPolicy_js_1.tracingPolicyName; } }));
-var defaultRetryPolicy_js_1 = __nccwpck_require__(8170);
-Object.defineProperty(exports, "defaultRetryPolicy", ({ enumerable: true, get: function () { return defaultRetryPolicy_js_1.defaultRetryPolicy; } }));
-var userAgentPolicy_js_1 = __nccwpck_require__(2799);
-Object.defineProperty(exports, "userAgentPolicy", ({ enumerable: true, get: function () { return userAgentPolicy_js_1.userAgentPolicy; } }));
-Object.defineProperty(exports, "userAgentPolicyName", ({ enumerable: true, get: function () { return userAgentPolicy_js_1.userAgentPolicyName; } }));
-var tlsPolicy_js_1 = __nccwpck_require__(5798);
-Object.defineProperty(exports, "tlsPolicy", ({ enumerable: true, get: function () { return tlsPolicy_js_1.tlsPolicy; } }));
-Object.defineProperty(exports, "tlsPolicyName", ({ enumerable: true, get: function () { return tlsPolicy_js_1.tlsPolicyName; } }));
-var formDataPolicy_js_1 = __nccwpck_require__(5497);
-Object.defineProperty(exports, "formDataPolicy", ({ enumerable: true, get: function () { return formDataPolicy_js_1.formDataPolicy; } }));
-Object.defineProperty(exports, "formDataPolicyName", ({ enumerable: true, get: function () { return formDataPolicy_js_1.formDataPolicyName; } }));
-var bearerTokenAuthenticationPolicy_js_1 = __nccwpck_require__(6925);
-Object.defineProperty(exports, "bearerTokenAuthenticationPolicy", ({ enumerable: true, get: function () { return bearerTokenAuthenticationPolicy_js_1.bearerTokenAuthenticationPolicy; } }));
-Object.defineProperty(exports, "bearerTokenAuthenticationPolicyName", ({ enumerable: true, get: function () { return bearerTokenAuthenticationPolicy_js_1.bearerTokenAuthenticationPolicyName; } }));
-var ndJsonPolicy_js_1 = __nccwpck_require__(6827);
-Object.defineProperty(exports, "ndJsonPolicy", ({ enumerable: true, get: function () { return ndJsonPolicy_js_1.ndJsonPolicy; } }));
-Object.defineProperty(exports, "ndJsonPolicyName", ({ enumerable: true, get: function () { return ndJsonPolicy_js_1.ndJsonPolicyName; } }));
-var auxiliaryAuthenticationHeaderPolicy_js_1 = __nccwpck_require__(2262);
-Object.defineProperty(exports, "auxiliaryAuthenticationHeaderPolicy", ({ enumerable: true, get: function () { return auxiliaryAuthenticationHeaderPolicy_js_1.auxiliaryAuthenticationHeaderPolicy; } }));
-Object.defineProperty(exports, "auxiliaryAuthenticationHeaderPolicyName", ({ enumerable: true, get: function () { return auxiliaryAuthenticationHeaderPolicy_js_1.auxiliaryAuthenticationHeaderPolicyName; } }));
-var file_js_1 = __nccwpck_require__(7073);
-Object.defineProperty(exports, "createFile", ({ enumerable: true, get: function () { return file_js_1.createFile; } }));
-Object.defineProperty(exports, "createFileFromStream", ({ enumerable: true, get: function () { return file_js_1.createFileFromStream; } }));
-//# sourceMappingURL=index.js.map
+exports.CRC32C = CRC32C;
+_CRC32C_crc32c = new WeakMap();
+CRC32C.CRC32C_EXTENSIONS = CRC32C_EXTENSIONS;
+CRC32C.CRC32C_EXTENSION_TABLE = CRC32C_EXTENSION_TABLE;
-/***/ }),
-
-/***/ 544:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.logger = void 0;
-const logger_1 = __nccwpck_require__(6515);
-exports.logger = (0, logger_1.createClientLogger)("core-rest-pipeline");
-//# sourceMappingURL=log.js.map
/***/ }),
-/***/ 195:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 69975:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getBodyLength = getBodyLength;
-exports.createNodeHttpClient = createNodeHttpClient;
-const tslib_1 = __nccwpck_require__(1860);
-const http = tslib_1.__importStar(__nccwpck_require__(7067));
-const https = tslib_1.__importStar(__nccwpck_require__(4708));
-const zlib = tslib_1.__importStar(__nccwpck_require__(8522));
-const node_stream_1 = __nccwpck_require__(7075);
-const abort_controller_1 = __nccwpck_require__(3287);
-const httpHeaders_js_1 = __nccwpck_require__(192);
-const restError_js_1 = __nccwpck_require__(8666);
-const log_js_1 = __nccwpck_require__(544);
-const DEFAULT_TLS_SETTINGS = {};
-function isReadableStream(body) {
- return body && typeof body.pipe === "function";
-}
-function isStreamComplete(stream) {
- if (stream.readable === false) {
- return Promise.resolve();
+// Copyright 2019 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ 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]; } };
}
- return new Promise((resolve) => {
- const handler = () => {
- resolve();
- stream.removeListener("close", handler);
- stream.removeListener("end", handler);
- stream.removeListener("error", handler);
+ 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 __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
+};
+var __importDefault = (this && this.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+var _File_instances, _File_validateIntegrity;
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.File = exports.FileExceptionMessages = exports.RequestError = exports.STORAGE_POST_POLICY_BASE_URL = exports.ActionToHTTPMethod = void 0;
+const index_js_1 = __nccwpck_require__(11325);
+const promisify_1 = __nccwpck_require__(60206);
+const crypto = __importStar(__nccwpck_require__(76982));
+const fs = __importStar(__nccwpck_require__(79896));
+const mime_1 = __importDefault(__nccwpck_require__(94900));
+const resumableUpload = __importStar(__nccwpck_require__(88043));
+const stream_1 = __nccwpck_require__(2203);
+const zlib = __importStar(__nccwpck_require__(43106));
+const storage_js_1 = __nccwpck_require__(92848);
+const bucket_js_1 = __nccwpck_require__(82887);
+const acl_js_1 = __nccwpck_require__(76637);
+const signer_js_1 = __nccwpck_require__(7319);
+const util_js_1 = __nccwpck_require__(37325);
+const duplexify_1 = __importDefault(__nccwpck_require__(29112));
+const util_js_2 = __nccwpck_require__(74557);
+const crc32c_js_1 = __nccwpck_require__(34317);
+const hash_stream_validator_js_1 = __nccwpck_require__(14873);
+const async_retry_1 = __importDefault(__nccwpck_require__(45195));
+var ActionToHTTPMethod;
+(function (ActionToHTTPMethod) {
+ ActionToHTTPMethod["read"] = "GET";
+ ActionToHTTPMethod["write"] = "PUT";
+ ActionToHTTPMethod["delete"] = "DELETE";
+ ActionToHTTPMethod["resumable"] = "POST";
+})(ActionToHTTPMethod || (exports.ActionToHTTPMethod = ActionToHTTPMethod = {}));
+/**
+ * @deprecated - no longer used
+ */
+exports.STORAGE_POST_POLICY_BASE_URL = 'https://storage.googleapis.com';
+/**
+ * @private
+ */
+const GS_URL_REGEXP = /^gs:\/\/([a-z0-9_.-]+)\/(.+)$/;
+/**
+ * @private
+ * This regex will match compressible content types. These are primarily text/*, +json, +text, +xml content types.
+ * This was based off of mime-db and may periodically need to be updated if new compressible content types become
+ * standards.
+ */
+const COMPRESSIBLE_MIME_REGEX = new RegExp([
+ /^text\/|application\/ecmascript|application\/javascript|application\/json/,
+ /|application\/postscript|application\/rtf|application\/toml|application\/vnd.dart/,
+ /|application\/vnd.ms-fontobject|application\/wasm|application\/x-httpd-php|application\/x-ns-proxy-autoconfig/,
+ /|application\/x-sh(?!ockwave-flash)|application\/x-tar|application\/x-virtualbox-hdd|application\/x-virtualbox-ova|application\/x-virtualbox-ovf/,
+ /|^application\/x-virtualbox-vbox$|application\/x-virtualbox-vdi|application\/x-virtualbox-vhd|application\/x-virtualbox-vmdk/,
+ /|application\/xml|application\/xml-dtd|font\/otf|font\/ttf|image\/bmp|image\/vnd.adobe.photoshop|image\/vnd.microsoft.icon/,
+ /|image\/vnd.ms-dds|image\/x-icon|image\/x-ms-bmp|message\/rfc822|model\/gltf-binary|\+json|\+text|\+xml|\+yaml/,
+]
+ .map(r => r.source)
+ .join(''), 'i');
+class RequestError extends Error {
+}
+exports.RequestError = RequestError;
+const SEVEN_DAYS = 7 * 24 * 60 * 60;
+const GS_UTIL_URL_REGEX = /(gs):\/\/([a-z0-9_.-]+)\/(.+)/g;
+const HTTPS_PUBLIC_URL_REGEX = /(https):\/\/(storage\.googleapis\.com)\/([a-z0-9_.-]+)\/(.+)/g;
+var FileExceptionMessages;
+(function (FileExceptionMessages) {
+ FileExceptionMessages["EXPIRATION_TIME_NA"] = "An expiration time is not available.";
+ FileExceptionMessages["DESTINATION_NO_NAME"] = "Destination file should have a name.";
+ FileExceptionMessages["INVALID_VALIDATION_FILE_RANGE"] = "Cannot use validation with file ranges (start/end).";
+ FileExceptionMessages["MD5_NOT_AVAILABLE"] = "MD5 verification was specified, but is not available for the requested object. MD5 is not available for composite objects.";
+ FileExceptionMessages["EQUALS_CONDITION_TWO_ELEMENTS"] = "Equals condition must be an array of 2 elements.";
+ FileExceptionMessages["STARTS_WITH_TWO_ELEMENTS"] = "StartsWith condition must be an array of 2 elements.";
+ FileExceptionMessages["CONTENT_LENGTH_RANGE_MIN_MAX"] = "ContentLengthRange must have numeric min & max fields.";
+ FileExceptionMessages["DOWNLOAD_MISMATCH"] = "The downloaded data did not match the data from the server. To be sure the content is the same, you should download the file again.";
+ FileExceptionMessages["UPLOAD_MISMATCH_DELETE_FAIL"] = "The uploaded data did not match the data from the server.\n As a precaution, we attempted to delete the file, but it was not successful.\n To be sure the content is the same, you should try removing the file manually,\n then uploading the file again.\n \n\nThe delete attempt failed with this message:\n\n ";
+ FileExceptionMessages["UPLOAD_MISMATCH"] = "The uploaded data did not match the data from the server.\n As a precaution, the file has been deleted.\n To be sure the content is the same, you should try uploading the file again.";
+ FileExceptionMessages["MD5_RESUMED_UPLOAD"] = "MD5 cannot be used with a continued resumable upload as MD5 cannot be extended from an existing value";
+ FileExceptionMessages["MISSING_RESUME_CRC32C_FINAL_UPLOAD"] = "The CRC32C is missing for the final portion of a resumed upload, which is required for validation. Please provide `resumeCRC32C` if validation is required, or disable `validation`.";
+})(FileExceptionMessages || (exports.FileExceptionMessages = FileExceptionMessages = {}));
+/**
+ * A File object is created from your {@link Bucket} object using
+ * {@link Bucket#file}.
+ *
+ * @class
+ */
+class File extends index_js_1.ServiceObject {
+ /**
+ * Cloud Storage uses access control lists (ACLs) to manage object and
+ * bucket access. ACLs are the mechanism you use to share objects with other
+ * users and allow other users to access your buckets and objects.
+ *
+ * An ACL consists of one or more entries, where each entry grants permissions
+ * to an entity. Permissions define the actions that can be performed against
+ * an object or bucket (for example, `READ` or `WRITE`); the entity defines
+ * who the permission applies to (for example, a specific user or group of
+ * users).
+ *
+ * The `acl` object on a File instance provides methods to get you a list of
+ * the ACLs defined on your bucket, as well as set, update, and delete them.
+ *
+ * See {@link http://goo.gl/6qBBPO| About Access Control lists}
+ *
+ * @name File#acl
+ * @mixes Acl
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const myBucket = storage.bucket('my-bucket');
+ *
+ * const file = myBucket.file('my-file');
+ * //-
+ * // Make a file publicly readable.
+ * //-
+ * const options = {
+ * entity: 'allUsers',
+ * role: storage.acl.READER_ROLE
+ * };
+ *
+ * file.acl.add(options, function(err, aclObject) {});
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * file.acl.add(options).then(function(data) {
+ * const aclObject = data[0];
+ * const apiResponse = data[1];
+ * });
+ * ```
+ */
+ /**
+ * The API-formatted resource description of the file.
+ *
+ * Note: This is not guaranteed to be up-to-date when accessed. To get the
+ * latest record, call the `getMetadata()` method.
+ *
+ * @name File#metadata
+ * @type {object}
+ */
+ /**
+ * The file's name.
+ * @name File#name
+ * @type {string}
+ */
+ /**
+ * @callback Crc32cGeneratorToStringCallback
+ * A method returning the CRC32C as a base64-encoded string.
+ *
+ * @returns {string}
+ *
+ * @example
+ * Hashing the string 'data' should return 'rth90Q=='
+ *
+ * ```js
+ * const buffer = Buffer.from('data');
+ * crc32c.update(buffer);
+ * crc32c.toString(); // 'rth90Q=='
+ * ```
+ **/
+ /**
+ * @callback Crc32cGeneratorValidateCallback
+ * A method validating a base64-encoded CRC32C string.
+ *
+ * @param {string} [value] base64-encoded CRC32C string to validate
+ * @returns {boolean}
+ *
+ * @example
+ * Should return `true` if the value matches, `false` otherwise
+ *
+ * ```js
+ * const buffer = Buffer.from('data');
+ * crc32c.update(buffer);
+ * crc32c.validate('DkjKuA=='); // false
+ * crc32c.validate('rth90Q=='); // true
+ * ```
+ **/
+ /**
+ * @callback Crc32cGeneratorUpdateCallback
+ * A method for passing `Buffer`s for CRC32C generation.
+ *
+ * @param {Buffer} [data] data to update CRC32C value with
+ * @returns {undefined}
+ *
+ * @example
+ * Hashing buffers from 'some ' and 'text\n'
+ *
+ * ```js
+ * const buffer1 = Buffer.from('some ');
+ * crc32c.update(buffer1);
+ *
+ * const buffer2 = Buffer.from('text\n');
+ * crc32c.update(buffer2);
+ *
+ * crc32c.toString(); // 'DkjKuA=='
+ * ```
+ **/
+ /**
+ * @typedef {object} CRC32CValidator
+ * @property {Crc32cGeneratorToStringCallback}
+ * @property {Crc32cGeneratorValidateCallback}
+ * @property {Crc32cGeneratorUpdateCallback}
+ */
+ /**
+ * @callback Crc32cGeneratorCallback
+ * @returns {CRC32CValidator}
+ */
+ /**
+ * @typedef {object} FileOptions Options passed to the File constructor.
+ * @property {string} [encryptionKey] A custom encryption key.
+ * @property {number} [generation] Generation to scope the file to.
+ * @property {string} [kmsKeyName] Cloud KMS Key used to encrypt this
+ * object, if the object is encrypted by such a key. Limited availability;
+ * usable only by enabled projects.
+ * @property {string} [userProject] The ID of the project which will be
+ * billed for all requests made from File object.
+ * @property {Crc32cGeneratorCallback} [callback] A function that generates a CRC32C Validator. Defaults to {@link CRC32C}
+ */
+ /**
+ * Constructs a file object.
+ *
+ * @param {Bucket} bucket The Bucket instance this file is
+ * attached to.
+ * @param {string} name The name of the remote file.
+ * @param {FileOptions} [options] Configuration options.
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const myBucket = storage.bucket('my-bucket');
+ *
+ * const file = myBucket.file('my-file');
+ * ```
+ */
+ constructor(bucket, name, options = {}) {
+ var _a, _b;
+ const requestQueryObject = {};
+ let generation;
+ if (options.generation !== null) {
+ if (typeof options.generation === 'string') {
+ generation = Number(options.generation);
+ }
+ else {
+ generation = options.generation;
+ }
+ if (!isNaN(generation)) {
+ requestQueryObject.generation = generation;
+ }
+ }
+ Object.assign(requestQueryObject, options.preconditionOpts);
+ const userProject = options.userProject || bucket.userProject;
+ if (typeof userProject === 'string') {
+ requestQueryObject.userProject = userProject;
+ }
+ const methods = {
+ /**
+ * @typedef {array} DeleteFileResponse
+ * @property {object} 0 The full API response.
+ */
+ /**
+ * @callback DeleteFileCallback
+ * @param {?Error} err Request error, if any.
+ * @param {object} apiResponse The full API response.
+ */
+ /**
+ * Delete the file.
+ *
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/delete| Objects: delete API Documentation}
+ *
+ * @method File#delete
+ * @param {object} [options] Configuration options.
+ * @param {boolean} [options.ignoreNotFound = false] Ignore an error if
+ * the file does not exist.
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {DeleteFileCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const myBucket = storage.bucket('my-bucket');
+ *
+ * const file = myBucket.file('my-file');
+ * file.delete(function(err, apiResponse) {});
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * file.delete().then(function(data) {
+ * const apiResponse = data[0];
+ * });
+ *
+ * ```
+ * @example include:samples/files.js
+ * region_tag:storage_delete_file
+ * Another example:
+ */
+ delete: {
+ reqOpts: {
+ qs: requestQueryObject,
+ },
+ },
+ /**
+ * @typedef {array} FileExistsResponse
+ * @property {boolean} 0 Whether the {@link File} exists.
+ */
+ /**
+ * @callback FileExistsCallback
+ * @param {?Error} err Request error, if any.
+ * @param {boolean} exists Whether the {@link File} exists.
+ */
+ /**
+ * Check if the file exists.
+ *
+ * @method File#exists
+ * @param {options} [options] Configuration options.
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {FileExistsCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const myBucket = storage.bucket('my-bucket');
+ *
+ * const file = myBucket.file('my-file');
+ *
+ * file.exists(function(err, exists) {});
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * file.exists().then(function(data) {
+ * const exists = data[0];
+ * });
+ * ```
+ */
+ exists: {
+ reqOpts: {
+ qs: requestQueryObject,
+ },
+ },
+ /**
+ * @typedef {array} GetFileResponse
+ * @property {File} 0 The {@link File}.
+ * @property {object} 1 The full API response.
+ */
+ /**
+ * @callback GetFileCallback
+ * @param {?Error} err Request error, if any.
+ * @param {File} file The {@link File}.
+ * @param {object} apiResponse The full API response.
+ */
+ /**
+ * Get a file object and its metadata if it exists.
+ *
+ * @method File#get
+ * @param {options} [options] Configuration options.
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {number} [options.generation] The generation number to get
+ * @param {string} [options.restoreToken] If this is a soft-deleted object in an HNS-enabled bucket, returns the restore token which will
+ * be necessary to restore it if there's a name conflict with another object.
+ * @param {boolean} [options.softDeleted] If true, returns the soft-deleted object.
+ Object `generation` is required if `softDeleted` is set to True.
+ * @param {GetFileCallback} [callback] Callback function.
+ * @returns {Promise}
+ *
+ * @example
+ * ```
+ * const {Storage} = require('@google-cloud/storage');
+ * const storage = new Storage();
+ * const myBucket = storage.bucket('my-bucket');
+ *
+ * const file = myBucket.file('my-file');
+ *
+ * file.get(function(err, file, apiResponse) {
+ * // file.metadata` has been populated.
+ * });
+ *
+ * //-
+ * // If the callback is omitted, we'll return a Promise.
+ * //-
+ * file.get().then(function(data) {
+ * const file = data[0];
+ * const apiResponse = data[1];
+ * });
+ * ```
+ */
+ get: {
+ reqOpts: {
+ qs: requestQueryObject,
+ },
+ },
+ /**
+ * @typedef {array} GetFileMetadataResponse
+ * @property {object} 0 The {@link File} metadata.
+ * @property {object} 1 The full API response.
+ */
+ /**
+ * @callback GetFileMetadataCallback
+ * @param {?Error} err Request error, if any.
+ * @param {object} metadata The {@link File} metadata.
+ * @param {object} apiResponse The full API response.
+ */
+ /**
+ * Get the file's metadata.
+ *
+ * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/get| Objects: get API Documentation}
+ *
+ * @method File#getMetadata
+ * @param {object} [options] Configuration options.
+ * @param {string} [options.userProject] The ID of the project which will be
+ * billed for the request.
+ * @param {GetFileMetadataCallback} [callback] Callback function.
+ * @returns {Promise