agentvasya
Version:
Autonomous coding agent CLI - capable of creating/editing files, running commands, using the browser, and more
1,230 lines (1,219 loc) • 40.5 MB
JavaScript
const _importMetaUrl=require('url').pathToFileURL(__filename)
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __glob = (map5) => (path81) => {
var fn = map5[path81];
if (fn) return fn();
throw new Error("Module not found in bundle: " + path81);
};
var __esm = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb2, mod2) => function __require() {
return mod2 || (0, cb2[__getOwnPropNames(cb2)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
};
var __export = (target, all3) => {
for (var name6 in all3)
__defProp(target, name6, { get: all3[name6], enumerable: true });
};
var __copyProps = (to, from2, except, desc) => {
if (from2 && typeof from2 === "object" || typeof from2 === "function") {
for (let key of __getOwnPropNames(from2))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from2[key], enumerable: !(desc = __getOwnPropDesc(from2, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
mod2
));
var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
var __decorateClass = (decorators, target, key, kind5) => {
var result2 = kind5 > 1 ? void 0 : kind5 ? __getOwnPropDesc(target, key) : target;
for (var i6 = decorators.length - 1, decorator; i6 >= 0; i6--)
if (decorator = decorators[i6])
result2 = (kind5 ? decorator(target, key, result2) : decorator(result2)) || result2;
if (kind5 && result2) __defProp(target, key, result2);
return result2;
};
// node_modules/@grpc/grpc-js/build/src/constants.js
var require_constants = __commonJS({
"node_modules/@grpc/grpc-js/build/src/constants.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = exports2.DEFAULT_MAX_SEND_MESSAGE_LENGTH = exports2.Propagate = exports2.LogVerbosity = exports2.Status = void 0;
var Status;
(function(Status2) {
Status2[Status2["OK"] = 0] = "OK";
Status2[Status2["CANCELLED"] = 1] = "CANCELLED";
Status2[Status2["UNKNOWN"] = 2] = "UNKNOWN";
Status2[Status2["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT";
Status2[Status2["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED";
Status2[Status2["NOT_FOUND"] = 5] = "NOT_FOUND";
Status2[Status2["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS";
Status2[Status2["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED";
Status2[Status2["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED";
Status2[Status2["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION";
Status2[Status2["ABORTED"] = 10] = "ABORTED";
Status2[Status2["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE";
Status2[Status2["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED";
Status2[Status2["INTERNAL"] = 13] = "INTERNAL";
Status2[Status2["UNAVAILABLE"] = 14] = "UNAVAILABLE";
Status2[Status2["DATA_LOSS"] = 15] = "DATA_LOSS";
Status2[Status2["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED";
})(Status || (exports2.Status = Status = {}));
var LogVerbosity;
(function(LogVerbosity2) {
LogVerbosity2[LogVerbosity2["DEBUG"] = 0] = "DEBUG";
LogVerbosity2[LogVerbosity2["INFO"] = 1] = "INFO";
LogVerbosity2[LogVerbosity2["ERROR"] = 2] = "ERROR";
LogVerbosity2[LogVerbosity2["NONE"] = 3] = "NONE";
})(LogVerbosity || (exports2.LogVerbosity = LogVerbosity = {}));
var Propagate;
(function(Propagate2) {
Propagate2[Propagate2["DEADLINE"] = 1] = "DEADLINE";
Propagate2[Propagate2["CENSUS_STATS_CONTEXT"] = 2] = "CENSUS_STATS_CONTEXT";
Propagate2[Propagate2["CENSUS_TRACING_CONTEXT"] = 4] = "CENSUS_TRACING_CONTEXT";
Propagate2[Propagate2["CANCELLATION"] = 8] = "CANCELLATION";
Propagate2[Propagate2["DEFAULTS"] = 65535] = "DEFAULTS";
})(Propagate || (exports2.Propagate = Propagate = {}));
exports2.DEFAULT_MAX_SEND_MESSAGE_LENGTH = -1;
exports2.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = 4 * 1024 * 1024;
}
});
// node_modules/@grpc/grpc-js/package.json
var require_package = __commonJS({
"node_modules/@grpc/grpc-js/package.json"(exports2, module2) {
module2.exports = {
name: "@grpc/grpc-js",
version: "1.9.15",
description: "gRPC Library for Node - pure JS implementation",
homepage: "https://grpc.io/",
repository: "https://github.com/grpc/grpc-node/tree/master/packages/grpc-js",
main: "build/src/index.js",
engines: {
node: "^8.13.0 || >=10.10.0"
},
keywords: [],
author: {
name: "Google Inc."
},
types: "build/src/index.d.ts",
license: "Apache-2.0",
devDependencies: {
"@types/gulp": "^4.0.6",
"@types/gulp-mocha": "0.0.32",
"@types/lodash": "^4.14.186",
"@types/mocha": "^5.2.6",
"@types/ncp": "^2.0.1",
"@types/pify": "^3.0.2",
"@types/semver": "^7.3.9",
"@typescript-eslint/eslint-plugin": "^5.59.11",
"@typescript-eslint/parser": "^5.59.11",
"@typescript-eslint/typescript-estree": "^5.59.11",
"clang-format": "^1.0.55",
eslint: "^8.42.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prettier": "^4.2.1",
execa: "^2.0.3",
gulp: "^4.0.2",
"gulp-mocha": "^6.0.0",
lodash: "^4.17.4",
madge: "^5.0.1",
"mocha-jenkins-reporter": "^0.4.1",
ncp: "^2.0.0",
pify: "^4.0.1",
prettier: "^2.8.8",
rimraf: "^3.0.2",
semver: "^7.3.5",
"ts-node": "^10.9.1",
typescript: "^5.1.3"
},
contributors: [
{
name: "Google Inc."
}
],
scripts: {
build: "npm run compile",
clean: "rimraf ./build",
compile: "tsc -p .",
format: 'clang-format -i -style="{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}" src/*.ts test/*.ts',
lint: "eslint src/*.ts test/*.ts",
prepare: "npm run generate-types && npm run compile",
test: "gulp test",
check: "npm run lint",
fix: "eslint --fix src/*.ts test/*.ts",
pretest: "npm run generate-types && npm run generate-test-types && npm run compile",
posttest: "npm run check && madge -c ./build/src",
"generate-types": "proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --includeDirs proto/ --include-dirs test/fixtures/ -O src/generated/ --grpcLib ../index channelz.proto",
"generate-test-types": "proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --include-dirs test/fixtures/ -O test/generated/ --grpcLib ../../src/index test_service.proto"
},
dependencies: {
"@grpc/proto-loader": "^0.7.8",
"@types/node": ">=12.12.47"
},
files: [
"src/**/*.ts",
"build/src/**/*.{js,d.ts,js.map}",
"proto/*.proto",
"LICENSE",
"deps/envoy-api/envoy/api/v2/**/*.proto",
"deps/envoy-api/envoy/config/**/*.proto",
"deps/envoy-api/envoy/service/**/*.proto",
"deps/envoy-api/envoy/type/**/*.proto",
"deps/udpa/udpa/**/*.proto",
"deps/googleapis/google/api/*.proto",
"deps/googleapis/google/rpc/*.proto",
"deps/protoc-gen-validate/validate/**/*.proto"
]
};
}
});
// node_modules/@grpc/grpc-js/build/src/logging.js
var require_logging = __commonJS({
"node_modules/@grpc/grpc-js/build/src/logging.js"(exports2) {
"use strict";
var _a10;
var _b2;
var _c2;
var _d;
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.isTracerEnabled = exports2.trace = exports2.log = exports2.setLoggerVerbosity = exports2.setLogger = exports2.getLogger = void 0;
var constants_1 = require_constants();
var process_1 = require("process");
var clientVersion = require_package().version;
var DEFAULT_LOGGER = {
error: (message, ...optionalParams) => {
console.error("E " + message, ...optionalParams);
},
info: (message, ...optionalParams) => {
console.error("I " + message, ...optionalParams);
},
debug: (message, ...optionalParams) => {
console.error("D " + message, ...optionalParams);
}
};
var _logger = DEFAULT_LOGGER;
var _logVerbosity = constants_1.LogVerbosity.ERROR;
var verbosityString = (_b2 = (_a10 = process.env.GRPC_NODE_VERBOSITY) !== null && _a10 !== void 0 ? _a10 : process.env.GRPC_VERBOSITY) !== null && _b2 !== void 0 ? _b2 : "";
switch (verbosityString.toUpperCase()) {
case "DEBUG":
_logVerbosity = constants_1.LogVerbosity.DEBUG;
break;
case "INFO":
_logVerbosity = constants_1.LogVerbosity.INFO;
break;
case "ERROR":
_logVerbosity = constants_1.LogVerbosity.ERROR;
break;
case "NONE":
_logVerbosity = constants_1.LogVerbosity.NONE;
break;
default:
}
var getLogger = () => {
return _logger;
};
exports2.getLogger = getLogger;
var setLogger = (logger9) => {
_logger = logger9;
};
exports2.setLogger = setLogger;
var setLoggerVerbosity = (verbosity) => {
_logVerbosity = verbosity;
};
exports2.setLoggerVerbosity = setLoggerVerbosity;
var log2 = (severity, ...args2) => {
let logFunction;
if (severity >= _logVerbosity) {
switch (severity) {
case constants_1.LogVerbosity.DEBUG:
logFunction = _logger.debug;
break;
case constants_1.LogVerbosity.INFO:
logFunction = _logger.info;
break;
case constants_1.LogVerbosity.ERROR:
logFunction = _logger.error;
break;
}
if (!logFunction) {
logFunction = _logger.error;
}
if (logFunction) {
logFunction.bind(_logger)(...args2);
}
}
};
exports2.log = log2;
var tracersString = (_d = (_c2 = process.env.GRPC_NODE_TRACE) !== null && _c2 !== void 0 ? _c2 : process.env.GRPC_TRACE) !== null && _d !== void 0 ? _d : "";
var enabledTracers = /* @__PURE__ */ new Set();
var disabledTracers = /* @__PURE__ */ new Set();
for (const tracerName of tracersString.split(",")) {
if (tracerName.startsWith("-")) {
disabledTracers.add(tracerName.substring(1));
} else {
enabledTracers.add(tracerName);
}
}
var allEnabled = enabledTracers.has("all");
function trace2(severity, tracer, text3) {
if (isTracerEnabled(tracer)) {
(0, exports2.log)(severity, (/* @__PURE__ */ new Date()).toISOString() + " | v" + clientVersion + " " + process_1.pid + " | " + tracer + " | " + text3);
}
}
exports2.trace = trace2;
function isTracerEnabled(tracer) {
return !disabledTracers.has(tracer) && (allEnabled || enabledTracers.has(tracer));
}
exports2.isTracerEnabled = isTracerEnabled;
}
});
// node_modules/@grpc/grpc-js/build/src/error.js
var require_error = __commonJS({
"node_modules/@grpc/grpc-js/build/src/error.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.getErrorCode = exports2.getErrorMessage = void 0;
function getErrorMessage2(error) {
if (error instanceof Error) {
return error.message;
} else {
return String(error);
}
}
exports2.getErrorMessage = getErrorMessage2;
function getErrorCode(error) {
if (typeof error === "object" && error !== null && "code" in error && typeof error.code === "number") {
return error.code;
} else {
return null;
}
}
exports2.getErrorCode = getErrorCode;
}
});
// node_modules/@grpc/grpc-js/build/src/metadata.js
var require_metadata = __commonJS({
"node_modules/@grpc/grpc-js/build/src/metadata.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.Metadata = void 0;
var logging_1 = require_logging();
var constants_1 = require_constants();
var error_1 = require_error();
var LEGAL_KEY_REGEX = /^[0-9a-z_.-]+$/;
var LEGAL_NON_BINARY_VALUE_REGEX = /^[ -~]*$/;
function isLegalKey(key) {
return LEGAL_KEY_REGEX.test(key);
}
function isLegalNonBinaryValue(value) {
return LEGAL_NON_BINARY_VALUE_REGEX.test(value);
}
function isBinaryKey(key) {
return key.endsWith("-bin");
}
function isCustomMetadata(key) {
return !key.startsWith("grpc-");
}
function normalizeKey(key) {
return key.toLowerCase();
}
function validate5(key, value) {
if (!isLegalKey(key)) {
throw new Error('Metadata key "' + key + '" contains illegal characters');
}
if (value !== null && value !== void 0) {
if (isBinaryKey(key)) {
if (!Buffer.isBuffer(value)) {
throw new Error("keys that end with '-bin' must have Buffer values");
}
} else {
if (Buffer.isBuffer(value)) {
throw new Error("keys that don't end with '-bin' must have String values");
}
if (!isLegalNonBinaryValue(value)) {
throw new Error('Metadata string value "' + value + '" contains illegal characters');
}
}
}
}
var Metadata23 = class _Metadata {
constructor(options = {}) {
this.internalRepr = /* @__PURE__ */ new Map();
this.options = options;
}
/**
* Sets the given value for the given key by replacing any other values
* associated with that key. Normalizes the key.
* @param key The key to whose value should be set.
* @param value The value to set. Must be a buffer if and only
* if the normalized key ends with '-bin'.
*/
set(key, value) {
key = normalizeKey(key);
validate5(key, value);
this.internalRepr.set(key, [value]);
}
/**
* Adds the given value for the given key by appending to a list of previous
* values associated with that key. Normalizes the key.
* @param key The key for which a new value should be appended.
* @param value The value to add. Must be a buffer if and only
* if the normalized key ends with '-bin'.
*/
add(key, value) {
key = normalizeKey(key);
validate5(key, value);
const existingValue = this.internalRepr.get(key);
if (existingValue === void 0) {
this.internalRepr.set(key, [value]);
} else {
existingValue.push(value);
}
}
/**
* Removes the given key and any associated values. Normalizes the key.
* @param key The key whose values should be removed.
*/
remove(key) {
key = normalizeKey(key);
this.internalRepr.delete(key);
}
/**
* Gets a list of all values associated with the key. Normalizes the key.
* @param key The key whose value should be retrieved.
* @return A list of values associated with the given key.
*/
get(key) {
key = normalizeKey(key);
return this.internalRepr.get(key) || [];
}
/**
* Gets a plain object mapping each key to the first value associated with it.
* This reflects the most common way that people will want to see metadata.
* @return A key/value mapping of the metadata.
*/
getMap() {
const result2 = {};
for (const [key, values2] of this.internalRepr) {
if (values2.length > 0) {
const v7 = values2[0];
result2[key] = Buffer.isBuffer(v7) ? Buffer.from(v7) : v7;
}
}
return result2;
}
/**
* Clones the metadata object.
* @return The newly cloned object.
*/
clone() {
const newMetadata = new _Metadata(this.options);
const newInternalRepr = newMetadata.internalRepr;
for (const [key, value] of this.internalRepr) {
const clonedValue = value.map((v7) => {
if (Buffer.isBuffer(v7)) {
return Buffer.from(v7);
} else {
return v7;
}
});
newInternalRepr.set(key, clonedValue);
}
return newMetadata;
}
/**
* Merges all key-value pairs from a given Metadata object into this one.
* If both this object and the given object have values in the same key,
* values from the other Metadata object will be appended to this object's
* values.
* @param other A Metadata object.
*/
merge(other) {
for (const [key, values2] of other.internalRepr) {
const mergedValue = (this.internalRepr.get(key) || []).concat(values2);
this.internalRepr.set(key, mergedValue);
}
}
setOptions(options) {
this.options = options;
}
getOptions() {
return this.options;
}
/**
* Creates an OutgoingHttpHeaders object that can be used with the http2 API.
*/
toHttp2Headers() {
const result2 = {};
for (const [key, values2] of this.internalRepr) {
result2[key] = values2.map(bufToString);
}
return result2;
}
/**
* This modifies the behavior of JSON.stringify to show an object
* representation of the metadata map.
*/
toJSON() {
const result2 = {};
for (const [key, values2] of this.internalRepr) {
result2[key] = values2;
}
return result2;
}
/**
* Returns a new Metadata object based fields in a given IncomingHttpHeaders
* object.
* @param headers An IncomingHttpHeaders object.
*/
static fromHttp2Headers(headers) {
const result2 = new _Metadata();
for (const key of Object.keys(headers)) {
if (key.charAt(0) === ":") {
continue;
}
const values2 = headers[key];
try {
if (isBinaryKey(key)) {
if (Array.isArray(values2)) {
values2.forEach((value) => {
result2.add(key, Buffer.from(value, "base64"));
});
} else if (values2 !== void 0) {
if (isCustomMetadata(key)) {
values2.split(",").forEach((v7) => {
result2.add(key, Buffer.from(v7.trim(), "base64"));
});
} else {
result2.add(key, Buffer.from(values2, "base64"));
}
}
} else {
if (Array.isArray(values2)) {
values2.forEach((value) => {
result2.add(key, value);
});
} else if (values2 !== void 0) {
result2.add(key, values2);
}
}
} catch (error) {
const message = `Failed to add metadata entry ${key}: ${values2}. ${(0, error_1.getErrorMessage)(error)}. For more information see https://github.com/grpc/grpc-node/issues/1173`;
(0, logging_1.log)(constants_1.LogVerbosity.ERROR, message);
}
}
return result2;
}
};
exports2.Metadata = Metadata23;
var bufToString = (val3) => {
return Buffer.isBuffer(val3) ? val3.toString("base64") : val3;
};
}
});
// node_modules/@grpc/grpc-js/build/src/call-credentials.js
var require_call_credentials = __commonJS({
"node_modules/@grpc/grpc-js/build/src/call-credentials.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.CallCredentials = void 0;
var metadata_1 = require_metadata();
function isCurrentOauth2Client(client) {
return "getRequestHeaders" in client && typeof client.getRequestHeaders === "function";
}
var CallCredentials = class _CallCredentials {
/**
* Creates a new CallCredentials object from a given function that generates
* Metadata objects.
* @param metadataGenerator A function that accepts a set of options, and
* generates a Metadata object based on these options, which is passed back
* to the caller via a supplied (err, metadata) callback.
*/
static createFromMetadataGenerator(metadataGenerator) {
return new SingleCallCredentials(metadataGenerator);
}
/**
* Create a gRPC credential from a Google credential object.
* @param googleCredentials The authentication client to use.
* @return The resulting CallCredentials object.
*/
static createFromGoogleCredential(googleCredentials) {
return _CallCredentials.createFromMetadataGenerator((options, callback) => {
let getHeaders;
if (isCurrentOauth2Client(googleCredentials)) {
getHeaders = googleCredentials.getRequestHeaders(options.service_url);
} else {
getHeaders = new Promise((resolve16, reject2) => {
googleCredentials.getRequestMetadata(options.service_url, (err2, headers) => {
if (err2) {
reject2(err2);
return;
}
if (!headers) {
reject2(new Error("Headers not set by metadata plugin"));
return;
}
resolve16(headers);
});
});
}
getHeaders.then((headers) => {
const metadata2 = new metadata_1.Metadata();
for (const key of Object.keys(headers)) {
metadata2.add(key, headers[key]);
}
callback(null, metadata2);
}, (err2) => {
callback(err2);
});
});
}
static createEmpty() {
return new EmptyCallCredentials();
}
};
exports2.CallCredentials = CallCredentials;
var ComposedCallCredentials = class _ComposedCallCredentials extends CallCredentials {
constructor(creds) {
super();
this.creds = creds;
}
async generateMetadata(options) {
const base = new metadata_1.Metadata();
const generated = await Promise.all(this.creds.map((cred) => cred.generateMetadata(options)));
for (const gen of generated) {
base.merge(gen);
}
return base;
}
compose(other) {
return new _ComposedCallCredentials(this.creds.concat([other]));
}
_equals(other) {
if (this === other) {
return true;
}
if (other instanceof _ComposedCallCredentials) {
return this.creds.every((value, index3) => value._equals(other.creds[index3]));
} else {
return false;
}
}
};
var SingleCallCredentials = class _SingleCallCredentials extends CallCredentials {
constructor(metadataGenerator) {
super();
this.metadataGenerator = metadataGenerator;
}
generateMetadata(options) {
return new Promise((resolve16, reject2) => {
this.metadataGenerator(options, (err2, metadata2) => {
if (metadata2 !== void 0) {
resolve16(metadata2);
} else {
reject2(err2);
}
});
});
}
compose(other) {
return new ComposedCallCredentials([this, other]);
}
_equals(other) {
if (this === other) {
return true;
}
if (other instanceof _SingleCallCredentials) {
return this.metadataGenerator === other.metadataGenerator;
} else {
return false;
}
}
};
var EmptyCallCredentials = class _EmptyCallCredentials extends CallCredentials {
generateMetadata(options) {
return Promise.resolve(new metadata_1.Metadata());
}
compose(other) {
return other;
}
_equals(other) {
return other instanceof _EmptyCallCredentials;
}
};
}
});
// node_modules/@grpc/grpc-js/build/src/tls-helpers.js
var require_tls_helpers = __commonJS({
"node_modules/@grpc/grpc-js/build/src/tls-helpers.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.getDefaultRootsData = exports2.CIPHER_SUITES = void 0;
var fs61 = require("fs");
exports2.CIPHER_SUITES = process.env.GRPC_SSL_CIPHER_SUITES;
var DEFAULT_ROOTS_FILE_PATH = process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH;
var defaultRootsData = null;
function getDefaultRootsData() {
if (DEFAULT_ROOTS_FILE_PATH) {
if (defaultRootsData === null) {
defaultRootsData = fs61.readFileSync(DEFAULT_ROOTS_FILE_PATH);
}
return defaultRootsData;
}
return null;
}
exports2.getDefaultRootsData = getDefaultRootsData;
}
});
// node_modules/@grpc/grpc-js/build/src/channel-credentials.js
var require_channel_credentials = __commonJS({
"node_modules/@grpc/grpc-js/build/src/channel-credentials.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.ChannelCredentials = void 0;
var tls_1 = require("tls");
var call_credentials_1 = require_call_credentials();
var tls_helpers_1 = require_tls_helpers();
function verifyIsBufferOrNull(obj2, friendlyName) {
if (obj2 && !(obj2 instanceof Buffer)) {
throw new TypeError(`${friendlyName}, if provided, must be a Buffer.`);
}
}
var ChannelCredentials20 = class {
constructor(callCredentials) {
this.callCredentials = callCredentials || call_credentials_1.CallCredentials.createEmpty();
}
/**
* Gets the set of per-call credentials associated with this instance.
*/
_getCallCredentials() {
return this.callCredentials;
}
/**
* Return a new ChannelCredentials instance with a given set of credentials.
* The resulting instance can be used to construct a Channel that communicates
* over TLS.
* @param rootCerts The root certificate data.
* @param privateKey The client certificate private key, if available.
* @param certChain The client certificate key chain, if available.
* @param verifyOptions Additional options to modify certificate verification
*/
static createSsl(rootCerts, privateKey, certChain, verifyOptions) {
var _a10;
verifyIsBufferOrNull(rootCerts, "Root certificate");
verifyIsBufferOrNull(privateKey, "Private key");
verifyIsBufferOrNull(certChain, "Certificate chain");
if (privateKey && !certChain) {
throw new Error("Private key must be given with accompanying certificate chain");
}
if (!privateKey && certChain) {
throw new Error("Certificate chain must be given with accompanying private key");
}
const secureContext = (0, tls_1.createSecureContext)({
ca: (_a10 = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a10 !== void 0 ? _a10 : void 0,
key: privateKey !== null && privateKey !== void 0 ? privateKey : void 0,
cert: certChain !== null && certChain !== void 0 ? certChain : void 0,
ciphers: tls_helpers_1.CIPHER_SUITES
});
return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {});
}
/**
* Return a new ChannelCredentials instance with credentials created using
* the provided secureContext. The resulting instances can be used to
* construct a Channel that communicates over TLS. gRPC will not override
* anything in the provided secureContext, so the environment variables
* GRPC_SSL_CIPHER_SUITES and GRPC_DEFAULT_SSL_ROOTS_FILE_PATH will
* not be applied.
* @param secureContext The return value of tls.createSecureContext()
* @param verifyOptions Additional options to modify certificate verification
*/
static createFromSecureContext(secureContext, verifyOptions) {
return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {});
}
/**
* Return a new ChannelCredentials instance with no credentials.
*/
static createInsecure() {
return new InsecureChannelCredentialsImpl();
}
};
exports2.ChannelCredentials = ChannelCredentials20;
var InsecureChannelCredentialsImpl = class _InsecureChannelCredentialsImpl extends ChannelCredentials20 {
constructor(callCredentials) {
super(callCredentials);
}
compose(callCredentials) {
throw new Error("Cannot compose insecure credentials");
}
_getConnectionOptions() {
return null;
}
_isSecure() {
return false;
}
_equals(other) {
return other instanceof _InsecureChannelCredentialsImpl;
}
};
var SecureChannelCredentialsImpl = class _SecureChannelCredentialsImpl extends ChannelCredentials20 {
constructor(secureContext, verifyOptions) {
super();
this.secureContext = secureContext;
this.verifyOptions = verifyOptions;
this.connectionOptions = {
secureContext
};
if (verifyOptions === null || verifyOptions === void 0 ? void 0 : verifyOptions.checkServerIdentity) {
this.connectionOptions.checkServerIdentity = verifyOptions.checkServerIdentity;
}
}
compose(callCredentials) {
const combinedCallCredentials = this.callCredentials.compose(callCredentials);
return new ComposedChannelCredentialsImpl(this, combinedCallCredentials);
}
_getConnectionOptions() {
return Object.assign({}, this.connectionOptions);
}
_isSecure() {
return true;
}
_equals(other) {
if (this === other) {
return true;
}
if (other instanceof _SecureChannelCredentialsImpl) {
return this.secureContext === other.secureContext && this.verifyOptions.checkServerIdentity === other.verifyOptions.checkServerIdentity;
} else {
return false;
}
}
};
var ComposedChannelCredentialsImpl = class _ComposedChannelCredentialsImpl extends ChannelCredentials20 {
constructor(channelCredentials, callCreds) {
super(callCreds);
this.channelCredentials = channelCredentials;
}
compose(callCredentials) {
const combinedCallCredentials = this.callCredentials.compose(callCredentials);
return new _ComposedChannelCredentialsImpl(this.channelCredentials, combinedCallCredentials);
}
_getConnectionOptions() {
return this.channelCredentials._getConnectionOptions();
}
_isSecure() {
return true;
}
_equals(other) {
if (this === other) {
return true;
}
if (other instanceof _ComposedChannelCredentialsImpl) {
return this.channelCredentials._equals(other.channelCredentials) && this.callCredentials._equals(other.callCredentials);
} else {
return false;
}
}
};
}
});
// node_modules/@grpc/grpc-js/build/src/load-balancer.js
var require_load_balancer = __commonJS({
"node_modules/@grpc/grpc-js/build/src/load-balancer.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.validateLoadBalancingConfig = exports2.getFirstUsableConfig = exports2.isLoadBalancerNameRegistered = exports2.createLoadBalancer = exports2.registerDefaultLoadBalancerType = exports2.registerLoadBalancerType = exports2.createChildChannelControlHelper = void 0;
function createChildChannelControlHelper(parent2, overrides) {
var _a10, _b2, _c2, _d, _e2, _f, _g, _h, _j, _k;
return {
createSubchannel: (_b2 = (_a10 = overrides.createSubchannel) === null || _a10 === void 0 ? void 0 : _a10.bind(overrides)) !== null && _b2 !== void 0 ? _b2 : parent2.createSubchannel.bind(parent2),
updateState: (_d = (_c2 = overrides.updateState) === null || _c2 === void 0 ? void 0 : _c2.bind(overrides)) !== null && _d !== void 0 ? _d : parent2.updateState.bind(parent2),
requestReresolution: (_f = (_e2 = overrides.requestReresolution) === null || _e2 === void 0 ? void 0 : _e2.bind(overrides)) !== null && _f !== void 0 ? _f : parent2.requestReresolution.bind(parent2),
addChannelzChild: (_h = (_g = overrides.addChannelzChild) === null || _g === void 0 ? void 0 : _g.bind(overrides)) !== null && _h !== void 0 ? _h : parent2.addChannelzChild.bind(parent2),
removeChannelzChild: (_k = (_j = overrides.removeChannelzChild) === null || _j === void 0 ? void 0 : _j.bind(overrides)) !== null && _k !== void 0 ? _k : parent2.removeChannelzChild.bind(parent2)
};
}
exports2.createChildChannelControlHelper = createChildChannelControlHelper;
var registeredLoadBalancerTypes = {};
var defaultLoadBalancerType = null;
function registerLoadBalancerType(typeName, loadBalancerType, loadBalancingConfigType) {
registeredLoadBalancerTypes[typeName] = {
LoadBalancer: loadBalancerType,
LoadBalancingConfig: loadBalancingConfigType
};
}
exports2.registerLoadBalancerType = registerLoadBalancerType;
function registerDefaultLoadBalancerType(typeName) {
defaultLoadBalancerType = typeName;
}
exports2.registerDefaultLoadBalancerType = registerDefaultLoadBalancerType;
function createLoadBalancer(config7, channelControlHelper) {
const typeName = config7.getLoadBalancerName();
if (typeName in registeredLoadBalancerTypes) {
return new registeredLoadBalancerTypes[typeName].LoadBalancer(channelControlHelper);
} else {
return null;
}
}
exports2.createLoadBalancer = createLoadBalancer;
function isLoadBalancerNameRegistered(typeName) {
return typeName in registeredLoadBalancerTypes;
}
exports2.isLoadBalancerNameRegistered = isLoadBalancerNameRegistered;
function getFirstUsableConfig(configs, fallbackTodefault = false) {
for (const config7 of configs) {
if (config7.getLoadBalancerName() in registeredLoadBalancerTypes) {
return config7;
}
}
if (fallbackTodefault) {
if (defaultLoadBalancerType) {
return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig();
} else {
return null;
}
} else {
return null;
}
}
exports2.getFirstUsableConfig = getFirstUsableConfig;
function validateLoadBalancingConfig(obj2) {
if (!(obj2 !== null && typeof obj2 === "object")) {
throw new Error("Load balancing config must be an object");
}
const keys2 = Object.keys(obj2);
if (keys2.length !== 1) {
throw new Error("Provided load balancing config has multiple conflicting entries");
}
const typeName = keys2[0];
if (typeName in registeredLoadBalancerTypes) {
return registeredLoadBalancerTypes[typeName].LoadBalancingConfig.createFromJson(obj2[typeName]);
} else {
throw new Error(`Unrecognized load balancing config name ${typeName}`);
}
}
exports2.validateLoadBalancingConfig = validateLoadBalancingConfig;
}
});
// node_modules/@grpc/grpc-js/build/src/service-config.js
var require_service_config = __commonJS({
"node_modules/@grpc/grpc-js/build/src/service-config.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.extractAndSelectServiceConfig = exports2.validateServiceConfig = exports2.validateRetryThrottling = void 0;
var os29 = require("os");
var constants_1 = require_constants();
var load_balancer_1 = require_load_balancer();
var DURATION_REGEX = /^\d+(\.\d{1,9})?s$/;
var CLIENT_LANGUAGE_STRING = "node";
function validateName(obj2) {
if ("service" in obj2 && obj2.service !== "") {
if (typeof obj2.service !== "string") {
throw new Error(`Invalid method config name: invalid service: expected type string, got ${typeof obj2.service}`);
}
if ("method" in obj2 && obj2.method !== "") {
if (typeof obj2.method !== "string") {
throw new Error(`Invalid method config name: invalid method: expected type string, got ${typeof obj2.service}`);
}
return {
service: obj2.service,
method: obj2.method
};
} else {
return {
service: obj2.service
};
}
} else {
if ("method" in obj2 && obj2.method !== void 0) {
throw new Error(`Invalid method config name: method set with empty or unset service`);
}
return {};
}
}
function validateRetryPolicy(obj2) {
if (!("maxAttempts" in obj2) || !Number.isInteger(obj2.maxAttempts) || obj2.maxAttempts < 2) {
throw new Error("Invalid method config retry policy: maxAttempts must be an integer at least 2");
}
if (!("initialBackoff" in obj2) || typeof obj2.initialBackoff !== "string" || !DURATION_REGEX.test(obj2.initialBackoff)) {
throw new Error("Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer followed by s");
}
if (!("maxBackoff" in obj2) || typeof obj2.maxBackoff !== "string" || !DURATION_REGEX.test(obj2.maxBackoff)) {
throw new Error("Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer followed by s");
}
if (!("backoffMultiplier" in obj2) || typeof obj2.backoffMultiplier !== "number" || obj2.backoffMultiplier <= 0) {
throw new Error("Invalid method config retry policy: backoffMultiplier must be a number greater than 0");
}
if (!("retryableStatusCodes" in obj2 && Array.isArray(obj2.retryableStatusCodes))) {
throw new Error("Invalid method config retry policy: retryableStatusCodes is required");
}
if (obj2.retryableStatusCodes.length === 0) {
throw new Error("Invalid method config retry policy: retryableStatusCodes must be non-empty");
}
for (const value of obj2.retryableStatusCodes) {
if (typeof value === "number") {
if (!Object.values(constants_1.Status).includes(value)) {
throw new Error("Invalid method config retry policy: retryableStatusCodes value not in status code range");
}
} else if (typeof value === "string") {
if (!Object.values(constants_1.Status).includes(value.toUpperCase())) {
throw new Error("Invalid method config retry policy: retryableStatusCodes value not a status code name");
}
} else {
throw new Error("Invalid method config retry policy: retryableStatusCodes value must be a string or number");
}
}
return {
maxAttempts: obj2.maxAttempts,
initialBackoff: obj2.initialBackoff,
maxBackoff: obj2.maxBackoff,
backoffMultiplier: obj2.backoffMultiplier,
retryableStatusCodes: obj2.retryableStatusCodes
};
}
function validateHedgingPolicy(obj2) {
if (!("maxAttempts" in obj2) || !Number.isInteger(obj2.maxAttempts) || obj2.maxAttempts < 2) {
throw new Error("Invalid method config hedging policy: maxAttempts must be an integer at least 2");
}
if ("hedgingDelay" in obj2 && (typeof obj2.hedgingDelay !== "string" || !DURATION_REGEX.test(obj2.hedgingDelay))) {
throw new Error("Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s");
}
if ("nonFatalStatusCodes" in obj2 && Array.isArray(obj2.nonFatalStatusCodes)) {
for (const value of obj2.nonFatalStatusCodes) {
if (typeof value === "number") {
if (!Object.values(constants_1.Status).includes(value)) {
throw new Error("Invlid method config hedging policy: nonFatalStatusCodes value not in status code range");
}
} else if (typeof value === "string") {
if (!Object.values(constants_1.Status).includes(value.toUpperCase())) {
throw new Error("Invlid method config hedging policy: nonFatalStatusCodes value not a status code name");
}
} else {
throw new Error("Invlid method config hedging policy: nonFatalStatusCodes value must be a string or number");
}
}
}
const result2 = {
maxAttempts: obj2.maxAttempts
};
if (obj2.hedgingDelay) {
result2.hedgingDelay = obj2.hedgingDelay;
}
if (obj2.nonFatalStatusCodes) {
result2.nonFatalStatusCodes = obj2.nonFatalStatusCodes;
}
return result2;
}
function validateMethodConfig(obj2) {
var _a10;
const result2 = {
name: []
};
if (!("name" in obj2) || !Array.isArray(obj2.name)) {
throw new Error("Invalid method config: invalid name array");
}
for (const name6 of obj2.name) {
result2.name.push(validateName(name6));
}
if ("waitForReady" in obj2) {
if (typeof obj2.waitForReady !== "boolean") {
throw new Error("Invalid method config: invalid waitForReady");
}
result2.waitForReady = obj2.waitForReady;
}
if ("timeout" in obj2) {
if (typeof obj2.timeout === "object") {
if (!("seconds" in obj2.timeout) || !(typeof obj2.timeout.seconds === "number")) {
throw new Error("Invalid method config: invalid timeout.seconds");
}
if (!("nanos" in obj2.timeout) || !(typeof obj2.timeout.nanos === "number")) {
throw new Error("Invalid method config: invalid timeout.nanos");
}
result2.timeout = obj2.timeout;
} else if (typeof obj2.timeout === "string" && DURATION_REGEX.test(obj2.timeout)) {
const timeoutParts = obj2.timeout.substring(0, obj2.timeout.length - 1).split(".");
result2.timeout = {
seconds: timeoutParts[0] | 0,
nanos: ((_a10 = timeoutParts[1]) !== null && _a10 !== void 0 ? _a10 : 0) | 0
};
} else {
throw new Error("Invalid method config: invalid timeout");
}
}
if ("maxRequestBytes" in obj2) {
if (typeof obj2.maxRequestBytes !== "number") {
throw new Error("Invalid method config: invalid maxRequestBytes");
}
result2.maxRequestBytes = obj2.maxRequestBytes;
}
if ("maxResponseBytes" in obj2) {
if (typeof obj2.maxResponseBytes !== "number") {
throw new Error("Invalid method config: invalid maxRequestBytes");
}
result2.maxResponseBytes = obj2.maxResponseBytes;
}
if ("retryPolicy" in obj2) {
if ("hedgingPolicy" in obj2) {
throw new Error("Invalid method config: retryPolicy and hedgingPolicy cannot both be specified");
} else {
result2.retryPolicy = validateRetryPolicy(obj2.retryPolicy);
}
} else if ("hedgingPolicy" in obj2) {
result2.hedgingPolicy = validateHedgingPolicy(obj2.hedgingPolicy);
}
return result2;
}
function validateRetryThrottling(obj2) {
if (!("maxTokens" in obj2) || typeof obj2.maxTokens !== "number" || obj2.maxTokens <= 0 || obj2.maxTokens > 1e3) {
throw new Error("Invalid retryThrottling: maxTokens must be a number in (0, 1000]");
}
if (!("tokenRatio" in obj2) || typeof obj2.tokenRatio !== "number" || obj2.tokenRatio <= 0) {
throw new Error("Invalid retryThrottling: tokenRatio must be a number greater than 0");
}
return {
maxTokens: +obj2.maxTokens.toFixed(3),
tokenRatio: +obj2.tokenRatio.toFixed(3)
};
}
exports2.validateRetryThrottling = validateRetryThrottling;
function validateServiceConfig(obj2) {
const result2 = {
loadBalancingConfig: [],
methodConfig: []
};
if ("loadBalancingPolicy" in obj2) {
if (typeof obj2.loadBalancingPolicy === "string") {
result2.loadBalancingPolicy = obj2.loadBalancingPolicy;
} else {
throw new Error("Invalid service config: invalid loadBalancingPolicy");
}
}
if ("loadBalancingConfig" in obj2) {
if (Array.isArray(obj2.loadBalancingConfig)) {
for (const config7 of obj2.loadBalancingConfig) {
result2.loadBalancingConfig.push((0, load_balancer_1.validateLoadBalancingConfig)(config7));
}
} else {
throw new Error("Invalid service config: invalid loadBalancingConfig");
}
}
if ("methodConfig" in obj2) {
if (Array.isArray(obj2.methodConfig)) {
for (const methodConfig of obj2.methodConfig) {
result2.methodConfig.push(validateMethodConfig(methodConfig));
}
}
}
if ("retryThrottling" in obj2) {
result2.retryThrottling = validateRetryThrottling(obj2.retryThrottling);
}
const seenMethodNames = [];
for (const methodConfig of result2.methodConfig) {
for (const name6 of methodConfig.name) {
for (const seenName of seenMethodNames) {
if (name6.service === seenName.service && name6.method === seenName.method) {
throw new Error(`Invalid service config: duplicate name ${name6.service}/${name6.method}`);
}
}
seenMethodNames.push(name6);
}
}
return result2;
}
exports2.validateServiceConfig = validateServiceConfig;
function validateCanaryConfig(obj2) {
if (!("serviceConfig" in obj2)) {
throw new Error("Invalid service config choice: missing service config");
}
const result2 = {
serviceConfig: validateServiceConfig(obj2.serviceConfig)
};
if ("clientLanguage" in obj2) {
if (Array.isArray(obj2.clientLanguage)) {
result2.clientLanguage = [];
for (const lang of obj2.clientLanguage) {
if (typeof lang === "string") {
result2.clientLanguage.push(lang);
} else {
throw new Error("Invalid service config choice: invalid clientLanguage");
}
}
} else {
throw new Error("Invalid service config choice: invalid clientLanguage");
}
}
if ("clientHostname" in obj2) {
if (Array.isArray(obj2.clientHostname)) {
result2.clientHostname = [];
for (const lang of obj2.clientHostname) {
if (typeof lang === "string") {
result2.clientHostname.push(lang);
} else {
throw new Error("Invalid service config choice: invalid clientHostname");
}
}
} else {
throw new Error("Invalid service config choice: invalid clientHostname");
}
}
if ("percentage" in obj2) {
if (typeof obj2.percentage === "number" && 0 <= obj2.percentage && obj2.percentage <= 100) {
result2.percentage = obj2.percentage;
} else {
throw new Error("Invalid service config choice: invalid percentage");
}
}
const allowedFields = [
"clientLanguage",
"percentage",
"clientHostname",
"serviceConfig"
];
for (const field in obj2) {
if (!allowedFields.includes(field)) {
throw new Error(`Invalid service config choice: unexpected field ${field}`);
}
}
return result2;
}
function validateAndSelectCanaryConfig(obj2, percentage) {
if (!Array.isArray(obj2)) {
throw new Error("Invalid service config list");
}
for (const config7 of obj2) {
const validatedConfig = validateCanaryConfig(config7);
if (typeof validatedConfig.percentage === "number" && percentage > validatedConfig.percentage) {
continue;
}
if (Array.isArray(validatedConfig.clientHostname)) {
let hostnameMatched = false;
for (const hostname of validatedConfig.clientHostname) {
if (hostname === os29.hostname()) {
hostnameMatched = true;
}
}
if (!hostnameMatched) {
continue;
}
}
if (Array.isArray(validatedConfig.clientLanguage)) {
let languageMatched = false;
for (const language of validatedConfig.clientLanguage) {
if (language === CLIENT_LANGUAGE_STRING) {
languageMatched = true;
}
}
if (!languageMatched) {